diff --git a/.gitignore b/.gitignore
index 9eabbed..4397477 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,3 +43,4 @@ projects/
debug/
*.tar.gz
tests/test-results/
+ui-electrobun/build/
diff --git a/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Info.plist b/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Info.plist
deleted file mode 100644
index a550f06..0000000
--- a/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Info.plist
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
- CFBundleExecutable
- launcher
- CFBundleIdentifier
- dev.agor.orchestrator
- CFBundleName
- AgentOrchestrator-dev
- CFBundleVersion
- 0.0.1
- CFBundlePackageType
- APPL
- CFBundleIconFile
- AppIcon
-
-
\ No newline at end of file
diff --git a/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Resources/app/bun/index.js b/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Resources/app/bun/index.js
deleted file mode 100644
index c463cb5..0000000
--- a/ui-electrobun/build/dev-linux-x64/AgentOrchestrator-dev/Resources/app/bun/index.js
+++ /dev/null
@@ -1,232336 +0,0 @@
-// @bun
-var __defProp = Object.defineProperty;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __moduleCache = /* @__PURE__ */ new WeakMap;
-var __toCommonJS = (from) => {
- var entry = __moduleCache.get(from), desc;
- if (entry)
- return entry;
- entry = __defProp({}, "__esModule", { value: true });
- if (from && typeof from === "object" || typeof from === "function")
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
- get: () => from[key],
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
- }));
- __moduleCache.set(from, entry);
- return entry;
-};
-var __export = (target, all) => {
- for (var name2 in all)
- __defProp(target, name2, {
- get: all[name2],
- enumerable: true,
- configurable: true,
- set: (newValue) => all[name2] = () => newValue
- });
-};
-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
-var __promiseAll = (args) => Promise.all(args);
-
-// node_modules/electrobun/dist/api/bun/events/event.ts
-class ElectrobunEvent {
- name;
- data;
- _response;
- responseWasSet = false;
- constructor(name2, data) {
- this.name = name2;
- this.data = data;
- }
- get response() {
- return this._response;
- }
- set response(value) {
- this._response = value;
- this.responseWasSet = true;
- }
- clearResponse() {
- this._response = undefined;
- this.responseWasSet = false;
- }
-}
-
-// node_modules/electrobun/dist/api/bun/events/windowEvents.ts
-var windowEvents_default;
-var init_windowEvents = __esm(() => {
- windowEvents_default = {
- close: (data) => new ElectrobunEvent("close", data),
- resize: (data) => new ElectrobunEvent("resize", data),
- move: (data) => new ElectrobunEvent("move", data),
- focus: (data) => new ElectrobunEvent("focus", data),
- blur: (data) => new ElectrobunEvent("blur", data),
- keyDown: (data) => new ElectrobunEvent("keyDown", data),
- keyUp: (data) => new ElectrobunEvent("keyUp", data)
- };
-});
-
-// node_modules/electrobun/dist/api/bun/events/webviewEvents.ts
-var webviewEvents_default;
-var init_webviewEvents = __esm(() => {
- webviewEvents_default = {
- willNavigate: (data) => new ElectrobunEvent("will-navigate", data),
- didNavigate: (data) => new ElectrobunEvent("did-navigate", data),
- didNavigateInPage: (data) => new ElectrobunEvent("did-navigate-in-page", data),
- didCommitNavigation: (data) => new ElectrobunEvent("did-commit-navigation", data),
- domReady: (data) => new ElectrobunEvent("dom-ready", data),
- newWindowOpen: (data) => new ElectrobunEvent("new-window-open", data),
- hostMessage: (data) => new ElectrobunEvent("host-message", data),
- downloadStarted: (data) => new ElectrobunEvent("download-started", data),
- downloadProgress: (data) => new ElectrobunEvent("download-progress", data),
- downloadCompleted: (data) => new ElectrobunEvent("download-completed", data),
- downloadFailed: (data) => new ElectrobunEvent("download-failed", data)
- };
-});
-
-// node_modules/electrobun/dist/api/bun/events/trayEvents.ts
-var trayEvents_default;
-var init_trayEvents = __esm(() => {
- trayEvents_default = {
- trayClicked: (data) => new ElectrobunEvent("tray-clicked", data)
- };
-});
-
-// node_modules/electrobun/dist/api/bun/events/ApplicationEvents.ts
-var ApplicationEvents_default;
-var init_ApplicationEvents = __esm(() => {
- ApplicationEvents_default = {
- applicationMenuClicked: (data) => new ElectrobunEvent("application-menu-clicked", data),
- contextMenuClicked: (data) => new ElectrobunEvent("context-menu-clicked", data),
- openUrl: (data) => new ElectrobunEvent("open-url", data),
- reopen: (data) => new ElectrobunEvent("reopen", data),
- beforeQuit: (data) => new ElectrobunEvent("before-quit", data)
- };
-});
-
-// node_modules/electrobun/dist/api/bun/events/eventEmitter.ts
-import EventEmitter from "events";
-var ElectrobunEventEmitter, electrobunEventEmitter, eventEmitter_default;
-var init_eventEmitter = __esm(() => {
- init_windowEvents();
- init_webviewEvents();
- init_trayEvents();
- init_ApplicationEvents();
- ElectrobunEventEmitter = class ElectrobunEventEmitter extends EventEmitter {
- constructor() {
- super();
- }
- emitEvent(ElectrobunEvent2, specifier) {
- if (specifier) {
- this.emit(`${ElectrobunEvent2.name}-${specifier}`, ElectrobunEvent2);
- } else {
- this.emit(ElectrobunEvent2.name, ElectrobunEvent2);
- }
- }
- events = {
- window: {
- ...windowEvents_default
- },
- webview: {
- ...webviewEvents_default
- },
- tray: {
- ...trayEvents_default
- },
- app: {
- ...ApplicationEvents_default
- }
- };
- };
- electrobunEventEmitter = new ElectrobunEventEmitter;
- eventEmitter_default = electrobunEventEmitter;
-});
-
-// node_modules/electrobun/dist/api/shared/rpc.ts
-function missingTransportMethodError(methods, action) {
- const methodsString = methods.map((m) => `"${m}"`).join(", ");
- return new Error(`This RPC instance cannot ${action} because the transport did not provide one or more of these methods: ${methodsString}`);
-}
-function createRPC(options = {}) {
- let debugHooks = {};
- let transport = {};
- let requestHandler = undefined;
- function setTransport(newTransport) {
- if (transport.unregisterHandler)
- transport.unregisterHandler();
- transport = newTransport;
- transport.registerHandler?.(handler);
- }
- function setRequestHandler(h) {
- if (typeof h === "function") {
- requestHandler = h;
- return;
- }
- requestHandler = (method, params) => {
- const handlerFn = h[method];
- if (handlerFn)
- return handlerFn(params);
- const fallbackHandler = h._;
- if (!fallbackHandler)
- throw new Error(`The requested method has no handler: ${String(method)}`);
- return fallbackHandler(method, params);
- };
- }
- const { maxRequestTime = DEFAULT_MAX_REQUEST_TIME } = options;
- if (options.transport)
- setTransport(options.transport);
- if (options.requestHandler)
- setRequestHandler(options.requestHandler);
- if (options._debugHooks)
- debugHooks = options._debugHooks;
- let lastRequestId = 0;
- function getRequestId() {
- if (lastRequestId <= MAX_ID)
- return ++lastRequestId;
- return lastRequestId = 0;
- }
- const requestListeners = new Map;
- const requestTimeouts = new Map;
- function requestFn(method, ...args) {
- const params = args[0];
- return new Promise((resolve, reject) => {
- if (!transport.send)
- throw missingTransportMethodError(["send"], "make requests");
- const requestId = getRequestId();
- const request2 = {
- type: "request",
- id: requestId,
- method,
- params
- };
- requestListeners.set(requestId, { resolve, reject });
- if (maxRequestTime !== Infinity)
- requestTimeouts.set(requestId, setTimeout(() => {
- requestTimeouts.delete(requestId);
- requestListeners.delete(requestId);
- reject(new Error("RPC request timed out."));
- }, maxRequestTime));
- debugHooks.onSend?.(request2);
- transport.send(request2);
- });
- }
- const request = new Proxy(requestFn, {
- get: (target, prop, receiver) => {
- if (prop in target)
- return Reflect.get(target, prop, receiver);
- return (params) => requestFn(prop, params);
- }
- });
- const requestProxy = request;
- function sendFn(message, ...args) {
- const payload = args[0];
- if (!transport.send)
- throw missingTransportMethodError(["send"], "send messages");
- const rpcMessage = {
- type: "message",
- id: message,
- payload
- };
- debugHooks.onSend?.(rpcMessage);
- transport.send(rpcMessage);
- }
- const send = new Proxy(sendFn, {
- get: (target, prop, receiver) => {
- if (prop in target)
- return Reflect.get(target, prop, receiver);
- return (payload) => sendFn(prop, payload);
- }
- });
- const sendProxy = send;
- const messageListeners = new Map;
- const wildcardMessageListeners = new Set;
- function addMessageListener(message, listener) {
- if (!transport.registerHandler)
- throw missingTransportMethodError(["registerHandler"], "register message listeners");
- if (message === "*") {
- wildcardMessageListeners.add(listener);
- return;
- }
- if (!messageListeners.has(message))
- messageListeners.set(message, new Set);
- messageListeners.get(message).add(listener);
- }
- function removeMessageListener(message, listener) {
- if (message === "*") {
- wildcardMessageListeners.delete(listener);
- return;
- }
- messageListeners.get(message)?.delete(listener);
- if (messageListeners.get(message)?.size === 0)
- messageListeners.delete(message);
- }
- async function handler(message) {
- debugHooks.onReceive?.(message);
- if (!("type" in message))
- throw new Error("Message does not contain a type.");
- if (message.type === "request") {
- if (!transport.send || !requestHandler)
- throw missingTransportMethodError(["send", "requestHandler"], "handle requests");
- const { id, method, params } = message;
- let response;
- try {
- response = {
- type: "response",
- id,
- success: true,
- payload: await requestHandler(method, params)
- };
- } catch (error) {
- if (!(error instanceof Error))
- throw error;
- response = {
- type: "response",
- id,
- success: false,
- error: error.message
- };
- }
- debugHooks.onSend?.(response);
- transport.send(response);
- return;
- }
- if (message.type === "response") {
- const timeout = requestTimeouts.get(message.id);
- if (timeout != null)
- clearTimeout(timeout);
- requestTimeouts.delete(message.id);
- const { resolve, reject } = requestListeners.get(message.id) ?? {};
- requestListeners.delete(message.id);
- if (!message.success)
- reject?.(new Error(message.error));
- else
- resolve?.(message.payload);
- return;
- }
- if (message.type === "message") {
- for (const listener of wildcardMessageListeners)
- listener(message.id, message.payload);
- const listeners = messageListeners.get(message.id);
- if (!listeners)
- return;
- for (const listener of listeners)
- listener(message.payload);
- return;
- }
- throw new Error(`Unexpected RPC message type: ${message.type}`);
- }
- const proxy = { send: sendProxy, request: requestProxy };
- return {
- setTransport,
- setRequestHandler,
- request,
- requestProxy,
- send,
- sendProxy,
- addMessageListener,
- removeMessageListener,
- proxy
- };
-}
-function defineElectrobunRPC(_side, config) {
- const rpcOptions = {
- maxRequestTime: config.maxRequestTime,
- requestHandler: {
- ...config.handlers.requests,
- ...config.extraRequestHandlers
- },
- transport: {
- registerHandler: () => {}
- }
- };
- const rpc = createRPC(rpcOptions);
- const messageHandlers = config.handlers.messages;
- if (messageHandlers) {
- rpc.addMessageListener("*", (messageName, payload) => {
- const globalHandler = messageHandlers["*"];
- if (globalHandler) {
- globalHandler(messageName, payload);
- }
- const messageHandler = messageHandlers[messageName];
- if (messageHandler) {
- messageHandler(payload);
- }
- });
- }
- return rpc;
-}
-var MAX_ID = 10000000000, DEFAULT_MAX_REQUEST_TIME = 1000;
-
-// node_modules/electrobun/dist/api/shared/platform.ts
-import { platform, arch } from "os";
-var platformName, archName, OS, ARCH;
-var init_platform = __esm(() => {
- platformName = platform();
- archName = arch();
- OS = (() => {
- switch (platformName) {
- case "win32":
- return "win";
- case "darwin":
- return "macos";
- case "linux":
- return "linux";
- default:
- throw new Error(`Unsupported platform: ${platformName}`);
- }
- })();
- ARCH = (() => {
- if (OS === "win") {
- return "x64";
- }
- switch (archName) {
- case "arm64":
- return "arm64";
- case "x64":
- return "x64";
- default:
- throw new Error(`Unsupported architecture: ${archName}`);
- }
- })();
-});
-
-// node_modules/electrobun/dist/api/shared/naming.ts
-function sanitizeAppName(appName) {
- return appName.replace(/ /g, "");
-}
-function getAppFileName(appName, buildEnvironment) {
- const sanitized = sanitizeAppName(appName);
- return buildEnvironment === "stable" ? sanitized : `${sanitized}-${buildEnvironment}`;
-}
-function getPlatformPrefix(buildEnvironment, os, arch2) {
- return `${buildEnvironment}-${os}-${arch2}`;
-}
-function getTarballFileName(appFileName, os) {
- return os === "macos" ? `${appFileName}.app.tar.zst` : `${appFileName}.tar.zst`;
-}
-
-// node_modules/electrobun/dist/api/bun/core/Utils.ts
-var exports_Utils = {};
-__export(exports_Utils, {
- showNotification: () => showNotification,
- showMessageBox: () => showMessageBox,
- showItemInFolder: () => showItemInFolder,
- setDockIconVisible: () => setDockIconVisible,
- quit: () => quit,
- paths: () => paths,
- openPath: () => openPath,
- openFileDialog: () => openFileDialog,
- openExternal: () => openExternal,
- moveToTrash: () => moveToTrash,
- isDockIconVisible: () => isDockIconVisible,
- clipboardWriteText: () => clipboardWriteText,
- clipboardWriteImage: () => clipboardWriteImage,
- clipboardReadText: () => clipboardReadText,
- clipboardReadImage: () => clipboardReadImage,
- clipboardClear: () => clipboardClear,
- clipboardAvailableFormats: () => clipboardAvailableFormats
-});
-import { homedir, tmpdir } from "os";
-import { join } from "path";
-import { readFileSync } from "fs";
-function getLinuxXdgUserDirs() {
- try {
- const content = readFileSync(join(home, ".config", "user-dirs.dirs"), "utf-8");
- const dirs = {};
- for (const line of content.split(`
-`)) {
- const trimmed = line.trim();
- if (trimmed.startsWith("#") || !trimmed.includes("="))
- continue;
- const eqIdx = trimmed.indexOf("=");
- const key = trimmed.slice(0, eqIdx);
- let value = trimmed.slice(eqIdx + 1);
- if (value.startsWith('"') && value.endsWith('"')) {
- value = value.slice(1, -1);
- }
- value = value.replace(/\$HOME/g, home);
- dirs[key] = value;
- }
- return dirs;
- } catch {
- return {};
- }
-}
-function xdgUserDir(key, fallbackName) {
- if (OS !== "linux")
- return "";
- if (!_xdgUserDirs)
- _xdgUserDirs = getLinuxXdgUserDirs();
- return _xdgUserDirs[key] || join(home, fallbackName);
-}
-function getVersionInfo() {
- if (_versionInfo)
- return _versionInfo;
- try {
- const resourcesDir = "Resources";
- const raw = readFileSync(join("..", resourcesDir, "version.json"), "utf-8");
- const parsed = JSON.parse(raw);
- _versionInfo = { identifier: parsed.identifier, channel: parsed.channel };
- return _versionInfo;
- } catch (error) {
- console.error("Failed to read version.json", error);
- throw error;
- }
-}
-function getAppDataDir() {
- switch (OS) {
- case "macos":
- return join(home, "Library", "Application Support");
- case "win":
- return process.env["LOCALAPPDATA"] || join(home, "AppData", "Local");
- case "linux":
- return process.env["XDG_DATA_HOME"] || join(home, ".local", "share");
- }
-}
-function getCacheDir() {
- switch (OS) {
- case "macos":
- return join(home, "Library", "Caches");
- case "win":
- return process.env["LOCALAPPDATA"] || join(home, "AppData", "Local");
- case "linux":
- return process.env["XDG_CACHE_HOME"] || join(home, ".cache");
- }
-}
-function getLogsDir() {
- switch (OS) {
- case "macos":
- return join(home, "Library", "Logs");
- case "win":
- return process.env["LOCALAPPDATA"] || join(home, "AppData", "Local");
- case "linux":
- return process.env["XDG_STATE_HOME"] || join(home, ".local", "state");
- }
-}
-function getConfigDir() {
- switch (OS) {
- case "macos":
- return join(home, "Library", "Application Support");
- case "win":
- return process.env["APPDATA"] || join(home, "AppData", "Roaming");
- case "linux":
- return process.env["XDG_CONFIG_HOME"] || join(home, ".config");
- }
-}
-function getUserDir(macName, winName, xdgKey, fallbackName) {
- switch (OS) {
- case "macos":
- return join(home, macName);
- case "win": {
- const userProfile = process.env["USERPROFILE"] || home;
- return join(userProfile, winName);
- }
- case "linux":
- return xdgUserDir(xdgKey, fallbackName);
- }
-}
-var moveToTrash = (path) => {
- return ffi.request.moveToTrash({ path });
-}, showItemInFolder = (path) => {
- return ffi.request.showItemInFolder({ path });
-}, openExternal = (url) => {
- return ffi.request.openExternal({ url });
-}, openPath = (path) => {
- return ffi.request.openPath({ path });
-}, setDockIconVisible = (visible) => {
- ffi.request.setDockIconVisible({ visible });
-}, isDockIconVisible = () => {
- return ffi.request.isDockIconVisible();
-}, showNotification = (options) => {
- const { title, body, subtitle, silent } = options;
- ffi.request.showNotification({ title, body, subtitle, silent });
-}, isQuitting = false, quit = () => {
- if (isQuitting)
- return;
- isQuitting = true;
- const beforeQuitEvent = electrobunEventEmitter.events.app.beforeQuit({});
- electrobunEventEmitter.emitEvent(beforeQuitEvent);
- if (beforeQuitEvent.responseWasSet && beforeQuitEvent.response?.allow === false) {
- isQuitting = false;
- return;
- }
- native.symbols.stopEventLoop();
- native.symbols.waitForShutdownComplete(5000);
- native.symbols.forceExit(0);
-}, openFileDialog = async (opts = {}) => {
- const optsWithDefault = {
- ...{
- startingFolder: "~/",
- allowedFileTypes: "*",
- canChooseFiles: true,
- canChooseDirectory: true,
- allowsMultipleSelection: true
- },
- ...opts
- };
- const result = await ffi.request.openFileDialog({
- startingFolder: optsWithDefault.startingFolder,
- allowedFileTypes: optsWithDefault.allowedFileTypes,
- canChooseFiles: optsWithDefault.canChooseFiles,
- canChooseDirectory: optsWithDefault.canChooseDirectory,
- allowsMultipleSelection: optsWithDefault.allowsMultipleSelection
- });
- const filePaths = result.split(",");
- return filePaths;
-}, showMessageBox = async (opts = {}) => {
- const {
- type = "info",
- title = "",
- message = "",
- detail = "",
- buttons = ["OK"],
- defaultId = 0,
- cancelId = -1
- } = opts;
- const response = ffi.request.showMessageBox({
- type,
- title,
- message,
- detail,
- buttons,
- defaultId,
- cancelId
- });
- return { response };
-}, clipboardReadText = () => {
- return ffi.request.clipboardReadText();
-}, clipboardWriteText = (text) => {
- ffi.request.clipboardWriteText({ text });
-}, clipboardReadImage = () => {
- return ffi.request.clipboardReadImage();
-}, clipboardWriteImage = (pngData) => {
- ffi.request.clipboardWriteImage({ pngData });
-}, clipboardClear = () => {
- ffi.request.clipboardClear();
-}, clipboardAvailableFormats = () => {
- return ffi.request.clipboardAvailableFormats();
-}, home, _xdgUserDirs, _versionInfo, paths;
-var init_Utils = __esm(async () => {
- init_eventEmitter();
- init_platform();
- await init_native();
- process.exit = (code) => {
- if (isQuitting) {
- native.symbols.forceExit(code ?? 0);
- return;
- }
- quit();
- };
- home = homedir();
- paths = {
- get home() {
- return home;
- },
- get appData() {
- return getAppDataDir();
- },
- get config() {
- return getConfigDir();
- },
- get cache() {
- return getCacheDir();
- },
- get temp() {
- return tmpdir();
- },
- get logs() {
- return getLogsDir();
- },
- get documents() {
- return getUserDir("Documents", "Documents", "XDG_DOCUMENTS_DIR", "Documents");
- },
- get downloads() {
- return getUserDir("Downloads", "Downloads", "XDG_DOWNLOAD_DIR", "Downloads");
- },
- get desktop() {
- return getUserDir("Desktop", "Desktop", "XDG_DESKTOP_DIR", "Desktop");
- },
- get pictures() {
- return getUserDir("Pictures", "Pictures", "XDG_PICTURES_DIR", "Pictures");
- },
- get music() {
- return getUserDir("Music", "Music", "XDG_MUSIC_DIR", "Music");
- },
- get videos() {
- return getUserDir("Movies", "Videos", "XDG_VIDEOS_DIR", "Videos");
- },
- get userData() {
- const { identifier, channel } = getVersionInfo();
- return join(getAppDataDir(), identifier, channel);
- },
- get userCache() {
- const { identifier, channel } = getVersionInfo();
- return join(getCacheDir(), identifier, channel);
- },
- get userLogs() {
- const { identifier, channel } = getVersionInfo();
- return join(getLogsDir(), identifier, channel);
- }
- };
-});
-
-// node_modules/electrobun/dist/api/bun/core/Updater.ts
-import { join as join2, dirname, resolve } from "path";
-import { homedir as homedir2 } from "os";
-import {
- renameSync,
- unlinkSync,
- mkdirSync,
- rmSync,
- statSync,
- readdirSync
-} from "fs";
-import { execSync } from "child_process";
-function emitStatus(status, message, details) {
- const entry = {
- status,
- message,
- timestamp: Date.now(),
- details
- };
- statusHistory.push(entry);
- if (onStatusChangeCallback) {
- onStatusChangeCallback(entry);
- }
-}
-function getAppDataDir2() {
- switch (OS) {
- case "macos":
- return join2(homedir2(), "Library", "Application Support");
- case "win":
- return process.env["LOCALAPPDATA"] || join2(homedir2(), "AppData", "Local");
- case "linux":
- return process.env["XDG_DATA_HOME"] || join2(homedir2(), ".local", "share");
- default:
- return join2(homedir2(), ".config");
- }
-}
-function cleanupExtractionFolder(extractionFolder, keepTarHash) {
- const keepFile = `${keepTarHash}.tar`;
- try {
- const entries = readdirSync(extractionFolder);
- for (const entry of entries) {
- if (entry === keepFile)
- continue;
- const fullPath = join2(extractionFolder, entry);
- try {
- const s = statSync(fullPath);
- if (s.isDirectory()) {
- rmSync(fullPath, { recursive: true });
- } else {
- unlinkSync(fullPath);
- }
- } catch (e) {}
- }
- } catch (e) {}
-}
-var statusHistory, onStatusChangeCallback = null, localInfo, updateInfo, Updater;
-var init_Updater = __esm(async () => {
- init_platform();
- await init_Utils();
- statusHistory = [];
- Updater = {
- updateInfo: () => {
- return updateInfo;
- },
- getStatusHistory: () => {
- return [...statusHistory];
- },
- clearStatusHistory: () => {
- statusHistory.length = 0;
- },
- onStatusChange: (callback) => {
- onStatusChangeCallback = callback;
- },
- checkForUpdate: async () => {
- emitStatus("checking", "Checking for updates...");
- const localInfo2 = await Updater.getLocallocalInfo();
- if (localInfo2.channel === "dev") {
- emitStatus("no-update", "Dev channel - updates disabled", {
- currentHash: localInfo2.hash
- });
- return {
- version: localInfo2.version,
- hash: localInfo2.hash,
- updateAvailable: false,
- updateReady: false,
- error: ""
- };
- }
- const cacheBuster = Math.random().toString(36).substring(7);
- const platformPrefix = getPlatformPrefix(localInfo2.channel, OS, ARCH);
- const updateInfoUrl = `${localInfo2.baseUrl.replace(/\/+$/, "")}/${platformPrefix}-update.json?${cacheBuster}`;
- try {
- const updateInfoResponse = await fetch(updateInfoUrl);
- if (updateInfoResponse.ok) {
- const responseText = await updateInfoResponse.text();
- try {
- updateInfo = JSON.parse(responseText);
- } catch {
- emitStatus("error", "Invalid update.json: failed to parse JSON", {
- url: updateInfoUrl
- });
- return {
- version: "",
- hash: "",
- updateAvailable: false,
- updateReady: false,
- error: `Invalid update.json: failed to parse JSON`
- };
- }
- if (!updateInfo.hash) {
- emitStatus("error", "Invalid update.json: missing hash", {
- url: updateInfoUrl
- });
- return {
- version: "",
- hash: "",
- updateAvailable: false,
- updateReady: false,
- error: `Invalid update.json: missing hash`
- };
- }
- if (updateInfo.hash !== localInfo2.hash) {
- updateInfo.updateAvailable = true;
- emitStatus("update-available", `Update available: ${localInfo2.hash.slice(0, 8)} \u2192 ${updateInfo.hash.slice(0, 8)}`, {
- currentHash: localInfo2.hash,
- latestHash: updateInfo.hash
- });
- } else {
- emitStatus("no-update", "Already on latest version", {
- currentHash: localInfo2.hash
- });
- }
- } else {
- emitStatus("error", `Failed to fetch update info (HTTP ${updateInfoResponse.status})`, { url: updateInfoUrl });
- return {
- version: "",
- hash: "",
- updateAvailable: false,
- updateReady: false,
- error: `Failed to fetch update info from ${updateInfoUrl}`
- };
- }
- } catch (error) {
- return {
- version: "",
- hash: "",
- updateAvailable: false,
- updateReady: false,
- error: `Failed to fetch update info from ${updateInfoUrl}`
- };
- }
- return updateInfo;
- },
- downloadUpdate: async () => {
- emitStatus("download-starting", "Starting update download...");
- const appDataFolder = await Updater.appDataFolder();
- await Updater.channelBucketUrl();
- const appFileName = localInfo.name;
- let currentHash = (await Updater.getLocallocalInfo()).hash;
- let latestHash = (await Updater.checkForUpdate()).hash;
- const extractionFolder = join2(appDataFolder, "self-extraction");
- if (!await Bun.file(extractionFolder).exists()) {
- mkdirSync(extractionFolder, { recursive: true });
- }
- let currentTarPath = join2(extractionFolder, `${currentHash}.tar`);
- const latestTarPath = join2(extractionFolder, `${latestHash}.tar`);
- const seenHashes = [];
- let patchesApplied = 0;
- let usedPatchPath = false;
- if (!await Bun.file(latestTarPath).exists()) {
- emitStatus("checking-local-tar", `Checking for local tar file: ${currentHash.slice(0, 8)}`, { currentHash });
- while (currentHash !== latestHash) {
- seenHashes.push(currentHash);
- const currentTar = Bun.file(currentTarPath);
- if (!await currentTar.exists()) {
- emitStatus("local-tar-missing", `Local tar not found for ${currentHash.slice(0, 8)}, will download full bundle`, { currentHash });
- break;
- }
- emitStatus("local-tar-found", `Found local tar for ${currentHash.slice(0, 8)}`, { currentHash });
- const platformPrefix = getPlatformPrefix(localInfo.channel, OS, ARCH);
- const patchUrl = `${localInfo.baseUrl.replace(/\/+$/, "")}/${platformPrefix}-${currentHash}.patch`;
- emitStatus("fetching-patch", `Checking for patch: ${currentHash.slice(0, 8)}`, { currentHash, url: patchUrl });
- const patchResponse = await fetch(patchUrl);
- if (!patchResponse.ok) {
- emitStatus("patch-not-found", `No patch available for ${currentHash.slice(0, 8)}, will download full bundle`, { currentHash });
- break;
- }
- emitStatus("patch-found", `Patch found for ${currentHash.slice(0, 8)}`, { currentHash });
- emitStatus("downloading-patch", `Downloading patch for ${currentHash.slice(0, 8)}...`, { currentHash });
- const patchFilePath = join2(appDataFolder, "self-extraction", `${currentHash}.patch`);
- await Bun.write(patchFilePath, await patchResponse.arrayBuffer());
- const tmpPatchedTarFilePath = join2(appDataFolder, "self-extraction", `from-${currentHash}.tar`);
- const bunBinDir = dirname(process.execPath);
- const bspatchBinName = OS === "win" ? "bspatch.exe" : "bspatch";
- const bspatchPath = join2(bunBinDir, bspatchBinName);
- emitStatus("applying-patch", `Applying patch ${patchesApplied + 1} for ${currentHash.slice(0, 8)}...`, {
- currentHash,
- patchNumber: patchesApplied + 1
- });
- if (!statSync(bspatchPath, { throwIfNoEntry: false })) {
- emitStatus("patch-failed", `bspatch binary not found at ${bspatchPath}`, {
- currentHash,
- errorMessage: `bspatch not found: ${bspatchPath}`
- });
- console.error("bspatch not found:", bspatchPath);
- break;
- }
- if (!statSync(currentTarPath, { throwIfNoEntry: false })) {
- emitStatus("patch-failed", `Old tar not found at ${currentTarPath}`, {
- currentHash,
- errorMessage: `old tar not found: ${currentTarPath}`
- });
- console.error("old tar not found:", currentTarPath);
- break;
- }
- if (!statSync(patchFilePath, { throwIfNoEntry: false })) {
- emitStatus("patch-failed", `Patch file not found at ${patchFilePath}`, {
- currentHash,
- errorMessage: `patch not found: ${patchFilePath}`
- });
- console.error("patch file not found:", patchFilePath);
- break;
- }
- try {
- const patchResult = Bun.spawnSync([
- bspatchPath,
- currentTarPath,
- tmpPatchedTarFilePath,
- patchFilePath
- ]);
- if (patchResult.exitCode !== 0 || patchResult.success === false) {
- const stderr = patchResult.stderr ? patchResult.stderr.toString() : "";
- const stdout = patchResult.stdout ? patchResult.stdout.toString() : "";
- if (updateInfo) {
- updateInfo.error = stderr || `bspatch failed with exit code ${patchResult.exitCode}`;
- }
- emitStatus("patch-failed", `Patch application failed: ${stderr || `exit code ${patchResult.exitCode}`}`, {
- currentHash,
- errorMessage: stderr || `exit code ${patchResult.exitCode}`
- });
- console.error("bspatch failed", {
- exitCode: patchResult.exitCode,
- stdout,
- stderr,
- bspatchPath,
- oldTar: currentTarPath,
- newTar: tmpPatchedTarFilePath,
- patch: patchFilePath
- });
- break;
- }
- } catch (error) {
- emitStatus("patch-failed", `Patch threw exception: ${error.message}`, {
- currentHash,
- errorMessage: error.message
- });
- console.error("bspatch threw", error, { bspatchPath });
- break;
- }
- patchesApplied++;
- emitStatus("patch-applied", `Patch ${patchesApplied} applied successfully`, {
- currentHash,
- patchNumber: patchesApplied
- });
- emitStatus("extracting-version", "Extracting version info from patched tar...", { currentHash });
- let hashFilePath = "";
- const resourcesDir = "Resources";
- const patchedTarBytes = await Bun.file(tmpPatchedTarFilePath).arrayBuffer();
- const patchedArchive = new Bun.Archive(patchedTarBytes);
- const patchedFiles = await patchedArchive.files();
- for (const [filePath] of patchedFiles) {
- if (filePath.endsWith(`${resourcesDir}/version.json`) || filePath.endsWith("metadata.json")) {
- hashFilePath = filePath;
- break;
- }
- }
- if (!hashFilePath) {
- emitStatus("error", "Could not find version/metadata file in patched tar", { currentHash });
- console.error("Neither Resources/version.json nor metadata.json found in patched tar:", tmpPatchedTarFilePath);
- break;
- }
- const hashFile = patchedFiles.get(hashFilePath);
- const hashFileJson = JSON.parse(await hashFile.text());
- const nextHash = hashFileJson.hash;
- if (seenHashes.includes(nextHash)) {
- emitStatus("error", "Cyclical update detected, falling back to full download", { currentHash: nextHash });
- console.log("Warning: cyclical update detected");
- break;
- }
- seenHashes.push(nextHash);
- if (!nextHash) {
- emitStatus("error", "Could not determine next hash from patched tar", { currentHash });
- break;
- }
- const updatedTarPath = join2(appDataFolder, "self-extraction", `${nextHash}.tar`);
- renameSync(tmpPatchedTarFilePath, updatedTarPath);
- unlinkSync(currentTarPath);
- unlinkSync(patchFilePath);
- currentHash = nextHash;
- currentTarPath = join2(appDataFolder, "self-extraction", `${currentHash}.tar`);
- emitStatus("patch-applied", `Patched to ${nextHash.slice(0, 8)}, checking for more patches...`, {
- currentHash: nextHash,
- toHash: latestHash,
- totalPatchesApplied: patchesApplied
- });
- }
- if (currentHash === latestHash && patchesApplied > 0) {
- usedPatchPath = true;
- emitStatus("patch-chain-complete", `Patch chain complete! Applied ${patchesApplied} patches`, {
- totalPatchesApplied: patchesApplied,
- currentHash: latestHash,
- usedPatchPath: true
- });
- }
- if (currentHash !== latestHash) {
- emitStatus("downloading-full-bundle", "Downloading full update bundle...", {
- currentHash,
- latestHash,
- usedPatchPath: false
- });
- const cacheBuster = Math.random().toString(36).substring(7);
- const platformPrefix = getPlatformPrefix(localInfo.channel, OS, ARCH);
- const tarballName = getTarballFileName(appFileName, OS);
- const urlToLatestTarball = `${localInfo.baseUrl.replace(/\/+$/, "")}/${platformPrefix}-${tarballName}`;
- const prevVersionCompressedTarballPath = join2(appDataFolder, "self-extraction", "latest.tar.zst");
- emitStatus("download-progress", `Fetching ${tarballName}...`, {
- url: urlToLatestTarball
- });
- const response = await fetch(urlToLatestTarball + `?${cacheBuster}`);
- if (response.ok && response.body) {
- const contentLength = response.headers.get("content-length");
- const totalBytes = contentLength ? parseInt(contentLength, 10) : undefined;
- let bytesDownloaded = 0;
- const reader = response.body.getReader();
- const writer = Bun.file(prevVersionCompressedTarballPath).writer();
- while (true) {
- const { done, value } = await reader.read();
- if (done)
- break;
- await writer.write(value);
- bytesDownloaded += value.length;
- if (bytesDownloaded % 500000 < value.length) {
- emitStatus("download-progress", `Downloading: ${(bytesDownloaded / 1024 / 1024).toFixed(1)} MB`, {
- bytesDownloaded,
- totalBytes,
- progress: totalBytes ? Math.round(bytesDownloaded / totalBytes * 100) : undefined
- });
- }
- }
- await writer.flush();
- writer.end();
- emitStatus("download-progress", `Download complete: ${(bytesDownloaded / 1024 / 1024).toFixed(1)} MB`, {
- bytesDownloaded,
- totalBytes,
- progress: 100
- });
- } else {
- emitStatus("error", `Failed to download: ${urlToLatestTarball}`, {
- url: urlToLatestTarball
- });
- console.log("latest version not found at: ", urlToLatestTarball);
- }
- emitStatus("decompressing", "Decompressing update bundle...");
- const bunBinDir = dirname(process.execPath);
- const zstdBinName = OS === "win" ? "zig-zstd.exe" : "zig-zstd";
- const zstdPath = join2(bunBinDir, zstdBinName);
- if (!statSync(zstdPath, { throwIfNoEntry: false })) {
- updateInfo.error = `zig-zstd not found: ${zstdPath}`;
- emitStatus("error", updateInfo.error, { zstdPath });
- console.error("zig-zstd not found:", zstdPath);
- } else {
- const decompressResult = Bun.spawnSync([
- zstdPath,
- "decompress",
- "-i",
- prevVersionCompressedTarballPath,
- "-o",
- latestTarPath,
- "--no-timing"
- ], {
- cwd: extractionFolder,
- stdout: "inherit",
- stderr: "inherit"
- });
- if (!decompressResult.success) {
- updateInfo.error = `zig-zstd failed with exit code ${decompressResult.exitCode}`;
- emitStatus("error", updateInfo.error, {
- zstdPath,
- exitCode: decompressResult.exitCode
- });
- console.error("zig-zstd failed", {
- exitCode: decompressResult.exitCode,
- zstdPath
- });
- } else {
- emitStatus("decompressing", "Decompression complete");
- }
- }
- unlinkSync(prevVersionCompressedTarballPath);
- }
- }
- if (await Bun.file(latestTarPath).exists()) {
- updateInfo.updateReady = true;
- emitStatus("download-complete", `Update ready to install (used ${usedPatchPath ? "patch" : "full download"} path)`, {
- latestHash,
- usedPatchPath,
- totalPatchesApplied: patchesApplied
- });
- } else {
- updateInfo.error = "Failed to download latest version";
- emitStatus("error", "Failed to download latest version", { latestHash });
- }
- cleanupExtractionFolder(extractionFolder, latestHash);
- },
- applyUpdate: async () => {
- if (updateInfo?.updateReady) {
- emitStatus("applying", "Starting update installation...");
- const appDataFolder = await Updater.appDataFolder();
- const extractionFolder = join2(appDataFolder, "self-extraction");
- if (!await Bun.file(extractionFolder).exists()) {
- mkdirSync(extractionFolder, { recursive: true });
- }
- let latestHash = (await Updater.checkForUpdate()).hash;
- const latestTarPath = join2(extractionFolder, `${latestHash}.tar`);
- let appBundleSubpath = "";
- if (await Bun.file(latestTarPath).exists()) {
- emitStatus("extracting", `Extracting update to ${latestHash.slice(0, 8)}...`, { latestHash });
- const extractionDir = OS === "win" ? join2(extractionFolder, `temp-${latestHash}`) : extractionFolder;
- if (OS === "win") {
- mkdirSync(extractionDir, { recursive: true });
- }
- const latestTarBytes = await Bun.file(latestTarPath).arrayBuffer();
- const latestArchive = new Bun.Archive(latestTarBytes);
- await latestArchive.extract(extractionDir);
- if (OS === "macos") {
- const extractedFiles = readdirSync(extractionDir);
- for (const file of extractedFiles) {
- if (file.endsWith(".app")) {
- appBundleSubpath = file + "/";
- break;
- }
- }
- } else {
- appBundleSubpath = "./";
- }
- console.log(`Tar extraction completed. Found appBundleSubpath: ${appBundleSubpath}`);
- if (!appBundleSubpath) {
- console.error("Failed to find app in tarball");
- return;
- }
- const extractedAppPath = resolve(join2(extractionDir, appBundleSubpath));
- let newAppBundlePath;
- if (OS === "linux") {
- const extractedFiles = readdirSync(extractionDir);
- const appBundleDir = extractedFiles.find((file) => {
- const filePath = join2(extractionDir, file);
- return statSync(filePath).isDirectory() && !file.endsWith(".tar");
- });
- if (!appBundleDir) {
- console.error("Could not find app bundle directory in extraction");
- return;
- }
- newAppBundlePath = join2(extractionDir, appBundleDir);
- const bundleStats = statSync(newAppBundlePath, { throwIfNoEntry: false });
- if (!bundleStats || !bundleStats.isDirectory()) {
- console.error(`App bundle directory not found at: ${newAppBundlePath}`);
- console.log("Contents of extraction directory:");
- try {
- const files = readdirSync(extractionDir);
- for (const file of files) {
- console.log(` - ${file}`);
- const subPath = join2(extractionDir, file);
- if (statSync(subPath).isDirectory()) {
- const subFiles = readdirSync(subPath);
- for (const subFile of subFiles) {
- console.log(` - ${subFile}`);
- }
- }
- }
- } catch (e) {
- console.log("Could not list directory contents:", e);
- }
- return;
- }
- } else if (OS === "win") {
- const appBundleName = getAppFileName(localInfo.name, localInfo.channel);
- newAppBundlePath = join2(extractionDir, appBundleName);
- if (!statSync(newAppBundlePath, { throwIfNoEntry: false })) {
- console.error(`Extracted app not found at: ${newAppBundlePath}`);
- console.log("Contents of extraction directory:");
- try {
- const files = readdirSync(extractionDir);
- for (const file of files) {
- console.log(` - ${file}`);
- }
- } catch (e) {
- console.log("Could not list directory contents:", e);
- }
- return;
- }
- } else {
- newAppBundlePath = extractedAppPath;
- }
- let runningAppBundlePath;
- const appDataFolder2 = await Updater.appDataFolder();
- if (OS === "macos") {
- runningAppBundlePath = resolve(dirname(process.execPath), "..", "..");
- } else if (OS === "linux" || OS === "win") {
- runningAppBundlePath = join2(appDataFolder2, "app");
- } else {
- throw new Error(`Unsupported platform: ${OS}`);
- }
- try {
- emitStatus("replacing-app", "Removing old version...");
- if (OS === "macos") {
- if (statSync(runningAppBundlePath, { throwIfNoEntry: false })) {
- rmSync(runningAppBundlePath, { recursive: true });
- }
- emitStatus("replacing-app", "Installing new version...");
- renameSync(newAppBundlePath, runningAppBundlePath);
- try {
- execSync(`xattr -r -d com.apple.quarantine "${runningAppBundlePath}"`, { stdio: "ignore" });
- } catch (e) {}
- } else if (OS === "linux") {
- const appBundleDir = join2(appDataFolder2, "app");
- if (statSync(appBundleDir, { throwIfNoEntry: false })) {
- rmSync(appBundleDir, { recursive: true });
- }
- renameSync(newAppBundlePath, appBundleDir);
- const launcherPath = join2(appBundleDir, "bin", "launcher");
- if (statSync(launcherPath, { throwIfNoEntry: false })) {
- execSync(`chmod +x "${launcherPath}"`);
- }
- const bunPath = join2(appBundleDir, "bin", "bun");
- if (statSync(bunPath, { throwIfNoEntry: false })) {
- execSync(`chmod +x "${bunPath}"`);
- }
- }
- if (OS !== "win") {
- cleanupExtractionFolder(extractionFolder, latestHash);
- }
- if (OS === "win") {
- const parentDir = dirname(runningAppBundlePath);
- const updateScriptPath = join2(parentDir, "update.bat");
- const launcherPath = join2(runningAppBundlePath, "bin", "launcher.exe");
- const runningAppWin = runningAppBundlePath.replace(/\//g, "\\");
- const newAppWin = newAppBundlePath.replace(/\//g, "\\");
- const extractionDirWin = extractionDir.replace(/\//g, "\\");
- const launcherPathWin = launcherPath.replace(/\//g, "\\");
- const updateScript = `@echo off
-setlocal
-
-:: Wait for the app to fully exit (check if launcher.exe is still running)
-:waitloop
-tasklist /FI "IMAGENAME eq launcher.exe" 2>NUL | find /I /N "launcher.exe">NUL
-if "%ERRORLEVEL%"=="0" (
- timeout /t 1 /nobreak >nul
- goto waitloop
-)
-
-:: Small extra delay to ensure all file handles are released
-timeout /t 2 /nobreak >nul
-
-:: Remove current app folder
-if exist "${runningAppWin}" (
- rmdir /s /q "${runningAppWin}"
-)
-
-:: Move new app to current location
-move "${newAppWin}" "${runningAppWin}"
-
-:: Clean up extraction directory
-rmdir /s /q "${extractionDirWin}" 2>nul
-
-:: Launch the new app
-start "" "${launcherPathWin}"
-
-:: Clean up scheduled tasks starting with ElectrobunUpdate_
-for /f "tokens=1" %%t in ('schtasks /query /fo list ^| findstr /i "ElectrobunUpdate_"') do (
- schtasks /delete /tn "%%t" /f >nul 2>&1
-)
-
-:: Delete this update script after a short delay
-ping -n 2 127.0.0.1 >nul
-del "%~f0"
-`;
- await Bun.write(updateScriptPath, updateScript);
- const scriptPathWin = updateScriptPath.replace(/\//g, "\\");
- const taskName = `ElectrobunUpdate_${Date.now()}`;
- execSync(`schtasks /create /tn "${taskName}" /tr "cmd /c \\"${scriptPathWin}\\"" /sc once /st 00:00 /f`, { stdio: "ignore" });
- execSync(`schtasks /run /tn "${taskName}"`, { stdio: "ignore" });
- quit();
- }
- } catch (error) {
- emitStatus("error", `Failed to replace app: ${error.message}`, {
- errorMessage: error.message
- });
- console.error("Failed to replace app with new version", error);
- return;
- }
- emitStatus("launching-new-version", "Launching updated version...");
- if (OS === "macos") {
- const pid = process.pid;
- Bun.spawn([
- "sh",
- "-c",
- `while kill -0 ${pid} 2>/dev/null; do sleep 0.5; done; sleep 1; open "${runningAppBundlePath}"`
- ], {
- detached: true,
- stdio: ["ignore", "ignore", "ignore"]
- });
- } else if (OS === "linux") {
- const launcherPath = join2(runningAppBundlePath, "bin", "launcher");
- Bun.spawn(["sh", "-c", `"${launcherPath}" &`], {
- detached: true
- });
- }
- emitStatus("complete", "Update complete, restarting application...");
- quit();
- }
- }
- },
- channelBucketUrl: async () => {
- await Updater.getLocallocalInfo();
- return localInfo.baseUrl;
- },
- appDataFolder: async () => {
- await Updater.getLocallocalInfo();
- const appDataFolder = join2(getAppDataDir2(), localInfo.identifier, localInfo.channel);
- return appDataFolder;
- },
- localInfo: {
- version: async () => {
- return (await Updater.getLocallocalInfo()).version;
- },
- hash: async () => {
- return (await Updater.getLocallocalInfo()).hash;
- },
- channel: async () => {
- return (await Updater.getLocallocalInfo()).channel;
- },
- baseUrl: async () => {
- return (await Updater.getLocallocalInfo()).baseUrl;
- }
- },
- getLocallocalInfo: async () => {
- if (localInfo) {
- return localInfo;
- }
- try {
- const resourcesDir = "Resources";
- localInfo = await Bun.file(`../${resourcesDir}/version.json`).json();
- return localInfo;
- } catch (error) {
- console.error("Failed to read version.json", error);
- throw error;
- }
- }
- };
-});
-
-// node_modules/electrobun/dist/api/bun/core/BuildConfig.ts
-var buildConfig = null, BuildConfig;
-var init_BuildConfig = __esm(() => {
- BuildConfig = {
- get: async () => {
- if (buildConfig) {
- return buildConfig;
- }
- try {
- const resourcesDir = "Resources";
- buildConfig = await Bun.file(`../${resourcesDir}/build.json`).json();
- return buildConfig;
- } catch (error) {
- buildConfig = {
- defaultRenderer: "native",
- availableRenderers: ["native"]
- };
- return buildConfig;
- }
- },
- getCached: () => buildConfig
- };
-});
-
-// node_modules/electrobun/dist/api/bun/core/Socket.ts
-import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
-function base64ToUint8Array(base64) {
- {
- return new Uint8Array(atob(base64).split("").map((char) => char.charCodeAt(0)));
- }
-}
-function encrypt(secretKey, text) {
- const iv = new Uint8Array(randomBytes(12));
- const cipher = createCipheriv("aes-256-gcm", secretKey, iv);
- const encrypted = Buffer.concat([
- new Uint8Array(cipher.update(text, "utf8")),
- new Uint8Array(cipher.final())
- ]).toString("base64");
- const tag = cipher.getAuthTag().toString("base64");
- return { encrypted, iv: Buffer.from(iv).toString("base64"), tag };
-}
-function decrypt(secretKey, encryptedData, iv, tag) {
- const decipher = createDecipheriv("aes-256-gcm", secretKey, iv);
- decipher.setAuthTag(tag);
- const decrypted = Buffer.concat([
- new Uint8Array(decipher.update(encryptedData)),
- new Uint8Array(decipher.final())
- ]);
- return decrypted.toString("utf8");
-}
-var socketMap, startRPCServer = () => {
- const startPort = 50000;
- const endPort = 65535;
- const payloadLimit = 1024 * 1024 * 500;
- let port = startPort;
- let server = null;
- while (port <= endPort) {
- try {
- server = Bun.serve({
- port,
- fetch(req, server2) {
- const url = new URL(req.url);
- if (url.pathname === "/socket") {
- const webviewIdString = url.searchParams.get("webviewId");
- if (!webviewIdString) {
- return new Response("Missing webviewId", { status: 400 });
- }
- const webviewId = parseInt(webviewIdString, 10);
- const success = server2.upgrade(req, { data: { webviewId } });
- return success ? undefined : new Response("Upgrade failed", { status: 500 });
- }
- console.log("unhandled RPC Server request", req.url);
- },
- websocket: {
- idleTimeout: 960,
- maxPayloadLength: payloadLimit,
- backpressureLimit: payloadLimit * 2,
- open(ws) {
- if (!ws?.data) {
- return;
- }
- const { webviewId } = ws.data;
- if (!socketMap[webviewId]) {
- socketMap[webviewId] = { socket: ws, queue: [] };
- } else {
- socketMap[webviewId].socket = ws;
- }
- },
- close(ws, _code, _reason) {
- if (!ws?.data) {
- return;
- }
- const { webviewId } = ws.data;
- if (socketMap[webviewId]) {
- socketMap[webviewId].socket = null;
- }
- },
- message(ws, message) {
- if (!ws?.data) {
- return;
- }
- const { webviewId } = ws.data;
- const browserView = BrowserView.getById(webviewId);
- if (!browserView) {
- return;
- }
- if (browserView.rpcHandler) {
- if (typeof message === "string") {
- try {
- const encryptedPacket = JSON.parse(message);
- const decrypted = decrypt(browserView.secretKey, base64ToUint8Array(encryptedPacket.encryptedData), base64ToUint8Array(encryptedPacket.iv), base64ToUint8Array(encryptedPacket.tag));
- browserView.rpcHandler(JSON.parse(decrypted));
- } catch (error) {
- console.log("Error handling message:", error);
- }
- } else if (message instanceof ArrayBuffer) {
- console.log("TODO: Received ArrayBuffer message:", message);
- }
- }
- }
- }
- });
- break;
- } catch (error) {
- if (error.code === "EADDRINUSE") {
- console.log(`Port ${port} in use, trying next port...`);
- port++;
- } else {
- throw error;
- }
- }
- }
- return { rpcServer: server, rpcPort: port };
-}, rpcServer, rpcPort, sendMessageToWebviewViaSocket = (webviewId, message) => {
- const rpc = socketMap[webviewId];
- const browserView = BrowserView.getById(webviewId);
- if (!browserView)
- return false;
- if (rpc?.socket?.readyState === WebSocket.OPEN) {
- try {
- const unencryptedString = JSON.stringify(message);
- const encrypted = encrypt(browserView.secretKey, unencryptedString);
- const encryptedPacket = {
- encryptedData: encrypted.encrypted,
- iv: encrypted.iv,
- tag: encrypted.tag
- };
- const encryptedPacketString = JSON.stringify(encryptedPacket);
- rpc.socket.send(encryptedPacketString);
- return true;
- } catch (error) {
- console.error("Error sending message to webview via socket:", error);
- }
- }
- return false;
-};
-var init_Socket = __esm(async () => {
- await init_BrowserView();
- socketMap = {};
- ({ rpcServer, rpcPort } = startRPCServer());
- console.log("Server started at", rpcServer?.url.origin);
-});
-
-// node_modules/electrobun/dist/api/bun/core/BrowserView.ts
-import { randomBytes as randomBytes2 } from "crypto";
-
-class BrowserView {
- id = nextWebviewId++;
- ptr;
- hostWebviewId;
- windowId;
- renderer;
- url = null;
- html = null;
- preload = null;
- viewsRoot = null;
- partition = null;
- autoResize = true;
- frame = {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- };
- pipePrefix;
- inStream;
- outStream;
- secretKey;
- rpc;
- rpcHandler;
- navigationRules = null;
- sandbox = false;
- startTransparent = false;
- startPassthrough = false;
- constructor(options = defaultOptions) {
- this.url = options.url || defaultOptions.url || null;
- this.html = options.html || defaultOptions.html || null;
- this.preload = options.preload || defaultOptions.preload || null;
- this.viewsRoot = options.viewsRoot || defaultOptions.viewsRoot || null;
- this.frame = {
- x: options.frame?.x ?? defaultOptions.frame.x,
- y: options.frame?.y ?? defaultOptions.frame.y,
- width: options.frame?.width ?? defaultOptions.frame.width,
- height: options.frame?.height ?? defaultOptions.frame.height
- };
- this.rpc = options.rpc;
- this.secretKey = new Uint8Array(randomBytes2(32));
- this.partition = options.partition || null;
- this.pipePrefix = `/private/tmp/electrobun_ipc_pipe_${hash}_${randomId}_${this.id}`;
- this.hostWebviewId = options.hostWebviewId;
- this.windowId = options.windowId ?? 0;
- this.autoResize = options.autoResize === false ? false : true;
- this.navigationRules = options.navigationRules || null;
- this.renderer = options.renderer ?? defaultOptions.renderer ?? "native";
- this.sandbox = options.sandbox ?? false;
- this.startTransparent = options.startTransparent ?? false;
- this.startPassthrough = options.startPassthrough ?? false;
- BrowserViewMap[this.id] = this;
- this.ptr = this.init();
- if (this.html) {
- setTimeout(() => {
- this.loadHTML(this.html);
- }, 100);
- }
- }
- init() {
- this.createStreams();
- return ffi.request.createWebview({
- id: this.id,
- windowId: this.windowId,
- renderer: this.renderer,
- rpcPort,
- secretKey: this.secretKey.toString(),
- hostWebviewId: this.hostWebviewId || null,
- pipePrefix: this.pipePrefix,
- partition: this.partition,
- url: this.html ? null : this.url,
- html: this.html,
- preload: this.preload,
- viewsRoot: this.viewsRoot,
- frame: {
- width: this.frame.width,
- height: this.frame.height,
- x: this.frame.x,
- y: this.frame.y
- },
- autoResize: this.autoResize,
- navigationRules: this.navigationRules,
- sandbox: this.sandbox,
- startTransparent: this.startTransparent,
- startPassthrough: this.startPassthrough
- });
- }
- createStreams() {
- if (!this.rpc) {
- this.rpc = BrowserView.defineRPC({
- handlers: { requests: {}, messages: {} }
- });
- }
- this.rpc.setTransport(this.createTransport());
- }
- sendMessageToWebviewViaExecute(jsonMessage) {
- const stringifiedMessage = typeof jsonMessage === "string" ? jsonMessage : JSON.stringify(jsonMessage);
- const wrappedMessage = `window.__electrobun.receiveMessageFromBun(${stringifiedMessage})`;
- this.executeJavascript(wrappedMessage);
- }
- sendInternalMessageViaExecute(jsonMessage) {
- const stringifiedMessage = typeof jsonMessage === "string" ? jsonMessage : JSON.stringify(jsonMessage);
- const wrappedMessage = `window.__electrobun.receiveInternalMessageFromBun(${stringifiedMessage})`;
- this.executeJavascript(wrappedMessage);
- }
- executeJavascript(js) {
- ffi.request.evaluateJavascriptWithNoCompletion({ id: this.id, js });
- }
- loadURL(url) {
- console.log(`DEBUG: loadURL called for webview ${this.id}: ${url}`);
- this.url = url;
- native.symbols.loadURLInWebView(this.ptr, toCString(this.url));
- }
- loadHTML(html) {
- this.html = html;
- console.log(`DEBUG: Setting HTML content for webview ${this.id}:`, html.substring(0, 50) + "...");
- if (this.renderer === "cef") {
- native.symbols.setWebviewHTMLContent(this.id, toCString(html));
- this.loadURL("views://internal/index.html");
- } else {
- native.symbols.loadHTMLInWebView(this.ptr, toCString(html));
- }
- }
- setNavigationRules(rules) {
- this.navigationRules = JSON.stringify(rules);
- const rulesJson = JSON.stringify(rules);
- native.symbols.setWebviewNavigationRules(this.ptr, toCString(rulesJson));
- }
- findInPage(searchText, options) {
- const forward = options?.forward ?? true;
- const matchCase = options?.matchCase ?? false;
- native.symbols.webviewFindInPage(this.ptr, toCString(searchText), forward, matchCase);
- }
- stopFindInPage() {
- native.symbols.webviewStopFind(this.ptr);
- }
- openDevTools() {
- native.symbols.webviewOpenDevTools(this.ptr);
- }
- closeDevTools() {
- native.symbols.webviewCloseDevTools(this.ptr);
- }
- toggleDevTools() {
- native.symbols.webviewToggleDevTools(this.ptr);
- }
- setPageZoom(zoomLevel) {
- native.symbols.webviewSetPageZoom(this.ptr, zoomLevel);
- }
- getPageZoom() {
- return native.symbols.webviewGetPageZoom(this.ptr);
- }
- on(name2, handler) {
- const specificName = `${name2}-${this.id}`;
- eventEmitter_default.on(specificName, handler);
- }
- createTransport = () => {
- const that = this;
- return {
- send(message) {
- const sentOverSocket = sendMessageToWebviewViaSocket(that.id, message);
- if (!sentOverSocket) {
- try {
- const messageString = JSON.stringify(message);
- that.sendMessageToWebviewViaExecute(messageString);
- } catch (error) {
- console.error("bun: failed to serialize message to webview", error);
- }
- }
- },
- registerHandler(handler) {
- that.rpcHandler = handler;
- }
- };
- };
- remove() {
- native.symbols.webviewRemove(this.ptr);
- delete BrowserViewMap[this.id];
- }
- static getById(id) {
- return BrowserViewMap[id];
- }
- static getAll() {
- return Object.values(BrowserViewMap);
- }
- static defineRPC(config) {
- return defineElectrobunRPC("bun", config);
- }
-}
-var BrowserViewMap, nextWebviewId = 1, hash, buildConfig2, defaultOptions, randomId;
-var init_BrowserView = __esm(async () => {
- init_eventEmitter();
- init_BuildConfig();
- await __promiseAll([
- init_native(),
- init_Updater(),
- init_Socket()
- ]);
- BrowserViewMap = {};
- hash = await Updater.localInfo.hash();
- buildConfig2 = await BuildConfig.get();
- defaultOptions = {
- url: null,
- html: null,
- preload: null,
- viewsRoot: null,
- renderer: buildConfig2.defaultRenderer,
- frame: {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- }
- };
- randomId = Math.random().toString(36).substring(7);
-});
-
-// node_modules/electrobun/dist/api/bun/core/WGPUView.ts
-class WGPUView {
- id = nextWGPUViewId++;
- ptr;
- windowId;
- autoResize = true;
- frame = {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- };
- startTransparent = false;
- startPassthrough = false;
- constructor(options = defaultOptions2) {
- this.frame = {
- x: options.frame?.x ?? defaultOptions2.frame.x,
- y: options.frame?.y ?? defaultOptions2.frame.y,
- width: options.frame?.width ?? defaultOptions2.frame.width,
- height: options.frame?.height ?? defaultOptions2.frame.height
- };
- this.windowId = options.windowId ?? 0;
- this.autoResize = options.autoResize === false ? false : true;
- this.startTransparent = options.startTransparent ?? false;
- this.startPassthrough = options.startPassthrough ?? false;
- WGPUViewMap[this.id] = this;
- this.ptr = this.init();
- }
- init() {
- return ffi.request.createWGPUView({
- id: this.id,
- windowId: this.windowId,
- frame: {
- width: this.frame.width,
- height: this.frame.height,
- x: this.frame.x,
- y: this.frame.y
- },
- autoResize: this.autoResize,
- startTransparent: this.startTransparent,
- startPassthrough: this.startPassthrough
- });
- }
- setFrame(x, y, width, height) {
- this.frame = { x, y, width, height };
- ffi.request.wgpuViewSetFrame({ id: this.id, x, y, width, height });
- }
- setTransparent(transparent) {
- ffi.request.wgpuViewSetTransparent({ id: this.id, transparent });
- }
- setPassthrough(passthrough) {
- ffi.request.wgpuViewSetPassthrough({ id: this.id, passthrough });
- }
- setHidden(hidden) {
- ffi.request.wgpuViewSetHidden({ id: this.id, hidden });
- }
- on(name2, handler) {
- const specificName = `${name2}-${this.id}`;
- eventEmitter_default.on(specificName, handler);
- }
- remove() {
- if (this.ptr === null) {
- return;
- }
- try {
- ffi.request.wgpuViewRemove({ id: this.id });
- } catch (e) {
- console.error(`Error removing WGPU view ${this.id}:`, e);
- }
- delete WGPUViewMap[this.id];
- this.ptr = null;
- }
- getNativeHandle() {
- return ffi.request.wgpuViewGetNativeHandle({ id: this.id });
- }
- static getById(id) {
- return WGPUViewMap[id];
- }
- static getAll() {
- return Object.values(WGPUViewMap);
- }
-}
-var WGPUViewMap, nextWGPUViewId = 1, defaultOptions2;
-var init_WGPUView = __esm(async () => {
- init_eventEmitter();
- await init_native();
- WGPUViewMap = {};
- defaultOptions2 = {
- frame: {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- },
- autoResize: true,
- startTransparent: false,
- startPassthrough: false
- };
-});
-
-// node_modules/electrobun/dist/api/bun/core/Paths.ts
-import { resolve as resolve2 } from "path";
-var RESOURCES_FOLDER, VIEWS_FOLDER;
-var init_Paths = __esm(() => {
- RESOURCES_FOLDER = resolve2("../Resources/");
- VIEWS_FOLDER = resolve2(RESOURCES_FOLDER, "app/views");
-});
-
-// node_modules/electrobun/dist/api/bun/core/Tray.ts
-import { join as join3 } from "path";
-
-class Tray {
- id = nextTrayId++;
- ptr = null;
- visible = true;
- title = "";
- image = "";
- template = true;
- width = 16;
- height = 16;
- menu = null;
- constructor({
- title = "",
- image = "",
- template = true,
- width = 16,
- height = 16
- } = {}) {
- this.title = title;
- this.image = image;
- this.template = template;
- this.width = width;
- this.height = height;
- this.createNativeTray();
- TrayMap[this.id] = this;
- }
- createNativeTray() {
- try {
- this.ptr = ffi.request.createTray({
- id: this.id,
- title: this.title,
- image: this.resolveImagePath(this.image),
- template: this.template,
- width: this.width,
- height: this.height
- });
- this.visible = true;
- } catch (error) {
- console.warn("Tray creation failed:", error);
- console.warn("System tray functionality may not be available on this platform");
- this.ptr = null;
- this.visible = false;
- }
- if (this.ptr && this.menu) {
- ffi.request.setTrayMenu({
- id: this.id,
- menuConfig: JSON.stringify(menuConfigWithDefaults(this.menu))
- });
- }
- }
- resolveImagePath(imgPath) {
- if (imgPath.startsWith("views://")) {
- return join3(VIEWS_FOLDER, imgPath.replace("views://", ""));
- } else {
- return imgPath;
- }
- }
- setTitle(title) {
- this.title = title;
- if (!this.ptr)
- return;
- ffi.request.setTrayTitle({ id: this.id, title });
- }
- setImage(imgPath) {
- this.image = imgPath;
- if (!this.ptr)
- return;
- ffi.request.setTrayImage({
- id: this.id,
- image: this.resolveImagePath(imgPath)
- });
- }
- setMenu(menu) {
- this.menu = menu;
- if (!this.ptr)
- return;
- const menuWithDefaults = menuConfigWithDefaults(menu);
- ffi.request.setTrayMenu({
- id: this.id,
- menuConfig: JSON.stringify(menuWithDefaults)
- });
- }
- on(name2, handler) {
- const specificName = `${name2}-${this.id}`;
- eventEmitter_default.on(specificName, handler);
- }
- setVisible(visible) {
- if (visible === this.visible) {
- return;
- }
- if (!visible) {
- if (this.ptr) {
- ffi.request.removeTray({ id: this.id });
- this.ptr = null;
- }
- this.visible = false;
- return;
- }
- this.createNativeTray();
- }
- getBounds() {
- return ffi.request.getTrayBounds({ id: this.id });
- }
- remove() {
- console.log("Tray.remove() called for id:", this.id);
- if (this.ptr) {
- ffi.request.removeTray({ id: this.id });
- this.ptr = null;
- }
- this.visible = false;
- delete TrayMap[this.id];
- console.log("Tray removed from TrayMap");
- }
- static getById(id) {
- return TrayMap[id];
- }
- static getAll() {
- return Object.values(TrayMap);
- }
- static removeById(id) {
- const tray = TrayMap[id];
- if (tray) {
- tray.remove();
- }
- }
-}
-var nextTrayId = 1, TrayMap, menuConfigWithDefaults = (menu) => {
- return menu.map((item) => {
- if (item.type === "divider" || item.type === "separator") {
- return { type: "divider" };
- } else {
- const menuItem = item;
- const actionWithDataId = ffi.internal.serializeMenuAction(menuItem.action || "", menuItem.data);
- return {
- label: menuItem.label || "",
- type: menuItem.type || "normal",
- action: actionWithDataId,
- enabled: menuItem.enabled === false ? false : true,
- checked: Boolean(menuItem.checked),
- hidden: Boolean(menuItem.hidden),
- tooltip: menuItem.tooltip || undefined,
- ...menuItem.submenu ? { submenu: menuConfigWithDefaults(menuItem.submenu) } : {}
- };
- }
- });
-};
-var init_Tray = __esm(async () => {
- init_eventEmitter();
- init_Paths();
- await init_native();
- TrayMap = {};
-});
-
-// node_modules/electrobun/dist/api/bun/preload/.generated/compiled.ts
-var preloadScript = `(function(){// src/bun/preload/encryption.ts
-function base64ToUint8Array(base64) {
- return new Uint8Array(atob(base64).split("").map((char) => char.charCodeAt(0)));
-}
-function uint8ArrayToBase64(uint8Array) {
- let binary = "";
- for (let i = 0;i < uint8Array.length; i++) {
- binary += String.fromCharCode(uint8Array[i]);
- }
- return btoa(binary);
-}
-async function generateKeyFromBytes(rawKey) {
- return await window.crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, true, ["encrypt", "decrypt"]);
-}
-async function initEncryption() {
- const secretKey = await generateKeyFromBytes(new Uint8Array(window.__electrobunSecretKeyBytes));
- const encryptString = async (plaintext) => {
- const encoder = new TextEncoder;
- const encodedText = encoder.encode(plaintext);
- const iv = window.crypto.getRandomValues(new Uint8Array(12));
- const encryptedBuffer = await window.crypto.subtle.encrypt({ name: "AES-GCM", iv }, secretKey, encodedText);
- const encryptedData = new Uint8Array(encryptedBuffer.slice(0, -16));
- const tag = new Uint8Array(encryptedBuffer.slice(-16));
- return {
- encryptedData: uint8ArrayToBase64(encryptedData),
- iv: uint8ArrayToBase64(iv),
- tag: uint8ArrayToBase64(tag)
- };
- };
- const decryptString = async (encryptedDataB64, ivB64, tagB64) => {
- const encryptedData = base64ToUint8Array(encryptedDataB64);
- const iv = base64ToUint8Array(ivB64);
- const tag = base64ToUint8Array(tagB64);
- const combinedData = new Uint8Array(encryptedData.length + tag.length);
- combinedData.set(encryptedData);
- combinedData.set(tag, encryptedData.length);
- const decryptedBuffer = await window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, secretKey, combinedData);
- const decoder = new TextDecoder;
- return decoder.decode(decryptedBuffer);
- };
- window.__electrobun_encrypt = encryptString;
- window.__electrobun_decrypt = decryptString;
-}
-
-// src/bun/preload/internalRpc.ts
-var pendingRequests = {};
-var requestId = 0;
-var isProcessingQueue = false;
-var sendQueue = [];
-function processQueue() {
- if (isProcessingQueue) {
- setTimeout(processQueue);
- return;
- }
- if (sendQueue.length === 0)
- return;
- isProcessingQueue = true;
- const batch = JSON.stringify(sendQueue);
- sendQueue.length = 0;
- window.__electrobunInternalBridge?.postMessage(batch);
- setTimeout(() => {
- isProcessingQueue = false;
- }, 2);
-}
-function send(type, payload) {
- sendQueue.push(JSON.stringify({ type: "message", id: type, payload }));
- processQueue();
-}
-function request(type, payload) {
- return new Promise((resolve, reject) => {
- const id = \`req_\${++requestId}_\${Date.now()}\`;
- pendingRequests[id] = { resolve, reject };
- sendQueue.push(JSON.stringify({
- type: "request",
- method: type,
- id,
- params: payload,
- hostWebviewId: window.__electrobunWebviewId
- }));
- processQueue();
- setTimeout(() => {
- if (pendingRequests[id]) {
- delete pendingRequests[id];
- reject(new Error(\`Request timeout: \${type}\`));
- }
- }, 1e4);
- });
-}
-function handleResponse(msg) {
- if (msg && msg.type === "response" && msg.id) {
- const pending = pendingRequests[msg.id];
- if (pending) {
- delete pendingRequests[msg.id];
- if (msg.success)
- pending.resolve(msg.payload);
- else
- pending.reject(msg.payload);
- }
- }
-}
-
-// src/bun/preload/dragRegions.ts
-function isAppRegionDrag(e) {
- const target = e.target;
- if (!target || !target.closest)
- return false;
- if (target.closest(".electrobun-webkit-app-region-no-drag") || target.closest('[style*="app-region"][style*="no-drag"]')) {
- return false;
- }
- const draggableByStyle = target.closest('[style*="app-region"][style*="drag"]');
- const draggableByClass = target.closest(".electrobun-webkit-app-region-drag");
- return !!(draggableByStyle || draggableByClass);
-}
-function initDragRegions() {
- document.addEventListener("mousedown", (e) => {
- if (isAppRegionDrag(e)) {
- send("startWindowMove", { id: window.__electrobunWindowId });
- }
- });
- document.addEventListener("mouseup", (e) => {
- if (isAppRegionDrag(e)) {
- send("stopWindowMove", { id: window.__electrobunWindowId });
- }
- });
-}
-
-// src/bun/preload/overlaySync.ts
-class OverlaySyncController {
- element;
- options;
- lastRect = { x: 0, y: 0, width: 0, height: 0 };
- resizeObserver = null;
- positionLoop = null;
- resizeHandler = null;
- burstUntil = 0;
- constructor(element, options) {
- this.element = element;
- this.options = {
- onSync: options.onSync,
- getMasks: options.getMasks ?? (() => []),
- burstIntervalMs: options.burstIntervalMs ?? 50,
- baseIntervalMs: options.baseIntervalMs ?? 100,
- burstDurationMs: options.burstDurationMs ?? 500
- };
- }
- start() {
- this.resizeObserver = new ResizeObserver(() => this.sync());
- this.resizeObserver.observe(this.element);
- const loop = () => {
- this.sync();
- const now = performance.now();
- const interval = now < this.burstUntil ? this.options.burstIntervalMs : this.options.baseIntervalMs;
- this.positionLoop = setTimeout(loop, interval);
- };
- this.positionLoop = setTimeout(loop, this.options.baseIntervalMs);
- this.resizeHandler = () => this.sync(true);
- window.addEventListener("resize", this.resizeHandler);
- }
- stop() {
- if (this.resizeObserver)
- this.resizeObserver.disconnect();
- if (this.positionLoop)
- clearTimeout(this.positionLoop);
- if (this.resizeHandler) {
- window.removeEventListener("resize", this.resizeHandler);
- }
- this.resizeObserver = null;
- this.positionLoop = null;
- this.resizeHandler = null;
- }
- forceSync() {
- this.sync(true);
- }
- setLastRect(rect) {
- this.lastRect = rect;
- }
- sync(force = false) {
- const rect = this.element.getBoundingClientRect();
- const newRect = {
- x: rect.x,
- y: rect.y,
- width: rect.width,
- height: rect.height
- };
- if (newRect.width === 0 && newRect.height === 0) {
- return;
- }
- if (!force && newRect.x === this.lastRect.x && newRect.y === this.lastRect.y && newRect.width === this.lastRect.width && newRect.height === this.lastRect.height) {
- return;
- }
- this.burstUntil = performance.now() + this.options.burstDurationMs;
- this.lastRect = newRect;
- const masks = this.options.getMasks();
- this.options.onSync(newRect, JSON.stringify(masks));
- }
-}
-
-// src/bun/preload/webviewTag.ts
-var webviewRegistry = {};
-
-class ElectrobunWebviewTag extends HTMLElement {
- webviewId = null;
- maskSelectors = new Set;
- _sync = null;
- transparent = false;
- passthroughEnabled = false;
- hidden = false;
- sandboxed = false;
- _eventListeners = {};
- constructor() {
- super();
- }
- connectedCallback() {
- requestAnimationFrame(() => this.initWebview());
- }
- disconnectedCallback() {
- if (this.webviewId !== null) {
- send("webviewTagRemove", { id: this.webviewId });
- delete webviewRegistry[this.webviewId];
- }
- if (this._sync)
- this._sync.stop();
- }
- async initWebview() {
- const rect = this.getBoundingClientRect();
- const initialRect = {
- x: rect.x,
- y: rect.y,
- width: rect.width,
- height: rect.height
- };
- const url = this.getAttribute("src");
- const html = this.getAttribute("html");
- const preload = this.getAttribute("preload");
- const partition = this.getAttribute("partition");
- const renderer = this.getAttribute("renderer") || "native";
- const masks = this.getAttribute("masks");
- const sandbox = this.hasAttribute("sandbox");
- this.sandboxed = sandbox;
- const transparent = this.hasAttribute("transparent");
- const passthrough = this.hasAttribute("passthrough");
- this.transparent = transparent;
- this.passthroughEnabled = passthrough;
- if (transparent)
- this.style.opacity = "0";
- if (passthrough)
- this.style.pointerEvents = "none";
- if (masks) {
- masks.split(",").forEach((s) => this.maskSelectors.add(s.trim()));
- }
- try {
- const webviewId = await request("webviewTagInit", {
- hostWebviewId: window.__electrobunWebviewId,
- windowId: window.__electrobunWindowId,
- renderer,
- url,
- html,
- preload,
- partition,
- frame: {
- width: rect.width,
- height: rect.height,
- x: rect.x,
- y: rect.y
- },
- navigationRules: null,
- sandbox,
- transparent,
- passthrough
- });
- this.webviewId = webviewId;
- this.id = \`electrobun-webview-\${webviewId}\`;
- webviewRegistry[webviewId] = this;
- this.setupObservers(initialRect);
- this.syncDimensions(true);
- requestAnimationFrame(() => {
- Object.values(webviewRegistry).forEach((webview) => {
- if (webview !== this && webview.webviewId !== null) {
- webview.syncDimensions(true);
- }
- });
- });
- } catch (err) {
- console.error("Failed to init webview:", err);
- }
- }
- setupObservers(initialRect) {
- const getMasks = () => {
- const rect = this.getBoundingClientRect();
- const masks = [];
- this.maskSelectors.forEach((selector) => {
- try {
- document.querySelectorAll(selector).forEach((el) => {
- const mr = el.getBoundingClientRect();
- masks.push({
- x: mr.x - rect.x,
- y: mr.y - rect.y,
- width: mr.width,
- height: mr.height
- });
- });
- } catch (_e) {}
- });
- return masks;
- };
- this._sync = new OverlaySyncController(this, {
- onSync: (rect, masksJson) => {
- if (this.webviewId === null)
- return;
- send("webviewTagResize", {
- id: this.webviewId,
- frame: rect,
- masks: masksJson
- });
- },
- getMasks,
- burstIntervalMs: 10,
- baseIntervalMs: 100,
- burstDurationMs: 50
- });
- this._sync.setLastRect(initialRect);
- this._sync.start();
- }
- syncDimensions(force = false) {
- if (!this._sync)
- return;
- if (force) {
- this._sync.forceSync();
- }
- }
- loadURL(url) {
- if (this.webviewId === null)
- return;
- this.setAttribute("src", url);
- send("webviewTagUpdateSrc", { id: this.webviewId, url });
- }
- loadHTML(html) {
- if (this.webviewId === null)
- return;
- send("webviewTagUpdateHtml", { id: this.webviewId, html });
- }
- reload() {
- if (this.webviewId !== null)
- send("webviewTagReload", { id: this.webviewId });
- }
- goBack() {
- if (this.webviewId !== null)
- send("webviewTagGoBack", { id: this.webviewId });
- }
- goForward() {
- if (this.webviewId !== null)
- send("webviewTagGoForward", { id: this.webviewId });
- }
- async canGoBack() {
- if (this.webviewId === null)
- return false;
- return await request("webviewTagCanGoBack", {
- id: this.webviewId
- });
- }
- async canGoForward() {
- if (this.webviewId === null)
- return false;
- return await request("webviewTagCanGoForward", {
- id: this.webviewId
- });
- }
- toggleTransparent(value) {
- if (this.webviewId === null)
- return;
- this.transparent = value !== undefined ? value : !this.transparent;
- this.style.opacity = this.transparent ? "0" : "";
- send("webviewTagSetTransparent", {
- id: this.webviewId,
- transparent: this.transparent
- });
- }
- togglePassthrough(value) {
- if (this.webviewId === null)
- return;
- this.passthroughEnabled = value !== undefined ? value : !this.passthroughEnabled;
- this.style.pointerEvents = this.passthroughEnabled ? "none" : "";
- send("webviewTagSetPassthrough", {
- id: this.webviewId,
- enablePassthrough: this.passthroughEnabled
- });
- }
- toggleHidden(value) {
- if (this.webviewId === null)
- return;
- this.hidden = value !== undefined ? value : !this.hidden;
- send("webviewTagSetHidden", { id: this.webviewId, hidden: this.hidden });
- }
- addMaskSelector(selector) {
- this.maskSelectors.add(selector);
- this.syncDimensions(true);
- }
- removeMaskSelector(selector) {
- this.maskSelectors.delete(selector);
- this.syncDimensions(true);
- }
- setNavigationRules(rules) {
- if (this.webviewId !== null) {
- send("webviewTagSetNavigationRules", { id: this.webviewId, rules });
- }
- }
- findInPage(searchText, options) {
- if (this.webviewId === null)
- return;
- const forward = options?.forward !== false;
- const matchCase = options?.matchCase || false;
- send("webviewTagFindInPage", {
- id: this.webviewId,
- searchText,
- forward,
- matchCase
- });
- }
- stopFindInPage() {
- if (this.webviewId !== null)
- send("webviewTagStopFind", { id: this.webviewId });
- }
- openDevTools() {
- if (this.webviewId !== null)
- send("webviewTagOpenDevTools", { id: this.webviewId });
- }
- closeDevTools() {
- if (this.webviewId !== null)
- send("webviewTagCloseDevTools", { id: this.webviewId });
- }
- toggleDevTools() {
- if (this.webviewId !== null)
- send("webviewTagToggleDevTools", { id: this.webviewId });
- }
- executeJavascript(js) {
- if (this.webviewId === null)
- return;
- send("webviewTagExecuteJavascript", { id: this.webviewId, js });
- }
- on(event, listener) {
- if (!this._eventListeners[event])
- this._eventListeners[event] = [];
- this._eventListeners[event].push(listener);
- }
- off(event, listener) {
- if (!this._eventListeners[event])
- return;
- const idx = this._eventListeners[event].indexOf(listener);
- if (idx !== -1)
- this._eventListeners[event].splice(idx, 1);
- }
- emit(event, detail) {
- const listeners = this._eventListeners[event];
- if (listeners) {
- const customEvent = new CustomEvent(event, { detail });
- listeners.forEach((fn) => fn(customEvent));
- }
- }
- get src() {
- return this.getAttribute("src");
- }
- set src(value) {
- if (value) {
- this.setAttribute("src", value);
- if (this.webviewId !== null)
- this.loadURL(value);
- } else {
- this.removeAttribute("src");
- }
- }
- get html() {
- return this.getAttribute("html");
- }
- set html(value) {
- if (value) {
- this.setAttribute("html", value);
- if (this.webviewId !== null)
- this.loadHTML(value);
- } else {
- this.removeAttribute("html");
- }
- }
- get preload() {
- return this.getAttribute("preload");
- }
- set preload(value) {
- if (value)
- this.setAttribute("preload", value);
- else
- this.removeAttribute("preload");
- }
- get renderer() {
- return this.getAttribute("renderer") || "native";
- }
- set renderer(value) {
- this.setAttribute("renderer", value);
- }
- get sandbox() {
- return this.sandboxed;
- }
-}
-function initWebviewTag() {
- if (!customElements.get("electrobun-webview")) {
- customElements.define("electrobun-webview", ElectrobunWebviewTag);
- }
- const injectStyles = () => {
- const style = document.createElement("style");
- style.textContent = \`
-electrobun-webview {
- display: block;
- width: 800px;
- height: 300px;
- background: #fff;
- background-repeat: no-repeat !important;
- overflow: hidden;
-}
-\`;
- if (document.head?.firstChild) {
- document.head.insertBefore(style, document.head.firstChild);
- } else if (document.head) {
- document.head.appendChild(style);
- }
- };
- if (document.head) {
- injectStyles();
- } else {
- document.addEventListener("DOMContentLoaded", injectStyles);
- }
-}
-
-// src/bun/preload/wgpuTag.ts
-var wgpuTagRegistry = {};
-
-class ElectrobunWgpuTag extends HTMLElement {
- wgpuViewId = null;
- maskSelectors = new Set;
- _sync = null;
- transparent = false;
- passthroughEnabled = false;
- hidden = false;
- _eventListeners = {};
- constructor() {
- super();
- }
- connectedCallback() {
- requestAnimationFrame(() => this.initWgpuView());
- }
- disconnectedCallback() {
- if (this.wgpuViewId !== null) {
- send("wgpuTagRemove", { id: this.wgpuViewId });
- delete wgpuTagRegistry[this.wgpuViewId];
- }
- if (this._sync)
- this._sync.stop();
- }
- async initWgpuView() {
- const rect = this.getBoundingClientRect();
- const initialRect = {
- x: rect.x,
- y: rect.y,
- width: rect.width,
- height: rect.height
- };
- const transparent = this.hasAttribute("transparent");
- const passthrough = this.hasAttribute("passthrough");
- const hidden = this.hasAttribute("hidden");
- const masks = this.getAttribute("masks");
- this.transparent = transparent;
- this.passthroughEnabled = passthrough;
- this.hidden = hidden;
- if (masks) {
- masks.split(",").forEach((s) => this.maskSelectors.add(s.trim()));
- }
- if (transparent)
- this.style.opacity = "0";
- if (passthrough)
- this.style.pointerEvents = "none";
- try {
- const wgpuViewId = await request("wgpuTagInit", {
- windowId: window.__electrobunWindowId,
- frame: {
- width: rect.width,
- height: rect.height,
- x: rect.x,
- y: rect.y
- },
- transparent,
- passthrough
- });
- this.wgpuViewId = wgpuViewId;
- this.id = \`electrobun-wgpu-\${wgpuViewId}\`;
- wgpuTagRegistry[wgpuViewId] = this;
- this.setupObservers(initialRect);
- this.syncDimensions(true);
- if (hidden) {
- this.toggleHidden(true);
- }
- requestAnimationFrame(() => {
- Object.values(wgpuTagRegistry).forEach((view) => {
- if (view !== this && view.wgpuViewId !== null) {
- view.syncDimensions(true);
- }
- });
- });
- this.emit("ready", { id: wgpuViewId });
- } catch (err) {
- console.error("Failed to init WGPU view:", err);
- }
- }
- setupObservers(initialRect) {
- const getMasks = () => {
- const rect = this.getBoundingClientRect();
- const masks = [];
- this.maskSelectors.forEach((selector) => {
- try {
- document.querySelectorAll(selector).forEach((el) => {
- const mr = el.getBoundingClientRect();
- masks.push({
- x: mr.x - rect.x,
- y: mr.y - rect.y,
- width: mr.width,
- height: mr.height
- });
- });
- } catch (_e) {}
- });
- return masks;
- };
- this._sync = new OverlaySyncController(this, {
- onSync: (rect, masksJson) => {
- if (this.wgpuViewId === null)
- return;
- send("wgpuTagResize", {
- id: this.wgpuViewId,
- frame: rect,
- masks: masksJson
- });
- },
- getMasks,
- burstIntervalMs: 10,
- baseIntervalMs: 100,
- burstDurationMs: 50
- });
- this._sync.setLastRect(initialRect);
- this._sync.start();
- }
- syncDimensions(force = false) {
- if (!this._sync)
- return;
- if (force) {
- this._sync.forceSync();
- }
- }
- toggleTransparent(value) {
- if (this.wgpuViewId === null)
- return;
- this.transparent = value !== undefined ? value : !this.transparent;
- this.style.opacity = this.transparent ? "0" : "";
- send("wgpuTagSetTransparent", {
- id: this.wgpuViewId,
- transparent: this.transparent
- });
- }
- togglePassthrough(value) {
- if (this.wgpuViewId === null)
- return;
- this.passthroughEnabled = value !== undefined ? value : !this.passthroughEnabled;
- this.style.pointerEvents = this.passthroughEnabled ? "none" : "";
- send("wgpuTagSetPassthrough", {
- id: this.wgpuViewId,
- passthrough: this.passthroughEnabled
- });
- }
- toggleHidden(value) {
- if (this.wgpuViewId === null)
- return;
- this.hidden = value !== undefined ? value : !this.hidden;
- send("wgpuTagSetHidden", { id: this.wgpuViewId, hidden: this.hidden });
- }
- runTest() {
- if (this.wgpuViewId === null)
- return;
- send("wgpuTagRunTest", { id: this.wgpuViewId });
- }
- addMaskSelector(selector) {
- this.maskSelectors.add(selector);
- this.syncDimensions(true);
- }
- removeMaskSelector(selector) {
- this.maskSelectors.delete(selector);
- this.syncDimensions(true);
- }
- on(event, listener) {
- if (!this._eventListeners[event])
- this._eventListeners[event] = [];
- this._eventListeners[event].push(listener);
- }
- off(event, listener) {
- if (!this._eventListeners[event])
- return;
- const idx = this._eventListeners[event].indexOf(listener);
- if (idx !== -1)
- this._eventListeners[event].splice(idx, 1);
- }
- emit(event, detail) {
- const listeners = this._eventListeners[event];
- if (listeners) {
- const customEvent = new CustomEvent(event, { detail });
- listeners.forEach((fn) => fn(customEvent));
- }
- }
-}
-function initWgpuTag() {
- if (!customElements.get("electrobun-wgpu")) {
- customElements.define("electrobun-wgpu", ElectrobunWgpuTag);
- }
- const injectStyles = () => {
- const style = document.createElement("style");
- style.textContent = \`
-electrobun-wgpu {
- display: block;
- width: 800px;
- height: 300px;
- background: #000;
- overflow: hidden;
-}
-\`;
- if (document.head?.firstChild) {
- document.head.insertBefore(style, document.head.firstChild);
- } else if (document.head) {
- document.head.appendChild(style);
- }
- };
- if (document.head) {
- injectStyles();
- } else {
- document.addEventListener("DOMContentLoaded", injectStyles);
- }
-}
-
-// src/bun/preload/events.ts
-function emitWebviewEvent(eventName, detail) {
- setTimeout(() => {
- const bridge = window.__electrobunEventBridge || window.__electrobunInternalBridge;
- bridge?.postMessage(JSON.stringify({
- id: "webviewEvent",
- type: "message",
- payload: {
- id: window.__electrobunWebviewId,
- eventName,
- detail
- }
- }));
- });
-}
-function initLifecycleEvents() {
- window.addEventListener("load", () => {
- if (window === window.top) {
- emitWebviewEvent("dom-ready", document.location.href);
- }
- });
- window.addEventListener("popstate", () => {
- emitWebviewEvent("did-navigate-in-page", window.location.href);
- });
- window.addEventListener("hashchange", () => {
- emitWebviewEvent("did-navigate-in-page", window.location.href);
- });
-}
-var cmdKeyHeld = false;
-var cmdKeyTimestamp = 0;
-var CMD_KEY_THRESHOLD_MS = 500;
-function isCmdHeld() {
- if (cmdKeyHeld)
- return true;
- return Date.now() - cmdKeyTimestamp < CMD_KEY_THRESHOLD_MS && cmdKeyTimestamp > 0;
-}
-function initCmdClickHandling() {
- window.addEventListener("keydown", (event) => {
- if (event.key === "Meta" || event.metaKey) {
- cmdKeyHeld = true;
- cmdKeyTimestamp = Date.now();
- }
- }, true);
- window.addEventListener("keyup", (event) => {
- if (event.key === "Meta") {
- cmdKeyHeld = false;
- cmdKeyTimestamp = Date.now();
- }
- }, true);
- window.addEventListener("blur", () => {
- cmdKeyHeld = false;
- });
- window.addEventListener("click", (event) => {
- if (event.metaKey || event.ctrlKey) {
- const anchor = event.target?.closest?.("a");
- if (anchor && anchor.href) {
- event.preventDefault();
- event.stopPropagation();
- event.stopImmediatePropagation();
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: anchor.href,
- isCmdClick: true,
- isSPANavigation: false
- }));
- }
- }
- }, true);
-}
-function initSPANavigationInterception() {
- const originalPushState = history.pushState;
- const originalReplaceState = history.replaceState;
- history.pushState = function(state, title, url) {
- if (isCmdHeld() && url) {
- const resolvedUrl = new URL(String(url), window.location.href).href;
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: resolvedUrl,
- isCmdClick: true,
- isSPANavigation: true
- }));
- return;
- }
- return originalPushState.apply(this, [state, title, url]);
- };
- history.replaceState = function(state, title, url) {
- if (isCmdHeld() && url) {
- const resolvedUrl = new URL(String(url), window.location.href).href;
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: resolvedUrl,
- isCmdClick: true,
- isSPANavigation: true
- }));
- return;
- }
- return originalReplaceState.apply(this, [state, title, url]);
- };
-}
-function initOverscrollPrevention() {
- document.addEventListener("DOMContentLoaded", () => {
- const style = document.createElement("style");
- style.type = "text/css";
- style.appendChild(document.createTextNode("html, body { overscroll-behavior: none; }"));
- document.head.appendChild(style);
- });
-}
-
-// src/bun/preload/index.ts
-initEncryption().catch((err) => console.error("Failed to initialize encryption:", err));
-var internalMessageHandler = (msg) => {
- handleResponse(msg);
-};
-if (!window.__electrobun) {
- window.__electrobun = {
- receiveInternalMessageFromBun: internalMessageHandler,
- receiveMessageFromBun: (msg) => {
- console.log("receiveMessageFromBun (no handler):", msg);
- }
- };
-} else {
- window.__electrobun.receiveInternalMessageFromBun = internalMessageHandler;
- window.__electrobun.receiveMessageFromBun = (msg) => {
- console.log("receiveMessageFromBun (no handler):", msg);
- };
-}
-window.__electrobunSendToHost = (message) => {
- emitWebviewEvent("host-message", JSON.stringify(message));
-};
-initLifecycleEvents();
-initCmdClickHandling();
-initSPANavigationInterception();
-initOverscrollPrevention();
-initDragRegions();
-initWebviewTag();
-initWgpuTag();
-})();`, preloadScriptSandboxed = `(function(){// src/bun/preload/events.ts
-function emitWebviewEvent(eventName, detail) {
- setTimeout(() => {
- const bridge = window.__electrobunEventBridge || window.__electrobunInternalBridge;
- bridge?.postMessage(JSON.stringify({
- id: "webviewEvent",
- type: "message",
- payload: {
- id: window.__electrobunWebviewId,
- eventName,
- detail
- }
- }));
- });
-}
-function initLifecycleEvents() {
- window.addEventListener("load", () => {
- if (window === window.top) {
- emitWebviewEvent("dom-ready", document.location.href);
- }
- });
- window.addEventListener("popstate", () => {
- emitWebviewEvent("did-navigate-in-page", window.location.href);
- });
- window.addEventListener("hashchange", () => {
- emitWebviewEvent("did-navigate-in-page", window.location.href);
- });
-}
-var cmdKeyHeld = false;
-var cmdKeyTimestamp = 0;
-var CMD_KEY_THRESHOLD_MS = 500;
-function isCmdHeld() {
- if (cmdKeyHeld)
- return true;
- return Date.now() - cmdKeyTimestamp < CMD_KEY_THRESHOLD_MS && cmdKeyTimestamp > 0;
-}
-function initCmdClickHandling() {
- window.addEventListener("keydown", (event) => {
- if (event.key === "Meta" || event.metaKey) {
- cmdKeyHeld = true;
- cmdKeyTimestamp = Date.now();
- }
- }, true);
- window.addEventListener("keyup", (event) => {
- if (event.key === "Meta") {
- cmdKeyHeld = false;
- cmdKeyTimestamp = Date.now();
- }
- }, true);
- window.addEventListener("blur", () => {
- cmdKeyHeld = false;
- });
- window.addEventListener("click", (event) => {
- if (event.metaKey || event.ctrlKey) {
- const anchor = event.target?.closest?.("a");
- if (anchor && anchor.href) {
- event.preventDefault();
- event.stopPropagation();
- event.stopImmediatePropagation();
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: anchor.href,
- isCmdClick: true,
- isSPANavigation: false
- }));
- }
- }
- }, true);
-}
-function initSPANavigationInterception() {
- const originalPushState = history.pushState;
- const originalReplaceState = history.replaceState;
- history.pushState = function(state, title, url) {
- if (isCmdHeld() && url) {
- const resolvedUrl = new URL(String(url), window.location.href).href;
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: resolvedUrl,
- isCmdClick: true,
- isSPANavigation: true
- }));
- return;
- }
- return originalPushState.apply(this, [state, title, url]);
- };
- history.replaceState = function(state, title, url) {
- if (isCmdHeld() && url) {
- const resolvedUrl = new URL(String(url), window.location.href).href;
- emitWebviewEvent("new-window-open", JSON.stringify({
- url: resolvedUrl,
- isCmdClick: true,
- isSPANavigation: true
- }));
- return;
- }
- return originalReplaceState.apply(this, [state, title, url]);
- };
-}
-function initOverscrollPrevention() {
- document.addEventListener("DOMContentLoaded", () => {
- const style = document.createElement("style");
- style.type = "text/css";
- style.appendChild(document.createTextNode("html, body { overscroll-behavior: none; }"));
- document.head.appendChild(style);
- });
-}
-
-// src/bun/preload/index-sandboxed.ts
-initLifecycleEvents();
-initCmdClickHandling();
-initSPANavigationInterception();
-initOverscrollPrevention();
-})();`;
-
-// node_modules/electrobun/dist/api/bun/core/windowIds.ts
-function getNextWindowId() {
- return nextWindowId++;
-}
-var nextWindowId = 1;
-
-// node_modules/electrobun/dist/api/bun/core/GpuWindow.ts
-class GpuWindow {
- id = getNextWindowId();
- ptr;
- title = "Electrobun";
- state = "creating";
- transparent = false;
- frame = {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- };
- wgpuViewId;
- constructor(options = defaultOptions3) {
- this.title = options.title || "New Window";
- this.frame = options.frame ? { ...defaultOptions3.frame, ...options.frame } : { ...defaultOptions3.frame };
- this.transparent = options.transparent ?? false;
- this.init(options);
- }
- init({
- styleMask,
- titleBarStyle,
- transparent
- }) {
- this.ptr = ffi.request.createWindow({
- id: this.id,
- title: this.title,
- url: "",
- frame: {
- width: this.frame.width,
- height: this.frame.height,
- x: this.frame.x,
- y: this.frame.y
- },
- styleMask: {
- Borderless: false,
- Titled: true,
- Closable: true,
- Miniaturizable: true,
- Resizable: true,
- UnifiedTitleAndToolbar: false,
- FullScreen: false,
- FullSizeContentView: false,
- UtilityWindow: false,
- DocModalWindow: false,
- NonactivatingPanel: false,
- HUDWindow: false,
- ...styleMask || {},
- ...titleBarStyle === "hiddenInset" ? {
- Titled: true,
- FullSizeContentView: true
- } : {},
- ...titleBarStyle === "hidden" ? {
- Titled: false,
- FullSizeContentView: true
- } : {}
- },
- titleBarStyle: titleBarStyle || "default",
- transparent: transparent ?? false
- });
- GpuWindowMap[this.id] = this;
- const wgpuView = new WGPUView({
- frame: {
- x: 0,
- y: 0,
- width: this.frame.width,
- height: this.frame.height
- },
- windowId: this.id,
- autoResize: true,
- startTransparent: false,
- startPassthrough: false
- });
- this.wgpuViewId = wgpuView.id;
- }
- get wgpuView() {
- return WGPUView.getById(this.wgpuViewId);
- }
- static getById(id) {
- return GpuWindowMap[id];
- }
- setTitle(title) {
- this.title = title;
- return ffi.request.setTitle({ winId: this.id, title });
- }
- close() {
- return ffi.request.closeWindow({ winId: this.id });
- }
- focus() {
- return ffi.request.focusWindow({ winId: this.id });
- }
- show() {
- return ffi.request.focusWindow({ winId: this.id });
- }
- minimize() {
- return ffi.request.minimizeWindow({ winId: this.id });
- }
- unminimize() {
- return ffi.request.restoreWindow({ winId: this.id });
- }
- isMinimized() {
- return ffi.request.isWindowMinimized({ winId: this.id });
- }
- maximize() {
- return ffi.request.maximizeWindow({ winId: this.id });
- }
- unmaximize() {
- return ffi.request.unmaximizeWindow({ winId: this.id });
- }
- isMaximized() {
- return ffi.request.isWindowMaximized({ winId: this.id });
- }
- setFullScreen(fullScreen) {
- return ffi.request.setWindowFullScreen({ winId: this.id, fullScreen });
- }
- isFullScreen() {
- return ffi.request.isWindowFullScreen({ winId: this.id });
- }
- setAlwaysOnTop(alwaysOnTop) {
- return ffi.request.setWindowAlwaysOnTop({ winId: this.id, alwaysOnTop });
- }
- isAlwaysOnTop() {
- return ffi.request.isWindowAlwaysOnTop({ winId: this.id });
- }
- setPosition(x, y) {
- this.frame.x = x;
- this.frame.y = y;
- return ffi.request.setWindowPosition({ winId: this.id, x, y });
- }
- setSize(width, height) {
- this.frame.width = width;
- this.frame.height = height;
- return ffi.request.setWindowSize({ winId: this.id, width, height });
- }
- setFrame(x, y, width, height) {
- this.frame = { x, y, width, height };
- return ffi.request.setWindowFrame({ winId: this.id, x, y, width, height });
- }
- getFrame() {
- const frame = ffi.request.getWindowFrame({ winId: this.id });
- this.frame = frame;
- return frame;
- }
- getPosition() {
- const frame = this.getFrame();
- return { x: frame.x, y: frame.y };
- }
- getSize() {
- const frame = this.getFrame();
- return { width: frame.width, height: frame.height };
- }
- on(name2, handler) {
- const specificName = `${name2}-${this.id}`;
- eventEmitter_default.on(specificName, handler);
- }
-}
-var defaultOptions3, GpuWindowMap;
-var init_GpuWindow = __esm(async () => {
- init_eventEmitter();
- await __promiseAll([
- init_native(),
- init_WGPUView()
- ]);
- defaultOptions3 = {
- title: "Electrobun",
- frame: {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- },
- titleBarStyle: "default",
- transparent: false
- };
- GpuWindowMap = {};
- eventEmitter_default.on("close", (event) => {
- const windowId = event.data.id;
- delete GpuWindowMap[windowId];
- for (const view of WGPUView.getAll()) {
- if (view.windowId === windowId) {
- view.remove();
- }
- }
- });
-});
-
-// node_modules/electrobun/dist/api/bun/proc/native.ts
-import { join as join4 } from "path";
-import {
- dlopen,
- suffix,
- JSCallback,
- CString,
- ptr,
- FFIType,
- toArrayBuffer
-} from "bun:ffi";
-function storeMenuData(data) {
- const id = `menuData_${++menuDataCounter}`;
- menuDataRegistry.set(id, data);
- return id;
-}
-function getMenuData(id) {
- return menuDataRegistry.get(id);
-}
-function clearMenuData(id) {
- menuDataRegistry.delete(id);
-}
-function serializeMenuAction(action, data) {
- const dataId = storeMenuData(data);
- return `${ELECTROBUN_DELIMITER}${dataId}|${action}`;
-}
-function deserializeMenuAction(encodedAction) {
- let actualAction = encodedAction;
- let data = undefined;
- if (encodedAction.startsWith(ELECTROBUN_DELIMITER)) {
- const parts = encodedAction.split("|");
- if (parts.length >= 4) {
- const dataId = parts[2];
- actualAction = parts.slice(3).join("|");
- data = getMenuData(dataId);
- clearMenuData(dataId);
- }
- }
- return { action: actualAction, data };
-}
-function getWindowPtr(winId) {
- return BrowserWindow.getById(winId)?.ptr ?? GpuWindow.getById(winId)?.ptr ?? null;
-}
-function toCString(jsString, addNullTerminator = true) {
- let appendWith = "";
- if (addNullTerminator && !jsString.endsWith("\x00")) {
- appendWith = "\x00";
- }
- const buff = Buffer.from(jsString + appendWith, "utf8");
- return ptr(buff);
-}
-var menuDataRegistry, menuDataCounter = 0, ELECTROBUN_DELIMITER = "|EB|", native, ffi, WGPUBridge, windowCloseCallback, windowMoveCallback, windowResizeCallback, windowFocusCallback, windowBlurCallback, windowKeyCallback, getMimeType, getHTMLForWebviewSync, urlOpenCallback, appReopenCallback, quitRequestedCallback, globalShortcutHandlers, globalShortcutCallback, sessionCache, webviewDecideNavigation, webviewEventHandler = (id, eventName, detail) => {
- const webview = BrowserView.getById(id);
- if (!webview) {
- console.error("[webviewEventHandler] No webview found for id:", id);
- return;
- }
- if (webview.hostWebviewId) {
- const hostWebview = BrowserView.getById(webview.hostWebviewId);
- if (!hostWebview) {
- console.error("[webviewEventHandler] No webview found for id:", id);
- return;
- }
- let js;
- if (eventName === "new-window-open" || eventName === "host-message") {
- js = `document.querySelector('#electrobun-webview-${id}').emit(${JSON.stringify(eventName)}, ${detail});`;
- } else {
- js = `document.querySelector('#electrobun-webview-${id}').emit(${JSON.stringify(eventName)}, ${JSON.stringify(detail)});`;
- }
- native.symbols.evaluateJavaScriptWithNoCompletion(hostWebview.ptr, toCString(js));
- }
- const eventMap = {
- "will-navigate": "willNavigate",
- "did-navigate": "didNavigate",
- "did-navigate-in-page": "didNavigateInPage",
- "did-commit-navigation": "didCommitNavigation",
- "dom-ready": "domReady",
- "new-window-open": "newWindowOpen",
- "host-message": "hostMessage",
- "download-started": "downloadStarted",
- "download-progress": "downloadProgress",
- "download-completed": "downloadCompleted",
- "download-failed": "downloadFailed",
- "load-started": "loadStarted",
- "load-committed": "loadCommitted",
- "load-finished": "loadFinished"
- };
- const mappedName = eventMap[eventName];
- const handler = mappedName ? eventEmitter_default.events.webview[mappedName] : undefined;
- if (!handler) {
- return { success: false };
- }
- let parsedDetail = detail;
- if (eventName === "new-window-open" || eventName === "host-message" || eventName === "download-started" || eventName === "download-progress" || eventName === "download-completed" || eventName === "download-failed") {
- try {
- parsedDetail = JSON.parse(detail);
- } catch (e) {
- console.error("[webviewEventHandler] Failed to parse JSON:", e);
- parsedDetail = detail;
- }
- }
- const event = handler({
- detail: parsedDetail
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
-}, webviewEventJSCallback, bunBridgePostmessageHandler, eventBridgeHandler, internalBridgeHandler, trayItemHandler, applicationMenuHandler, contextMenuHandler, internalRpcHandlers;
-var init_native = __esm(async () => {
- init_eventEmitter();
- await __promiseAll([
- init_BrowserView(),
- init_WGPUView(),
- init_Tray(),
- init_BrowserWindow(),
- init_GpuWindow()
- ]);
- menuDataRegistry = new Map;
- native = (() => {
- try {
- const nativeWrapperPath = join4(process.cwd(), `libNativeWrapper.${suffix}`);
- return dlopen(nativeWrapperPath, {
- createWindowWithFrameAndStyleFromWorker: {
- args: [
- FFIType.u32,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.u32,
- FFIType.cstring,
- FFIType.bool,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.function
- ],
- returns: FFIType.ptr
- },
- setWindowTitle: {
- args: [
- FFIType.ptr,
- FFIType.cstring
- ],
- returns: FFIType.void
- },
- showWindow: {
- args: [
- FFIType.ptr
- ],
- returns: FFIType.void
- },
- closeWindow: {
- args: [
- FFIType.ptr
- ],
- returns: FFIType.void
- },
- minimizeWindow: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- restoreWindow: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- isWindowMinimized: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- maximizeWindow: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- unmaximizeWindow: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- isWindowMaximized: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- setWindowFullScreen: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- isWindowFullScreen: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- setWindowAlwaysOnTop: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- isWindowAlwaysOnTop: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- setWindowVisibleOnAllWorkspaces: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- isWindowVisibleOnAllWorkspaces: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- setWindowPosition: {
- args: [FFIType.ptr, FFIType.f64, FFIType.f64],
- returns: FFIType.void
- },
- setWindowSize: {
- args: [FFIType.ptr, FFIType.f64, FFIType.f64],
- returns: FFIType.void
- },
- setWindowFrame: {
- args: [FFIType.ptr, FFIType.f64, FFIType.f64, FFIType.f64, FFIType.f64],
- returns: FFIType.void
- },
- getWindowFrame: {
- args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr],
- returns: FFIType.void
- },
- initWebview: {
- args: [
- FFIType.u32,
- FFIType.ptr,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.bool,
- FFIType.cstring,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.function,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.bool,
- FFIType.bool
- ],
- returns: FFIType.ptr
- },
- initWGPUView: {
- args: [
- FFIType.u32,
- FFIType.ptr,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool
- ],
- returns: FFIType.ptr
- },
- setNextWebviewFlags: {
- args: [
- FFIType.bool,
- FFIType.bool
- ],
- returns: FFIType.void
- },
- webviewCanGoBack: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- webviewCanGoForward: {
- args: [FFIType.ptr],
- returns: FFIType.bool
- },
- resizeWebview: {
- args: [
- FFIType.ptr,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.cstring
- ],
- returns: FFIType.void
- },
- loadURLInWebView: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- loadHTMLInWebView: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- updatePreloadScriptToWebView: {
- args: [
- FFIType.ptr,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.bool
- ],
- returns: FFIType.void
- },
- webviewGoBack: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewGoForward: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewReload: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewRemove: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- setWebviewHTMLContent: {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void
- },
- startWindowMove: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- stopWindowMove: {
- args: [],
- returns: FFIType.void
- },
- webviewSetTransparent: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- webviewSetPassthrough: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- webviewSetHidden: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- setWebviewNavigationRules: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- webviewFindInPage: {
- args: [FFIType.ptr, FFIType.cstring, FFIType.bool, FFIType.bool],
- returns: FFIType.void
- },
- webviewStopFind: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- evaluateJavaScriptWithNoCompletion: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- webviewOpenDevTools: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewCloseDevTools: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewToggleDevTools: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- webviewSetPageZoom: {
- args: [FFIType.ptr, FFIType.f64],
- returns: FFIType.void
- },
- webviewGetPageZoom: {
- args: [FFIType.ptr],
- returns: FFIType.f64
- },
- wgpuViewSetFrame: {
- args: [
- FFIType.ptr,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64,
- FFIType.f64
- ],
- returns: FFIType.void
- },
- wgpuViewSetTransparent: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- wgpuViewSetPassthrough: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- wgpuViewSetHidden: {
- args: [FFIType.ptr, FFIType.bool],
- returns: FFIType.void
- },
- wgpuViewRemove: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- wgpuViewGetNativeHandle: {
- args: [FFIType.ptr],
- returns: FFIType.ptr
- },
- wgpuInstanceCreateSurfaceMainThread: {
- args: [FFIType.ptr, FFIType.ptr],
- returns: FFIType.ptr
- },
- wgpuSurfaceConfigureMainThread: {
- args: [FFIType.ptr, FFIType.ptr],
- returns: FFIType.void
- },
- wgpuSurfaceGetCurrentTextureMainThread: {
- args: [FFIType.ptr, FFIType.ptr],
- returns: FFIType.void
- },
- wgpuSurfacePresentMainThread: {
- args: [FFIType.ptr],
- returns: FFIType.i32
- },
- wgpuQueueOnSubmittedWorkDoneShim: {
- args: [FFIType.ptr, FFIType.ptr],
- returns: FFIType.u64
- },
- wgpuBufferMapAsyncShim: {
- args: [FFIType.ptr, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.ptr],
- returns: FFIType.u64
- },
- wgpuInstanceWaitAnyShim: {
- args: [FFIType.ptr, FFIType.u64, FFIType.u64],
- returns: FFIType.i32
- },
- wgpuBufferReadSyncShim: {
- args: [FFIType.ptr, FFIType.ptr, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.ptr],
- returns: FFIType.ptr
- },
- wgpuBufferReadSyncIntoShim: {
- args: [FFIType.ptr, FFIType.ptr, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.ptr],
- returns: FFIType.i32
- },
- wgpuBufferReadbackBeginShim: {
- args: [FFIType.ptr, FFIType.u64, FFIType.u64, FFIType.ptr],
- returns: FFIType.ptr
- },
- wgpuBufferReadbackStatusShim: {
- args: [FFIType.ptr],
- returns: FFIType.i32
- },
- wgpuBufferReadbackFreeShim: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- wgpuRunGPUTest: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- wgpuCreateAdapterDeviceMainThread: {
- args: [FFIType.ptr, FFIType.ptr, FFIType.ptr],
- returns: FFIType.void
- },
- wgpuCreateSurfaceForView: {
- args: [FFIType.ptr, FFIType.ptr],
- returns: FFIType.ptr
- },
- createTray: {
- args: [
- FFIType.u32,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.bool,
- FFIType.u32,
- FFIType.u32,
- FFIType.function
- ],
- returns: FFIType.ptr
- },
- setTrayTitle: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- setTrayImage: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- setTrayMenu: {
- args: [FFIType.ptr, FFIType.cstring],
- returns: FFIType.void
- },
- removeTray: {
- args: [FFIType.ptr],
- returns: FFIType.void
- },
- getTrayBounds: {
- args: [FFIType.ptr],
- returns: FFIType.cstring
- },
- setApplicationMenu: {
- args: [FFIType.cstring, FFIType.function],
- returns: FFIType.void
- },
- showContextMenu: {
- args: [FFIType.cstring, FFIType.function],
- returns: FFIType.void
- },
- moveToTrash: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- showItemInFolder: {
- args: [FFIType.cstring],
- returns: FFIType.void
- },
- openExternal: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- openPath: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- showNotification: {
- args: [
- FFIType.cstring,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.bool
- ],
- returns: FFIType.void
- },
- setGlobalShortcutCallback: {
- args: [FFIType.function],
- returns: FFIType.void
- },
- registerGlobalShortcut: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- unregisterGlobalShortcut: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- unregisterAllGlobalShortcuts: {
- args: [],
- returns: FFIType.void
- },
- isGlobalShortcutRegistered: {
- args: [FFIType.cstring],
- returns: FFIType.bool
- },
- getAllDisplays: {
- args: [],
- returns: FFIType.cstring
- },
- getPrimaryDisplay: {
- args: [],
- returns: FFIType.cstring
- },
- getCursorScreenPoint: {
- args: [],
- returns: FFIType.cstring
- },
- getMouseButtons: {
- args: [],
- returns: FFIType.u64
- },
- openFileDialog: {
- args: [
- FFIType.cstring,
- FFIType.cstring,
- FFIType.int,
- FFIType.int,
- FFIType.int
- ],
- returns: FFIType.cstring
- },
- showMessageBox: {
- args: [
- FFIType.cstring,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.cstring,
- FFIType.int,
- FFIType.int
- ],
- returns: FFIType.int
- },
- clipboardReadText: {
- args: [],
- returns: FFIType.cstring
- },
- clipboardWriteText: {
- args: [FFIType.cstring],
- returns: FFIType.void
- },
- clipboardReadImage: {
- args: [FFIType.ptr],
- returns: FFIType.ptr
- },
- clipboardWriteImage: {
- args: [FFIType.ptr, FFIType.u64],
- returns: FFIType.void
- },
- clipboardClear: {
- args: [],
- returns: FFIType.void
- },
- clipboardAvailableFormats: {
- args: [],
- returns: FFIType.cstring
- },
- sessionGetCookies: {
- args: [FFIType.cstring, FFIType.cstring],
- returns: FFIType.cstring
- },
- sessionSetCookie: {
- args: [FFIType.cstring, FFIType.cstring],
- returns: FFIType.bool
- },
- sessionRemoveCookie: {
- args: [FFIType.cstring, FFIType.cstring, FFIType.cstring],
- returns: FFIType.bool
- },
- sessionClearCookies: {
- args: [FFIType.cstring],
- returns: FFIType.void
- },
- sessionClearStorageData: {
- args: [FFIType.cstring, FFIType.cstring],
- returns: FFIType.void
- },
- setURLOpenHandler: {
- args: [FFIType.function],
- returns: FFIType.void
- },
- setAppReopenHandler: {
- args: [FFIType.function],
- returns: FFIType.void
- },
- setDockIconVisible: {
- args: [FFIType.bool],
- returns: FFIType.void
- },
- isDockIconVisible: {
- args: [],
- returns: FFIType.bool
- },
- getWindowStyle: {
- args: [
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool,
- FFIType.bool
- ],
- returns: FFIType.u32
- },
- setJSUtils: {
- args: [
- FFIType.function,
- FFIType.function
- ],
- returns: FFIType.void
- },
- setWindowIcon: {
- args: [
- FFIType.ptr,
- FFIType.cstring
- ],
- returns: FFIType.void
- },
- killApp: {
- args: [],
- returns: FFIType.void
- },
- stopEventLoop: {
- args: [],
- returns: FFIType.void
- },
- waitForShutdownComplete: {
- args: [FFIType.i32],
- returns: FFIType.void
- },
- forceExit: {
- args: [FFIType.i32],
- returns: FFIType.void
- },
- setQuitRequestedHandler: {
- args: [FFIType.function],
- returns: FFIType.void
- },
- testFFI2: {
- args: [FFIType.function],
- returns: FFIType.void
- }
- });
- } catch (err) {
- console.log("FATAL Error opening native FFI:", err.message);
- console.log("This may be due to:");
- console.log(" - Missing libNativeWrapper.dll/so/dylib");
- console.log(" - Architecture mismatch (ARM64 vs x64)");
- console.log(" - Missing WebView2 or CEF dependencies");
- if (suffix === "so") {
- console.log(" - Missing system libraries (try: ldd ./libNativeWrapper.so)");
- }
- console.log("Check that the build process completed successfully for your architecture.");
- process.exit();
- }
- })();
- ffi = {
- request: {
- createWindow: (params) => {
- const {
- id,
- url: _url,
- title,
- frame: { x, y, width, height },
- styleMask: {
- Borderless,
- Titled,
- Closable,
- Miniaturizable,
- Resizable,
- UnifiedTitleAndToolbar,
- FullScreen,
- FullSizeContentView,
- UtilityWindow,
- DocModalWindow,
- NonactivatingPanel,
- HUDWindow
- },
- titleBarStyle,
- transparent,
- hidden = false
- } = params;
- const styleMask = native.symbols.getWindowStyle(Borderless, Titled, Closable, Miniaturizable, Resizable, UnifiedTitleAndToolbar, FullScreen, FullSizeContentView, UtilityWindow, DocModalWindow, NonactivatingPanel, HUDWindow);
- const windowPtr = native.symbols.createWindowWithFrameAndStyleFromWorker(id, x, y, width, height, styleMask, toCString(titleBarStyle), transparent, windowCloseCallback, windowMoveCallback, windowResizeCallback, windowFocusCallback, windowBlurCallback, windowKeyCallback);
- if (!windowPtr) {
- throw "Failed to create window";
- }
- native.symbols.setWindowTitle(windowPtr, toCString(title));
- if (!hidden) {
- native.symbols.showWindow(windowPtr);
- }
- return windowPtr;
- },
- setTitle: (params) => {
- const { winId, title } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't add webview to window. window no longer exists`;
- }
- native.symbols.setWindowTitle(windowPtr, toCString(title));
- },
- closeWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return;
- }
- native.symbols.closeWindow(windowPtr);
- },
- focusWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't focus window. Window no longer exists`;
- }
- native.symbols.showWindow(windowPtr);
- },
- minimizeWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't minimize window. Window no longer exists`;
- }
- native.symbols.minimizeWindow(windowPtr);
- },
- restoreWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't restore window. Window no longer exists`;
- }
- native.symbols.restoreWindow(windowPtr);
- },
- isWindowMinimized: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return false;
- }
- return native.symbols.isWindowMinimized(windowPtr);
- },
- maximizeWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't maximize window. Window no longer exists`;
- }
- native.symbols.maximizeWindow(windowPtr);
- },
- unmaximizeWindow: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't unmaximize window. Window no longer exists`;
- }
- native.symbols.unmaximizeWindow(windowPtr);
- },
- isWindowMaximized: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return false;
- }
- return native.symbols.isWindowMaximized(windowPtr);
- },
- setWindowFullScreen: (params) => {
- const { winId, fullScreen } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't set fullscreen. Window no longer exists`;
- }
- native.symbols.setWindowFullScreen(windowPtr, fullScreen);
- },
- isWindowFullScreen: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return false;
- }
- return native.symbols.isWindowFullScreen(windowPtr);
- },
- setWindowAlwaysOnTop: (params) => {
- const { winId, alwaysOnTop } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't set always on top. Window no longer exists`;
- }
- native.symbols.setWindowAlwaysOnTop(windowPtr, alwaysOnTop);
- },
- isWindowAlwaysOnTop: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return false;
- }
- return native.symbols.isWindowAlwaysOnTop(windowPtr);
- },
- setWindowVisibleOnAllWorkspaces: (params) => {
- const { winId, visibleOnAllWorkspaces } = params;
- const windowPtr = BrowserWindow.getById(winId)?.ptr;
- if (!windowPtr) {
- throw `Can't set visible on all workspaces. Window no longer exists`;
- }
- native.symbols.setWindowVisibleOnAllWorkspaces(windowPtr, visibleOnAllWorkspaces);
- },
- isWindowVisibleOnAllWorkspaces: (params) => {
- const { winId } = params;
- const windowPtr = BrowserWindow.getById(winId)?.ptr;
- if (!windowPtr) {
- return false;
- }
- return native.symbols.isWindowVisibleOnAllWorkspaces(windowPtr);
- },
- setWindowPosition: (params) => {
- const { winId, x, y } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't set window position. Window no longer exists`;
- }
- native.symbols.setWindowPosition(windowPtr, x, y);
- },
- setWindowSize: (params) => {
- const { winId, width, height } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't set window size. Window no longer exists`;
- }
- native.symbols.setWindowSize(windowPtr, width, height);
- },
- setWindowFrame: (params) => {
- const { winId, x, y, width, height } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- throw `Can't set window frame. Window no longer exists`;
- }
- native.symbols.setWindowFrame(windowPtr, x, y, width, height);
- },
- getWindowFrame: (params) => {
- const { winId } = params;
- const windowPtr = getWindowPtr(winId);
- if (!windowPtr) {
- return { x: 0, y: 0, width: 0, height: 0 };
- }
- const xBuf = new Float64Array(1);
- const yBuf = new Float64Array(1);
- const widthBuf = new Float64Array(1);
- const heightBuf = new Float64Array(1);
- native.symbols.getWindowFrame(windowPtr, ptr(xBuf), ptr(yBuf), ptr(widthBuf), ptr(heightBuf));
- return {
- x: xBuf[0],
- y: yBuf[0],
- width: widthBuf[0],
- height: heightBuf[0]
- };
- },
- createWebview: (params) => {
- const {
- id,
- windowId,
- renderer,
- rpcPort: rpcPort2,
- secretKey,
- url,
- partition,
- preload,
- viewsRoot,
- frame: { x, y, width, height },
- autoResize,
- sandbox,
- startTransparent,
- startPassthrough
- } = params;
- const parentWindow = BrowserWindow.getById(windowId);
- const windowPtr = parentWindow?.ptr;
- const transparent = parentWindow?.transparent ?? false;
- if (!windowPtr) {
- throw `Can't add webview to window. window no longer exists`;
- }
- let dynamicPreload;
- let selectedPreloadScript;
- if (sandbox) {
- dynamicPreload = `
-window.__electrobunWebviewId = ${id};
-window.__electrobunWindowId = ${windowId};
-window.__electrobunEventBridge = window.__electrobunEventBridge || window.webkit?.messageHandlers?.eventBridge || window.eventBridge || window.chrome?.webview?.hostObjects?.eventBridge;
-window.__electrobunInternalBridge = window.__electrobunInternalBridge || window.webkit?.messageHandlers?.internalBridge || window.internalBridge || window.chrome?.webview?.hostObjects?.internalBridge;
-`;
- selectedPreloadScript = preloadScriptSandboxed;
- } else {
- dynamicPreload = `
-window.__electrobunWebviewId = ${id};
-window.__electrobunWindowId = ${windowId};
-window.__electrobunRpcSocketPort = ${rpcPort2};
-window.__electrobunSecretKeyBytes = [${secretKey}];
-window.__electrobunEventBridge = window.__electrobunEventBridge || window.webkit?.messageHandlers?.eventBridge || window.eventBridge || window.chrome?.webview?.hostObjects?.eventBridge;
-window.__electrobunInternalBridge = window.__electrobunInternalBridge || window.webkit?.messageHandlers?.internalBridge || window.internalBridge || window.chrome?.webview?.hostObjects?.internalBridge;
-window.__electrobunBunBridge = window.__electrobunBunBridge || window.webkit?.messageHandlers?.bunBridge || window.bunBridge || window.chrome?.webview?.hostObjects?.bunBridge;
-`;
- selectedPreloadScript = preloadScript;
- }
- const electrobunPreload = dynamicPreload + selectedPreloadScript;
- const customPreload = preload;
- native.symbols.setNextWebviewFlags(startTransparent, startPassthrough);
- const webviewPtr = native.symbols.initWebview(id, windowPtr, toCString(renderer), toCString(url || ""), x, y, width, height, autoResize, toCString(partition || "persist:default"), webviewDecideNavigation, webviewEventJSCallback, eventBridgeHandler, bunBridgePostmessageHandler, internalBridgeHandler, toCString(electrobunPreload), toCString(customPreload || ""), toCString(viewsRoot || ""), transparent, sandbox);
- if (!webviewPtr) {
- throw "Failed to create webview";
- }
- return webviewPtr;
- },
- createWGPUView: (params) => {
- const {
- id,
- windowId,
- frame: { x, y, width, height },
- autoResize,
- startTransparent,
- startPassthrough
- } = params;
- const windowPtr = getWindowPtr(windowId);
- if (!windowPtr) {
- throw `Can't add WGPUView to window. window no longer exists`;
- }
- const viewPtr = native.symbols.initWGPUView(id, windowPtr, x, y, width, height, autoResize, startTransparent, startPassthrough);
- if (!viewPtr) {
- throw "Failed to create WGPUView";
- }
- return viewPtr;
- },
- wgpuViewSetFrame: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewSetFrame: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetFrame(view.ptr, params.x, params.y, params.width, params.height);
- },
- wgpuViewSetTransparent: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewSetTransparent: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetTransparent(view.ptr, params.transparent);
- },
- wgpuViewSetPassthrough: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewSetPassthrough: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetPassthrough(view.ptr, params.passthrough);
- },
- wgpuViewSetHidden: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewSetHidden: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetHidden(view.ptr, params.hidden);
- },
- wgpuViewRemove: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewRemove: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewRemove(view.ptr);
- },
- wgpuViewGetNativeHandle: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuViewGetNativeHandle: WGPUView not found or has no ptr for id ${params.id}`);
- return null;
- }
- const handle = native.symbols.wgpuViewGetNativeHandle(view.ptr);
- return handle || null;
- },
- evaluateJavascriptWithNoCompletion: (params) => {
- const { id, js } = params;
- const webview = BrowserView.getById(id);
- if (!webview?.ptr) {
- return;
- }
- native.symbols.evaluateJavaScriptWithNoCompletion(webview.ptr, toCString(js));
- },
- createTray: (params) => {
- const { id, title, image, template, width, height } = params;
- const trayPtr = native.symbols.createTray(id, toCString(title), toCString(image), template, width, height, trayItemHandler);
- if (!trayPtr) {
- throw "Failed to create tray";
- }
- return trayPtr;
- },
- setTrayTitle: (params) => {
- const { id, title } = params;
- const tray = Tray.getById(id);
- if (!tray)
- return;
- native.symbols.setTrayTitle(tray.ptr, toCString(title));
- },
- setTrayImage: (params) => {
- const { id, image } = params;
- const tray = Tray.getById(id);
- if (!tray)
- return;
- native.symbols.setTrayImage(tray.ptr, toCString(image));
- },
- setTrayMenu: (params) => {
- const { id, menuConfig } = params;
- const tray = Tray.getById(id);
- if (!tray)
- return;
- native.symbols.setTrayMenu(tray.ptr, toCString(menuConfig));
- },
- removeTray: (params) => {
- const { id } = params;
- const tray = Tray.getById(id);
- if (!tray) {
- throw `Can't remove tray. Tray no longer exists`;
- }
- native.symbols.removeTray(tray.ptr);
- },
- getTrayBounds: (params) => {
- const tray = Tray.getById(params.id);
- if (!tray?.ptr) {
- return { x: 0, y: 0, width: 0, height: 0 };
- }
- const jsonStr = native.symbols.getTrayBounds(tray.ptr);
- if (!jsonStr) {
- return { x: 0, y: 0, width: 0, height: 0 };
- }
- try {
- return JSON.parse(jsonStr.toString());
- } catch {
- return { x: 0, y: 0, width: 0, height: 0 };
- }
- },
- setApplicationMenu: (params) => {
- const { menuConfig } = params;
- native.symbols.setApplicationMenu(toCString(menuConfig), applicationMenuHandler);
- },
- showContextMenu: (params) => {
- const { menuConfig } = params;
- native.symbols.showContextMenu(toCString(menuConfig), contextMenuHandler);
- },
- moveToTrash: (params) => {
- const { path } = params;
- return native.symbols.moveToTrash(toCString(path));
- },
- showItemInFolder: (params) => {
- const { path } = params;
- native.symbols.showItemInFolder(toCString(path));
- },
- openExternal: (params) => {
- const { url } = params;
- return native.symbols.openExternal(toCString(url));
- },
- openPath: (params) => {
- const { path } = params;
- return native.symbols.openPath(toCString(path));
- },
- showNotification: (params) => {
- const { title, body = "", subtitle = "", silent = false } = params;
- native.symbols.showNotification(toCString(title), toCString(body), toCString(subtitle), silent);
- },
- setDockIconVisible: (params) => {
- native.symbols.setDockIconVisible(params.visible);
- },
- isDockIconVisible: () => {
- return native.symbols.isDockIconVisible();
- },
- openFileDialog: (params) => {
- const {
- startingFolder,
- allowedFileTypes,
- canChooseFiles,
- canChooseDirectory,
- allowsMultipleSelection
- } = params;
- const filePath = native.symbols.openFileDialog(toCString(startingFolder), toCString(allowedFileTypes), canChooseFiles ? 1 : 0, canChooseDirectory ? 1 : 0, allowsMultipleSelection ? 1 : 0);
- return filePath.toString();
- },
- showMessageBox: (params) => {
- const {
- type = "info",
- title = "",
- message = "",
- detail = "",
- buttons = ["OK"],
- defaultId = 0,
- cancelId = -1
- } = params;
- const buttonsStr = buttons.join(",");
- return native.symbols.showMessageBox(toCString(type), toCString(title), toCString(message), toCString(detail), toCString(buttonsStr), defaultId, cancelId);
- },
- clipboardReadText: () => {
- const result = native.symbols.clipboardReadText();
- if (!result)
- return null;
- return result.toString();
- },
- clipboardWriteText: (params) => {
- native.symbols.clipboardWriteText(toCString(params.text));
- },
- clipboardReadImage: () => {
- const sizeBuffer = new BigUint64Array(1);
- const dataPtr = native.symbols.clipboardReadImage(ptr(sizeBuffer));
- if (!dataPtr)
- return null;
- const size = Number(sizeBuffer[0]);
- if (size === 0)
- return null;
- const result = new Uint8Array(size);
- const sourceView = new Uint8Array(toArrayBuffer(dataPtr, 0, size));
- result.set(sourceView);
- return result;
- },
- clipboardWriteImage: (params) => {
- const { pngData } = params;
- native.symbols.clipboardWriteImage(ptr(pngData), BigInt(pngData.length));
- },
- clipboardClear: () => {
- native.symbols.clipboardClear();
- },
- clipboardAvailableFormats: () => {
- const result = native.symbols.clipboardAvailableFormats();
- if (!result)
- return [];
- const formatsStr = result.toString();
- if (!formatsStr)
- return [];
- return formatsStr.split(",").filter((f) => f.length > 0);
- }
- },
- internal: {
- storeMenuData,
- getMenuData,
- clearMenuData,
- serializeMenuAction,
- deserializeMenuAction
- }
- };
- WGPUBridge = {
- available: !!native?.symbols?.wgpuInstanceCreateSurfaceMainThread,
- instanceCreateSurface: (instancePtr, descriptorPtr) => native.symbols.wgpuInstanceCreateSurfaceMainThread(instancePtr, descriptorPtr),
- surfaceConfigure: (surfacePtr, configPtr) => native.symbols.wgpuSurfaceConfigureMainThread(surfacePtr, configPtr),
- surfaceGetCurrentTexture: (surfacePtr, surfaceTexturePtr) => native.symbols.wgpuSurfaceGetCurrentTextureMainThread(surfacePtr, surfaceTexturePtr),
- surfacePresent: (surfacePtr) => native.symbols.wgpuSurfacePresentMainThread(surfacePtr),
- queueOnSubmittedWorkDone: (queuePtr, callbackInfoPtr) => native.symbols.wgpuQueueOnSubmittedWorkDoneShim(queuePtr, callbackInfoPtr),
- bufferMapAsync: (bufferPtr, mode, offset, size, callbackInfoPtr) => native.symbols.wgpuBufferMapAsyncShim(bufferPtr, mode, offset, size, callbackInfoPtr),
- instanceWaitAny: (instancePtr, futureId, timeoutNs) => native.symbols.wgpuInstanceWaitAnyShim(instancePtr, futureId, timeoutNs),
- bufferReadSync: (instancePtr, bufferPtr, offset, size, timeoutNs, outSizePtr) => native.symbols.wgpuBufferReadSyncShim(instancePtr, bufferPtr, offset, size, timeoutNs, outSizePtr),
- bufferReadSyncInto: (instancePtr, bufferPtr, offset, size, timeoutNs, dstPtr) => native.symbols.wgpuBufferReadSyncIntoShim(instancePtr, bufferPtr, offset, size, timeoutNs, dstPtr),
- bufferReadbackBegin: (bufferPtr, offset, size, dstPtr) => native.symbols.wgpuBufferReadbackBeginShim(bufferPtr, offset, size, dstPtr),
- bufferReadbackStatus: (jobPtr) => native.symbols.wgpuBufferReadbackStatusShim(jobPtr),
- bufferReadbackFree: (jobPtr) => native.symbols.wgpuBufferReadbackFreeShim(jobPtr),
- runTest: (viewId) => {
- const view = WGPUView.getById(viewId);
- if (!view?.ptr) {
- console.error(`wgpuRunGPUTest: WGPUView not found for id ${viewId}`);
- return;
- }
- if (!native?.symbols?.wgpuRunGPUTest) {
- console.error("wgpuRunGPUTest not available");
- return;
- }
- native.symbols.wgpuRunGPUTest(view.ptr);
- },
- createAdapterDeviceMainThread: (instancePtr, surfacePtr, outAdapterDevicePtr) => native.symbols.wgpuCreateAdapterDeviceMainThread(instancePtr, surfacePtr, outAdapterDevicePtr),
- createSurfaceForView: (instancePtr, viewPtr) => {
- if (!native?.symbols?.wgpuCreateSurfaceForView)
- return null;
- return native.symbols.wgpuCreateSurfaceForView(instancePtr, viewPtr);
- }
- };
- process.on("uncaughtException", (err) => {
- console.error("Uncaught exception in worker:", err);
- native.symbols.stopEventLoop();
- native.symbols.waitForShutdownComplete(5000);
- native.symbols.forceExit(1);
- });
- process.on("unhandledRejection", (reason, _promise) => {
- console.error("Unhandled rejection in worker:", reason);
- });
- process.on("SIGINT", () => {
- console.log("[electrobun] Received SIGINT, running quit sequence...");
- const { quit: quit2 } = (init_Utils(), __toCommonJS(exports_Utils));
- quit2();
- });
- process.on("SIGTERM", () => {
- console.log("[electrobun] Received SIGTERM, running quit sequence...");
- const { quit: quit2 } = (init_Utils(), __toCommonJS(exports_Utils));
- quit2();
- });
- windowCloseCallback = new JSCallback((id) => {
- const handler = eventEmitter_default.events.window.close;
- const event = handler({
- id
- });
- eventEmitter_default.emitEvent(event, id);
- eventEmitter_default.emitEvent(event);
- }, {
- args: ["u32"],
- returns: "void",
- threadsafe: true
- });
- windowMoveCallback = new JSCallback((id, x, y) => {
- const handler = eventEmitter_default.events.window.move;
- const event = handler({
- id,
- x,
- y
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: ["u32", "f64", "f64"],
- returns: "void",
- threadsafe: true
- });
- windowResizeCallback = new JSCallback((id, x, y, width, height) => {
- const handler = eventEmitter_default.events.window.resize;
- const event = handler({
- id,
- x,
- y,
- width,
- height
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: ["u32", "f64", "f64", "f64", "f64"],
- returns: "void",
- threadsafe: true
- });
- windowFocusCallback = new JSCallback((id) => {
- const handler = eventEmitter_default.events.window.focus;
- const event = handler({
- id
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: ["u32"],
- returns: "void",
- threadsafe: true
- });
- windowBlurCallback = new JSCallback((id) => {
- const handler = eventEmitter_default.events.window.blur;
- const event = handler({
- id
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: ["u32"],
- returns: "void",
- threadsafe: true
- });
- windowKeyCallback = new JSCallback((id, keyCode, modifiers, isDown, isRepeat) => {
- const handler = isDown ? eventEmitter_default.events.window.keyDown : eventEmitter_default.events.window.keyUp;
- const event = handler({
- id,
- keyCode,
- modifiers,
- isRepeat: !!isRepeat
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: ["u32", "u32", "u32", "u32", "u32"],
- returns: "void",
- threadsafe: true
- });
- getMimeType = new JSCallback((filePath) => {
- const _filePath = new CString(filePath).toString();
- const mimeType = Bun.file(_filePath).type;
- return toCString(mimeType.split(";")[0]);
- }, {
- args: [FFIType.cstring],
- returns: FFIType.cstring
- });
- getHTMLForWebviewSync = new JSCallback((webviewId) => {
- const webview = BrowserView.getById(webviewId);
- return toCString(webview?.html || "");
- }, {
- args: [FFIType.u32],
- returns: FFIType.cstring
- });
- native.symbols.setJSUtils(getMimeType, getHTMLForWebviewSync);
- urlOpenCallback = new JSCallback((urlPtr) => {
- const url = new CString(urlPtr).toString();
- const handler = eventEmitter_default.events.app.openUrl;
- const event = handler({ url });
- eventEmitter_default.emitEvent(event);
- }, {
- args: [FFIType.cstring],
- returns: "void",
- threadsafe: true
- });
- if (process.platform === "darwin") {
- native.symbols.setURLOpenHandler(urlOpenCallback);
- }
- appReopenCallback = new JSCallback(() => {
- if (process.platform === "darwin") {
- native.symbols.setDockIconVisible(true);
- }
- const handler = eventEmitter_default.events.app.reopen;
- const event = handler({});
- eventEmitter_default.emitEvent(event);
- }, {
- args: [],
- returns: "void",
- threadsafe: true
- });
- if (process.platform === "darwin") {
- native.symbols.setAppReopenHandler(appReopenCallback);
- }
- quitRequestedCallback = new JSCallback(() => {
- const { quit: quit2 } = (init_Utils(), __toCommonJS(exports_Utils));
- quit2();
- }, {
- args: [],
- returns: "void",
- threadsafe: true
- });
- native.symbols.setQuitRequestedHandler(quitRequestedCallback);
- globalShortcutHandlers = new Map;
- globalShortcutCallback = new JSCallback((acceleratorPtr) => {
- const accelerator = new CString(acceleratorPtr).toString();
- const handler = globalShortcutHandlers.get(accelerator);
- if (handler) {
- handler();
- }
- }, {
- args: [FFIType.cstring],
- returns: "void",
- threadsafe: true
- });
- native.symbols.setGlobalShortcutCallback(globalShortcutCallback);
- sessionCache = new Map;
- webviewDecideNavigation = new JSCallback((_webviewId, _url) => {
- return true;
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.u32,
- threadsafe: true
- });
- webviewEventJSCallback = new JSCallback((id, _eventName, _detail) => {
- let eventName = "";
- let detail = "";
- try {
- eventName = new CString(_eventName).toString();
- detail = new CString(_detail).toString();
- } catch (err) {
- console.error("[webviewEventJSCallback] Error converting strings:", err);
- console.error("[webviewEventJSCallback] Raw values:", {
- _eventName,
- _detail
- });
- return;
- }
- webviewEventHandler(id, eventName, detail);
- }, {
- args: [FFIType.u32, FFIType.cstring, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- bunBridgePostmessageHandler = new JSCallback((id, msg) => {
- try {
- const msgStr = new CString(msg);
- if (!msgStr.length) {
- return;
- }
- const rawMessage = msgStr.toString().trim();
- if (!rawMessage || rawMessage[0] !== "{" && rawMessage[0] !== "[") {
- return;
- }
- const msgJson = JSON.parse(rawMessage);
- const webview = BrowserView.getById(id);
- if (!webview)
- return;
- webview.rpcHandler?.(msgJson);
- } catch (err) {
- console.error("error sending message to bun: ", err);
- }
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- eventBridgeHandler = new JSCallback((_id, msg) => {
- try {
- const message = new CString(msg);
- const rawMessage = message.toString().trim();
- if (!rawMessage || rawMessage[0] !== "{" && rawMessage[0] !== "[") {
- return;
- }
- const jsonMessage = JSON.parse(rawMessage);
- if (jsonMessage.id === "webviewEvent") {
- const { payload } = jsonMessage;
- webviewEventHandler(payload.id, payload.eventName, payload.detail);
- }
- } catch (err) {
- console.error("error in eventBridgeHandler: ", err);
- }
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- internalBridgeHandler = new JSCallback((_id, msg) => {
- try {
- const batchMessage = new CString(msg);
- const jsonBatch = JSON.parse(batchMessage.toString());
- if (jsonBatch.id === "webviewEvent") {
- const { payload } = jsonBatch;
- webviewEventHandler(payload.id, payload.eventName, payload.detail);
- return;
- }
- jsonBatch.forEach((msgStr) => {
- const msgJson = JSON.parse(msgStr);
- if (msgJson.type === "message") {
- const handler = internalRpcHandlers.message[msgJson.id];
- handler?.(msgJson.payload);
- } else if (msgJson.type === "request") {
- const hostWebview = BrowserView.getById(msgJson.hostWebviewId);
- const handler = internalRpcHandlers.request[msgJson.method];
- const payload = handler?.(msgJson.params);
- const resultObj = {
- type: "response",
- id: msgJson.id,
- success: true,
- payload
- };
- if (!hostWebview) {
- console.log("--->>> internal request in bun: NO HOST WEBVIEW FOUND");
- return;
- }
- hostWebview.sendInternalMessageViaExecute(resultObj);
- }
- });
- } catch (err) {
- console.error("error in internalBridgeHandler: ", err);
- }
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- trayItemHandler = new JSCallback((id, action) => {
- const actionString = (new CString(action).toString() || "").trim();
- const { action: actualAction, data } = deserializeMenuAction(actionString);
- const event = eventEmitter_default.events.tray.trayClicked({
- id,
- action: actualAction,
- data
- });
- eventEmitter_default.emitEvent(event);
- eventEmitter_default.emitEvent(event, id);
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- applicationMenuHandler = new JSCallback((id, action) => {
- const actionString = new CString(action).toString();
- const { action: actualAction, data } = deserializeMenuAction(actionString);
- const event = eventEmitter_default.events.app.applicationMenuClicked({
- id,
- action: actualAction,
- data
- });
- eventEmitter_default.emitEvent(event);
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- contextMenuHandler = new JSCallback((_id, action) => {
- const actionString = new CString(action).toString();
- const { action: actualAction, data } = deserializeMenuAction(actionString);
- const event = eventEmitter_default.events.app.contextMenuClicked({
- action: actualAction,
- data
- });
- eventEmitter_default.emitEvent(event);
- }, {
- args: [FFIType.u32, FFIType.cstring],
- returns: FFIType.void,
- threadsafe: true
- });
- internalRpcHandlers = {
- request: {
- webviewTagInit: (params) => {
- const {
- hostWebviewId,
- windowId,
- renderer,
- html,
- preload,
- partition,
- frame,
- navigationRules,
- sandbox,
- transparent,
- passthrough
- } = params;
- const url = !params.url && !html ? "https://electrobun.dev" : params.url;
- const webviewForTag = new BrowserView({
- url,
- html,
- preload,
- partition,
- frame,
- hostWebviewId,
- autoResize: false,
- windowId,
- renderer,
- navigationRules,
- sandbox,
- startTransparent: transparent,
- startPassthrough: passthrough
- });
- return webviewForTag.id;
- },
- wgpuTagInit: (params) => {
- const {
- windowId,
- frame,
- transparent,
- passthrough
- } = params;
- const viewForTag = new WGPUView({
- windowId,
- frame,
- autoResize: false,
- startTransparent: transparent,
- startPassthrough: passthrough
- });
- return viewForTag.id;
- },
- webviewTagCanGoBack: (params) => {
- const { id } = params;
- const webviewPtr = BrowserView.getById(id)?.ptr;
- if (!webviewPtr) {
- console.error("no webview ptr");
- return false;
- }
- return native.symbols.webviewCanGoBack(webviewPtr);
- },
- webviewTagCanGoForward: (params) => {
- const { id } = params;
- const webviewPtr = BrowserView.getById(id)?.ptr;
- if (!webviewPtr) {
- console.error("no webview ptr");
- return false;
- }
- return native.symbols.webviewCanGoForward(webviewPtr);
- }
- },
- message: {
- webviewTagResize: (params) => {
- const browserView = BrowserView.getById(params.id);
- const webviewPtr = browserView?.ptr;
- if (!webviewPtr) {
- console.log("[Bun] ERROR: webviewTagResize - no webview ptr found for id:", params.id);
- return;
- }
- const { x, y, width, height } = params.frame;
- native.symbols.resizeWebview(webviewPtr, x, y, width, height, toCString(params.masks));
- },
- wgpuTagResize: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagResize: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- const { x, y, width, height } = params.frame;
- native.symbols.resizeWebview(view.ptr, x, y, width, height, toCString(params.masks ?? "[]"));
- },
- webviewTagUpdateSrc: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagUpdateSrc: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.loadURLInWebView(webview.ptr, toCString(params.url));
- },
- webviewTagUpdateHtml: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagUpdateHtml: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.setWebviewHTMLContent(webview.id, toCString(params.html));
- webview.loadHTML(params.html);
- webview.html = params.html;
- },
- webviewTagUpdatePreload: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagUpdatePreload: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.updatePreloadScriptToWebView(webview.ptr, toCString("electrobun_custom_preload_script"), toCString(params.preload), true);
- },
- webviewTagGoBack: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagGoBack: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewGoBack(webview.ptr);
- },
- webviewTagGoForward: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagGoForward: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewGoForward(webview.ptr);
- },
- webviewTagReload: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagReload: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewReload(webview.ptr);
- },
- webviewTagRemove: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagRemove: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewRemove(webview.ptr);
- },
- startWindowMove: (params) => {
- const windowPtr = getWindowPtr(params.id);
- if (!windowPtr)
- return;
- native.symbols.startWindowMove(windowPtr);
- },
- stopWindowMove: (_params) => {
- native.symbols.stopWindowMove();
- },
- webviewTagSetTransparent: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagSetTransparent: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewSetTransparent(webview.ptr, params.transparent);
- },
- wgpuTagSetTransparent: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagSetTransparent: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetTransparent(view.ptr, params.transparent);
- },
- webviewTagSetPassthrough: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagSetPassthrough: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewSetPassthrough(webview.ptr, params.enablePassthrough);
- },
- wgpuTagSetPassthrough: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagSetPassthrough: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetPassthrough(view.ptr, params.passthrough);
- },
- webviewTagSetHidden: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagSetHidden: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewSetHidden(webview.ptr, params.hidden);
- },
- wgpuTagSetHidden: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagSetHidden: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.wgpuViewSetHidden(view.ptr, params.hidden);
- },
- wgpuTagRemove: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagRemove: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- view.remove();
- },
- wgpuTagRunTest: (params) => {
- const view = WGPUView.getById(params.id);
- if (!view?.ptr) {
- console.error(`wgpuTagRunTest: WGPUView not found or has no ptr for id ${params.id}`);
- return;
- }
- if (!native?.symbols?.wgpuRunGPUTest) {
- console.error("wgpuTagRunTest: wgpuRunGPUTest not available");
- return;
- }
- native.symbols.wgpuRunGPUTest(view.ptr);
- },
- webviewTagSetNavigationRules: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagSetNavigationRules: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- const rulesJson = JSON.stringify(params.rules);
- native.symbols.setWebviewNavigationRules(webview.ptr, toCString(rulesJson));
- },
- webviewTagFindInPage: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagFindInPage: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewFindInPage(webview.ptr, toCString(params.searchText), params.forward, params.matchCase);
- },
- webviewTagStopFind: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagStopFind: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewStopFind(webview.ptr);
- },
- webviewTagOpenDevTools: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagOpenDevTools: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewOpenDevTools(webview.ptr);
- },
- webviewTagCloseDevTools: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagCloseDevTools: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewCloseDevTools(webview.ptr);
- },
- webviewTagToggleDevTools: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagToggleDevTools: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.webviewToggleDevTools(webview.ptr);
- },
- webviewTagExecuteJavascript: (params) => {
- const webview = BrowserView.getById(params.id);
- if (!webview || !webview.ptr) {
- console.error(`webviewTagExecuteJavascript: BrowserView not found or has no ptr for id ${params.id}`);
- return;
- }
- native.symbols.evaluateJavaScriptWithNoCompletion(webview.ptr, toCString(params.js));
- },
- webviewEvent: (params) => {
- console.log("-----------------+webviewEvent", params);
- }
- }
- };
-});
-
-// node_modules/electrobun/dist/api/bun/core/BrowserWindow.ts
-class BrowserWindow {
- id = getNextWindowId();
- ptr;
- title = "Electrobun";
- state = "creating";
- url = null;
- html = null;
- preload = null;
- viewsRoot = null;
- renderer = "native";
- transparent = false;
- passthrough = false;
- hidden = false;
- navigationRules = null;
- sandbox = false;
- frame = {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- };
- webviewId;
- constructor(options = defaultOptions4) {
- this.title = options.title || "New Window";
- this.frame = options.frame ? { ...defaultOptions4.frame, ...options.frame } : { ...defaultOptions4.frame };
- this.url = options.url || null;
- this.html = options.html || null;
- this.preload = options.preload || null;
- this.viewsRoot = options.viewsRoot || null;
- this.renderer = options.renderer || defaultOptions4.renderer;
- this.transparent = options.transparent ?? false;
- this.passthrough = options.passthrough ?? false;
- this.hidden = options.hidden ?? false;
- this.navigationRules = options.navigationRules || null;
- this.sandbox = options.sandbox ?? false;
- this.init(options);
- }
- init({
- rpc,
- styleMask,
- titleBarStyle,
- transparent,
- hidden
- }) {
- this.ptr = ffi.request.createWindow({
- id: this.id,
- title: this.title,
- url: this.url || "",
- frame: {
- width: this.frame.width,
- height: this.frame.height,
- x: this.frame.x,
- y: this.frame.y
- },
- styleMask: {
- Borderless: false,
- Titled: true,
- Closable: true,
- Miniaturizable: true,
- Resizable: true,
- UnifiedTitleAndToolbar: false,
- FullScreen: false,
- FullSizeContentView: false,
- UtilityWindow: false,
- DocModalWindow: false,
- NonactivatingPanel: false,
- HUDWindow: false,
- ...styleMask || {},
- ...titleBarStyle === "hiddenInset" ? {
- Titled: true,
- FullSizeContentView: true
- } : {},
- ...titleBarStyle === "hidden" ? {
- Titled: false,
- FullSizeContentView: true
- } : {}
- },
- titleBarStyle: titleBarStyle || "default",
- transparent: transparent ?? false,
- hidden: hidden ?? false
- });
- BrowserWindowMap[this.id] = this;
- const webview = new BrowserView({
- url: this.url,
- html: this.html,
- preload: this.preload,
- viewsRoot: this.viewsRoot,
- renderer: this.renderer,
- frame: {
- x: 0,
- y: 0,
- width: this.frame.width,
- height: this.frame.height
- },
- rpc,
- windowId: this.id,
- navigationRules: this.navigationRules,
- sandbox: this.sandbox,
- startPassthrough: this.passthrough
- });
- this.webviewId = webview.id;
- }
- get webview() {
- return BrowserView.getById(this.webviewId);
- }
- static getById(id) {
- return BrowserWindowMap[id];
- }
- setTitle(title) {
- this.title = title;
- return ffi.request.setTitle({ winId: this.id, title });
- }
- close() {
- return ffi.request.closeWindow({ winId: this.id });
- }
- focus() {
- return ffi.request.focusWindow({ winId: this.id });
- }
- show() {
- return ffi.request.focusWindow({ winId: this.id });
- }
- minimize() {
- return ffi.request.minimizeWindow({ winId: this.id });
- }
- unminimize() {
- return ffi.request.restoreWindow({ winId: this.id });
- }
- isMinimized() {
- return ffi.request.isWindowMinimized({ winId: this.id });
- }
- maximize() {
- return ffi.request.maximizeWindow({ winId: this.id });
- }
- unmaximize() {
- return ffi.request.unmaximizeWindow({ winId: this.id });
- }
- isMaximized() {
- return ffi.request.isWindowMaximized({ winId: this.id });
- }
- setFullScreen(fullScreen) {
- return ffi.request.setWindowFullScreen({ winId: this.id, fullScreen });
- }
- isFullScreen() {
- return ffi.request.isWindowFullScreen({ winId: this.id });
- }
- setAlwaysOnTop(alwaysOnTop) {
- return ffi.request.setWindowAlwaysOnTop({ winId: this.id, alwaysOnTop });
- }
- isAlwaysOnTop() {
- return ffi.request.isWindowAlwaysOnTop({ winId: this.id });
- }
- setVisibleOnAllWorkspaces(visibleOnAllWorkspaces) {
- return ffi.request.setWindowVisibleOnAllWorkspaces({ winId: this.id, visibleOnAllWorkspaces });
- }
- isVisibleOnAllWorkspaces() {
- return ffi.request.isWindowVisibleOnAllWorkspaces({ winId: this.id });
- }
- setPosition(x, y) {
- this.frame.x = x;
- this.frame.y = y;
- return ffi.request.setWindowPosition({ winId: this.id, x, y });
- }
- setSize(width, height) {
- this.frame.width = width;
- this.frame.height = height;
- return ffi.request.setWindowSize({ winId: this.id, width, height });
- }
- setFrame(x, y, width, height) {
- this.frame = { x, y, width, height };
- return ffi.request.setWindowFrame({ winId: this.id, x, y, width, height });
- }
- getFrame() {
- const frame = ffi.request.getWindowFrame({ winId: this.id });
- this.frame = frame;
- return frame;
- }
- getPosition() {
- const frame = this.getFrame();
- return { x: frame.x, y: frame.y };
- }
- getSize() {
- const frame = this.getFrame();
- return { width: frame.width, height: frame.height };
- }
- setPageZoom(zoomLevel) {
- this.webview?.setPageZoom(zoomLevel);
- }
- getPageZoom() {
- return this.webview?.getPageZoom() ?? 1;
- }
- on(name2, handler) {
- const specificName = `${name2}-${this.id}`;
- eventEmitter_default.on(specificName, handler);
- }
-}
-var buildConfig3, defaultOptions4, BrowserWindowMap;
-var init_BrowserWindow = __esm(async () => {
- init_eventEmitter();
- init_BuildConfig();
- await __promiseAll([
- init_native(),
- init_BrowserView(),
- init_Utils(),
- init_GpuWindow(),
- init_WGPUView()
- ]);
- buildConfig3 = await BuildConfig.get();
- defaultOptions4 = {
- title: "Electrobun",
- frame: {
- x: 0,
- y: 0,
- width: 800,
- height: 600
- },
- url: "https://electrobun.dev",
- html: null,
- preload: null,
- viewsRoot: null,
- renderer: buildConfig3.defaultRenderer,
- titleBarStyle: "default",
- transparent: false,
- passthrough: false,
- hidden: false,
- navigationRules: null,
- sandbox: false
- };
- BrowserWindowMap = {};
- eventEmitter_default.on("close", (event) => {
- const windowId = event.data.id;
- delete BrowserWindowMap[windowId];
- for (const view of BrowserView.getAll()) {
- if (view.windowId === windowId) {
- view.remove();
- }
- }
- const wgpuViews = WGPUView.getAll().filter((v) => v.windowId === windowId);
- for (const view of wgpuViews) {
- try {
- if (view.ptr === null) {} else {
- view.remove();
- }
- } catch (e) {
- console.error(`Error cleaning up WGPU view ${view.id}:`, e);
- view.ptr = null;
- }
- }
- const exitOnLastWindowClosed = buildConfig3.runtime?.exitOnLastWindowClosed ?? true;
- if (exitOnLastWindowClosed && Object.keys(BrowserWindowMap).length === 0 && Object.keys(GpuWindowMap).length === 0) {
- quit();
- }
- });
-});
-
-// node_modules/@babylonjs/core/Actions/abstractActionManager.js
-class AbstractActionManager {
- constructor() {
- this.hoverCursor = "";
- this.actions = [];
- this.isRecursive = false;
- this.disposeWhenUnowned = true;
- }
- static get HasTriggers() {
- for (const t in AbstractActionManager.Triggers) {
- if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {
- return true;
- }
- }
- return false;
- }
- 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;
- }
- 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;
- }
-}
-var init_abstractActionManager = __esm(() => {
- AbstractActionManager.Triggers = {};
-});
-
-// node_modules/@babylonjs/core/Misc/observable.js
-class EventState {
- constructor(mask, skipNextObservers = false, target, currentTarget) {
- this.initialize(mask, skipNextObservers, target, currentTarget);
- }
- initialize(mask, skipNextObservers = false, target, currentTarget) {
- this.mask = mask;
- this.skipNextObservers = skipNextObservers;
- this.target = target;
- this.currentTarget = currentTarget;
- return this;
- }
-}
-
-class Observer {
- constructor(callback, mask, scope = null) {
- this.callback = callback;
- this.mask = mask;
- this.scope = scope;
- this._willBeUnregistered = false;
- this.unregisterOnNextCall = false;
- this._remove = null;
- }
- remove() {
- if (this._remove) {
- this._remove();
- }
- }
-}
-
-class 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;
- }
- get observers() {
- return this._observers;
- }
- constructor(onObserverAdded, 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 (this._hasNotified && this.notifyIfTriggered) {
- if (this._lastNotifiedValue !== undefined) {
- this.notifyObserver(observer, this._lastNotifiedValue);
- }
- }
- 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(observer) {
- if (!observer) {
- return false;
- }
- observer._remove = null;
- const index = this._observers.indexOf(observer);
- if (index !== -1) {
- this._deferUnregister(observer);
- return true;
- }
- return false;
- }
- 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;
- }
- _deferUnregister(observer) {
- if (observer._willBeUnregistered) {
- return;
- }
- this._numObserversMarkedAsDeleted++;
- observer.unregisterOnNextCall = false;
- observer._willBeUnregistered = true;
- setTimeout(() => {
- this._remove(observer);
- }, 0);
- }
- _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;
- }
- makeObserverTopPriority(observer) {
- this._remove(observer, false);
- this._observers.unshift(observer);
- }
- makeObserverBottomPriority(observer) {
- this._remove(observer, false);
- this._observers.push(observer);
- }
- notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) {
- 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;
- }
- notifyObserver(observer, eventData, mask = -1) {
- 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);
- }
- hasObservers() {
- return this._observers.length - this._numObserversMarkedAsDeleted > 0;
- }
- clear() {
- while (this._observers.length) {
- const o = this._observers.pop();
- if (o) {
- o._remove = null;
- }
- }
- this._onObserverAdded = null;
- this._numObserversMarkedAsDeleted = 0;
- this.cleanLastNotifiedState();
- }
- cleanLastNotifiedState() {
- this._hasNotified = false;
- this._lastNotifiedValue = undefined;
- }
- clone() {
- const result = new Observable;
- result._observers = this._observers.slice(0);
- return result;
- }
- hasSpecificMask(mask = -1) {
- for (const obs of this._observers) {
- if (obs.mask & mask || obs.mask === mask) {
- return true;
- }
- }
- return false;
- }
-}
-var isWeakRefSupported;
-var init_observable = __esm(() => {
- isWeakRefSupported = typeof WeakRef !== "undefined";
-});
-
-// node_modules/@babylonjs/core/Maths/math.constants.js
-var ToGammaSpace, ToLinearSpace = 2.2, PHI, Epsilon = 0.001;
-var init_math_constants = __esm(() => {
- ToGammaSpace = 1 / 2.2;
- PHI = (1 + Math.sqrt(5)) / 2;
-});
-
-// node_modules/@babylonjs/core/Misc/arrayTools.js
-function BuildArray(size, itemBuilder) {
- const a = [];
- for (let i = 0;i < size; ++i) {
- a.push(itemBuilder());
- }
- return a;
-}
-function BuildTuple(size, itemBuilder) {
- return BuildArray(size, itemBuilder);
-}
-function _observeArrayfunction(object, functionName, callback) {
- const oldFunction = object[functionName];
- if (typeof oldFunction !== "function") {
- return null;
- }
- const newFunction = function() {
- const previousLength = object.length;
- const returnValue = newFunction.previous.apply(object, arguments);
- callback(functionName, previousLength);
- return returnValue;
- };
- oldFunction.next = newFunction;
- newFunction.previous = oldFunction;
- object[functionName] = newFunction;
- return () => {
- const previous = newFunction.previous;
- if (!previous) {
- return;
- }
- const next = newFunction.next;
- if (next) {
- previous.next = next;
- next.previous = previous;
- } else {
- previous.next = undefined;
- object[functionName] = previous;
- }
- newFunction.next = undefined;
- newFunction.previous = undefined;
- };
-}
-function _ObserveArray(array, callback) {
- const unObserveFunctions = observedArrayFunctions.map((name2) => {
- return _observeArrayfunction(array, name2, callback);
- });
- return () => {
- unObserveFunctions.forEach((unObserveFunction) => {
- unObserveFunction?.();
- });
- };
-}
-var observedArrayFunctions;
-var init_arrayTools = __esm(() => {
- observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"];
-});
-
-// node_modules/@babylonjs/core/Misc/typeStore.js
-function RegisterClass(className, type) {
- _RegisteredTypes[className] = type;
-}
-function GetClass(fqdn) {
- return _RegisteredTypes[fqdn];
-}
-var _RegisteredTypes;
-var init_typeStore = __esm(() => {
- _RegisteredTypes = {};
-});
-
-// node_modules/@babylonjs/core/Engines/performanceConfigurator.js
-class PerformanceConfigurator {
- 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;
- }
-}
-var init_performanceConfigurator = __esm(() => {
- PerformanceConfigurator.MatrixUse64Bits = false;
- PerformanceConfigurator.MatrixTrackPrecisionChange = true;
- PerformanceConfigurator.MatrixCurrentType = Float32Array;
- PerformanceConfigurator.MatrixTrackedMatrices = [];
-});
-
-// node_modules/@babylonjs/core/Engines/engineStore.js
-class EngineStore {
- static get LastCreatedEngine() {
- if (this.Instances.length === 0) {
- return null;
- }
- return this.Instances[this.Instances.length - 1];
- }
- static get LastCreatedScene() {
- return this._LastCreatedScene;
- }
-}
-var init_engineStore = __esm(() => {
- init_observable();
- EngineStore.Instances = [];
- EngineStore.OnEnginesDisposedObservable = new Observable;
- EngineStore._LastCreatedScene = null;
- EngineStore.UseFallbackTexture = true;
- EngineStore.FallbackTexture = "";
-});
-
-// node_modules/@babylonjs/core/Maths/math.scalar.functions.js
-var exports_math_scalar_functions = {};
-__export(exports_math_scalar_functions, {
- WithinEpsilon: () => WithinEpsilon,
- ToHex: () => ToHex,
- SmoothStep: () => SmoothStep,
- Repeat: () => Repeat,
- RangeToPercent: () => RangeToPercent,
- RandomRange: () => RandomRange,
- PingPong: () => PingPong,
- PercentToRange: () => PercentToRange,
- OutsideRange: () => OutsideRange,
- NormalizeRadians: () => NormalizeRadians,
- Normalize: () => Normalize,
- MoveTowardsAngle: () => MoveTowardsAngle,
- MoveTowards: () => MoveTowards,
- LerpAngle: () => LerpAngle,
- Lerp: () => Lerp,
- InverseLerp: () => InverseLerp,
- ILog2: () => ILog2,
- HighestCommonFactor: () => HighestCommonFactor,
- Hermite1stDerivative: () => Hermite1stDerivative,
- Hermite: () => Hermite,
- ExtractAsInt: () => ExtractAsInt,
- Denormalize: () => Denormalize,
- DeltaAngle: () => DeltaAngle,
- Clamp: () => Clamp
-});
-function ExtractAsInt(value) {
- return parseInt(value.toString().replace(/\W/g, ""));
-}
-function WithinEpsilon(a, b, epsilon = 0.000000000000000000000000000000000000000000001401298) {
- return Math.abs(a - b) <= epsilon;
-}
-function OutsideRange(num, min, max, epsilon = 0.000000000000000000000000000000000000000000001401298) {
- return num < min - epsilon || num > max + epsilon;
-}
-function RandomRange(min, max) {
- if (min === max) {
- return min;
- }
- return Math.random() * (max - min) + min;
-}
-function Lerp(start, end, amount) {
- return start + (end - start) * amount;
-}
-function LerpAngle(start, end, amount) {
- let num = Repeat(end - start, 360);
- if (num > 180) {
- num -= 360;
- }
- return start + num * Clamp(amount);
-}
-function InverseLerp(a, b, value) {
- let result = 0;
- if (a != b) {
- result = Clamp((value - a) / (b - a));
- } else {
- result = 0;
- }
- return result;
-}
-function Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * squared + amount;
- const part4 = cubed - squared;
- return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;
-}
-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;
-}
-function Clamp(value, min = 0, max = 1) {
- return Math.min(max, Math.max(min, value));
-}
-function NormalizeRadians(angle) {
- angle -= Math.PI * 2 * Math.floor((angle + Math.PI) / (Math.PI * 2));
- return angle;
-}
-function ToHex(i) {
- const str = i.toString(16);
- if (i <= 15) {
- return ("0" + str).toUpperCase();
- }
- return str.toUpperCase();
-}
-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;
-}
-function Repeat(value, length) {
- return value - Math.floor(value / length) * length;
-}
-function Normalize(value, min, max) {
- return (value - min) / (max - min);
-}
-function Denormalize(normalized, min, max) {
- return normalized * (max - min) + min;
-}
-function DeltaAngle(current, target) {
- let num = Repeat(target - current, 360);
- if (num > 180) {
- num -= 360;
- }
- return num;
-}
-function PingPong(tx, length) {
- const t = Repeat(tx, length * 2);
- return length - Math.abs(t - length);
-}
-function SmoothStep(from, to, tx) {
- let t = Clamp(tx);
- t = -2 * t * t * t + 3 * t * t;
- return to * t + from * (1 - t);
-}
-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;
-}
-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;
-}
-function RangeToPercent(number, min, max) {
- return (number - min) / (max - min);
-}
-function PercentToRange(percent, min, max) {
- return (max - min) * percent + min;
-}
-function HighestCommonFactor(a, b) {
- const r = a % b;
- if (r === 0) {
- return b;
- }
- return HighestCommonFactor(b, r);
-}
-
-// node_modules/@babylonjs/core/Maths/math.vector.js
-class Vector2 {
- constructor(x = 0, y = 0) {
- this.x = x;
- this.y = y;
- }
- toString() {
- return `{X: ${this.x} Y: ${this.y}}`;
- }
- getClassName() {
- return "Vector2";
- }
- getHashCode() {
- const x = _ExtractAsInt(this.x);
- const y = _ExtractAsInt(this.y);
- let hash2 = x;
- hash2 = hash2 * 397 ^ y;
- return hash2;
- }
- toArray(array, index = 0) {
- array[index] = this.x;
- array[index + 1] = this.y;
- return this;
- }
- fromArray(array, offset = 0) {
- Vector2.FromArrayToRef(array, offset, this);
- return this;
- }
- asArray() {
- return [this.x, this.y];
- }
- copyFrom(source) {
- this.x = source.x;
- this.y = source.y;
- return this;
- }
- copyFromFloats(x, y) {
- this.x = x;
- this.y = y;
- return this;
- }
- set(x, y) {
- return this.copyFromFloats(x, y);
- }
- setAll(v) {
- return this.copyFromFloats(v, v);
- }
- add(otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- }
- addToRef(otherVector, result) {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- return result;
- }
- addInPlace(otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- return this;
- }
- addInPlaceFromFloats(x, y) {
- this.x += x;
- this.y += y;
- return this;
- }
- addVector3(otherVector) {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- }
- subtract(otherVector) {
- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
- }
- subtractToRef(otherVector, result) {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- return result;
- }
- subtractInPlace(otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- return this;
- }
- multiplyInPlace(otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- return this;
- }
- multiply(otherVector) {
- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
- }
- multiplyToRef(otherVector, result) {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- return result;
- }
- multiplyByFloats(x, y) {
- return new Vector2(this.x * x, this.y * y);
- }
- divide(otherVector) {
- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
- }
- divideToRef(otherVector, result) {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- return result;
- }
- divideInPlace(otherVector) {
- this.x = this.x / otherVector.x;
- this.y = this.y / otherVector.y;
- return this;
- }
- minimizeInPlace(other) {
- return this.minimizeInPlaceFromFloats(other.x, other.y);
- }
- maximizeInPlace(other) {
- return this.maximizeInPlaceFromFloats(other.x, other.y);
- }
- minimizeInPlaceFromFloats(x, y) {
- this.x = Math.min(x, this.x);
- this.y = Math.min(y, this.y);
- return this;
- }
- maximizeInPlaceFromFloats(x, y) {
- this.x = Math.max(x, this.x);
- this.y = Math.max(y, this.y);
- return this;
- }
- subtractFromFloats(x, y) {
- return new Vector2(this.x - x, this.y - y);
- }
- subtractFromFloatsToRef(x, y, result) {
- result.x = this.x - x;
- result.y = this.y - y;
- return result;
- }
- negate() {
- return new Vector2(-this.x, -this.y);
- }
- negateInPlace() {
- this.x *= -1;
- this.y *= -1;
- return this;
- }
- negateToRef(result) {
- result.x = -this.x;
- result.y = -this.y;
- return result;
- }
- scaleInPlace(scale) {
- this.x *= scale;
- this.y *= scale;
- return this;
- }
- scale(scale) {
- return new Vector2(this.x * scale, this.y * scale);
- }
- scaleToRef(scale, result) {
- result.x = this.x * scale;
- result.y = this.y * scale;
- return result;
- }
- scaleAndAddToRef(scale, result) {
- result.x += this.x * scale;
- result.y += this.y * scale;
- return result;
- }
- equals(otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y;
- }
- equalsWithEpsilon(otherVector, epsilon = Epsilon) {
- return otherVector && WithinEpsilon(this.x, otherVector.x, epsilon) && WithinEpsilon(this.y, otherVector.y, epsilon);
- }
- equalsToFloats(x, y) {
- return this.x === x && this.y === y;
- }
- floor() {
- return new Vector2(Math.floor(this.x), Math.floor(this.y));
- }
- floorToRef(result) {
- result.x = Math.floor(this.x);
- result.y = Math.floor(this.y);
- return result;
- }
- fract() {
- return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
- }
- fractToRef(result) {
- result.x = this.x - Math.floor(this.x);
- result.y = this.y - Math.floor(this.y);
- return result;
- }
- 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;
- }
- length() {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- }
- lengthSquared() {
- return this.x * this.x + this.y * this.y;
- }
- normalize() {
- return this.normalizeFromLength(this.length());
- }
- normalizeFromLength(len) {
- if (len === 0 || len === 1) {
- return this;
- }
- return this.scaleInPlace(1 / len);
- }
- normalizeToNew() {
- const normalized = new Vector2;
- this.normalizeToRef(normalized);
- return normalized;
- }
- normalizeToRef(result) {
- const len = this.length();
- if (len === 0) {
- result.x = this.x;
- result.y = this.y;
- }
- return this.scaleToRef(1 / len, result);
- }
- clone() {
- return new Vector2(this.x, this.y);
- }
- dot(otherVector) {
- return this.x * otherVector.x + this.y * otherVector.y;
- }
- static Zero() {
- return new Vector2(0, 0);
- }
- static One() {
- return new Vector2(1, 1);
- }
- static Random(min = 0, max = 1) {
- return new Vector2(RandomRange(min, max), RandomRange(min, max));
- }
- static RandomToRef(min = 0, max = 1, ref) {
- return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max));
- }
- static get ZeroReadOnly() {
- return Vector2._ZeroReadOnly;
- }
- static FromArray(array, offset = 0) {
- return new Vector2(array[offset], array[offset + 1]);
- }
- static FromArrayToRef(array, offset, result) {
- result.x = array[offset];
- result.y = array[offset + 1];
- return result;
- }
- static FromFloatsToRef(x, y, result) {
- result.copyFromFloats(x, y);
- return result;
- }
- static CatmullRom(value1, value2, value3, value4, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const x = 0.5 * (2 * value2.x + (-value1.x + value3.x) * amount + (2 * value1.x - 5 * value2.x + 4 * value3.x - value4.x) * squared + (-value1.x + 3 * value2.x - 3 * value3.x + value4.x) * cubed);
- const y = 0.5 * (2 * value2.y + (-value1.y + value3.y) * amount + (2 * value1.y - 5 * value2.y + 4 * value3.y - value4.y) * squared + (-value1.y + 3 * value2.y - 3 * value3.y + value4.y) * cubed);
- return new Vector2(x, y);
- }
- 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;
- }
- 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);
- }
- static Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * 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);
- }
- static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
- return this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, new Vector2);
- }
- 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;
- }
- static Lerp(start, end, amount) {
- return Vector2.LerpToRef(start, end, amount, new Vector2);
- }
- 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;
- }
- static Dot(left, right) {
- return left.x * right.x + left.y * right.y;
- }
- static Normalize(vector) {
- return Vector2.NormalizeToRef(vector, new Vector2);
- }
- static NormalizeToRef(vector, result) {
- vector.normalizeToRef(result);
- return result;
- }
- 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);
- }
- 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);
- }
- static Transform(vector, transformation) {
- return Vector2.TransformToRef(vector, transformation, new Vector2);
- }
- 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;
- }
- 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;
- }
- static Distance(value1, value2) {
- return Math.sqrt(Vector2.DistanceSquared(value1, value2));
- }
- static DistanceSquared(value1, value2) {
- const x = value1.x - value2.x;
- const y = value1.y - value2.y;
- return x * x + y * y;
- }
- static Center(value1, value2) {
- return Vector2.CenterToRef(value1, value2, new Vector2);
- }
- static CenterToRef(value1, value2, ref) {
- return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);
- }
- static DistanceOfPointFromSegment(p, segA, segB) {
- const l2 = Vector2.DistanceSquared(segA, segB);
- if (l2 === 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);
- }
-}
-
-class Vector3 {
- get x() {
- return this._x;
- }
- set x(value) {
- this._x = value;
- this._isDirty = true;
- }
- get y() {
- return this._y;
- }
- set y(value) {
- this._y = value;
- this._isDirty = true;
- }
- get z() {
- return this._z;
- }
- set z(value) {
- this._z = value;
- this._isDirty = true;
- }
- constructor(x = 0, y = 0, z = 0) {
- this._isDirty = true;
- this._x = x;
- this._y = y;
- this._z = z;
- }
- toString() {
- return `{X: ${this._x} Y: ${this._y} Z: ${this._z}}`;
- }
- getClassName() {
- return "Vector3";
- }
- getHashCode() {
- const x = _ExtractAsInt(this._x);
- const y = _ExtractAsInt(this._y);
- const z = _ExtractAsInt(this._z);
- let hash2 = x;
- hash2 = hash2 * 397 ^ y;
- hash2 = hash2 * 397 ^ z;
- return hash2;
- }
- asArray() {
- return [this._x, this._y, this._z];
- }
- toArray(array, index = 0) {
- array[index] = this._x;
- array[index + 1] = this._y;
- array[index + 2] = this._z;
- return this;
- }
- fromArray(array, offset = 0) {
- Vector3.FromArrayToRef(array, offset, this);
- return this;
- }
- toQuaternion() {
- return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z);
- }
- addInPlace(otherVector) {
- this._x += otherVector._x;
- this._y += otherVector._y;
- this._z += otherVector._z;
- this._isDirty = true;
- return this;
- }
- addInPlaceFromFloats(x, y, z) {
- this._x += x;
- this._y += y;
- this._z += z;
- this._isDirty = true;
- return this;
- }
- add(otherVector) {
- return new Vector3(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z);
- }
- 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;
- }
- subtractInPlace(otherVector) {
- this._x -= otherVector._x;
- this._y -= otherVector._y;
- this._z -= otherVector._z;
- this._isDirty = true;
- return this;
- }
- subtract(otherVector) {
- return new Vector3(this._x - otherVector._x, this._y - otherVector._y, this._z - otherVector._z);
- }
- subtractToRef(otherVector, result) {
- return this.subtractFromFloatsToRef(otherVector._x, otherVector._y, otherVector._z, result);
- }
- subtractFromFloats(x, y, z) {
- return new Vector3(this._x - x, this._y - y, this._z - z);
- }
- 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;
- }
- negate() {
- return new Vector3(-this._x, -this._y, -this._z);
- }
- negateInPlace() {
- this._x *= -1;
- this._y *= -1;
- this._z *= -1;
- this._isDirty = true;
- return this;
- }
- negateToRef(result) {
- result._x = this._x * -1;
- result._y = this._y * -1;
- result._z = this._z * -1;
- result._isDirty = true;
- return result;
- }
- scaleInPlace(scale) {
- this._x *= scale;
- this._y *= scale;
- this._z *= scale;
- this._isDirty = true;
- return this;
- }
- scale(scale) {
- return new Vector3(this._x * scale, this._y * scale, this._z * scale);
- }
- scaleToRef(scale, result) {
- result._x = this._x * scale;
- result._y = this._y * scale;
- result._z = this._z * scale;
- result._isDirty = true;
- return result;
- }
- getNormalToRef(result) {
- const radius = this.length();
- let theta = Math.acos(this.y / radius);
- const phi = Math.atan2(this.z, this.x);
- if (theta > Math.PI / 2) {
- theta -= Math.PI / 2;
- } else {
- theta += Math.PI / 2;
- }
- 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;
- }
- applyRotationQuaternionToRef(q, result) {
- const vx = this._x, vy = this._y, vz = this._z;
- const { _x: qx, _y: qy, _z: qz, _w: qw } = q;
- const tx = 2 * (qy * vz - qz * vy);
- const ty = 2 * (qz * vx - qx * vz);
- const tz = 2 * (qx * vy - qy * vx);
- 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;
- }
- applyRotationQuaternionInPlace(q) {
- return this.applyRotationQuaternionToRef(q, this);
- }
- applyRotationQuaternion(q) {
- return this.applyRotationQuaternionToRef(q, new Vector3);
- }
- scaleAndAddToRef(scale, result) {
- result._x += this._x * scale;
- result._y += this._y * scale;
- result._z += this._z * scale;
- result._isDirty = true;
- return result;
- }
- projectOnPlane(plane, origin) {
- return this.projectOnPlaneToRef(plane, origin, new Vector3);
- }
- projectOnPlaneToRef(plane, origin, result) {
- const n = plane.normal;
- const d = plane.d;
- const V = MathTmp.Vector3[0];
- this.subtractToRef(origin, V);
- V.normalize();
- const denom = Vector3.Dot(V, n);
- if (Math.abs(denom) < 0.0000000001) {
- result.setAll(Infinity);
- } else {
- const t = -(Vector3.Dot(origin, n) + d) / denom;
- const scaledV = V.scaleInPlace(t);
- origin.addToRef(scaledV, result);
- }
- return result;
- }
- equals(otherVector) {
- return otherVector && this._x === otherVector._x && this._y === otherVector._y && this._z === otherVector._z;
- }
- equalsWithEpsilon(otherVector, epsilon = Epsilon) {
- return otherVector && WithinEpsilon(this._x, otherVector._x, epsilon) && WithinEpsilon(this._y, otherVector._y, epsilon) && WithinEpsilon(this._z, otherVector._z, epsilon);
- }
- equalsToFloats(x, y, z) {
- return this._x === x && this._y === y && this._z === z;
- }
- multiplyInPlace(otherVector) {
- this._x *= otherVector._x;
- this._y *= otherVector._y;
- this._z *= otherVector._z;
- this._isDirty = true;
- return this;
- }
- multiply(otherVector) {
- return this.multiplyByFloats(otherVector._x, otherVector._y, otherVector._z);
- }
- 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;
- }
- multiplyByFloats(x, y, z) {
- return new Vector3(this._x * x, this._y * y, this._z * z);
- }
- divide(otherVector) {
- return new Vector3(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z);
- }
- 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;
- }
- 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;
- }
- minimizeInPlace(other) {
- return this.minimizeInPlaceFromFloats(other._x, other._y, other._z);
- }
- maximizeInPlace(other) {
- return this.maximizeInPlaceFromFloats(other._x, other._y, other._z);
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- floor() {
- return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
- }
- 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;
- }
- fract() {
- return new Vector3(this.x - Math.floor(this._x), this.y - Math.floor(this._y), this.z - Math.floor(this._z));
- }
- length() {
- return Math.sqrt(this.lengthSquared());
- }
- lengthSquared() {
- return this._x * this._x + this._y * this._y + this._z * this._z;
- }
- get hasAZeroComponent() {
- return this._x * this._y * this._z === 0;
- }
- normalize() {
- return this.normalizeFromLength(this.length());
- }
- 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;
- }
- rotateByQuaternionToRef(quaternion, result) {
- quaternion.toRotationMatrix(MathTmp.Matrix[0]);
- Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
- return result;
- }
- 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;
- }
- cross(other) {
- return Vector3.CrossToRef(this, other, new Vector3);
- }
- normalizeFromLength(len) {
- if (len === 0 || len === 1) {
- return this;
- }
- return this.scaleInPlace(1 / len);
- }
- normalizeToNew() {
- return this.normalizeToRef(new Vector3);
- }
- normalizeToRef(result) {
- const len = this.length();
- if (len === 0 || len === 1) {
- result._x = this._x;
- result._y = this._y;
- result._z = this._z;
- result._isDirty = true;
- return result;
- }
- return this.scaleToRef(1 / len, result);
- }
- clone() {
- return new Vector3(this._x, this._y, this._z);
- }
- copyFrom(source) {
- return this.copyFromFloats(source._x, source._y, source._z);
- }
- copyFromFloats(x, y, z) {
- this._x = x;
- this._y = y;
- this._z = z;
- this._isDirty = true;
- return this;
- }
- set(x, y, z) {
- return this.copyFromFloats(x, y, z);
- }
- setAll(v) {
- this._x = this._y = this._z = v;
- this._isDirty = true;
- return this;
- }
- static GetClipFactor(vector0, vector1, axis, size) {
- const d0 = Vector3.Dot(vector0, axis);
- const d1 = Vector3.Dot(vector1, axis);
- return (d0 - size) / (d0 - d1);
- }
- 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);
- 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);
- }
- 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);
- }
- 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;
- }
- static PitchYawRollToMoveBetweenPoints(start, target) {
- const ref = Vector3.Zero();
- return Vector3.PitchYawRollToMoveBetweenPointsToRef(start, target, ref);
- }
- 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 {
- scale0 = 1 - slerp;
- scale1 = slerp;
- }
- vector0Dir.scaleInPlace(scale0);
- vector1Dir.scaleInPlace(scale1);
- result.copyFrom(vector0Dir).addInPlace(vector1Dir);
- result.scaleInPlace(Lerp(vector0Length, vector1Length, slerp));
- return result;
- }
- static SmoothToRef(source, goal, deltaTime, lerpTime, result) {
- Vector3.SlerpToRef(source, goal, lerpTime === 0 ? 1 : deltaTime / lerpTime, result);
- return result;
- }
- static FromArray(array, offset = 0) {
- return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
- }
- static FromFloatArray(array, offset) {
- return Vector3.FromArray(array, offset);
- }
- static FromArrayToRef(array, offset, result) {
- result._x = array[offset];
- result._y = array[offset + 1];
- result._z = array[offset + 2];
- result._isDirty = true;
- return result;
- }
- static FromFloatArrayToRef(array, offset, result) {
- return Vector3.FromArrayToRef(array, offset, result);
- }
- static FromFloatsToRef(x, y, z, result) {
- result.copyFromFloats(x, y, z);
- return result;
- }
- static Zero() {
- return new Vector3(0, 0, 0);
- }
- static One() {
- return new Vector3(1, 1, 1);
- }
- static Up() {
- return new Vector3(0, 1, 0);
- }
- static get UpReadOnly() {
- return Vector3._UpReadOnly;
- }
- static get DownReadOnly() {
- return Vector3._DownReadOnly;
- }
- static get RightReadOnly() {
- return Vector3._RightReadOnly;
- }
- static get LeftReadOnly() {
- return Vector3._LeftReadOnly;
- }
- static get LeftHandedForwardReadOnly() {
- return Vector3._LeftHandedForwardReadOnly;
- }
- static get RightHandedForwardReadOnly() {
- return Vector3._RightHandedForwardReadOnly;
- }
- static get LeftHandedBackwardReadOnly() {
- return Vector3._LeftHandedBackwardReadOnly;
- }
- static get RightHandedBackwardReadOnly() {
- return Vector3._RightHandedBackwardReadOnly;
- }
- static get ZeroReadOnly() {
- return Vector3._ZeroReadOnly;
- }
- static get OneReadOnly() {
- return Vector3._OneReadOnly;
- }
- static Down() {
- return new Vector3(0, -1, 0);
- }
- static Forward(rightHandedSystem = false) {
- return new Vector3(0, 0, rightHandedSystem ? -1 : 1);
- }
- static Backward(rightHandedSystem = false) {
- return new Vector3(0, 0, rightHandedSystem ? 1 : -1);
- }
- static Right() {
- return new Vector3(1, 0, 0);
- }
- static Left() {
- return new Vector3(-1, 0, 0);
- }
- static Random(min = 0, max = 1) {
- return new Vector3(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
- }
- static RandomToRef(min = 0, max = 1, ref) {
- return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
- }
- static TransformCoordinates(vector, transformation) {
- const result = Vector3.Zero();
- Vector3.TransformCoordinatesToRef(vector, transformation, result);
- return result;
- }
- static TransformCoordinatesToRef(vector, transformation, result) {
- Vector3.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
- return result;
- }
- 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;
- }
- static TransformNormal(vector, transformation) {
- const result = Vector3.Zero();
- Vector3.TransformNormalToRef(vector, transformation, result);
- return result;
- }
- static TransformNormalToRef(vector, transformation, result) {
- this.TransformNormalFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
- return result;
- }
- 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;
- }
- static CatmullRom(value1, value2, value3, value4, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const x = 0.5 * (2 * value2._x + (-value1._x + value3._x) * amount + (2 * value1._x - 5 * value2._x + 4 * value3._x - value4._x) * squared + (-value1._x + 3 * value2._x - 3 * value3._x + value4._x) * cubed);
- const y = 0.5 * (2 * value2._y + (-value1._y + value3._y) * amount + (2 * value1._y - 5 * value2._y + 4 * value3._y - value4._y) * squared + (-value1._y + 3 * value2._y - 3 * value3._y + value4._y) * cubed);
- const z = 0.5 * (2 * value2._z + (-value1._z + value3._z) * amount + (2 * value1._z - 5 * value2._z + 4 * value3._z - value4._z) * squared + (-value1._z + 3 * value2._z - 3 * value3._z + value4._z) * cubed);
- return new Vector3(x, y, z);
- }
- static Clamp(value, min, max) {
- const result = new Vector3;
- Vector3.ClampToRef(value, min, max, result);
- return result;
- }
- 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;
- }
- static CheckExtends(v, min, max) {
- min.minimizeInPlace(v);
- max.maximizeInPlace(v);
- }
- static Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * 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);
- }
- static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
- const result = new Vector3;
- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
- return result;
- }
- 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;
- }
- static Lerp(start, end, amount) {
- const result = new Vector3(0, 0, 0);
- Vector3.LerpToRef(start, end, amount, result);
- return result;
- }
- 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;
- }
- static Dot(left, right) {
- return left._x * right._x + left._y * right._y + left._z * right._z;
- }
- dot(otherVector) {
- return this._x * otherVector._x + this._y * otherVector._y + this._z * otherVector._z;
- }
- static Cross(left, right) {
- const result = new Vector3;
- Vector3.CrossToRef(left, right, result);
- return result;
- }
- 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;
- }
- static Normalize(vector) {
- const result = Vector3.Zero();
- Vector3.NormalizeToRef(vector, result);
- return result;
- }
- static NormalizeToRef(vector, result) {
- vector.normalizeToRef(result);
- return result;
- }
- static Project(vector, world, transform, viewport) {
- const result = new Vector3;
- Vector3.ProjectToRef(vector, world, transform, viewport, result);
- return result;
- }
- 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, -ch / 2, 0, 0, 0, 0, zScale, 0, cx + cw / 2, ch / 2 + cy, zOffset, 1, viewportMatrix);
- const matrix = MathTmp.Matrix[0];
- world.multiplyToRef(transform, matrix);
- matrix.multiplyToRef(viewportMatrix, matrix);
- Vector3.TransformCoordinatesToRef(vector, matrix, result);
- return result;
- }
- static Reflect(inDirection, normal) {
- return this.ReflectToRef(inDirection, normal, new Vector3);
- }
- 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);
- }
- 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)) {
- result.scaleInPlace(1 / num);
- }
- return result;
- }
- static UnprojectFromTransform(source, viewportWidth, viewportHeight, world, transform) {
- return this.Unproject(source, viewportWidth, viewportHeight, world, transform, Matrix.IdentityReadOnly);
- }
- static Unproject(source, viewportWidth, viewportHeight, world, view, projection) {
- const result = new Vector3;
- Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
- return result;
- }
- 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;
- }
- 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;
- }
- Vector3._UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
- return result;
- }
- static Minimize(left, right) {
- const min = new Vector3;
- min.copyFrom(left);
- min.minimizeInPlace(right);
- return min;
- }
- static Maximize(left, right) {
- const max = new Vector3;
- max.copyFrom(left);
- max.maximizeInPlace(right);
- return max;
- }
- static Distance(value1, value2) {
- return Math.sqrt(Vector3.DistanceSquared(value1, value2));
- }
- 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;
- }
- 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];
- 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) {
- ref.copyFrom(p0);
- return Vector3.Distance(vector, p0);
- }
- vector.subtractToRef(p0, vectorp0);
- Vector3.CrossToRef(p1p0, p2p0, normal);
- const nl = normal.length();
- if (nl < Epsilon) {
- ref.copyFrom(p0);
- return Vector3.Distance(vector, p0);
- }
- normal.normalizeFromLength(nl);
- let l = vectorp0.length();
- if (l < Epsilon) {
- ref.copyFrom(p0);
- return 0;
- }
- vectorp0.normalizeFromLength(l);
- 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);
- 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);
- 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;
- }
- 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 (!isOutside) {
- ref.copyFrom(proj);
- return Math.abs(l * cosA);
- }
- 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) {
- 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));
- 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);
- }
- static Center(value1, value2) {
- return Vector3.CenterToRef(value1, value2, Vector3.Zero());
- }
- static CenterToRef(value1, value2, ref) {
- return ref.copyFromFloats((value1._x + value2._x) / 2, (value1._y + value2._y) / 2, (value1._z + value2._z) / 2);
- }
- static RotationFromAxis(axis1, axis2, axis3) {
- const rotation = new Vector3;
- Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
- return rotation;
- }
- static RotationFromAxisToRef(axis1, axis2, axis3, ref) {
- const quat = MathTmp.Quaternion[0];
- Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
- quat.toEulerAnglesToRef(ref);
- return ref;
- }
-}
-
-class Vector4 {
- constructor(x = 0, y = 0, z = 0, w = 0) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- }
- toString() {
- return `{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`;
- }
- getClassName() {
- return "Vector4";
- }
- getHashCode() {
- const x = _ExtractAsInt(this.x);
- const y = _ExtractAsInt(this.y);
- const z = _ExtractAsInt(this.z);
- const w = _ExtractAsInt(this.w);
- let hash2 = x;
- hash2 = hash2 * 397 ^ y;
- hash2 = hash2 * 397 ^ z;
- hash2 = hash2 * 397 ^ w;
- return hash2;
- }
- asArray() {
- return [this.x, this.y, this.z, this.w];
- }
- 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;
- }
- fromArray(array, offset = 0) {
- Vector4.FromArrayToRef(array, offset, this);
- return this;
- }
- addInPlace(otherVector) {
- this.x += otherVector.x;
- this.y += otherVector.y;
- this.z += otherVector.z;
- this.w += otherVector.w;
- return this;
- }
- addInPlaceFromFloats(x, y, z, w) {
- this.x += x;
- this.y += y;
- this.z += z;
- this.w += w;
- return this;
- }
- add(otherVector) {
- return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
- }
- 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;
- }
- subtractInPlace(otherVector) {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- this.z -= otherVector.z;
- this.w -= otherVector.w;
- return this;
- }
- subtract(otherVector) {
- return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
- }
- 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;
- }
- subtractFromFloats(x, y, z, w) {
- return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
- }
- 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;
- }
- negate() {
- return new Vector4(-this.x, -this.y, -this.z, -this.w);
- }
- negateInPlace() {
- this.x *= -1;
- this.y *= -1;
- this.z *= -1;
- this.w *= -1;
- return this;
- }
- negateToRef(result) {
- result.x = -this.x;
- result.y = -this.y;
- result.z = -this.z;
- result.w = -this.w;
- return result;
- }
- scaleInPlace(scale) {
- this.x *= scale;
- this.y *= scale;
- this.z *= scale;
- this.w *= scale;
- return this;
- }
- scale(scale) {
- return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
- }
- 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;
- }
- 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;
- }
- equals(otherVector) {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
- }
- 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);
- }
- equalsToFloats(x, y, z, w) {
- return this.x === x && this.y === y && this.z === z && this.w === w;
- }
- multiplyInPlace(otherVector) {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- this.z *= otherVector.z;
- this.w *= otherVector.w;
- return this;
- }
- multiply(otherVector) {
- return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
- }
- 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;
- }
- multiplyByFloats(x, y, z, w) {
- return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
- }
- divide(otherVector) {
- return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
- }
- 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;
- }
- divideInPlace(otherVector) {
- return this.divideToRef(otherVector, this);
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- floor() {
- return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
- }
- 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;
- }
- 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));
- }
- length() {
- return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
- }
- lengthSquared() {
- return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
- }
- normalize() {
- return this.normalizeFromLength(this.length());
- }
- normalizeFromLength(len) {
- if (len === 0 || len === 1) {
- return this;
- }
- return this.scaleInPlace(1 / len);
- }
- normalizeToNew() {
- return this.normalizeToRef(new Vector4);
- }
- normalizeToRef(reference) {
- const len = this.length();
- if (len === 0 || len === 1) {
- reference.x = this.x;
- reference.y = this.y;
- reference.z = this.z;
- reference.w = this.w;
- return reference;
- }
- return this.scaleToRef(1 / len, reference);
- }
- toVector3() {
- return new Vector3(this.x, this.y, this.z);
- }
- clone() {
- return new Vector4(this.x, this.y, this.z, this.w);
- }
- copyFrom(source) {
- this.x = source.x;
- this.y = source.y;
- this.z = source.z;
- this.w = source.w;
- return this;
- }
- copyFromFloats(x, y, z, w) {
- this.x = x;
- this.y = y;
- this.z = z;
- this.w = w;
- return this;
- }
- set(x, y, z, w) {
- return this.copyFromFloats(x, y, z, w);
- }
- setAll(v) {
- this.x = this.y = this.z = this.w = v;
- return this;
- }
- dot(otherVector) {
- return this.x * otherVector.x + this.y * otherVector.y + this.z * otherVector.z + this.w * otherVector.w;
- }
- static FromArray(array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- }
- 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;
- }
- static FromFloatArrayToRef(array, offset, result) {
- Vector4.FromArrayToRef(array, offset, result);
- return result;
- }
- static FromFloatsToRef(x, y, z, w, result) {
- result.x = x;
- result.y = y;
- result.z = z;
- result.w = w;
- return result;
- }
- static Zero() {
- return new Vector4(0, 0, 0, 0);
- }
- static One() {
- return new Vector4(1, 1, 1, 1);
- }
- static Random(min = 0, max = 1) {
- return new Vector4(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, 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;
- }
- static Clamp(value, min, max) {
- return Vector4.ClampToRef(value, min, max, new Vector4);
- }
- 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;
- }
- static CheckExtends(v, min, max) {
- min.minimizeInPlace(v);
- max.maximizeInPlace(v);
- }
- static get ZeroReadOnly() {
- return Vector4._ZeroReadOnly;
- }
- static Normalize(vector) {
- return Vector4.NormalizeToRef(vector, new Vector4);
- }
- static NormalizeToRef(vector, result) {
- vector.normalizeToRef(result);
- return result;
- }
- static Minimize(left, right) {
- const min = new Vector4;
- min.copyFrom(left);
- min.minimizeInPlace(right);
- return min;
- }
- static Maximize(left, right) {
- const max = new Vector4;
- max.copyFrom(left);
- max.maximizeInPlace(right);
- return max;
- }
- static Distance(value1, value2) {
- return Math.sqrt(Vector4.DistanceSquared(value1, value2));
- }
- 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;
- }
- static Center(value1, value2) {
- return Vector4.CenterToRef(value1, value2, new Vector4);
- }
- 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;
- }
- static TransformCoordinates(vector, transformation) {
- return Vector4.TransformCoordinatesToRef(vector, transformation, new Vector4);
- }
- static TransformCoordinatesToRef(vector, transformation, result) {
- Vector4.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result);
- return result;
- }
- 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;
- }
- static TransformNormal(vector, transformation) {
- return Vector4.TransformNormalToRef(vector, transformation, new Vector4);
- }
- 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;
- }
- 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;
- }
- static FromVector3(source, w = 0) {
- return new Vector4(source._x, source._y, source._z, w);
- }
- static Dot(left, right) {
- return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
- }
-}
-
-class Quaternion {
- get x() {
- return this._x;
- }
- set x(value) {
- this._x = value;
- this._isDirty = true;
- }
- get y() {
- return this._y;
- }
- set y(value) {
- this._y = value;
- this._isDirty = true;
- }
- get z() {
- return this._z;
- }
- set z(value) {
- this._z = value;
- this._isDirty = true;
- }
- get w() {
- return this._w;
- }
- set w(value) {
- this._w = value;
- this._isDirty = true;
- }
- constructor(x = 0, y = 0, z = 0, w = 1) {
- this._isDirty = true;
- this._x = x;
- this._y = y;
- this._z = z;
- this._w = w;
- }
- toString() {
- return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`;
- }
- getClassName() {
- return "Quaternion";
- }
- getHashCode() {
- const x = _ExtractAsInt(this._x);
- const y = _ExtractAsInt(this._y);
- const z = _ExtractAsInt(this._z);
- const w = _ExtractAsInt(this._w);
- let hash2 = x;
- hash2 = hash2 * 397 ^ y;
- hash2 = hash2 * 397 ^ z;
- hash2 = hash2 * 397 ^ w;
- return hash2;
- }
- asArray() {
- return [this._x, this._y, this._z, this._w];
- }
- 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);
- }
- equals(otherQuaternion) {
- return otherQuaternion && this._x === otherQuaternion._x && this._y === otherQuaternion._y && this._z === otherQuaternion._z && this._w === otherQuaternion._w;
- }
- 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);
- }
- 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() {
- return new Quaternion(this._x, this._y, this._z, this._w);
- }
- copyFrom(other) {
- this._x = other._x;
- this._y = other._y;
- this._z = other._z;
- this._w = other._w;
- this._isDirty = true;
- return this;
- }
- copyFromFloats(x, y, z, w) {
- this._x = x;
- this._y = y;
- this._z = z;
- this._w = w;
- this._isDirty = true;
- return this;
- }
- set(x, y, z, w) {
- return this.copyFromFloats(x, y, z, w);
- }
- setAll(value) {
- return this.copyFromFloats(value, value, value, value);
- }
- add(other) {
- return new Quaternion(this._x + other._x, this._y + other._y, this._z + other._z, this._w + other._w);
- }
- 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(other) {
- return new Quaternion(this._x - other._x, this._y - other._y, this._z - other._z, this._w - other._w);
- }
- subtractInPlace(other) {
- this._x -= other._x;
- this._y -= other._y;
- this._z -= other._z;
- this._w -= other._w;
- this._isDirty = true;
- return this;
- }
- scale(value) {
- return new Quaternion(this._x * value, this._y * value, this._z * value, this._w * value);
- }
- 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;
- }
- scaleInPlace(value) {
- this._x *= value;
- this._y *= value;
- this._z *= value;
- this._w *= value;
- this._isDirty = true;
- return this;
- }
- 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;
- }
- multiply(q1) {
- const result = new Quaternion(0, 0, 0, 1);
- this.multiplyToRef(q1, result);
- return result;
- }
- 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;
- }
- 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;
- }
- divide(_other) {
- throw new ReferenceError("Can not divide a quaternion");
- }
- divideToRef(_other, _result) {
- throw new ReferenceError("Can not divide a quaternion");
- }
- divideInPlace(_other) {
- throw new ReferenceError("Can not divide a quaternion");
- }
- minimizeInPlace() {
- throw new ReferenceError("Can not minimize a quaternion");
- }
- minimizeInPlaceFromFloats() {
- throw new ReferenceError("Can not minimize a quaternion");
- }
- maximizeInPlace() {
- throw new ReferenceError("Can not maximize a quaternion");
- }
- 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;
- }
- floorToRef(_result) {
- throw new ReferenceError("Can not floor a quaternion");
- }
- floor() {
- throw new ReferenceError("Can not floor a quaternion");
- }
- fractToRef(_result) {
- throw new ReferenceError("Can not fract a quaternion");
- }
- fract() {
- throw new ReferenceError("Can not fract a quaternion");
- }
- conjugateToRef(ref) {
- ref.copyFromFloats(-this._x, -this._y, -this._z, this._w);
- return ref;
- }
- conjugateInPlace() {
- this._x *= -1;
- this._y *= -1;
- this._z *= -1;
- this._isDirty = true;
- return this;
- }
- conjugate() {
- return new Quaternion(-this._x, -this._y, -this._z, this._w);
- }
- invert() {
- const conjugate = this.conjugate();
- const lengthSquared = this.lengthSquared();
- if (lengthSquared == 0 || lengthSquared == 1) {
- return conjugate;
- }
- conjugate.scaleInPlace(1 / lengthSquared);
- return conjugate;
- }
- invertInPlace() {
- this.conjugateInPlace();
- const lengthSquared = this.lengthSquared();
- if (lengthSquared == 0 || lengthSquared == 1) {
- return this;
- }
- this.scaleInPlace(1 / lengthSquared);
- return this;
- }
- lengthSquared() {
- return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
- }
- length() {
- return Math.sqrt(this.lengthSquared());
- }
- normalize() {
- return this.normalizeFromLength(this.length());
- }
- normalizeFromLength(len) {
- if (len === 0 || len === 1) {
- return this;
- }
- return this.scaleInPlace(1 / len);
- }
- normalizeToNew() {
- const normalized = new Quaternion(0, 0, 0, 1);
- this.normalizeToRef(normalized);
- return normalized;
- }
- normalizeToRef(reference) {
- const len = this.length();
- if (len === 0 || len === 1) {
- return reference.copyFromFloats(this._x, this._y, this._z, this._w);
- }
- return this.scaleToRef(1 / len, reference);
- }
- toEulerAngles() {
- const result = Vector3.Zero();
- this.toEulerAnglesToRef(result);
- return result;
- }
- 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 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw);
- result._x = Math.asin(-2 * zAxisY);
- result._y = Math.atan2(2 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw);
- result._isDirty = true;
- }
- return result;
- }
- toAlphaBetaGammaToRef(result) {
- const qz = this._z;
- const qx = this._x;
- const qy = this._y;
- const qw = this._w;
- const sinHalfBeta = Math.sqrt(qx * qx + qy * qy);
- const cosHalfBeta = Math.sqrt(qz * qz + qw * qw);
- const beta = 2 * Math.atan2(sinHalfBeta, cosHalfBeta);
- const gammaPlusAlpha = 2 * Math.atan2(qz, qw);
- const gammaMinusAlpha = 2 * Math.atan2(qy, qx);
- const gamma = (gammaPlusAlpha + gammaMinusAlpha) / 2;
- const alpha = (gammaPlusAlpha - gammaMinusAlpha) / 2;
- result.set(alpha, beta, gamma);
- return result;
- }
- toRotationMatrix(result) {
- Matrix.FromQuaternionToRef(this, result);
- return result;
- }
- fromRotationMatrix(matrix) {
- Quaternion.FromRotationMatrixToRef(matrix, this);
- return this;
- }
- dot(other) {
- return this._x * other._x + this._y * other._y + this._z * other._z + this._w * other._w;
- }
- static FromRotationMatrix(matrix) {
- const result = new Quaternion;
- Quaternion.FromRotationMatrixToRef(matrix, result);
- return result;
- }
- 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);
- 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 * Math.sqrt(1 + 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 * Math.sqrt(1 + 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 * Math.sqrt(1 + 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;
- }
- static Dot(left, right) {
- return left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w;
- }
- static AreClose(quat0, quat1, epsilon = 0.1) {
- const dot = Quaternion.Dot(quat0, quat1);
- return 1 - dot * dot <= epsilon;
- }
- 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;
- }
- static Zero() {
- return new Quaternion(0, 0, 0, 0);
- }
- static Inverse(q) {
- return new Quaternion(-q._x, -q._y, -q._z, q._w);
- }
- static InverseToRef(q, result) {
- result.set(-q._x, -q._y, -q._z, q._w);
- return result;
- }
- static Identity() {
- return new Quaternion(0, 0, 0, 1);
- }
- static IsIdentity(quaternion) {
- return quaternion && quaternion._x === 0 && quaternion._y === 0 && quaternion._z === 0 && quaternion._w === 1;
- }
- static RotationAxis(axis, angle) {
- return Quaternion.RotationAxisToRef(axis, angle, new 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;
- }
- static FromArray(array, offset) {
- if (!offset) {
- offset = 0;
- }
- return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- }
- 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;
- }
- static FromFloatsToRef(x, y, z, w, result) {
- result.copyFromFloats(x, y, z, w);
- return result;
- }
- static FromEulerAngles(x, y, z) {
- const q = new Quaternion;
- Quaternion.RotationYawPitchRollToRef(y, x, z, q);
- return q;
- }
- static FromEulerAnglesToRef(x, y, z, result) {
- Quaternion.RotationYawPitchRollToRef(y, x, z, result);
- return result;
- }
- static FromEulerVector(vec) {
- const q = new Quaternion;
- Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, q);
- return q;
- }
- static FromEulerVectorToRef(vec, result) {
- Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, result);
- return result;
- }
- 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();
- }
- static RotationYawPitchRoll(yaw, pitch, roll) {
- const q = new Quaternion;
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
- return q;
- }
- static RotationYawPitchRollToRef(yaw, pitch, roll, result) {
- 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;
- }
- static RotationAlphaBetaGamma(alpha, beta, gamma) {
- const result = new Quaternion;
- Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
- return result;
- }
- static RotationAlphaBetaGammaToRef(alpha, beta, gamma, result) {
- 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;
- }
- static RotationQuaternionFromAxis(axis1, axis2, axis3) {
- const quat = new Quaternion(0, 0, 0, 0);
- Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
- return quat;
- }
- 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;
- }
- static FromLookDirectionLH(forward, up) {
- const quat = new Quaternion;
- Quaternion.FromLookDirectionLHToRef(forward, up, quat);
- return quat;
- }
- static FromLookDirectionLHToRef(forward, up, ref) {
- const rotMat = MathTmp.Matrix[0];
- Matrix.LookDirectionLHToRef(forward, up, rotMat);
- Quaternion.FromRotationMatrixToRef(rotMat, ref);
- return ref;
- }
- static FromLookDirectionRH(forward, up) {
- const quat = new Quaternion;
- Quaternion.FromLookDirectionRHToRef(forward, up, quat);
- return quat;
- }
- static FromLookDirectionRHToRef(forward, up, ref) {
- const rotMat = MathTmp.Matrix[0];
- Matrix.LookDirectionRHToRef(forward, up, rotMat);
- return Quaternion.FromRotationMatrixToRef(rotMat, ref);
- }
- static Slerp(left, right, amount) {
- const result = Quaternion.Identity();
- Quaternion.SlerpToRef(left, right, amount, result);
- return result;
- }
- 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 / Math.sin(num5);
- num3 = Math.sin((1 - 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;
- }
- static Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * 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);
- }
- static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
- const result = new Quaternion;
- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
- return result;
- }
- 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;
- }
- static Normalize(quat) {
- const result = Quaternion.Zero();
- Quaternion.NormalizeToRef(quat, result);
- return result;
- }
- static NormalizeToRef(quat, result) {
- quat.normalizeToRef(result);
- return result;
- }
- static Clamp(value, min, max) {
- const result = new Quaternion;
- Quaternion.ClampToRef(value, min, max, result);
- return result;
- }
- 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));
- }
- static Random(min = 0, max = 1) {
- return new Quaternion(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
- }
- static RandomToRef(min = 0, max = 1, ref) {
- return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max));
- }
- static Minimize() {
- throw new ReferenceError("Quaternion.Minimize does not make sense");
- }
- static Maximize() {
- throw new ReferenceError("Quaternion.Maximize does not make sense");
- }
- static Distance(value1, value2) {
- return Math.sqrt(Quaternion.DistanceSquared(value1, value2));
- }
- 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;
- }
- static Center(value1, value2) {
- return Quaternion.CenterToRef(value1, value2, Quaternion.Zero());
- }
- 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);
- }
-}
-
-class Matrix {
- static get Use64Bits() {
- return PerformanceConfigurator.MatrixUse64Bits;
- }
- get m() {
- return this._m;
- }
- 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;
- }
- constructor() {
- this._isIdentity = false;
- this._isIdentityDirty = true;
- this._isIdentity3x2 = true;
- this._isIdentity3x2Dirty = true;
- this.updateFlag = -1;
- if (PerformanceConfigurator.MatrixTrackPrecisionChange) {
- PerformanceConfigurator.MatrixTrackedMatrices.push(this);
- }
- this._m = new PerformanceConfigurator.MatrixCurrentType(16);
- this.markAsUpdated();
- }
- isIdentity() {
- if (this._isIdentityDirty) {
- this._isIdentityDirty = false;
- const m = this._m;
- this._isIdentity = m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 0 && m[4] === 0 && m[5] === 1 && m[6] === 0 && m[7] === 0 && m[8] === 0 && m[9] === 0 && m[10] === 1 && m[11] === 0 && m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1;
- }
- return this._isIdentity;
- }
- isIdentityAs3x2() {
- if (this._isIdentity3x2Dirty) {
- this._isIdentity3x2Dirty = false;
- if (this._m[0] !== 1 || this._m[5] !== 1 || this._m[15] !== 1) {
- this._isIdentity3x2 = false;
- } else if (this._m[1] !== 0 || this._m[2] !== 0 || this._m[3] !== 0 || this._m[4] !== 0 || this._m[6] !== 0 || this._m[7] !== 0 || this._m[8] !== 0 || this._m[9] !== 0 || this._m[10] !== 0 || this._m[11] !== 0 || this._m[12] !== 0 || this._m[13] !== 0 || this._m[14] !== 0) {
- this._isIdentity3x2 = false;
- } else {
- this._isIdentity3x2 = true;
- }
- }
- return this._isIdentity3x2;
- }
- 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];
- 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;
- }
- toString() {
- return `{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}
-${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}
-${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}
-${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;
- }
- 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;
- }
- invert() {
- this.invertToRef(this);
- return this;
- }
- reset() {
- Matrix.FromValuesToRef(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this);
- this._updateIdentityStatus(false);
- return this;
- }
- add(other) {
- const result = new Matrix;
- this.addToRef(other, result);
- return result;
- }
- 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;
- }
- 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;
- }
- invertToRef(other) {
- if (this._isIdentity === true) {
- Matrix.IdentityToRef(other);
- return other;
- }
- 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) {
- 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;
- }
- addAtIndex(index, value) {
- this._m[index] += value;
- this.markAsUpdated();
- return this;
- }
- multiplyAtIndex(index, value) {
- this._m[index] *= value;
- this.markAsUpdated();
- return this;
- }
- setTranslationFromFloats(x, y, z) {
- this._m[12] = x;
- this._m[13] = y;
- this._m[14] = z;
- this.markAsUpdated();
- return this;
- }
- addTranslationFromFloats(x, y, z) {
- this._m[12] += x;
- this._m[13] += y;
- this._m[14] += z;
- this.markAsUpdated();
- return this;
- }
- setTranslation(vector3) {
- return this.setTranslationFromFloats(vector3._x, vector3._y, vector3._z);
- }
- getTranslation() {
- return new Vector3(this._m[12], this._m[13], this._m[14]);
- }
- getTranslationToRef(result) {
- result.x = this._m[12];
- result.y = this._m[13];
- result.z = this._m[14];
- return result;
- }
- removeRotationAndScaling() {
- const m = this.m;
- Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 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;
- }
- 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;
- }
- 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(other) {
- const result = new Matrix;
- this.multiplyToRef(other, result);
- return result;
- }
- multiplyInPlace(other) {
- const m = this._m, otherM = other.m;
- for (let i = 0;i < 16; i++) {
- m[i] *= otherM[i];
- }
- this.markAsUpdated();
- return this;
- }
- multiplyByFloats(...floats) {
- const m = this._m;
- for (let i = 0;i < 16; i++) {
- m[i] *= floats[i];
- }
- this.markAsUpdated();
- return this;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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() {
- const matrix = new Matrix;
- matrix.copyFrom(this);
- return matrix;
- }
- getClassName() {
- return "Matrix";
- }
- getHashCode() {
- let hash2 = _ExtractAsInt(this._m[0]);
- for (let i = 1;i < 16; i++) {
- hash2 = hash2 * 397 ^ _ExtractAsInt(this._m[i]);
- }
- return hash2;
- }
- decomposeToTransformNode(node) {
- node.rotationQuaternion = node.rotationQuaternion || new Quaternion;
- return this.decompose(node.scaling, node.rotationQuaternion, node.position);
- }
- 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, 1);
- }
- 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, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
- Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
- }
- return true;
- }
- 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]);
- }
- 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;
- }
- setRow(index, row) {
- return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
- }
- transpose() {
- const result = new Matrix;
- Matrix.TransposeToRef(this, result);
- return result;
- }
- transposeToRef(result) {
- Matrix.TransposeToRef(this, result);
- return result;
- }
- 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;
- }
- scale(scale) {
- const result = new Matrix;
- this.scaleToRef(scale, result);
- return result;
- }
- scaleToRef(scale, result) {
- for (let index = 0;index < 16; index++) {
- result._m[index] = this._m[index] * scale;
- }
- result.markAsUpdated();
- return result;
- }
- 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;
- }
- 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, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
- return ref;
- }
- getRotationMatrix() {
- const result = new Matrix;
- this.getRotationMatrixToRef(result);
- return result;
- }
- 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, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, result);
- return result;
- }
- toggleModelMatrixHandInPlace() {
- const m = this._m;
- m[2] *= -1;
- m[6] *= -1;
- m[8] *= -1;
- m[9] *= -1;
- m[14] *= -1;
- this.markAsUpdated();
- return this;
- }
- toggleProjectionMatrixHandInPlace() {
- const m = this._m;
- m[8] *= -1;
- m[9] *= -1;
- m[10] *= -1;
- m[11] *= -1;
- this.markAsUpdated();
- return this;
- }
- static FromArray(array, offset = 0) {
- const result = new Matrix;
- Matrix.FromArrayToRef(array, offset, result);
- return result;
- }
- static FromArrayToRef(array, offset, result) {
- for (let index = 0;index < 16; index++) {
- result._m[index] = array[index + offset];
- }
- result.markAsUpdated();
- return result;
- }
- 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;
- }
- static get IdentityReadOnly() {
- return Matrix._IdentityReadOnly;
- }
- 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();
- }
- 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;
- }
- static Compose(scale, rotation, translation) {
- const result = new Matrix;
- Matrix.ComposeToRef(scale, rotation, translation, result);
- return result;
- }
- static ComposeToRef(scale, rotation, translation, result) {
- const m = result._m;
- const { _x: x, _y: y, _z: z, _w: w } = rotation;
- 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 { _x: sx, _y: sy, _z: sz } = scale;
- 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;
- }
- static Identity() {
- const identity = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- identity._updateIdentityStatus(true);
- return identity;
- }
- static IdentityToRef(result) {
- Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, result);
- result._updateIdentityStatus(true);
- return result;
- }
- static Zero() {
- const zero = Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
- zero._updateIdentityStatus(false);
- return zero;
- }
- static RotationX(angle) {
- const result = new Matrix;
- Matrix.RotationXToRef(angle, result);
- return result;
- }
- static Invert(source) {
- const result = new Matrix;
- source.invertToRef(result);
- return result;
- }
- static RotationXToRef(angle, result) {
- const s = Math.sin(angle);
- const c = Math.cos(angle);
- Matrix.FromValuesToRef(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, result);
- result._updateIdentityStatus(c === 1 && s === 0);
- return result;
- }
- static RotationY(angle) {
- const result = new Matrix;
- Matrix.RotationYToRef(angle, result);
- return result;
- }
- static RotationYToRef(angle, result) {
- const s = Math.sin(angle);
- const c = Math.cos(angle);
- Matrix.FromValuesToRef(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1, result);
- result._updateIdentityStatus(c === 1 && s === 0);
- return result;
- }
- static RotationZ(angle) {
- const result = new Matrix;
- Matrix.RotationZToRef(angle, result);
- return result;
- }
- static RotationZToRef(angle, result) {
- const s = Math.sin(angle);
- const c = Math.cos(angle);
- Matrix.FromValuesToRef(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, result);
- result._updateIdentityStatus(c === 1 && s === 0);
- return result;
- }
- static RotationAxis(axis, angle) {
- const result = new Matrix;
- Matrix.RotationAxisToRef(axis, angle, result);
- return result;
- }
- 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;
- 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;
- 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;
- m[12] = 0;
- m[13] = 0;
- m[14] = 0;
- m[15] = 1;
- result.markAsUpdated();
- return result;
- }
- static RotationAlignToRef(from, to, result, useYAxisForCoplanar = false) {
- const c = Vector3.Dot(to, from);
- const m = result._m;
- if (c < -1 + Epsilon) {
- 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;
- }
- static RotationYawPitchRoll(yaw, pitch, roll) {
- const result = new Matrix;
- Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
- return result;
- }
- static RotationYawPitchRollToRef(yaw, pitch, roll, result) {
- Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
- MathTmp.Quaternion[0].toRotationMatrix(result);
- return result;
- }
- static Scaling(x, y, z) {
- const result = new Matrix;
- Matrix.ScalingToRef(x, y, z, result);
- return result;
- }
- static ScalingToRef(x, y, z, result) {
- Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, result);
- result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
- return result;
- }
- static Translation(x, y, z) {
- const result = new Matrix;
- Matrix.TranslationToRef(x, y, z, result);
- return result;
- }
- static TranslationToRef(x, y, z, result) {
- Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1, result);
- result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
- return result;
- }
- static Lerp(startValue, endValue, gradient) {
- const result = new Matrix;
- Matrix.LerpToRef(startValue, endValue, gradient, result);
- return result;
- }
- 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 - gradient) + endM[index] * gradient;
- }
- result.markAsUpdated();
- return result;
- }
- static DecomposeLerp(startValue, endValue, gradient) {
- const result = new Matrix;
- Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
- return result;
- }
- 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;
- }
- static LookAtLH(eye, target, up) {
- const result = new Matrix;
- Matrix.LookAtLHToRef(eye, target, up, result);
- return result;
- }
- static LookAtLHToRef(eye, target, up, result) {
- const xAxis = MathTmp.Vector3[0];
- const yAxis = MathTmp.Vector3[1];
- const zAxis = MathTmp.Vector3[2];
- target.subtractToRef(eye, zAxis);
- zAxis.normalize();
- Vector3.CrossToRef(up, zAxis, xAxis);
- const xSquareLength = xAxis.lengthSquared();
- if (xSquareLength === 0) {
- xAxis.x = 1;
- } else {
- xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
- }
- Vector3.CrossToRef(zAxis, xAxis, yAxis);
- yAxis.normalize();
- 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, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, result);
- return result;
- }
- static LookAtRH(eye, target, up) {
- const result = new Matrix;
- Matrix.LookAtRHToRef(eye, target, up, result);
- return result;
- }
- static LookAtRHToRef(eye, target, up, result) {
- const xAxis = MathTmp.Vector3[0];
- const yAxis = MathTmp.Vector3[1];
- const zAxis = MathTmp.Vector3[2];
- eye.subtractToRef(target, zAxis);
- zAxis.normalize();
- Vector3.CrossToRef(up, zAxis, xAxis);
- const xSquareLength = xAxis.lengthSquared();
- if (xSquareLength === 0) {
- xAxis.x = 1;
- } else {
- xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
- }
- Vector3.CrossToRef(zAxis, xAxis, yAxis);
- yAxis.normalize();
- 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, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, result);
- return result;
- }
- static LookDirectionLH(forward, up) {
- const result = new Matrix;
- Matrix.LookDirectionLHToRef(forward, up, result);
- return result;
- }
- 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);
- Matrix.FromValuesToRef(left._x, left._y, left._z, 0, up._x, up._y, up._z, 0, back._x, back._y, back._z, 0, 0, 0, 0, 1, result);
- return result;
- }
- static LookDirectionRH(forward, up) {
- const result = new Matrix;
- Matrix.LookDirectionRHToRef(forward, up, result);
- return result;
- }
- static LookDirectionRHToRef(forward, up, result) {
- const right = MathTmp.Vector3[2];
- Vector3.CrossToRef(up, forward, right);
- Matrix.FromValuesToRef(right._x, right._y, right._z, 0, up._x, up._y, up._z, 0, forward._x, forward._y, forward._z, 0, 0, 0, 0, 1, result);
- return result;
- }
- static OrthoLH(width, height, znear, zfar, halfZRange) {
- const matrix = new Matrix;
- Matrix.OrthoLHToRef(width, height, znear, zfar, matrix, halfZRange);
- return matrix;
- }
- static OrthoLHToRef(width, height, znear, zfar, result, halfZRange) {
- const n = znear;
- const f = zfar;
- const a = 2 / width;
- const b = 2 / height;
- const c = 2 / (f - n);
- const d = -(f + n) / (f - n);
- Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
- return result;
- }
- 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;
- }
- static OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) {
- const n = znear;
- const f = zfar;
- const a = 2 / (right - left);
- const b = 2 / (top - bottom);
- const c = 2 / (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, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result.markAsUpdated();
- return result;
- }
- 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;
- }
- 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;
- }
- static OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) {
- Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange);
- result._m[10] *= -1;
- return result;
- }
- 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;
- }
- static PerspectiveLH(width, height, znear, zfar, halfZRange, projectionPlaneTilt = 0) {
- const matrix = new Matrix;
- const n = znear;
- const f = zfar;
- const a = 2 * n / width;
- const b = 2 * 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, b, 0, rot, 0, 0, c, 1, 0, 0, d, 0, matrix);
- if (halfZRange) {
- matrix.multiplyToRef(mtxConvertNDCToHalfZRange, matrix);
- }
- matrix._updateIdentityStatus(false);
- return 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;
- }
- static PerspectiveFovLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
- const n = znear;
- const f = zfar;
- const t = 1 / 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, b, 0, rot, 0, 0, c, 1, 0, 0, d, 0, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result._updateIdentityStatus(false);
- return result;
- }
- static PerspectiveFovReverseLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) {
- const t = 1 / 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, b, 0, rot, 0, 0, -znear, 1, 0, 0, 1, 0, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result._updateIdentityStatus(false);
- return result;
- }
- 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;
- }
- static PerspectiveFovRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) {
- const n = znear;
- const f = zfar;
- const t = 1 / 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, b, 0, rot, 0, 0, c, -1, 0, 0, d, 0, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result._updateIdentityStatus(false);
- return result;
- }
- static PerspectiveFovReverseRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) {
- const t = 1 / 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, b, 0, rot, 0, 0, -znear, -1, 0, 0, -1, 0, result);
- if (halfZRange) {
- result.multiplyToRef(mtxConvertNDCToHalfZRange, result);
- }
- result._updateIdentityStatus(false);
- return result;
- }
- 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, -ch / 2, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2, ch / 2 + cy, zmin, 1);
- const matrix = new Matrix;
- world.multiplyToRef(view, matrix);
- matrix.multiplyToRef(projection, matrix);
- return matrix.multiplyToRef(viewportMatrix, 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);
- }
- 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);
- }
- static Transpose(matrix) {
- const result = new Matrix;
- Matrix.TransposeToRef(matrix, result);
- return result;
- }
- 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();
- result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
- return result;
- }
- static Reflection(plane) {
- const matrix = new Matrix;
- Matrix.ReflectionToRef(plane, matrix);
- return matrix;
- }
- 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, temp * y, temp2 * y + 1, temp3 * y, 0, temp * z, temp2 * z, temp3 * z + 1, 0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1, result);
- return result;
- }
- static FromXYZAxesToRef(xaxis, yaxis, zaxis, result) {
- Matrix.FromValuesToRef(xaxis._x, xaxis._y, xaxis._z, 0, yaxis._x, yaxis._y, yaxis._z, 0, zaxis._x, zaxis._y, zaxis._z, 0, 0, 0, 0, 1, result);
- return result;
- }
- 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 - 2 * (yy + zz);
- result._m[1] = 2 * (xy + zw);
- result._m[2] = 2 * (zx - yw);
- result._m[3] = 0;
- result._m[4] = 2 * (xy - zw);
- result._m[5] = 1 - 2 * (zz + xx);
- result._m[6] = 2 * (yz + xw);
- result._m[7] = 0;
- result._m[8] = 2 * (zx + yw);
- result._m[9] = 2 * (yz - xw);
- result._m[10] = 1 - 2 * (yy + xx);
- result._m[11] = 0;
- result._m[12] = 0;
- result._m[13] = 0;
- result._m[14] = 0;
- result._m[15] = 1;
- result.markAsUpdated();
- return result;
- }
-}
-
-class MathTmp {
-}
-
-class TmpVectors {
-}
-var _ExtractAsInt = (value) => {
- return parseInt(value.toString().replace(/\W/g, ""));
-}, mtxConvertNDCToHalfZRange;
-var init_math_vector = __esm(() => {
- init_math_constants();
- init_arrayTools();
- init_typeStore();
- init_performanceConfigurator();
- init_engineStore();
- Vector2._V8PerformanceHack = new Vector2(0.5, 0.5);
- Vector2._ZeroReadOnly = Vector2.Zero();
- Object.defineProperties(Vector2.prototype, {
- dimension: { value: [2] },
- rank: { value: 1 }
- });
- 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._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 }
- });
- Quaternion._V8PerformanceHack = new Quaternion(0.5, 0.5, 0.5, 0.5);
- Object.defineProperties(Quaternion.prototype, {
- dimension: { value: [4] },
- rank: { value: 1 }
- });
- Matrix._UpdateFlagSeed = 0;
- Matrix._IdentityReadOnly = Matrix.Identity();
- Object.defineProperties(Matrix.prototype, {
- dimension: { value: [4, 4] },
- rank: { value: 2 }
- });
- MathTmp.Vector3 = BuildTuple(11, Vector3.Zero);
- MathTmp.Matrix = BuildTuple(2, Matrix.Identity);
- MathTmp.Quaternion = BuildTuple(3, Quaternion.Zero);
- TmpVectors.Vector2 = BuildTuple(3, Vector2.Zero);
- TmpVectors.Vector3 = BuildTuple(13, Vector3.Zero);
- TmpVectors.Vector4 = BuildTuple(3, Vector4.Zero);
- TmpVectors.Quaternion = BuildTuple(3, Quaternion.Zero);
- TmpVectors.Matrix = BuildTuple(8, Matrix.Identity);
- RegisterClass("BABYLON.Vector2", Vector2);
- RegisterClass("BABYLON.Vector3", Vector3);
- RegisterClass("BABYLON.Vector4", Vector4);
- RegisterClass("BABYLON.Matrix", Matrix);
- mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1);
-});
-
-// node_modules/@babylonjs/core/Maths/math.color.js
-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 Color3 {
- constructor(r = 0, g = 0, b = 0) {
- this.r = r;
- this.g = g;
- this.b = b;
- }
- toString() {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
- }
- getClassName() {
- return "Color3";
- }
- getHashCode() {
- let hash2 = this.r * 255 | 0;
- hash2 = hash2 * 397 ^ (this.g * 255 | 0);
- hash2 = hash2 * 397 ^ (this.b * 255 | 0);
- return hash2;
- }
- toArray(array, index = 0) {
- array[index] = this.r;
- array[index + 1] = this.g;
- array[index + 2] = this.b;
- return this;
- }
- fromArray(array, offset = 0) {
- Color3.FromArrayToRef(array, offset, this);
- return this;
- }
- toColor4(alpha = 1) {
- return new Color4(this.r, this.g, this.b, alpha);
- }
- asArray() {
- return [this.r, this.g, this.b];
- }
- toLuminance() {
- return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
- }
- multiply(otherColor) {
- return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
- }
- multiplyToRef(otherColor, result) {
- result.r = this.r * otherColor.r;
- result.g = this.g * otherColor.g;
- result.b = this.b * otherColor.b;
- return result;
- }
- multiplyInPlace(otherColor) {
- this.r *= otherColor.r;
- this.g *= otherColor.g;
- this.b *= otherColor.b;
- return this;
- }
- multiplyByFloats(r, g, b) {
- return new Color3(this.r * r, this.g * g, this.b * b);
- }
- divide(_other) {
- throw new ReferenceError("Can not divide a color");
- }
- divideToRef(_other, _result) {
- throw new ReferenceError("Can not divide a color");
- }
- divideInPlace(_other) {
- throw new ReferenceError("Can not divide a color");
- }
- minimizeInPlace(other) {
- return this.minimizeInPlaceFromFloats(other.r, other.g, other.b);
- }
- maximizeInPlace(other) {
- return this.maximizeInPlaceFromFloats(other.r, other.g, other.b);
- }
- 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;
- }
- 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;
- }
- floorToRef(_result) {
- throw new ReferenceError("Can not floor a color");
- }
- floor() {
- throw new ReferenceError("Can not floor a color");
- }
- fractToRef(_result) {
- throw new ReferenceError("Can not fract a color");
- }
- fract() {
- throw new ReferenceError("Can not fract a color");
- }
- equals(otherColor) {
- return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
- }
- equalsFloats(r, g, b) {
- return this.equalsToFloats(r, g, b);
- }
- equalsToFloats(r, g, b) {
- return this.r === r && this.g === g && this.b === b;
- }
- equalsWithEpsilon(otherColor, epsilon = Epsilon) {
- return WithinEpsilon(this.r, otherColor.r, epsilon) && WithinEpsilon(this.g, otherColor.g, epsilon) && WithinEpsilon(this.b, otherColor.b, epsilon);
- }
- negate() {
- throw new ReferenceError("Can not negate a color");
- }
- negateInPlace() {
- throw new ReferenceError("Can not negate a color");
- }
- negateToRef(_result) {
- throw new ReferenceError("Can not negate a color");
- }
- scale(scale) {
- return new Color3(this.r * scale, this.g * scale, this.b * scale);
- }
- scaleInPlace(scale) {
- this.r *= scale;
- this.g *= scale;
- this.b *= scale;
- return this;
- }
- scaleToRef(scale, result) {
- result.r = this.r * scale;
- result.g = this.g * scale;
- result.b = this.b * scale;
- return result;
- }
- scaleAndAddToRef(scale, result) {
- result.r += this.r * scale;
- result.g += this.g * scale;
- result.b += this.b * scale;
- return result;
- }
- 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;
- }
- add(otherColor) {
- return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
- }
- addInPlace(otherColor) {
- this.r += otherColor.r;
- this.g += otherColor.g;
- this.b += otherColor.b;
- return this;
- }
- addInPlaceFromFloats(r, g, b) {
- this.r += r;
- this.g += g;
- this.b += b;
- return this;
- }
- addToRef(otherColor, result) {
- result.r = this.r + otherColor.r;
- result.g = this.g + otherColor.g;
- result.b = this.b + otherColor.b;
- return result;
- }
- subtract(otherColor) {
- return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
- }
- subtractToRef(otherColor, result) {
- result.r = this.r - otherColor.r;
- result.g = this.g - otherColor.g;
- result.b = this.b - otherColor.b;
- return result;
- }
- subtractInPlace(otherColor) {
- this.r -= otherColor.r;
- this.g -= otherColor.g;
- this.b -= otherColor.b;
- return this;
- }
- subtractFromFloats(r, g, b) {
- return new Color3(this.r - r, this.g - g, this.b - b);
- }
- subtractFromFloatsToRef(r, g, b, result) {
- result.r = this.r - r;
- result.g = this.g - g;
- result.b = this.b - b;
- return result;
- }
- clone() {
- return new Color3(this.r, this.g, this.b);
- }
- copyFrom(source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- return this;
- }
- copyFromFloats(r, g, b) {
- this.r = r;
- this.g = g;
- this.b = b;
- return this;
- }
- set(r, g, b) {
- return this.copyFromFloats(r, g, b);
- }
- setAll(v) {
- this.r = this.g = this.b = v;
- return this;
- }
- 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);
- }
- 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;
- }
- toHSV() {
- return this.toHSVToRef(new Color3);
- }
- 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;
- }
- toLinearSpace(exact = false) {
- const convertedColor = new Color3;
- this.toLinearSpaceToRef(convertedColor, exact);
- return convertedColor;
- }
- 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;
- }
- toGammaSpace(exact = false) {
- const convertedColor = new Color3;
- this.toGammaSpaceToRef(convertedColor, exact);
- return convertedColor;
- }
- 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;
- }
- 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;
- }
- static FromHSV(hue, saturation, value) {
- const result = new Color3(0, 0, 0);
- Color3.HSVtoRGBToRef(hue, saturation, value, result);
- return result;
- }
- static FromHexString(hex) {
- return new Color3(0, 0, 0).fromHexString(hex);
- }
- static FromArray(array, offset = 0) {
- return new Color3(array[offset], array[offset + 1], array[offset + 2]);
- }
- static FromArrayToRef(array, offset = 0, result) {
- result.r = array[offset];
- result.g = array[offset + 1];
- result.b = array[offset + 2];
- }
- static FromInts(r, g, b) {
- return new Color3(r / 255, g / 255, b / 255);
- }
- static Lerp(start, end, amount) {
- const result = new Color3(0, 0, 0);
- Color3.LerpToRef(start, end, amount, result);
- return 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;
- }
- static Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * 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);
- }
- static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
- const result = Color3.Black();
- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
- return result;
- }
- 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;
- }
- static Red() {
- return new Color3(1, 0, 0);
- }
- static Green() {
- return new Color3(0, 1, 0);
- }
- static Blue() {
- return new Color3(0, 0, 1);
- }
- static Black() {
- return new Color3(0, 0, 0);
- }
- static get BlackReadOnly() {
- return Color3._BlackReadOnly;
- }
- static White() {
- return new Color3(1, 1, 1);
- }
- static Purple() {
- return new Color3(0.5, 0, 0.5);
- }
- static Magenta() {
- return new Color3(1, 0, 1);
- }
- static Yellow() {
- return new Color3(1, 1, 0);
- }
- static Gray() {
- return new Color3(0.5, 0.5, 0.5);
- }
- static Teal() {
- return new Color3(0, 1, 1);
- }
- static Random() {
- return new Color3(Math.random(), Math.random(), Math.random());
- }
-}
-
-class Color4 {
- constructor(r = 0, g = 0, b = 0, a = 1) {
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- }
- asArray() {
- return [this.r, this.g, this.b, this.a];
- }
- 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;
- }
- 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;
- }
- equals(otherColor) {
- return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a;
- }
- add(otherColor) {
- return new Color4(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b, this.a + otherColor.a);
- }
- 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;
- }
- addInPlace(otherColor) {
- this.r += otherColor.r;
- this.g += otherColor.g;
- this.b += otherColor.b;
- this.a += otherColor.a;
- return this;
- }
- addInPlaceFromFloats(r, g, b, a) {
- this.r += r;
- this.g += g;
- this.b += b;
- this.a += a;
- return this;
- }
- subtract(otherColor) {
- return new Color4(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b, this.a - otherColor.a);
- }
- 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;
- }
- subtractInPlace(otherColor) {
- this.r -= otherColor.r;
- this.g -= otherColor.g;
- this.b -= otherColor.b;
- this.a -= otherColor.a;
- return this;
- }
- subtractFromFloats(r, g, b, a) {
- return new Color4(this.r - r, this.g - g, this.b - b, this.a - a);
- }
- 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;
- }
- scale(scale) {
- return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
- }
- scaleInPlace(scale) {
- this.r *= scale;
- this.g *= scale;
- this.b *= scale;
- this.a *= scale;
- return this;
- }
- 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;
- }
- 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;
- }
- 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(color) {
- return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
- }
- 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;
- }
- multiplyInPlace(otherColor) {
- this.r *= otherColor.r;
- this.g *= otherColor.g;
- this.b *= otherColor.b;
- this.a *= otherColor.a;
- return this;
- }
- multiplyByFloats(r, g, b, a) {
- return new Color4(this.r * r, this.g * g, this.b * b, this.a * a);
- }
- divide(_other) {
- throw new ReferenceError("Can not divide a color");
- }
- divideToRef(_other, _result) {
- throw new ReferenceError("Can not divide a color");
- }
- divideInPlace(_other) {
- throw new ReferenceError("Can not divide a color");
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- floorToRef(_result) {
- throw new ReferenceError("Can not floor a color");
- }
- floor() {
- throw new ReferenceError("Can not floor a color");
- }
- fractToRef(_result) {
- throw new ReferenceError("Can not fract a color");
- }
- fract() {
- throw new ReferenceError("Can not fract a color");
- }
- negate() {
- throw new ReferenceError("Can not negate a color");
- }
- negateInPlace() {
- throw new ReferenceError("Can not negate a color");
- }
- negateToRef(_result) {
- throw new ReferenceError("Can not negate a color");
- }
- 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);
- }
- equalsToFloats(x, y, z, w) {
- return this.r === x && this.g === y && this.b === z && this.a === w;
- }
- toString() {
- return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
- }
- getClassName() {
- return "Color4";
- }
- getHashCode() {
- let hash2 = this.r * 255 | 0;
- hash2 = hash2 * 397 ^ (this.g * 255 | 0);
- hash2 = hash2 * 397 ^ (this.b * 255 | 0);
- hash2 = hash2 * 397 ^ (this.a * 255 | 0);
- return hash2;
- }
- clone() {
- const result = new Color4;
- return result.copyFrom(this);
- }
- copyFrom(source) {
- this.r = source.r;
- this.g = source.g;
- this.b = source.b;
- this.a = source.a;
- return this;
- }
- copyFromFloats(r, g, b, a) {
- this.r = r;
- this.g = g;
- this.b = b;
- this.a = a;
- return this;
- }
- set(r, g, b, a) {
- return this.copyFromFloats(r, g, b, a);
- }
- setAll(v) {
- this.r = this.g = this.b = this.a = v;
- return this;
- }
- 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);
- }
- 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;
- }
- toLinearSpace(exact = false) {
- const convertedColor = new Color4;
- this.toLinearSpaceToRef(convertedColor, exact);
- return convertedColor;
- }
- 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;
- }
- toGammaSpace(exact = false) {
- const convertedColor = new Color4;
- this.toGammaSpaceToRef(convertedColor, exact);
- return convertedColor;
- }
- 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;
- }
- static FromHexString(hex) {
- if (hex.substring(0, 1) !== "#" || hex.length !== 9 && hex.length !== 7) {
- return new Color4(0, 0, 0, 0);
- }
- return new Color4(0, 0, 0, 1).fromHexString(hex);
- }
- static Lerp(left, right, amount) {
- return Color4.LerpToRef(left, right, amount, new Color4);
- }
- 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;
- }
- static Hermite(value1, tangent1, value2, tangent2, amount) {
- const squared = amount * amount;
- const cubed = amount * squared;
- const part1 = 2 * cubed - 3 * squared + 1;
- const part2 = -2 * cubed + 3 * squared;
- const part3 = cubed - 2 * 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);
- }
- static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {
- const result = new Color4;
- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
- return result;
- }
- 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;
- }
- static FromColor3(color3, alpha = 1) {
- return new Color4(color3.r, color3.g, color3.b, alpha);
- }
- static FromArray(array, offset = 0) {
- return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
- }
- 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];
- }
- static FromInts(r, g, b, a) {
- return new Color4(r / 255, g / 255, b / 255, a / 255);
- }
- static CheckColors4(colors, count) {
- 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;
- }
- return colors4;
- }
- return colors;
- }
-}
-
-class TmpColors {
-}
-var init_math_color = __esm(() => {
- init_arrayTools();
- init_typeStore();
- init_math_constants();
- Color3._V8PerformanceHack = new Color3(0.5, 0.5, 0.5);
- Color3._BlackReadOnly = Color3.Black();
- Object.defineProperties(Color3.prototype, {
- dimension: { value: [3] },
- rank: { value: 1 }
- });
- Color4._V8PerformanceHack = new Color4(0.5, 0.5, 0.5, 0.5);
- Object.defineProperties(Color4.prototype, {
- dimension: { value: [4] },
- rank: { value: 1 }
- });
- TmpColors.Color3 = BuildArray(3, Color3.Black);
- TmpColors.Color4 = BuildArray(3, () => new Color4(0, 0, 0, 0));
- RegisterClass("BABYLON.Color3", Color3);
- RegisterClass("BABYLON.Color4", Color4);
-});
-
-// node_modules/@babylonjs/core/Actions/actionEvent.js
-class ActionEvent {
- constructor(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
- this.source = source;
- this.pointerX = pointerX;
- this.pointerY = pointerY;
- this.meshUnderPointer = meshUnderPointer;
- this.sourceEvent = sourceEvent;
- this.additionalData = additionalData;
- }
- static CreateNew(source, evt, additionalData) {
- const scene = source.getScene();
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData);
- }
- static CreateNewFromSprite(source, scene, evt, additionalData) {
- return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
- }
- static CreateNewFromScene(scene, evt) {
- return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
- }
- static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) {
- return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
- }
-}
-
-// node_modules/@babylonjs/core/Misc/logger.js
-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;
- }
- static _LogDisabled(message, limit) {}
- static _LogEnabled(level = 1, message, limit) {
- 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);
- }
- static get LogCache() {
- return Logger._LogCache;
- }
- static ClearLogCache() {
- Logger._LogCache = "";
- Logger._LogLimitOutputs = {};
- Logger.errorsCount = 0;
- }
- 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);
- }
- });
- }
-}
-var init_logger = __esm(() => {
- Logger.NoneLogLevel = 0;
- Logger.MessageLogLevel = 1;
- Logger.WarningLogLevel = 2;
- Logger.ErrorLogLevel = 4;
- Logger.AllLogLevel = 7;
- Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";
- Logger._LogCache = "";
- Logger._LogLimitOutputs = {};
- Logger._Levels = [
- {},
- { color: "white", logFunc: console.log, name: "Log" },
- { color: "orange", logFunc: console.warn, name: "Warn" },
- {},
- { color: "red", logFunc: console.error, name: "Error" }
- ];
- Logger.errorsCount = 0;
- Logger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel);
- Logger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel);
- Logger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel);
-});
-
-// node_modules/@babylonjs/core/Misc/deepCopier.js
-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 DeepCopier {
- 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) {
- destination[prop].push(clonedValue);
- }
- }
- } else {
- destination[prop] = sourceValue.slice(0);
- }
- }
- } else {
- destination[prop] = CloneValue(sourceValue, destination, shallowCopyValues);
- }
- } else {
- destination[prop] = sourceValue;
- }
- } catch (e) {
- Logger.Warn(e.message);
- }
- }
- }
-}
-var 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;
-};
-var init_deepCopier = __esm(() => {
- init_logger();
-});
-
-// node_modules/@babylonjs/core/Animations/animationRange.js
-class AnimationRange {
- constructor(name2, from, to) {
- this.name = name2;
- this.from = from;
- this.to = to;
- }
- clone() {
- return new AnimationRange(this.name, this.from, this.to);
- }
-}
-
-// node_modules/@babylonjs/core/tslib.es6.js
-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;
-}
-var init_tslib_es6 = () => {};
-
-// node_modules/@babylonjs/core/Misc/decorators.functions.js
-function GetDirectStore(target) {
- const classKey = target.getClassName();
- if (!__decoratorInitialStore[classKey]) {
- __decoratorInitialStore[classKey] = {};
- }
- return __decoratorInitialStore[classKey];
-}
-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;
-}
-var __mergedStore, __decoratorInitialStore;
-var init_decorators_functions = __esm(() => {
- __mergedStore = {};
- __decoratorInitialStore = {};
-});
-
-// node_modules/@babylonjs/core/Misc/decorators.js
-function generateSerializableMember(type, sourceName) {
- return (target, propertyKey) => {
- const classStore = GetDirectStore(target);
- if (!classStore[propertyKey]) {
- classStore[propertyKey] = { type, 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) {
- 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);
-}
-function serializeAsTexture(sourceName) {
- return generateSerializableMember(1, sourceName);
-}
-function serializeAsColor3(sourceName) {
- return generateSerializableMember(2, sourceName);
-}
-function serializeAsFresnelParameters(sourceName) {
- return generateSerializableMember(3, sourceName);
-}
-function serializeAsVector2(sourceName) {
- return generateSerializableMember(4, sourceName);
-}
-function serializeAsVector3(sourceName) {
- return generateSerializableMember(5, sourceName);
-}
-function serializeAsMeshReference(sourceName) {
- return generateSerializableMember(6, sourceName);
-}
-function serializeAsColorCurves(sourceName) {
- return generateSerializableMember(7, sourceName);
-}
-function serializeAsColor4(sourceName) {
- return generateSerializableMember(8, sourceName);
-}
-function serializeAsImageProcessingConfiguration(sourceName) {
- return generateSerializableMember(9, sourceName);
-}
-function serializeAsQuaternion(sourceName) {
- return generateSerializableMember(10, sourceName);
-}
-function serializeAsMatrix(sourceName) {
- return generateSerializableMember(12, sourceName);
-}
-function serializeAsCameraReference(sourceName) {
- return generateSerializableMember(11, sourceName);
-}
-function nativeOverride(target, propertyKey, descriptor, predicate) {
- const jsFunc = descriptor.value;
- descriptor.value = (...params) => {
- let func = jsFunc;
- if (typeof _native !== "undefined" && _native[propertyKey]) {
- const nativeFunc = _native[propertyKey];
- if (predicate) {
- func = (...params2) => predicate(...params2) ? nativeFunc(...params2) : jsFunc(...params2);
- } else {
- func = nativeFunc;
- }
- }
- target[propertyKey] = func;
- return func(...params);
- };
-}
-var init_decorators = __esm(() => {
- init_decorators_functions();
- nativeOverride.filter = function(predicate) {
- return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate);
- };
-});
-
-// node_modules/@babylonjs/core/Misc/devTools.js
-function _WarnImport(name2, warnOnce = false) {
- if (warnOnce && warnedMap[name2]) {
- return;
- }
- warnedMap[name2] = true;
- return `${name2} needs to be imported before as it contains a side-effect required by your code.`;
-}
-var warnedMap;
-var init_devTools = __esm(() => {
- warnedMap = {};
-});
-
-// node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js
-class AndOrNotEvaluator {
- static Eval(query, evaluateCallback) {
- if (!query.match(/\([^()]*\)/g)) {
- query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
- } else {
- query = query.replace(/\([^()]*\)/g, (r) => {
- 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) {
- ori = "false";
- break;
- }
- }
- }
- if (result || ori === "true") {
- result = true;
- break;
- }
- if (ori !== "true" && ori !== "false") {
- if (ori[0] === "!") {
- result = !evaluateCallback(ori.substring(1));
- } else {
- result = evaluateCallback(ori);
- }
- } else {
- result = ori === "true" ? true : false;
- }
- }
- }
- return result ? "true" : "false";
- }
- static _SimplifyNegation(booleanString) {
- booleanString = booleanString.replace(/^[\s!]+/, (r) => {
- 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;
- }
-}
-
-// node_modules/@babylonjs/core/Misc/tags.js
-class Tags {
- 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);
- };
- }
- static DisableFor(obj) {
- delete obj._tags;
- delete obj.hasTags;
- delete obj.addTags;
- delete obj.removeTags;
- delete obj.matchesTagsQuery;
- }
- 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;
- }
- 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;
- }
- }
- static AddTagsTo(obj, tagsString) {
- if (!tagsString) {
- return;
- }
- if (typeof tagsString !== "string") {
- return;
- }
- const tags = tagsString.split(" ");
- tags.forEach(function(tag) {
- Tags._AddTagTo(obj, tag);
- });
- }
- 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;
- }
- static RemoveTagsFrom(obj, tagsString) {
- if (!Tags.HasTags(obj)) {
- return;
- }
- const tags = tagsString.split(" ");
- for (const t in tags) {
- Tags._RemoveTagFrom(obj, tags[t]);
- }
- }
- static _RemoveTagFrom(obj, tag) {
- delete obj._tags[tag];
- }
- 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]);
- }
-}
-var init_tags = () => {};
-
-// node_modules/@babylonjs/core/Misc/decorators.serialization.js
-class SerializationHelper {
- 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 Serialize(entity, serializationObject) {
- if (!serializationObject) {
- serializationObject = {};
- }
- if (Tags) {
- serializationObject.tags = Tags.GetTags(entity);
- }
- const serializedProperties = GetMergedStore(entity);
- 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:
- serializationObject[targetPropertyName] = sourceProperty;
- break;
- case 1:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 2:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 3:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 4:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 5:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 6:
- serializationObject[targetPropertyName] = sourceProperty.id;
- break;
- case 7:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 8:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 9:
- serializationObject[targetPropertyName] = sourceProperty.serialize();
- break;
- case 10:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- case 11:
- serializationObject[targetPropertyName] = sourceProperty.id;
- break;
- case 12:
- serializationObject[targetPropertyName] = sourceProperty.asArray();
- break;
- }
- }
- }
- return serializationObject;
- }
- static ParseProperties(source, destination, scene, rootUrl) {
- if (!rootUrl) {
- rootUrl = "";
- }
- const classStore = GetMergedStore(destination);
- 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:
- dest[property] = sourceProperty;
- break;
- case 1:
- if (scene) {
- dest[property] = SerializationHelper._TextureParser(sourceProperty, scene, rootUrl);
- }
- break;
- case 2:
- dest[property] = Color3.FromArray(sourceProperty);
- break;
- case 3:
- dest[property] = SerializationHelper._FresnelParametersParser(sourceProperty);
- break;
- case 4:
- dest[property] = Vector2.FromArray(sourceProperty);
- break;
- case 5:
- dest[property] = Vector3.FromArray(sourceProperty);
- break;
- case 6:
- if (scene) {
- dest[property] = scene.getLastMeshById(sourceProperty);
- }
- break;
- case 7:
- dest[property] = SerializationHelper._ColorCurvesParser(sourceProperty);
- break;
- case 8:
- dest[property] = Color4.FromArray(sourceProperty);
- break;
- case 9:
- dest[property] = SerializationHelper._ImageProcessingConfigurationParser(sourceProperty);
- break;
- case 10:
- dest[property] = Quaternion.FromArray(sourceProperty);
- break;
- case 11:
- if (scene) {
- dest[property] = scene.getCameraById(sourceProperty);
- }
- break;
- case 12:
- dest[property] = Matrix.FromArray(sourceProperty);
- break;
- }
- }
- }
- }
- static Parse(creationFunction, source, scene, rootUrl = null) {
- const destination = creationFunction();
- if (Tags) {
- Tags.AddTagsTo(destination, source.tags);
- }
- SerializationHelper.ParseProperties(source, destination, scene, rootUrl);
- return destination;
- }
- static Clone(creationFunction, source, options = {}) {
- return _copySource(creationFunction, source, false, options);
- }
- static Instanciate(creationFunction, source) {
- return _copySource(creationFunction, source, true);
- }
-}
-var _copySource = function(creationFunction, source, instanciate, options = {}) {
- const destination = creationFunction();
- if (Tags && Tags.HasTags(source)) {
- Tags.AddTagsTo(destination, Tags.GetTags(source, true));
- }
- const classStore = GetMergedStore(destination);
- const textureMap = {};
- 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:
- case 6:
- case 9:
- case 11:
- destination[property] = sourceProperty;
- break;
- case 1:
- 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:
- case 3:
- case 4:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:
- destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
- break;
- }
- }
- }
- return destination;
-};
-var init_decorators_serialization = __esm(() => {
- init_devTools();
- init_tags();
- init_math_color();
- init_math_vector();
- init_decorators_functions();
- SerializationHelper.AllowLoadingUniqueId = false;
- SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => {
- throw _WarnImport("ImageProcessingConfiguration");
- };
- SerializationHelper._FresnelParametersParser = (sourceProperty) => {
- throw _WarnImport("FresnelParameters");
- };
- SerializationHelper._ColorCurvesParser = (sourceProperty) => {
- throw _WarnImport("ColorCurves");
- };
- SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => {
- throw _WarnImport("Texture");
- };
-});
-
-// node_modules/@babylonjs/core/node.js
-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;
- }
-}
-
-class Node2 {
- static AddNodeConstructor(type, constructorFunc) {
- this._NodeConstructors[type] = constructorFunc;
- }
- static Construct(type, name2, scene, options) {
- const constructorFunc = this._NodeConstructors[type];
- if (!constructorFunc) {
- return null;
- }
- return constructorFunc(name2, scene, options);
- }
- set accessibilityTag(value) {
- this._accessibilityTag = value;
- this.onAccessibilityTagChangedObservable.notifyObservers(value);
- }
- get accessibilityTag() {
- return this._accessibilityTag;
- }
- get doNotSerialize() {
- if (this._nodeDataStorage._doNotSerialize) {
- return true;
- }
- if (this._parentNode) {
- return this._parentNode.doNotSerialize;
- }
- return false;
- }
- set doNotSerialize(value) {
- this._nodeDataStorage._doNotSerialize = value;
- }
- isDisposed() {
- return this._nodeDataStorage._isDisposed;
- }
- set parent(parent) {
- if (this._parentNode === parent) {
- return;
- }
- const previousParentNode = this._parentNode;
- 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();
- }
- }
- this._parentNode = parent;
- this._isDirty = true;
- 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();
- }
- }
- this._syncParentEnabledState();
- }
- get parent() {
- return this._parentNode;
- }
- _serializeAsParent(serializationObject) {
- serializationObject.parentId = this.uniqueId;
- }
- _addToSceneRootNodes() {
- if (this._nodeDataStorage._sceneRootNodesIndex === -1) {
- this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length;
- this._scene.rootNodes.push(this);
- }
- }
- _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;
- }
- }
- get animationPropertiesOverride() {
- if (!this._animationPropertiesOverride) {
- return this._scene.animationPropertiesOverride;
- }
- return this._animationPropertiesOverride;
- }
- set animationPropertiesOverride(value) {
- this._animationPropertiesOverride = value;
- }
- getClassName() {
- return "Node";
- }
- set onDispose(callback) {
- if (this._onDisposeObserver) {
- this.onDisposeObservable.remove(this._onDisposeObserver);
- }
- this._onDisposeObserver = this.onDisposeObservable.add(callback);
- }
- get onEnabledStateChangedObservable() {
- return this._nodeDataStorage._onEnabledStateChangedObservable;
- }
- get onClonedObservable() {
- return this._nodeDataStorage._onClonedObservable;
- }
- constructor(name2, scene = null, isPure = true) {
- this._isDirty = false;
- this._nodeDataStorage = new _InternalNodeDataInfo;
- this.state = "";
- this.metadata = null;
- this.reservedDataStore = null;
- this._accessibilityTag = null;
- this.onAccessibilityTagChangedObservable = new Observable;
- this._parentContainer = null;
- this.animations = [];
- this._ranges = {};
- this.onReady = null;
- this._currentRenderId = -1;
- this._parentUpdateId = -1;
- this._childUpdateId = -1;
- this._waitingParentId = null;
- this._waitingParentInstanceIndex = null;
- this._waitingParsedUniqueId = null;
- this._cache = {};
- this._parentNode = null;
- this._children = null;
- this._worldMatrix = Matrix.Identity();
- this._worldMatrixDeterminant = 0;
- this._worldMatrixDeterminantIsDirty = true;
- this._animationPropertiesOverride = null;
- this._isNode = true;
- this.onDisposeObservable = new Observable;
- this._onDisposeObserver = null;
- this._behaviors = new Array;
- this.name = name2;
- this.id = name2;
- this._scene = scene || EngineStore.LastCreatedScene;
- this.uniqueId = this._scene.getUniqueId();
- this._initCache();
- if (isPure) {
- this._addToSceneRootNodes();
- }
- }
- getScene() {
- return this._scene;
- }
- getEngine() {
- return this._scene.getEngine();
- }
- addBehavior(behavior, attachImmediately = false) {
- const index = this._behaviors.indexOf(behavior);
- if (index !== -1) {
- return this;
- }
- behavior.init();
- if (this._scene.isLoading && !attachImmediately) {
- this._scene.onDataLoadedObservable.addOnce(() => {
- behavior.attach(this);
- });
- } else {
- behavior.attach(this);
- }
- this._behaviors.push(behavior);
- return this;
- }
- removeBehavior(behavior) {
- const index = this._behaviors.indexOf(behavior);
- if (index === -1) {
- return this;
- }
- this._behaviors[index].detach();
- this._behaviors.splice(index, 1);
- return this;
- }
- get behaviors() {
- return this._behaviors;
- }
- getBehaviorByName(name2) {
- for (const behavior of this._behaviors) {
- if (behavior.name === name2) {
- return behavior;
- }
- }
- return null;
- }
- getWorldMatrix() {
- if (this._currentRenderId !== this._scene.getRenderId()) {
- this.computeWorldMatrix();
- }
- return this._worldMatrix;
- }
- _getWorldMatrixDeterminant() {
- if (this._worldMatrixDeterminantIsDirty) {
- this._worldMatrixDeterminantIsDirty = false;
- this._worldMatrixDeterminant = this._worldMatrix.determinant();
- }
- return this._worldMatrixDeterminant;
- }
- get worldMatrixFromCache() {
- return this._worldMatrix;
- }
- _initCache() {
- this._cache = {};
- }
- updateCache(force) {
- if (!force && this.isSynchronized()) {
- return;
- }
- this._updateCache();
- }
- _getActionManagerForTrigger(trigger, _initialCall = true) {
- if (!this.parent) {
- return null;
- }
- return this.parent._getActionManagerForTrigger(trigger, false);
- }
- _updateCache(_ignoreParentClass) {}
- _isSynchronized() {
- return true;
- }
- _markSyncedWithParent() {
- if (this._parentNode) {
- this._parentUpdateId = this._parentNode._childUpdateId;
- }
- }
- isSynchronizedWithParent() {
- if (!this._parentNode) {
- return true;
- }
- if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) {
- return false;
- }
- return this._parentNode.isSynchronized();
- }
- isSynchronized() {
- if (this._parentNode && !this.isSynchronizedWithParent()) {
- return false;
- }
- return this._isSynchronized();
- }
- isReady(_completeCheck = false) {
- return this._nodeDataStorage._isReady;
- }
- markAsDirty(_property) {
- this._currentRenderId = Number.MAX_VALUE;
- this._isDirty = true;
- return this;
- }
- isEnabled(checkAncestors = true) {
- if (checkAncestors === false) {
- return this._nodeDataStorage._isEnabled;
- }
- if (!this._nodeDataStorage._isEnabled) {
- return false;
- }
- return this._nodeDataStorage._isParentEnabled;
- }
- _syncParentEnabledState() {
- this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
- if (this._children) {
- this._children.forEach((c) => {
- c._syncParentEnabledState();
- });
- }
- }
- setEnabled(value) {
- if (this._nodeDataStorage._isEnabled === value) {
- return;
- }
- this._nodeDataStorage._isEnabled = value;
- this._syncParentEnabledState();
- this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value);
- }
- isDescendantOf(ancestor) {
- if (this.parent) {
- if (this.parent === ancestor) {
- return true;
- }
- return this.parent.isDescendantOf(ancestor);
- }
- return false;
- }
- _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);
- }
- }
- }
- getDescendants(directDescendantsOnly, predicate) {
- const results = [];
- this._getDescendants(results, directDescendantsOnly, predicate);
- return results;
- }
- getChildMeshes(directDescendantsOnly, predicate) {
- const results = [];
- this._getDescendants(results, directDescendantsOnly, (node) => {
- return (!predicate || predicate(node)) && node.cullingStrategy !== undefined;
- });
- return results;
- }
- getChildren(predicate, directDescendantsOnly = true) {
- return this.getDescendants(directDescendantsOnly, predicate);
- }
- _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;
- }
- getAnimationByName(name2) {
- for (let i = 0;i < this.animations.length; i++) {
- const animation = this.animations[i];
- if (animation.name === name2) {
- return animation;
- }
- }
- return null;
- }
- createAnimationRange(name2, from, to) {
- if (!this._ranges[name2]) {
- this._ranges[name2] = Node2._AnimationRangeFactory(name2, from, to);
- for (let i = 0, nAnimations = this.animations.length;i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].createRange(name2, from, to);
- }
- }
- }
- }
- deleteAnimationRange(name2, deleteFrames = true) {
- for (let i = 0, nAnimations = this.animations.length;i < nAnimations; i++) {
- if (this.animations[i]) {
- this.animations[i].deleteRange(name2, deleteFrames);
- }
- }
- this._ranges[name2] = null;
- }
- getAnimationRange(name2) {
- return this._ranges[name2] || null;
- }
- clone(name2, newParent, doNotCloneChildren) {
- const result = SerializationHelper.Clone(() => new Node2(name2, this.getScene()), this);
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- const directDescendants = this.getDescendants(true);
- for (let index = 0;index < directDescendants.length; index++) {
- const child = directDescendants[index];
- child.clone(name2 + "." + child.name, result);
- }
- }
- return result;
- }
- getAnimationRanges() {
- const animationRanges = [];
- let name2;
- for (name2 in this._ranges) {
- animationRanges.push(this._ranges[name2]);
- }
- return animationRanges;
- }
- beginAnimation(name2, loop, speedRatio, onAnimationEnd) {
- const range = this.getAnimationRange(name2);
- if (!range) {
- return null;
- }
- return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
- }
- serializeAnimationRanges() {
- const serializationRanges = [];
- for (const name2 in this._ranges) {
- const localRange = this._ranges[name2];
- if (!localRange) {
- continue;
- }
- const range = {};
- range.name = name2;
- range.from = localRange.from;
- range.to = localRange.to;
- serializationRanges.push(range);
- }
- return serializationRanges;
- }
- computeWorldMatrix(_force) {
- if (!this._worldMatrix) {
- this._worldMatrix = Matrix.Identity();
- }
- return this._worldMatrix;
- }
- 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;
- }
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- this.onEnabledStateChangedObservable.clear();
- this.onClonedObservable.clear();
- for (const behavior of this._behaviors) {
- behavior.detach();
- }
- this._behaviors.length = 0;
- this.metadata = null;
- }
- 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);
- }
- }
- }
- getHierarchyBoundingVectors(includeDescendants = true, predicate = null) {
- this.getScene().incrementRenderId();
- this.computeWorldMatrix(true);
- let min;
- let max;
- const thisAbstractMesh = this;
- if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) {
- 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);
- if (predicate && !predicate(childMesh)) {
- continue;
- }
- 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,
- max
- };
- }
-}
-var init_node = __esm(() => {
- init_tslib_es6();
- init_math_vector();
- init_decorators();
- init_observable();
- init_engineStore();
- init_devTools();
- init_decorators_serialization();
- Node2._AnimationRangeFactory = (_name, _from, _to) => {
- throw _WarnImport("AnimationRange");
- };
- Node2._NodeConstructors = {};
- __decorate([
- serialize()
- ], Node2.prototype, "name", undefined);
- __decorate([
- serialize()
- ], Node2.prototype, "id", undefined);
- __decorate([
- serialize()
- ], Node2.prototype, "uniqueId", undefined);
- __decorate([
- serialize()
- ], Node2.prototype, "state", undefined);
- __decorate([
- serialize()
- ], Node2.prototype, "metadata", undefined);
-});
-
-// node_modules/@babylonjs/core/Maths/math.size.js
-class Size {
- constructor(width, height) {
- this.width = width;
- this.height = height;
- }
- toString() {
- return `{W: ${this.width}, H: ${this.height}}`;
- }
- getClassName() {
- return "Size";
- }
- getHashCode() {
- let hash2 = this.width | 0;
- hash2 = hash2 * 397 ^ (this.height | 0);
- return hash2;
- }
- copyFrom(src) {
- this.width = src.width;
- this.height = src.height;
- }
- copyFromFloats(width, height) {
- this.width = width;
- this.height = height;
- return this;
- }
- set(width, height) {
- return this.copyFromFloats(width, height);
- }
- multiplyByFloats(w, h) {
- return new Size(this.width * w, this.height * h);
- }
- clone() {
- return new Size(this.width, this.height);
- }
- equals(other) {
- if (!other) {
- return false;
- }
- return this.width === other.width && this.height === other.height;
- }
- get surface() {
- return this.width * this.height;
- }
- static Zero() {
- return new Size(0, 0);
- }
- add(otherSize) {
- const r = new Size(this.width + otherSize.width, this.height + otherSize.height);
- return r;
- }
- subtract(otherSize) {
- const r = new Size(this.width - otherSize.width, this.height - otherSize.height);
- return r;
- }
- scale(scale) {
- return new Size(this.width * scale, this.height * scale);
- }
- 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);
- }
-}
-
-// node_modules/@babylonjs/core/Misc/webRequest.js
-function createXMLHttpRequest() {
- if (typeof _native !== "undefined" && _native.XMLHttpRequest) {
- return new _native.XMLHttpRequest;
- } else {
- return new XMLHttpRequest;
- }
-}
-
-class WebRequest {
- constructor() {
- this._xhr = createXMLHttpRequest();
- this._requestURL = "";
- }
- static get IsCustomRequestAvailable() {
- return Object.keys(WebRequest.CustomRequestHeaders).length > 0 || WebRequest.CustomRequestModifiers.length > 0;
- }
- 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"));
- }
- get onprogress() {
- return this._xhr.onprogress;
- }
- set onprogress(value) {
- this._xhr.onprogress = value;
- }
- get readyState() {
- return this._xhr.readyState;
- }
- get status() {
- return this._xhr.status;
- }
- get statusText() {
- return this._xhr.statusText;
- }
- get response() {
- return this._xhr.response;
- }
- get responseURL() {
- return this._xhr.responseURL;
- }
- get responseText() {
- return this._xhr.responseText;
- }
- get responseType() {
- return this._xhr.responseType;
- }
- set responseType(value) {
- this._xhr.responseType = value;
- }
- 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);
- }
- abort() {
- this._xhr.abort();
- }
- send(body) {
- if (WebRequest.CustomRequestHeaders) {
- this._injectCustomRequestHeaders();
- }
- this._xhr.send(body);
- }
- open(method, url) {
- for (const update of WebRequest.CustomRequestModifiers) {
- if (this._shouldSkipRequestModifications(url)) {
- return;
- }
- url = update(this._xhr, url) || url;
- }
- url = url.replace("file:http:", "http:");
- url = url.replace("file:https:", "https:");
- this._requestURL = url;
- this._xhr.open(method, url, true);
- }
- setRequestHeader(name2, value) {
- this._xhr.setRequestHeader(name2, value);
- }
- getResponseHeader(name2) {
- return this._xhr.getResponseHeader(name2);
- }
-}
-var init_webRequest = __esm(() => {
- WebRequest.CustomRequestHeaders = {};
- WebRequest.CustomRequestModifiers = new Array;
- WebRequest.SkipRequestModificationForBabylonCDN = true;
-});
-
-// node_modules/@babylonjs/core/Animations/animation.js
-class Animation {
- static _PrepareAnimation(name2, 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(name2, 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;
- }
- static CreateAnimation(property, animationType, framePerSecond, easingFunction) {
- const animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
- animation.setEasingFunction(easingFunction);
- return animation;
- }
- static CreateAndStartAnimation(name2, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) {
- const animation = Animation._PrepareAnimation(name2, 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, onAnimationEnd);
- }
- static CreateAndStartHierarchyAnimation(name2, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- const animation = Animation._PrepareAnimation(name2, 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, onAnimationEnd);
- }
- static CreateMergeAndStartAnimation(name2, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
- const animation = Animation._PrepareAnimation(name2, 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, onAnimationEnd);
- }
- static MakeAnimationAdditive(sourceAnimation, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) {
- let options;
- if (typeof referenceFrameOrOptions === "object") {
- options = referenceFrameOrOptions;
- } else {
- options = {
- referenceFrame: referenceFrameOrOptions ?? 0,
- 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);
- }
- if (animation._keys.length === 1) {
- const value = animation._getKeyValue(animation._keys[0]);
- valueStore.referenceValue = value.clone ? value.clone() : value;
- } else if (referenceFrame <= firstKey.frame) {
- const value = animation._getKeyValue(firstKey.value);
- valueStore.referenceValue = value.clone ? value.clone() : value;
- } else if (referenceFrame >= lastKey.frame) {
- const value = animation._getKeyValue(lastKey.value);
- valueStore.referenceValue = value.clone ? value.clone() : value;
- } else {
- evaluateAnimationState.key = 0;
- const value = animation._interpolate(referenceFrame, evaluateAnimationState);
- valueStore.referenceValue = value.clone ? value.clone() : value;
- }
- if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) {
- valueStore.referenceValue.normalize().conjugateInPlace();
- } 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;
- 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 (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;
- }
- 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;
- }
- get runtimeAnimations() {
- return this._runtimeAnimations;
- }
- get hasRunningRuntimeAnimations() {
- for (const runtimeAnimation of this._runtimeAnimations) {
- if (!runtimeAnimation.isStopped()) {
- return true;
- }
- }
- return false;
- }
- constructor(name2, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
- this.name = name2;
- this.targetProperty = targetProperty;
- this.framePerSecond = framePerSecond;
- this.dataType = dataType;
- this.loopMode = loopMode;
- this.enableBlending = enableBlending;
- this._easingFunction = null;
- this._runtimeAnimations = new Array;
- this._events = new Array;
- this.blendingSpeed = 0.01;
- this._ranges = {};
- this.targetPropertyPath = targetProperty.split(".");
- this.dataType = dataType;
- this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
- this.uniqueId = Animation._UniqueIdGenerator++;
- }
- 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 name2 in this._ranges) {
- if (first) {
- ret += ", ";
- first = false;
- }
- ret += name2;
- }
- ret += "}";
- }
- return ret;
- }
- addEvent(event) {
- this._events.push(event);
- this._events.sort((a, b) => a.frame - b.frame);
- }
- removeEvents(frame) {
- for (let index = 0;index < this._events.length; index++) {
- if (this._events[index].frame === frame) {
- this._events.splice(index, 1);
- index--;
- }
- }
- }
- getEvents() {
- return this._events;
- }
- createRange(name2, from, to) {
- if (!this._ranges[name2]) {
- this._ranges[name2] = new AnimationRange(name2, from, to);
- }
- }
- deleteRange(name2, deleteFrames = true) {
- const range = this._ranges[name2];
- if (!range) {
- return;
- }
- if (deleteFrames) {
- const from = range.from;
- const to = range.to;
- 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[name2] = null;
- }
- getRange(name2) {
- return this._ranges[name2];
- }
- getKeys() {
- return this._keys;
- }
- 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;
- }
- getEasingFunction() {
- return this._easingFunction;
- }
- setEasingFunction(easingFunction) {
- this._easingFunction = easingFunction;
- }
- floatInterpolateFunction(startValue, endValue, gradient) {
- return Lerp(startValue, endValue, gradient);
- }
- floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Hermite(startValue, outTangent, endValue, inTangent, gradient);
- }
- quaternionInterpolateFunction(startValue, endValue, gradient) {
- return Quaternion.Slerp(startValue, endValue, gradient);
- }
- quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
- }
- vector3InterpolateFunction(startValue, endValue, gradient) {
- return Vector3.Lerp(startValue, endValue, gradient);
- }
- vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
- }
- vector2InterpolateFunction(startValue, endValue, gradient) {
- return Vector2.Lerp(startValue, endValue, gradient);
- }
- vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
- }
- sizeInterpolateFunction(startValue, endValue, gradient) {
- return Size.Lerp(startValue, endValue, gradient);
- }
- color3InterpolateFunction(startValue, endValue, gradient) {
- return Color3.Lerp(startValue, endValue, gradient);
- }
- color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
- }
- color4InterpolateFunction(startValue, endValue, gradient) {
- return Color4.Lerp(startValue, endValue, gradient);
- }
- color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {
- return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient);
- }
- _getKeyValue(value) {
- if (typeof value === "function") {
- return value();
- }
- return value;
- }
- evaluate(currentFrame) {
- evaluateAnimationState.key = 0;
- return this._interpolate(currentFrame, evaluateAnimationState);
- }
- _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;
- }
- const startValue = this._getKeyValue(startKey.value);
- const endValue = this._getKeyValue(endKey.value);
- if (startKey.interpolation === 1) {
- if (endKey.frame > currentFrame) {
- return startValue;
- } else {
- return endValue;
- }
- }
- const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
- const frameDelta = endKey.frame - startKey.frame;
- let gradient = (currentFrame - startKey.frame) / frameDelta;
- const easingFunction = startKey.easingFunction || this.getEasingFunction();
- if (easingFunction) {
- gradient = easingFunction.ease(gradient);
- }
- switch (this.dataType) {
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- 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);
- }
- 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 name2 in this._ranges) {
- const range = this._ranges[name2];
- if (!range) {
- continue;
- }
- clone._ranges[name2] = range.clone();
- }
- }
- return clone;
- }
- setKeys(values, dontClone = false) {
- this._keys = !dontClone ? values.slice(0) : values;
- }
- createKeyForFrame(frame) {
- evaluateAnimationState.key = 0;
- const value = this._interpolate(frame, evaluateAnimationState, true);
- if (!value) {
- return this._keys[evaluateAnimationState.key].frame === frame ? evaluateAnimationState.key : evaluateAnimationState.key + 1;
- }
- const newKey = {
- frame,
- value: value.clone ? value.clone() : value
- };
- this._keys.splice(evaluateAnimationState.key + 1, 0, newKey);
- return evaluateAnimationState.key + 1;
- }
- 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 != null) {
- key.values.push(animationKey.inTangent.asArray());
- }
- if (animationKey.outTangent != null) {
- 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 name2 in this._ranges) {
- const source = this._ranges[name2];
- if (!source) {
- continue;
- }
- const range = {};
- range.name = name2;
- range.from = source.from;
- range.to = source.to;
- serializationObject.ranges.push(range);
- }
- return serializationObject;
- }
- static _UniversalLerp(left, right, amount) {
- const constructor = left.constructor;
- if (constructor.Lerp) {
- return constructor.Lerp(left, right, amount);
- } else if (constructor.Slerp) {
- return constructor.Slerp(left, right, amount);
- } else if (left.toFixed) {
- return left * (1 - amount) + amount * right;
- } else {
- return right;
- }
- }
- 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 != null) {
- keyData.inTangent = inTangent;
- }
- if (outTangent != null) {
- keyData.outTangent = outTangent;
- }
- if (interpolation != null) {
- 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;
- }
- static AppendSerializedAnimations(source, destination) {
- SerializationHelper.AppendSerializedAnimations(source, destination);
- }
- static ParseFromFileAsync(name2, url) {
- return new Promise((resolve3, 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));
- }
- resolve3(output);
- } else {
- const output = this.Parse(serializationObject);
- if (name2) {
- output.name = name2;
- }
- resolve3(output);
- }
- } else {
- reject("Unable to load the animation");
- }
- }
- });
- request.open("GET", url);
- request.send();
- });
- }
- static ParseFromSnippetAsync(snippetId) {
- return new Promise((resolve3, 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);
- }
- resolve3(outputs);
- } else {
- const serializationObject = JSON.parse(snippet.animation);
- const output = this.Parse(serializationObject);
- output.snippetId = snippetId;
- resolve3(output);
- }
- } else {
- reject("Unable to load the snippet " + snippetId);
- }
- }
- });
- request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
- request.send();
- });
- }
-}
-var _staticOffsetValueQuaternion, _staticOffsetValueVector3, _staticOffsetValueVector2, _staticOffsetValueSize, _staticOffsetValueColor3, _staticOffsetValueColor4, evaluateAnimationState;
-var init_animation = __esm(() => {
- init_math_vector();
- init_math_color();
- init_typeStore();
- init_node();
- init_webRequest();
- init_decorators_serialization();
- _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0));
- _staticOffsetValueVector3 = Object.freeze(Vector3.Zero());
- _staticOffsetValueVector2 = Object.freeze(Vector2.Zero());
- _staticOffsetValueSize = Object.freeze(Size.Zero());
- _staticOffsetValueColor3 = Object.freeze(Color3.Black());
- _staticOffsetValueColor4 = Object.freeze(new Color4(0, 0, 0, 0));
- evaluateAnimationState = {
- key: 0,
- repeatCount: 0,
- loopMode: 2
- };
- Animation._UniqueIdGenerator = 0;
- Animation.AllowMatricesInterpolation = false;
- Animation.AllowMatrixDecomposeForInterpolation = true;
- Animation.SnippetUrl = `https://snippet.babylonjs.com`;
- Animation.ANIMATIONTYPE_FLOAT = 0;
- Animation.ANIMATIONTYPE_VECTOR3 = 1;
- Animation.ANIMATIONTYPE_QUATERNION = 2;
- Animation.ANIMATIONTYPE_MATRIX = 3;
- Animation.ANIMATIONTYPE_COLOR3 = 4;
- Animation.ANIMATIONTYPE_COLOR4 = 7;
- Animation.ANIMATIONTYPE_VECTOR2 = 5;
- Animation.ANIMATIONTYPE_SIZE = 6;
- Animation.ANIMATIONLOOPMODE_RELATIVE = 0;
- Animation.ANIMATIONLOOPMODE_CYCLE = 1;
- Animation.ANIMATIONLOOPMODE_CONSTANT = 2;
- Animation.ANIMATIONLOOPMODE_YOYO = 4;
- Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT = 5;
- Animation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync;
- RegisterClass("BABYLON.Animation", Animation);
- Node2._AnimationRangeFactory = (name2, from, to) => new AnimationRange(name2, from, to);
-});
-
-// node_modules/@babylonjs/core/Bones/bone.js
-var Bone;
-var init_bone = __esm(() => {
- init_math_vector();
- init_arrayTools();
- init_node();
- Bone = class Bone extends Node2 {
- get _matrix() {
- this._compose();
- return this._localMatrix;
- }
- set _matrix(value) {
- if (value.updateFlag === this._localMatrix.updateFlag && !this._needToCompose) {
- return;
- }
- this._needToCompose = false;
- this._localMatrix.copyFrom(value);
- this._markAsDirtyAndDecompose();
- }
- constructor(name2, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) {
- super(name2, skeleton.getScene(), false);
- this.name = name2;
- this.children = [];
- this.animations = [];
- this._index = null;
- this._scalingDeterminant = 1;
- this._needToDecompose = true;
- this._needToCompose = false;
- this._linkedTransformNode = null;
- 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();
- }
- getClassName() {
- return "Bone";
- }
- getSkeleton() {
- return this._skeleton;
- }
- get parent() {
- return this._parentNode;
- }
- getParent() {
- return this.parent;
- }
- getChildren() {
- return this.children;
- }
- getIndex() {
- return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index;
- }
- set parent(newParent) {
- this.setParent(newParent);
- }
- 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();
- }
- getLocalMatrix() {
- this._compose();
- return this._localMatrix;
- }
- getBindMatrix() {
- return this._bindMatrix;
- }
- getBaseMatrix() {
- return this.getBindMatrix();
- }
- getRestMatrix() {
- return this._restMatrix;
- }
- getRestPose() {
- return this.getRestMatrix();
- }
- setRestMatrix(matrix) {
- this._restMatrix.copyFrom(matrix);
- }
- setRestPose(matrix) {
- this.setRestMatrix(matrix);
- }
- getBindPose() {
- return this.getBindMatrix();
- }
- setBindMatrix(matrix) {
- this.updateMatrix(matrix);
- }
- setBindPose(matrix) {
- this.setBindMatrix(matrix);
- }
- getFinalMatrix() {
- return this._finalMatrix;
- }
- getWorldMatrix() {
- return this.getFinalMatrix();
- }
- 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;
- }
- }
- getAbsoluteInverseBindMatrix() {
- return this._absoluteInverseBindMatrix;
- }
- getInvertedAbsoluteTransform() {
- return this.getAbsoluteInverseBindMatrix();
- }
- getAbsoluteMatrix() {
- return this._absoluteMatrix;
- }
- getAbsoluteTransform() {
- return this._absoluteMatrix;
- }
- linkTransformNode(transformNode) {
- if (this._linkedTransformNode) {
- this._skeleton._numBonesWithLinkedTransformNode--;
- }
- this._linkedTransformNode = transformNode;
- if (this._linkedTransformNode) {
- this._skeleton._numBonesWithLinkedTransformNode++;
- }
- }
- getTransformNode() {
- return this._linkedTransformNode;
- }
- get position() {
- this._decompose();
- return this._localPosition;
- }
- set position(newPosition) {
- this._decompose();
- this._localPosition.copyFrom(newPosition);
- this._markAsDirtyAndCompose();
- }
- get rotation() {
- return this.getRotation();
- }
- set rotation(newRotation) {
- this.setRotation(newRotation);
- }
- get rotationQuaternion() {
- this._decompose();
- return this._localRotation;
- }
- set rotationQuaternion(newRotation) {
- this.setRotationQuaternion(newRotation);
- }
- get scaling() {
- return this.getScale();
- }
- set scaling(newScaling) {
- this.setScale(newScaling);
- }
- get animationPropertiesOverride() {
- return this._skeleton.animationPropertiesOverride;
- }
- _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);
- }
- updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) {
- this._bindMatrix.copyFrom(bindMatrix);
- if (updateAbsoluteBindMatrices) {
- this._updateAbsoluteBindMatrices();
- }
- if (updateLocalMatrix) {
- this._matrix = bindMatrix;
- } else {
- this.markAsDirty();
- }
- }
- _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;
- }
- markAsDirty() {
- this._currentRenderId++;
- this._childUpdateId++;
- this._skeleton._markAsDirty();
- return this;
- }
- _markAsDirtyAndCompose() {
- this.markAsDirty();
- this._needToCompose = true;
- }
- _markAsDirtyAndDecompose() {
- this.markAsDirty();
- this._needToDecompose = true;
- }
- _updatePosition(vec, space = 0, tNode, translationMode = true) {
- const lm = this.getLocalMatrix();
- if (space == 0) {
- 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;
- 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(vec, space = 0, tNode) {
- this._updatePosition(vec, space, tNode, true);
- }
- setPosition(position, space = 0, tNode) {
- this._updatePosition(position, space, tNode, false);
- }
- setAbsolutePosition(position, tNode) {
- this.setPosition(position, 1, tNode);
- }
- scale(x, y, z, scaleChildren = false) {
- const locMat = this.getLocalMatrix();
- const scaleMat = Bone._TmpMats[0];
- Matrix.ScalingToRef(x, y, z, scaleMat);
- scaleMat.multiplyToRef(locMat, locMat);
- 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);
- }
- }
- }
- setScale(scale) {
- this._decompose();
- this._localScaling.copyFrom(scale);
- this._markAsDirtyAndCompose();
- }
- getScale() {
- this._decompose();
- return this._localScaling;
- }
- getScaleToRef(result) {
- this._decompose();
- result.copyFrom(this._localScaling);
- }
- setYawPitchRoll(yaw, pitch, roll, space = 0, tNode) {
- if (space === 0) {
- 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);
- }
- rotate(axis, amount, space = 0, tNode) {
- const rmat = Bone._TmpMats[0];
- rmat.setTranslationFromFloats(0, 0, 0);
- Matrix.RotationAxisToRef(axis, amount, rmat);
- this._rotateWithMatrix(rmat, space, tNode);
- }
- setAxisAngle(axis, angle, space = 0, tNode) {
- if (space === 0) {
- 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);
- }
- setRotation(rotation, space = 0, tNode) {
- this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode);
- }
- setRotationQuaternion(quat, space = 0, tNode) {
- if (space === 0) {
- 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);
- }
- setRotationMatrix(rotMat, space = 0, tNode) {
- if (space === 0) {
- 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, 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) {
- 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 && 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])) {
- return false;
- }
- scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
- rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
- return true;
- }
- getPosition(space = 0, tNode = null) {
- const pos = Vector3.Zero();
- this.getPositionToRef(space, tNode, pos);
- return pos;
- }
- getPositionToRef(space = 0, tNode, result) {
- if (space == 0) {
- const lm = this.getLocalMatrix();
- result.x = lm.m[12];
- result.y = lm.m[13];
- result.z = lm.m[14];
- } else {
- let wm = null;
- 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];
- }
- }
- getAbsolutePosition(tNode = null) {
- const pos = Vector3.Zero();
- this.getPositionToRef(1, tNode, pos);
- return pos;
- }
- getAbsolutePositionToRef(tNode, result) {
- this.getPositionToRef(1, tNode, result);
- }
- 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();
- }
- }
- computeAbsoluteTransforms() {
- this.computeAbsoluteMatrices();
- }
- getDirection(localAxis, tNode = null) {
- const result = Vector3.Zero();
- this.getDirectionToRef(localAxis, tNode, result);
- return result;
- }
- getDirectionToRef(localAxis, tNode = null, result) {
- let wm = null;
- 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();
- }
- getRotation(space = 0, tNode = null) {
- const result = Vector3.Zero();
- this.getRotationToRef(space, tNode, result);
- return result;
- }
- getRotationToRef(space = 0, tNode = null, result) {
- const quat = Bone._TmpQuat;
- this.getRotationQuaternionToRef(space, tNode, quat);
- quat.toEulerAnglesToRef(result);
- }
- getRotationQuaternion(space = 0, tNode = null) {
- const result = Quaternion.Identity();
- this.getRotationQuaternionToRef(space, tNode, result);
- return result;
- }
- getRotationQuaternionToRef(space = 0, tNode = null, result) {
- if (space == 0) {
- 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);
- }
- }
- getRotationMatrix(space = 0, tNode) {
- const result = Matrix.Identity();
- this.getRotationMatrixToRef(space, tNode, result);
- return result;
- }
- getRotationMatrixToRef(space = 0, tNode, result) {
- if (space == 0) {
- 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);
- }
- }
- getAbsolutePositionFromLocal(position, tNode = null) {
- const result = Vector3.Zero();
- this.getAbsolutePositionFromLocalToRef(position, tNode, result);
- return result;
- }
- getAbsolutePositionFromLocalToRef(position, tNode = null, result) {
- let wm = null;
- 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);
- }
- getLocalPositionFromAbsolute(position, tNode = null) {
- const result = Vector3.Zero();
- this.getLocalPositionFromAbsoluteToRef(position, tNode, result);
- return result;
- }
- getLocalPositionFromAbsoluteToRef(position, tNode = null, result) {
- let wm = null;
- 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);
- }
- setCurrentPoseAsRest() {
- this.setRestMatrix(this.getLocalMatrix());
- }
- 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 index2 = children.indexOf(this);
- if (index2 !== -1) {
- children.splice(index2, 1);
- }
- }
- super.dispose();
- }
- };
- Bone._TmpVecs = BuildArray(2, Vector3.Zero);
- Bone._TmpQuat = Quaternion.Identity();
- Bone._TmpMats = BuildArray(5, Matrix.Identity);
-});
-
-// node_modules/@babylonjs/core/Animations/runtimeAnimation.js
-class RuntimeAnimation {
- get currentFrame() {
- return this._currentFrame;
- }
- get weight() {
- return this._weight;
- }
- get currentValue() {
- return this._currentValue;
- }
- get targetPath() {
- return this._targetPath;
- }
- get target() {
- return this._currentActiveTarget;
- }
- get isAdditive() {
- return this._host && this._host.isAdditive;
- }
- constructor(target, animation, scene, host) {
- this._events = new Array;
- this._currentFrame = 0;
- this._originalValue = new Array;
- this._originalBlendValue = null;
- this._offsetsCache = {};
- this._highLimitsCache = {};
- this._stopped = false;
- this._blendingFactor = 0;
- this._currentValue = null;
- this._currentActiveTarget = null;
- this._directTarget = null;
- this._targetPath = "";
- this._weight = 1;
- this._absoluteFrameOffset = 0;
- this._previousElapsedTime = 0;
- this._yoyoDirection = 1;
- this._previousAbsoluteFrame = 0;
- this._targetIsArray = false;
- this._animation = animation;
- this._target = target;
- this._scene = scene;
- this._host = host;
- this._activeTargets = [];
- animation._runtimeAnimations.push(this);
- this._animationState = {
- key: 0,
- repeatCount: 0,
- loopMode: this._getCorrectLoopMode()
- };
- if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {
- this._animationState.workValue = Matrix.Zero();
- }
- 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;
- if (this._minFrame !== 0) {
- const newKey = { frame: 0, value: this._minValue };
- this._keys.splice(0, 0, newKey);
- }
- if (this._target instanceof Array) {
- let index = 0;
- for (const target2 of this._target) {
- this._preparePath(target2, index);
- this._getOriginalValues(index);
- index++;
- }
- this._targetIsArray = true;
- } else {
- this._preparePath(this._target);
- this._getOriginalValues();
- this._targetIsArray = false;
- this._directTarget = this._activeTargets[0];
- }
- 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 name2 = targetPropertyPath[index];
- property = property[name2];
- if (property === undefined) {
- throw new Error(`Invalid property (${name2}) 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(".")})`);
- }
- }
- get animation() {
- return this._animation;
- }
- 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;
- for (let index = 0;index < this._events.length; index++) {
- this._events[index].isDone = false;
- }
- }
- isStopped() {
- return this._stopped;
- }
- dispose() {
- const index = this._animation.runtimeAnimations.indexOf(this);
- if (index > -1) {
- this._animation.runtimeAnimations.splice(index, 1);
- }
- }
- 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") {
- 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
- };
- }
- 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) {
- this._currentActiveTarget = destination;
- this._weight = weight;
- if (this._enableBlending && this._blendingFactor <= 1) {
- if (!this._originalBlendValue) {
- const originalValue = destination[this._targetPath];
- if (originalValue.clone) {
- this._originalBlendValue = originalValue.clone();
- } else {
- this._originalBlendValue = originalValue;
- }
- }
- if (this._originalBlendValue.m) {
- 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);
- }
- }
- _getCorrectLoopMode() {
- if (this._target && this._target.animationPropertiesOverride) {
- return this._target.animationPropertiesOverride.loopMode;
- }
- return this._animation.loopMode;
- }
- 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;
- }
- const events = this._events;
- if (events.length) {
- for (let index = 0;index < events.length; index++) {
- if (!events[index].onlyOnce) {
- events[index].isDone = events[index].frame < frame;
- }
- }
- }
- this._currentFrame = frame;
- const currentValue = this._animation._interpolate(frame, this._animationState);
- this.setValue(currentValue, weight);
- }
- _prepareForSpeedRatioChange(newSpeedRatio) {
- const newAbsoluteFrame = this._previousElapsedTime * (this._animation.framePerSecond * newSpeedRatio) / 1000;
- this._absoluteFrameOffset = this._previousAbsoluteFrame - newAbsoluteFrame;
- }
- 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;
- 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;
- let absoluteFrame = elapsedTimeSinceAnimationStart * (animation.framePerSecond * speedRatio) / 1000 + this._absoluteFrameOffset;
- let highLimitValue = 0;
- let yoyoLoop = false;
- const yoyoMode = loop && this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_YOYO;
- if (yoyoMode) {
- const position = (absoluteFrame - from) / frameRange;
- const sin = Math.sin(position * Math.PI);
- const yoyoPosition = Math.abs(sin);
- 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)) {
- 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;
- const fromValue = animation._interpolate(from, this._animationState);
- const toValue = animation._interpolate(to, this._animationState);
- this._animationState.loopMode = this._getCorrectLoopMode();
- switch (animation.dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- this._offsetsCache[keyOffset] = toValue - fromValue;
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- case Animation.ANIMATIONTYPE_VECTOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- case Animation.ANIMATIONTYPE_VECTOR2:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- case Animation.ANIMATIONTYPE_SIZE:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- case Animation.ANIMATIONTYPE_COLOR3:
- this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
- break;
- default:
- break;
- }
- this._highLimitsCache[keyOffset] = toValue;
- }
- highLimitValue = this._highLimitsCache[keyOffset];
- offsetValue = this._offsetsCache[keyOffset];
- }
- if (offsetValue === undefined) {
- switch (animation.dataType) {
- case Animation.ANIMATIONTYPE_FLOAT:
- offsetValue = 0;
- break;
- case Animation.ANIMATIONTYPE_QUATERNION:
- offsetValue = _staticOffsetValueQuaternion;
- break;
- case Animation.ANIMATIONTYPE_VECTOR3:
- offsetValue = _staticOffsetValueVector3;
- break;
- case Animation.ANIMATIONTYPE_VECTOR2:
- offsetValue = _staticOffsetValueVector2;
- break;
- case Animation.ANIMATIONTYPE_SIZE:
- offsetValue = _staticOffsetValueSize;
- break;
- case Animation.ANIMATIONTYPE_COLOR3:
- offsetValue = _staticOffsetValueColor3;
- break;
- case Animation.ANIMATIONTYPE_COLOR4:
- offsetValue = _staticOffsetValueColor4;
- break;
- }
- }
- let currentFrame;
- if (this._host && this._host.syncRoot) {
- 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;
- if (!yoyoMode && (speedRatio > 0 && this.currentFrame > currentFrame || speedRatio < 0 && this.currentFrame < currentFrame) || yoyoMode && yoyoLoop) {
- this._onLoop();
- for (let index = 0;index < events.length; index++) {
- if (!events[index].onlyOnce) {
- 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);
- this.setValue(currentValue, weight);
- if (events.length) {
- for (let index = 0;index < events.length; index++) {
- 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.onlyOnce) {
- events.splice(index, 1);
- index--;
- }
- event.isDone = true;
- event.action(currentFrame);
- }
- }
- }
- }
- if (!returnValue) {
- this._stopped = true;
- }
- return returnValue;
- }
-}
-var init_runtimeAnimation = __esm(() => {
- init_math_vector();
- init_animation();
-});
-
-// node_modules/@babylonjs/core/Misc/domManagement.js
-function IsWindowObjectExist() {
- return typeof window !== "undefined";
-}
-function IsNavigatorAvailable() {
- return typeof navigator !== "undefined";
-}
-function IsDocumentAvailable() {
- return typeof document !== "undefined";
-}
-function GetDOMTextContent(element) {
- let result = "";
- let child = element.firstChild;
- while (child) {
- if (child.nodeType === 3) {
- result += child.textContent;
- }
- child = child.nextSibling;
- }
- return result;
-}
-var init_domManagement = () => {};
-
-// node_modules/@babylonjs/core/Misc/precisionDate.js
-class PrecisionDate {
- static get Now() {
- if (IsWindowObjectExist() && window.performance && window.performance.now) {
- return window.performance.now();
- }
- return Date.now();
- }
-}
-var init_precisionDate = __esm(() => {
- init_domManagement();
-});
-
-// node_modules/@babylonjs/core/Animations/animatable.core.js
-class Animatable {
- get syncRoot() {
- return this._syncRoot;
- }
- get masterFrame() {
- if (this._runtimeAnimations.length === 0) {
- return 0;
- }
- return this._runtimeAnimations[0].currentFrame;
- }
- get weight() {
- return this._weight;
- }
- set weight(value) {
- if (value === -1) {
- this._weight = -1;
- return;
- }
- this._weight = Math.min(Math.max(value, 0), 1);
- }
- 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;
- if (this._goToFrame !== null) {
- this.goToFrame(this._goToFrame);
- }
- }
- get elapsedTime() {
- return this._localDelayOffset === null ? 0 : this._scene._animationTime - this._localDelayOffset;
- }
- constructor(scene, target, fromFrame = 0, toFrame = 100, loopAnimation = false, speedRatio = 1, onAnimationEnd, animations, onAnimationLoop, isAdditive = false, 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;
- 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;
- this.disposeOnEnd = true;
- this.animationStarted = false;
- this.onAnimationEndObservable = new Observable;
- this.onAnimationLoopObservable = new Observable;
- this._scene = scene;
- if (animations) {
- this.appendAnimations(target, animations);
- }
- this._speedRatio = speedRatio;
- scene._activeAnimatables.push(this);
- }
- syncWith(root) {
- this._syncRoot = root;
- if (root) {
- const index = this._scene._activeAnimatables.indexOf(this);
- if (index > -1) {
- this._scene._activeAnimatables.splice(index, 1);
- this._scene._activeAnimatables.push(this);
- }
- }
- return this;
- }
- getAnimations() {
- return this._runtimeAnimations;
- }
- 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);
- }
- }
- 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;
- }
- 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;
- }
- reset() {
- const runtimeAnimations = this._runtimeAnimations;
- for (let index = 0;index < runtimeAnimations.length; index++) {
- runtimeAnimations[index].reset(true);
- }
- this._localDelayOffset = null;
- this._pausedDelay = null;
- }
- enableBlending(blendingSpeed) {
- const runtimeAnimations = this._runtimeAnimations;
- for (let index = 0;index < runtimeAnimations.length; index++) {
- runtimeAnimations[index].animation.enableBlending = true;
- runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
- }
- }
- disableBlending() {
- const runtimeAnimations = this._runtimeAnimations;
- for (let index = 0;index < runtimeAnimations.length; index++) {
- runtimeAnimations[index].animation.enableBlending = false;
- }
- }
- 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;
- }
- get paused() {
- return this._paused;
- }
- pause() {
- if (this._paused) {
- return;
- }
- this._paused = true;
- }
- restart() {
- this._paused = false;
- }
- _raiseOnAnimationEnd() {
- if (this.onAnimationEnd) {
- this.onAnimationEnd();
- }
- this.onAnimationEndObservable.notifyObservers(this);
- }
- 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 index2 = 0;index2 < runtimeAnimations.length; index2++) {
- runtimeAnimations[index2].dispose();
- }
- this._runtimeAnimations.length = 0;
- if (!skipOnAnimationEnd) {
- this._raiseOnAnimationEnd();
- }
- }
- }
- }
- waitAsync() {
- return new Promise((resolve3) => {
- this.onAnimationEndObservable.add(() => {
- resolve3(this);
- }, undefined, undefined, this, true);
- });
- }
- _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) {
- return true;
- }
- this._previousWeight = this._weight;
- 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) {
- index = this._scene._activeAnimatables.indexOf(this);
- this._scene._activeAnimatables.splice(index, 1);
- 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;
- }
-}
-function ProcessLateAnimationBindingsForMatrices(holder) {
- if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) {
- return holder.originalValue;
- }
- let normalizer = 1;
- 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) {
- scale = 1 - holder.totalWeight;
- originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
- } else {
- startIndex = 1;
- 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);
- }
- 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();
- }
- 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;
-}
-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, holder.totalWeight), cumulativeQuaternion);
- if (holder.totalAdditiveWeight === 0) {
- return cumulativeQuaternion;
- }
- } else if (holder.animations.length > 1) {
- let normalizer = 1;
- let quaternions;
- let weights;
- if (holder.totalWeight < 1) {
- const scale = 1 - holder.totalWeight;
- quaternions = [];
- weights = [];
- quaternions.push(originalValue);
- weights.push(scale);
- } else {
- if (holder.animations.length === 2) {
- 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);
- }
- 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++;
- }
- }
- 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;
-}
-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;
- 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;
- const originalAnimationIsLoopRelativeFromCurrent = originalAnimation && originalAnimation._animationState.loopMode === Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;
- if (holder.totalWeight < 1) {
- if (originalAnimationIsLoopRelativeFromCurrent) {
- finalValue = originalValue.clone ? originalValue.clone() : originalValue;
- } else if (originalAnimation && originalValue.scale) {
- finalValue = originalValue.scale(1 - holder.totalWeight);
- } else if (originalAnimation) {
- finalValue = originalValue * (1 - holder.totalWeight);
- } else if (originalValue.clone) {
- finalValue = originalValue.clone();
- } else {
- finalValue = originalValue;
- }
- } else if (originalAnimation) {
- 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;
- }
- 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;
- }
- }
- 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();
-}
-function AddAnimationExtensions(sceneClass, boneClass) {
- if (boneClass) {
- boneClass.prototype.copyAnimationRange = function(source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) {
- 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([]);
- }
- 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();
- 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();
- 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();
- if (parentScalingReqd) {
- origTranslation = mat.getTranslation();
- mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
- } else if (dimensionsScalingReqd && skelDimensionsRatio) {
- origTranslation = mat.getTranslation();
- mat.setTranslation(origTranslation.multiplyInPlace(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;
- }
- const now = PrecisionDate.Now;
- if (!this._animationTimeLast) {
- if (this._pendingData.length > 0) {
- return;
- }
- this._animationTimeLast = now;
- }
- this.deltaTime = customDeltaTime !== undefined ? customDeltaTime : this.useConstantAnimationDeltaTime ? 16 : (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--;
- }
- }
- 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, loop, speedRatio = 1, 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, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) {
- if (speedRatio < 0) {
- const tmp = from;
- from = to;
- to = tmp;
- speedRatio = -speedRatio;
- }
- 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;
- if (target.animations && shouldRunTargetAnimations) {
- animatable.appendAnimations(target, target.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, 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, onAnimationEnd, onAnimationLoop, isAdditive = false) {
- if (speedRatio < 0) {
- const tmp = from;
- from = to;
- to = tmp;
- speedRatio = -speedRatio;
- }
- 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();
- }
- };
-}
-var init_animatable_core = __esm(() => {
- init_observable();
- init_runtimeAnimation();
- init_animation();
- init_precisionDate();
- init_math_vector();
-});
-
-// node_modules/@babylonjs/core/Misc/filesInputStore.js
-class FilesInputStore {
-}
-var init_filesInputStore = __esm(() => {
- FilesInputStore.FilesToLoad = {};
-});
-
-// node_modules/@babylonjs/core/Misc/retryStrategy.js
-class RetryStrategy {
- 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;
- };
- }
-}
-
-// node_modules/@babylonjs/core/Misc/error.js
-var BaseError, ErrorCodes, RuntimeError;
-var init_error = __esm(() => {
- BaseError = class BaseError extends Error {
- };
- BaseError._setPrototypeOf = Object.setPrototypeOf || ((o, proto) => {
- o.__proto__ = proto;
- return o;
- });
- ErrorCodes = {
- MeshInvalidPositionsError: 0,
- UnsupportedTextureError: 1000,
- GLTFLoaderUnexpectedMagicError: 2000,
- SceneLoaderError: 3000,
- LoadFileError: 4000,
- RequestFileError: 4001,
- ReadFileError: 4002
- };
- RuntimeError = class RuntimeError extends BaseError {
- constructor(message, errorCode, innerError) {
- super(message);
- this.errorCode = errorCode;
- this.innerError = innerError;
- this.name = "RuntimeError";
- BaseError._setPrototypeOf(this, RuntimeError.prototype);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Misc/stringTools.js
-var 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;
-}, DecodeBase64ToString = (base64Data) => {
- return atob(base64Data);
-}, 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;
-};
-var init_stringTools = () => {};
-
-// node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js
-class ShaderCodeNode {
- constructor() {
- this.children = [];
- }
- isValid(preprocessors) {
- return true;
- }
- process(preprocessors, options) {
- let result = "";
- if (this.line) {
- let value = this.line;
- const processor = options.processor;
- if (processor) {
- 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)) {
- if (processor.uniformProcessor) {
- value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);
- }
- } else {
- 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 + `
-`;
- }
- this.children.forEach((child) => {
- result += child.process(preprocessors, options);
- });
- if (this.additionalDefineKey) {
- preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true";
- }
- return result;
- }
-}
-var defaultAttributeKeywordName = "attribute", defaultVaryingKeywordName = "varying";
-
-// node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js
-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) {
- if (!line || line === "\r") {
- continue;
- }
- if (line[0] === "#") {
- this._lines.push(line);
- continue;
- }
- const trimmedLine = line.trim();
- if (!trimmedLine) {
- continue;
- }
- if (trimmedLine.startsWith("//")) {
- this._lines.push(line);
- continue;
- }
- const semicolonIndex = trimmedLine.indexOf(";");
- if (semicolonIndex === -1) {
- this._lines.push(trimmedLine);
- } else if (semicolonIndex === trimmedLine.length - 1) {
- if (trimmedLine.length > 1) {
- this._lines.push(trimmedLine);
- }
- } else {
- 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 ? ";" : ""));
- }
- }
- }
- }
-}
-
-// node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js
-var ShaderCodeConditionNode;
-var init_shaderCodeConditionNode = __esm(() => {
- ShaderCodeConditionNode = 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 "";
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js
-var ShaderCodeTestNode;
-var init_shaderCodeTestNode = __esm(() => {
- ShaderCodeTestNode = class ShaderCodeTestNode extends ShaderCodeNode {
- isValid(preprocessors) {
- return this.testExpression.isTrue(preprocessors);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js
-class ShaderDefineExpression {
- 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];
- }
- static infixToPostfix(infix) {
- const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix);
- if (cacheItem) {
- cacheItem.accessTime = Date.now();
- return cacheItem.result;
- }
- 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 (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) {
- ShaderDefineExpression.ClearCache();
- }
- ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() });
- return result;
- }
- static ClearCache() {
- const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime);
- for (let i = 0;i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) {
- ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]);
- }
- }
-}
-var init_shaderDefineExpression = __esm(() => {
- ShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000;
- ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000;
- ShaderDefineExpression._InfixToPostfixCache = new Map;
- ShaderDefineExpression._OperatorPriority = {
- ")": 0,
- "(": 1,
- "||": 2,
- "&&": 3
- };
- ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js
-var ShaderDefineIsDefinedOperator;
-var init_shaderDefineIsDefinedOperator = __esm(() => {
- init_shaderDefineExpression();
- ShaderDefineIsDefinedOperator = class ShaderDefineIsDefinedOperator extends ShaderDefineExpression {
- constructor(define, not = false) {
- super();
- this.define = define;
- this.not = not;
- }
- isTrue(preprocessors) {
- let condition2 = preprocessors[this.define] !== undefined;
- if (this.not) {
- condition2 = !condition2;
- }
- return condition2;
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js
-var ShaderDefineOrOperator;
-var init_shaderDefineOrOperator = __esm(() => {
- init_shaderDefineExpression();
- ShaderDefineOrOperator = class ShaderDefineOrOperator extends ShaderDefineExpression {
- isTrue(preprocessors) {
- return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js
-var ShaderDefineAndOperator;
-var init_shaderDefineAndOperator = __esm(() => {
- init_shaderDefineExpression();
- ShaderDefineAndOperator = class ShaderDefineAndOperator extends ShaderDefineExpression {
- isTrue(preprocessors) {
- return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js
-var ShaderDefineArithmeticOperator;
-var init_shaderDefineArithmeticOperator = __esm(() => {
- init_shaderDefineExpression();
- ShaderDefineArithmeticOperator = 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 condition2 = false;
- const left = parseInt(value);
- const right = parseInt(this.testValue);
- switch (this.operand) {
- case ">":
- condition2 = left > right;
- break;
- case "<":
- condition2 = left < right;
- break;
- case "<=":
- condition2 = left <= right;
- break;
- case ">=":
- condition2 = left >= right;
- break;
- case "==":
- condition2 = left === right;
- break;
- case "!=":
- condition2 = left !== right;
- break;
- }
- return condition2;
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/abstractEngine.functions.js
-function _ConcatenateShader(source, defines, shaderVersion = "") {
- return shaderVersion + (defines ? defines + `
-` : "") + source;
-}
-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");
-}
-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 += `
-`;
- }
- s += "#define USE_REVERSE_DEPTHBUFFER";
- }
- if (useExactSrgbConversions) {
- if (s) {
- s += `
-`;
- }
- s += "#define USE_EXACT_SRGB_CONVERSIONS";
- }
- return s;
- }
-}
-function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) {
- switch (type) {
- case 3: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Int8Array(copyBuffer));
- }
- return buffer2;
- }
- case 0: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Uint8Array(copyBuffer));
- }
- return buffer2;
- }
- case 4: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Int16Array(copyBuffer));
- }
- return buffer2;
- }
- case 5:
- case 8:
- case 9:
- case 10:
- case 2: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Uint16Array(copyBuffer));
- }
- return buffer2;
- }
- case 6: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Int32Array(copyBuffer));
- }
- return buffer2;
- }
- case 7:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Uint32Array(copyBuffer));
- }
- return buffer2;
- }
- case 1: {
- const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);
- if (copyBuffer) {
- buffer2.set(new Float32Array(copyBuffer));
- }
- return buffer2;
- }
- }
- const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);
- if (copyBuffer) {
- buffer.set(new Uint8Array(copyBuffer));
- }
- return buffer;
-}
-var EngineFunctionContext;
-var init_abstractEngine_functions = __esm(() => {
- init_devTools();
- init_domManagement();
- EngineFunctionContext = {};
-});
-
-// node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js
-function Initialize(options) {
- if (options.processor && options.processor.initializeShaders) {
- options.processor.initializeShaders(options.processingContext);
- }
-}
-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);
- });
-}
-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);
- });
-}
-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;
-` + source;
- } else {
- source = `precision highp float;
-` + source;
- }
- } else {
- if (!shouldUseHighPrecisionShader) {
- 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)");
- }
- 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);
- 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(`
-`);
- _MoveCursor(cursor, rootNode);
- 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) {
- 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;
- }
- if (options.processor.shaderLanguage === 0 && 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);
- if (options.processor.preProcessor) {
- preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
- }
- preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
- if (options.processor.postProcessor) {
- preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? {
- drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true
- } : {});
- }
- 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);
- if (options.processor?.preProcessor) {
- preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext);
- }
- preparedSourceCode = _EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
- if (options.processor?.postProcessor) {
- preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? {
- drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true
- } : {});
- }
- if (engine._features.needShaderCodeInlining) {
- preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);
- }
- return preparedSourceCode;
-}
-function _ProcessIncludes(sourceCode, options, callback) {
- reusableMatches.length = 0;
- let match;
- while ((match = regexShaderInclude.exec(sourceCode)) !== null) {
- reusableMatches.push(match);
- }
- let returnValue = String(sourceCode);
- let parts = [sourceCode];
- let keepProcessing = false;
- for (const match2 of reusableMatches) {
- let includeFile = match2[1];
- 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]) {
- let includeContent = options.includesShadersStore[includeFile];
- if (match2[2]) {
- const splits = match2[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 (match2[4]) {
- const indexString = match2[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) {
- sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => {
- return p1 + "{X}";
- });
- }
- includeContent += sourceIncludeContent.replace(regexX, i.toString()) + `
-`;
- }
- } else {
- if (!options.supportsUniformBuffers) {
- includeContent = includeContent.replace(regexLightX, (str, p1) => {
- return p1 + "{X}";
- });
- }
- includeContent = includeContent.replace(regexX, indexString);
- }
- }
- const newParts = [];
- for (const part of parts) {
- const splitPart = part.split(match2[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);
- }
-}
-var regexSE, regexSERevert, regexShaderInclude, regexShaderDecl, regexLightX, regexX, reusableMatches, _MoveCursorRegex, _functionContainer;
-var init_shaderProcessor = __esm(() => {
- init_shaderCodeConditionNode();
- init_shaderCodeTestNode();
- init_shaderDefineIsDefinedOperator();
- init_shaderDefineOrOperator();
- init_shaderDefineAndOperator();
- init_shaderDefineExpression();
- init_shaderDefineArithmeticOperator();
- init_devTools();
- init_abstractEngine_functions();
- regexSE = /defined\s*?\((.+?)\)/g;
- regexSERevert = /defined\s*?\[(.+?)\]/g;
- regexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g;
- regexShaderDecl = /__decl__/;
- regexLightX = /light\{X\}.(\w*)/g;
- regexX = /\{X\}/g;
- reusableMatches = [];
- _MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
- _functionContainer = {
- loadFile: (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) => {
- throw _WarnImport("FileTools");
- }
- };
-});
-
-// node_modules/@babylonjs/core/Misc/timingTools.js
-class TimingTools {
- static SetImmediate(action2) {
- if (_immediateQueue.length === 0) {
- setTimeout(() => {
- const functionsToCall = _immediateQueue;
- _immediateQueue = [];
- for (const func of functionsToCall) {
- func();
- }
- }, 1);
- }
- _immediateQueue.push(action2);
- }
-}
-function _runWithCondition(condition2, onSuccess, onError) {
- try {
- if (condition2()) {
- onSuccess();
- return true;
- }
- } catch (e) {
- onError?.(e);
- return true;
- }
- return false;
-}
-var _immediateQueue, _retryWithInterval = (condition2, onSuccess, onError, step = 16, maxTimeout = 30000, checkConditionOnCall = true, additionalStringOnTimeout) => {
- if (checkConditionOnCall) {
- if (_runWithCondition(condition2, onSuccess, onError)) {
- return null;
- }
- }
- const int = setInterval(() => {
- if (_runWithCondition(condition2, 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);
-};
-var init_timingTools = __esm(() => {
- _immediateQueue = [];
-});
-
-// node_modules/@babylonjs/core/Engines/shaderStore.js
-class ShaderStore {
- static GetShadersRepository(shaderLanguage = 0) {
- return shaderLanguage === 0 ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL;
- }
- static GetShadersStore(shaderLanguage = 0) {
- return shaderLanguage === 0 ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL;
- }
- static GetIncludesShadersStore(shaderLanguage = 0) {
- return shaderLanguage === 0 ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL;
- }
-}
-var init_shaderStore = __esm(() => {
- ShaderStore.ShadersRepository = "src/Shaders/";
- ShaderStore.ShadersStore = {};
- ShaderStore.IncludesShadersStore = {};
- ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/";
- ShaderStore.ShadersStoreWGSL = {};
- ShaderStore.IncludesShadersStoreWGSL = {};
-});
-
-// node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js
-class WebGLPipelineContext {
- constructor() {
- this._valueCache = {};
- this.vertexCompilationError = null;
- this.fragmentCompilationError = null;
- this.programLinkError = null;
- this.programValidationError = null;
- 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 name2 in uniformBuffersNames) {
- effect.bindUniformBlock(name2, uniformBuffersNames[name2]);
- }
- }
- const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);
- effectAvailableUniforms.forEach((uniform, index2) => {
- uniforms[uniformsNames[index2]] = 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((name2, index2) => {
- samplers[name2] = index2;
- });
- for (const attr of engine.getAttributes(this, attributesNames)) {
- attributes.push(attr);
- }
- }
- dispose() {
- this._uniforms = {};
- this._isDisposed = true;
- }
- _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;
- }
- _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;
- }
- _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;
- }
- _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;
- }
- 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;
- }
- }
- setInt2(uniformName, x, y) {
- if (this._cacheFloat2(uniformName, x, y)) {
- if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) {
- this._valueCache[uniformName] = null;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- setIntArray(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray(this._uniforms[uniformName], array);
- }
- setIntArray2(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray2(this._uniforms[uniformName], array);
- }
- setIntArray3(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray3(this._uniforms[uniformName], array);
- }
- setIntArray4(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setIntArray4(this._uniforms[uniformName], array);
- }
- 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;
- }
- }
- setUInt2(uniformName, x, y) {
- if (this._cacheFloat2(uniformName, x, y)) {
- if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) {
- this._valueCache[uniformName] = null;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- setUIntArray(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setUIntArray(this._uniforms[uniformName], array);
- }
- setUIntArray2(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setUIntArray2(this._uniforms[uniformName], array);
- }
- setUIntArray3(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setUIntArray3(this._uniforms[uniformName], array);
- }
- setUIntArray4(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setUIntArray4(this._uniforms[uniformName], array);
- }
- setArray(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setArray(this._uniforms[uniformName], array);
- }
- setArray2(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setArray2(this._uniforms[uniformName], array);
- }
- setArray3(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setArray3(this._uniforms[uniformName], array);
- }
- setArray4(uniformName, array) {
- this._valueCache[uniformName] = null;
- this.engine.setArray4(this._uniforms[uniformName], array);
- }
- setMatrices(uniformName, matrices) {
- if (!matrices) {
- return;
- }
- this._valueCache[uniformName] = null;
- this.engine.setMatrices(this._uniforms[uniformName], matrices);
- }
- setMatrix(uniformName, matrix) {
- if (this._cacheMatrix(uniformName, matrix)) {
- if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.asArray())) {
- this._valueCache[uniformName] = null;
- }
- }
- }
- setMatrix3x3(uniformName, matrix) {
- this._valueCache[uniformName] = null;
- this.engine.setMatrix3x3(this._uniforms[uniformName], matrix);
- }
- setMatrix2x2(uniformName, matrix) {
- this._valueCache[uniformName] = null;
- this.engine.setMatrix2x2(this._uniforms[uniformName], matrix);
- }
- 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;
- }
- }
- 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;
- }
- }
- }
- setFloat2(uniformName, x, y) {
- if (this._cacheFloat2(uniformName, x, y)) {
- if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) {
- this._valueCache[uniformName] = null;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- 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;
- }
-}
-
-// node_modules/@babylonjs/core/Engines/thinEngine.functions.js
-function getStateObject(context) {
- let state = _stateObject.get(context);
- if (!state) {
- if (!context) {
- return singleStateObject;
- }
- state = {
- _webGLVersion: context.TEXTURE_BINDING_3D ? 2 : 1,
- _context: context,
- parallelShaderCompile: context.getExtension("KHR_parallel_shader_compile") || undefined,
- cachedPipelines: {}
- };
- _stateObject.set(context, state);
- }
- return state;
-}
-function deleteStateObject(context) {
- _stateObject.delete(context);
-}
-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);
-}
-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
-#define WEBGL2
-` : "";
- 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);
-}
-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;
-}
-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;
-}
-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;
-}
-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) {
- if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
- const log = gl.getShaderInfoLog(vertexShader);
- if (log) {
- pipelineContext.vertexCompilationError = log;
- throw new Error("VERTEX SHADER " + log);
- }
- }
- 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 (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;
- }
-}
-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;
-}
-function _setProgram(program, gl) {
- gl.useProgram(program);
-}
-function _executeWhenRenderingStateIsCompiled(pipelineContext, action2) {
- const webGLPipelineContext = pipelineContext;
- if (!webGLPipelineContext.isParallelCompiled) {
- action2(pipelineContext);
- return;
- }
- const oldHandler = webGLPipelineContext.onCompiled;
- webGLPipelineContext.onCompiled = () => {
- oldHandler?.();
- action2(pipelineContext);
- };
-}
-var _stateObject, singleStateObject;
-var init_thinEngine_functions = __esm(() => {
- init_abstractEngine_functions();
- _stateObject = new WeakMap;
- singleStateObject = {
- _webGLVersion: 2,
- cachedPipelines: {}
- };
-});
-
-// node_modules/@babylonjs/core/Materials/effect.functions.js
-function getCachedPipeline(name2, context) {
- const stateObject = getStateObject(context);
- return stateObject.cachedPipelines[name2];
-}
-function resetCachedPipeline(pipeline) {
- const name2 = pipeline._name;
- const context = pipeline.context;
- if (name2 && context) {
- const stateObject = getStateObject(context);
- const cachedPipeline = stateObject.cachedPipelines[name2];
- cachedPipeline?.dispose();
- delete stateObject.cachedPipelines[name2];
- }
-}
-function _processShaderCode(processorOptions, baseName, processFinalCode, onFinalCodeReady, shaderLanguage, engine, effectContext) {
- let vertexSource;
- let fragmentSource;
- 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") {
- if (shader instanceof HTMLElement) {
- const shaderCode = GetDOMTextContent(shader);
- callback(shaderCode);
- return;
- }
- }
- if (shader.substring(0, 7) === "source:") {
- callback(shader.substring(7));
- return;
- }
- if (shader.substring(0, 7) === "base64:") {
- const shaderBinary = window.atob(shader.substring(7));
- callback(shaderBinary);
- return;
- }
- const shaderStore = ShaderStore.GetShadersStore(shaderLanguage);
- 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) {
- throw new Error("loadFileInjection is not defined");
- }
- _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 ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + `
-` + migratedVertexCode,
- fragmentSourceCode: (shaderLanguage === 1 ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + `
-` + migratedFragmentCode
- };
- } else {
- return {
- vertexSourceCode: migratedVertexCode,
- fragmentSourceCode: migratedFragmentCode
- };
- }
-}
-var createAndPreparePipelineContext = (options, createPipelineContext2, _preparePipelineContext2, _executeWhenRenderingStateIsCompiled2) => {
- try {
- const stateObject = options.context ? getStateObject(options.context) : null;
- if (stateObject) {
- stateObject.disableParallelShaderCompile = options.disableParallelCompilation;
- }
- const pipelineContext = options.existingPipelineContext || createPipelineContext2(options.shaderProcessingContext);
- pipelineContext._name = options.name;
- if (options.name && stateObject) {
- stateObject.cachedPipelines[options.name] = pipelineContext;
- }
- _preparePipelineContext2(pipelineContext, options.vertex, options.fragment, !!options.createAsRaw, "", "", options.rebuildRebind, options.defines, options.transformFeedbackVaryings, "", () => {
- _executeWhenRenderingStateIsCompiled2(pipelineContext, () => {
- options.onRenderingStateCompiled?.(pipelineContext);
- });
- });
- return pipelineContext;
- } catch (e) {
- Logger.Error("Error compiling effect");
- throw e;
- }
-};
-var init_effect_functions = __esm(() => {
- init_domManagement();
- init_thinEngine_functions();
- init_shaderStore();
- init_logger();
- init_shaderProcessor();
- init_abstractEngine_functions();
-});
-
-// node_modules/@babylonjs/core/Materials/effect.js
-class Effect {
- static get ShadersRepository() {
- return ShaderStore.ShadersRepository;
- }
- static set ShadersRepository(repo) {
- ShaderStore.ShadersRepository = repo;
- }
- get isDisposed() {
- return this._isDisposed;
- }
- get onBindObservable() {
- if (!this._onBindObservable) {
- this._onBindObservable = new Observable;
- }
- return this._onBindObservable;
- }
- get shaderLanguage() {
- return this._shaderLanguage;
- }
- constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = "", shaderLanguage = 0, extraInitializationsAsync) {
- this.defines = "";
- this.onCompiled = null;
- this.onError = null;
- this.onBind = null;
- this.uniqueId = 0;
- this.onCompileObservable = new Observable;
- this.onErrorObservable = new Observable;
- this._onBindObservable = null;
- this._isDisposed = false;
- this._refCount = 1;
- this._bonesComputationForcedToCPU = false;
- this._uniformBuffersNames = {};
- this._multiTarget = false;
- this._samplers = {};
- this._isReady = false;
- this._compilationError = "";
- this._allFallbacksProcessed = false;
- this._uniforms = {};
- this._key = "";
- this._fallbacks = null;
- this._vertexSourceCodeOverride = "";
- this._fragmentSourceCodeOverride = "";
- this._transformFeedbackVaryings = null;
- this._disableParallelShaderCompilation = false;
- this._pipelineContext = null;
- this._vertexSourceCode = "";
- this._fragmentSourceCode = "";
- this._vertexSourceCodeBeforeMigration = "";
- this._fragmentSourceCodeBeforeMigration = "";
- this._rawVertexSourceCode = "";
- 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;
- 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;
- }
- 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);
- if (this._pipelineContext.program) {
- this._pipelineContext.program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
- }
- }
- this._engine.onReleaseEffectsObservable.addOnce(() => {
- if (this.isDisposed) {
- return;
- }
- this.dispose(true);
- });
- }
- 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(`
-`),
- 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);
- }
- get key() {
- return this._key;
- }
- isReady() {
- try {
- return this._isReadyInternal();
- } catch {
- return false;
- }
- }
- _isReadyInternal() {
- if (this._engine.isDisposed) {
- return true;
- }
- if (this._isReady) {
- return true;
- }
- if (this._pipelineContext) {
- return this._pipelineContext.isReady;
- }
- return false;
- }
- getEngine() {
- return this._engine;
- }
- getPipelineContext() {
- return this._pipelineContext;
- }
- getAttributesNames() {
- return this._attributesNames;
- }
- getAttributeLocation(index) {
- return this._attributes[index];
- }
- getAttributeLocationByName(name2) {
- return this._attributeLocationByName[name2];
- }
- getAttributesCount() {
- return this._attributes.length;
- }
- getUniformIndex(uniformName) {
- return this._uniformsNames.indexOf(uniformName);
- }
- getUniform(uniformName) {
- return this._uniforms[uniformName];
- }
- getSamplers() {
- return this._samplerList;
- }
- getUniformNames() {
- return this._uniformsNames;
- }
- getUniformBuffersNames() {
- return this._uniformBuffersNamesList;
- }
- getIndexParameters() {
- return this._indexParameters;
- }
- getCompilationError() {
- return this._compilationError;
- }
- allFallbacksProcessed() {
- return this._allFallbacksProcessed;
- }
- whenCompiledAsync() {
- return new Promise((resolve3) => {
- this.executeWhenCompiled(resolve3);
- });
- }
- 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;
- }, () => {}, (e) => {
- this._processCompilationErrors(e, previousPipelineContext);
- }, 16, 120000, true, ` - Effect: ${typeof this.name === "string" ? this.name : this.key}`);
- }
- get vertexSourceCode() {
- return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : this._pipelineContext?._getVertexShaderCode() ?? this._vertexSourceCode;
- }
- get fragmentSourceCode() {
- return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : this._pipelineContext?._getFragmentShaderCode() ?? this._fragmentSourceCode;
- }
- get vertexSourceCodeBeforeMigration() {
- return this._vertexSourceCodeBeforeMigration;
- }
- get fragmentSourceCodeBeforeMigration() {
- return this._fragmentSourceCodeBeforeMigration;
- }
- get rawVertexSourceCode() {
- return this._rawVertexSourceCode;
- }
- get rawFragmentSourceCode() {
- return this._rawFragmentSourceCode;
- }
- getPipelineGenerationOptions() {
- return {
- platformName: this._engine.shaderPlatformName,
- shaderLanguage: this._shaderLanguage,
- shaderNameOrContent: this.name,
- key: this._key,
- defines: this.defines.split(`
-`),
- 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)
- }
- };
- }
- _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);
- if (this._attributesNames) {
- for (let i = 0;i < this._attributesNames.length; i++) {
- const name2 = this._attributesNames[i];
- this._attributeLocationByName[name2] = 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();
- if (this._fallbacks) {
- this._fallbacks.unBindMesh();
- }
- if (Effect.AutomaticallyClearCodeCache) {
- this.clearCodeCache();
- }
- }
- _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(`
-`, -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;
- 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:
-` + 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 });
- };
- if (previousPipelineContext) {
- this._pipelineContext = previousPipelineContext;
- this._isReady = true;
- notifyErrors();
- }
- 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 {
- this._allFallbacksProcessed = true;
- notifyErrors();
- this.onErrorObservable.clear();
- if (this._fallbacks) {
- this._fallbacks.unBindMesh();
- }
- }
- } else {
- this._allFallbacksProcessed = true;
- if (!previousPipelineContext) {
- notifyErrors();
- }
- }
- }
- get isSupported() {
- return this._compilationError === "";
- }
- _bindTexture(channel, texture) {
- this._engine._bindTexture(this._samplers[channel], texture, channel);
- }
- setTexture(channel, texture) {
- this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel);
- }
- 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);
- }
- 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);
- }
- bindUniformBuffer(buffer, name2) {
- const bufferName = this._uniformBuffersNames[name2];
- if (bufferName === undefined || Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache) {
- return;
- }
- Effect._BaseCache[bufferName] = buffer;
- this._engine.bindUniformBufferBase(buffer, bufferName, name2);
- }
- bindUniformBlock(blockName, index) {
- this._engine.bindUniformBlock(this._pipelineContext, blockName, index);
- }
- setInt(uniformName, value) {
- this._pipelineContext.setInt(uniformName, value);
- return this;
- }
- setInt2(uniformName, x, y) {
- this._pipelineContext.setInt2(uniformName, x, y);
- return this;
- }
- setInt3(uniformName, x, y, z) {
- this._pipelineContext.setInt3(uniformName, x, y, z);
- return this;
- }
- setInt4(uniformName, x, y, z, w) {
- this._pipelineContext.setInt4(uniformName, x, y, z, w);
- return this;
- }
- setIntArray(uniformName, array) {
- this._pipelineContext.setIntArray(uniformName, array);
- return this;
- }
- setIntArray2(uniformName, array) {
- this._pipelineContext.setIntArray2(uniformName, array);
- return this;
- }
- setIntArray3(uniformName, array) {
- this._pipelineContext.setIntArray3(uniformName, array);
- return this;
- }
- setIntArray4(uniformName, array) {
- this._pipelineContext.setIntArray4(uniformName, array);
- return this;
- }
- setUInt(uniformName, value) {
- this._pipelineContext.setUInt(uniformName, value);
- return this;
- }
- setUInt2(uniformName, x, y) {
- this._pipelineContext.setUInt2(uniformName, x, y);
- return this;
- }
- setUInt3(uniformName, x, y, z) {
- this._pipelineContext.setUInt3(uniformName, x, y, z);
- return this;
- }
- setUInt4(uniformName, x, y, z, w) {
- this._pipelineContext.setUInt4(uniformName, x, y, z, w);
- return this;
- }
- setUIntArray(uniformName, array) {
- this._pipelineContext.setUIntArray(uniformName, array);
- return this;
- }
- setUIntArray2(uniformName, array) {
- this._pipelineContext.setUIntArray2(uniformName, array);
- return this;
- }
- setUIntArray3(uniformName, array) {
- this._pipelineContext.setUIntArray3(uniformName, array);
- return this;
- }
- setUIntArray4(uniformName, array) {
- this._pipelineContext.setUIntArray4(uniformName, array);
- return this;
- }
- setFloatArray(uniformName, array) {
- this._pipelineContext.setArray(uniformName, array);
- return this;
- }
- setFloatArray2(uniformName, array) {
- this._pipelineContext.setArray2(uniformName, array);
- return this;
- }
- setFloatArray3(uniformName, array) {
- this._pipelineContext.setArray3(uniformName, array);
- return this;
- }
- setFloatArray4(uniformName, array) {
- this._pipelineContext.setArray4(uniformName, array);
- return this;
- }
- setArray(uniformName, array) {
- this._pipelineContext.setArray(uniformName, array);
- return this;
- }
- setArray2(uniformName, array) {
- this._pipelineContext.setArray2(uniformName, array);
- return this;
- }
- setArray3(uniformName, array) {
- this._pipelineContext.setArray3(uniformName, array);
- return this;
- }
- setArray4(uniformName, array) {
- this._pipelineContext.setArray4(uniformName, array);
- return this;
- }
- setMatrices(uniformName, matrices) {
- this._pipelineContext.setMatrices(uniformName, matrices);
- return this;
- }
- setMatrix(uniformName, matrix) {
- this._pipelineContext.setMatrix(uniformName, matrix);
- return this;
- }
- setMatrix3x3(uniformName, matrix) {
- this._pipelineContext.setMatrix3x3(uniformName, matrix);
- return this;
- }
- setMatrix2x2(uniformName, matrix) {
- this._pipelineContext.setMatrix2x2(uniformName, matrix);
- return this;
- }
- setFloat(uniformName, value) {
- this._pipelineContext.setFloat(uniformName, value);
- return this;
- }
- setBool(uniformName, bool) {
- this._pipelineContext.setInt(uniformName, bool ? 1 : 0);
- return this;
- }
- setVector2(uniformName, vector2) {
- this._pipelineContext.setVector2(uniformName, vector2);
- return this;
- }
- setFloat2(uniformName, x, y) {
- this._pipelineContext.setFloat2(uniformName, x, y);
- return this;
- }
- setVector3(uniformName, vector3) {
- this._pipelineContext.setVector3(uniformName, vector3);
- return this;
- }
- setFloat3(uniformName, x, y, z) {
- this._pipelineContext.setFloat3(uniformName, x, y, z);
- return this;
- }
- setVector4(uniformName, vector4) {
- this._pipelineContext.setVector4(uniformName, vector4);
- return this;
- }
- setQuaternion(uniformName, quaternion) {
- this._pipelineContext.setQuaternion(uniformName, quaternion);
- return this;
- }
- setFloat4(uniformName, x, y, z, w) {
- this._pipelineContext.setFloat4(uniformName, x, y, z, w);
- return this;
- }
- setColor3(uniformName, color3) {
- this._pipelineContext.setColor3(uniformName, color3);
- return this;
- }
- setColor4(uniformName, color3, alpha) {
- this._pipelineContext.setColor4(uniformName, color3, alpha);
- return this;
- }
- setDirectColor4(uniformName, color4) {
- this._pipelineContext.setDirectColor4(uniformName, color4);
- return this;
- }
- clearCodeCache() {
- this._vertexSourceCode = "";
- this._fragmentSourceCode = "";
- this._fragmentSourceCodeBeforeMigration = "";
- this._vertexSourceCodeBeforeMigration = "";
- }
- dispose(force = false) {
- if (force) {
- this._refCount = 0;
- } else {
- if (Effect.PersistentMode) {
- return;
- }
- this._refCount--;
- }
- if (this._refCount > 0 || this._isDisposed) {
- return;
- }
- if (this._pipelineContext) {
- resetCachedPipeline(this._pipelineContext);
- }
- this._engine._releaseEffect(this);
- this.clearCodeCache();
- this._isDisposed = true;
- }
- static RegisterShader(name2, pixelShader, vertexShader, shaderLanguage = 0) {
- if (pixelShader) {
- ShaderStore.GetShadersStore(shaderLanguage)[`${name2}PixelShader`] = pixelShader;
- }
- if (vertexShader) {
- ShaderStore.GetShadersStore(shaderLanguage)[`${name2}VertexShader`] = vertexShader;
- }
- }
- static ResetCache() {
- Effect._BaseCache = {};
- }
-}
-var init_effect = __esm(() => {
- init_observable();
- init_logger();
- init_shaderStore();
- init_effect_functions();
- init_timingTools();
- Effect.LogShaderCodeOnCompilationError = true;
- Effect.PersistentMode = false;
- Effect.AutomaticallyClearCodeCache = false;
- Effect._UniqueIdSeed = 0;
- Effect._BaseCache = {};
- Effect.ShadersStore = ShaderStore.ShadersStore;
- Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore;
-});
-
-// node_modules/@babylonjs/core/States/depthCullingState.js
-class DepthCullingState {
- 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;
- }
- if (this._isCullDirty) {
- if (this.cull) {
- gl.enable(gl.CULL_FACE);
- } else {
- gl.disable(gl.CULL_FACE);
- }
- this._isCullDirty = false;
- }
- if (this._isCullFaceDirty) {
- gl.cullFace(this.cullFace);
- this._isCullFaceDirty = false;
- }
- if (this._isDepthMaskDirty) {
- gl.depthMask(this.depthMask);
- this._isDepthMaskDirty = false;
- }
- if (this._isDepthTestDirty) {
- if (this.depthTest) {
- gl.enable(gl.DEPTH_TEST);
- } else {
- gl.disable(gl.DEPTH_TEST);
- }
- this._isDepthTestDirty = false;
- }
- if (this._isDepthFuncDirty) {
- gl.depthFunc(this.depthFunc);
- this._isDepthFuncDirty = false;
- }
- 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;
- }
- if (this._isFrontFaceDirty) {
- gl.frontFace(this.frontFace);
- this._isFrontFaceDirty = false;
- }
- }
-}
-
-// node_modules/@babylonjs/core/States/stencilStateComposer.js
-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;
- }
- if (this._isStencilTestDirty) {
- if (this.enabled) {
- gl.enable(gl.STENCIL_TEST);
- } else {
- gl.disable(gl.STENCIL_TEST);
- }
- this._isStencilTestDirty = false;
- }
- if (this._isStencilMaskDirty) {
- gl.stencilMask(this.mask);
- this._isStencilMaskDirty = false;
- }
- if (this._isStencilFuncDirty) {
- gl.stencilFunc(this.func, this.funcRef, this.funcMask);
- this._isStencilFuncDirty = false;
- }
- if (this._isStencilOpDirty) {
- gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass);
- this._isStencilOpDirty = false;
- }
- }
-}
-
-// node_modules/@babylonjs/core/States/stencilState.js
-class StencilState {
- constructor() {
- this.reset();
- }
- reset() {
- this.enabled = false;
- this.mask = 255;
- this.func = StencilState.ALWAYS;
- this.funcRef = 1;
- this.funcMask = 255;
- 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;
- }
-}
-var init_stencilState = __esm(() => {
- StencilState.ALWAYS = 519;
- StencilState.KEEP = 7680;
- StencilState.REPLACE = 7681;
-});
-
-// node_modules/@babylonjs/core/States/alphaCullingState.js
-class AlphaState {
- 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;
- }
- if (this._isAlphaBlendDirty) {
- if (this._alphaBlend) {
- gl.enable(gl.BLEND);
- } else {
- gl.disable(gl.BLEND);
- }
- this._isAlphaBlendDirty = false;
- }
- if (this._isBlendFunctionParametersDirty) {
- gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
- this._isBlendFunctionParametersDirty = false;
- }
- if (this._isBlendEquationParametersDirty) {
- gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
- this._isBlendEquationParametersDirty = false;
- }
- if (this._isBlendConstantsDirty) {
- gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
- this._isBlendConstantsDirty = false;
- }
- }
-}
-
-// node_modules/@babylonjs/core/Materials/Textures/textureSampler.js
-class TextureSampler {
- get wrapU() {
- return this._cachedWrapU;
- }
- set wrapU(value) {
- this._cachedWrapU = value;
- }
- get wrapV() {
- return this._cachedWrapV;
- }
- set wrapV(value) {
- this._cachedWrapV = value;
- }
- get wrapR() {
- return this._cachedWrapR;
- }
- set wrapR(value) {
- this._cachedWrapR = value;
- }
- get anisotropicFilteringLevel() {
- return this._cachedAnisotropicFilteringLevel;
- }
- set anisotropicFilteringLevel(value) {
- this._cachedAnisotropicFilteringLevel = value;
- }
- get comparisonFunction() {
- return this._comparisonFunction;
- }
- set comparisonFunction(value) {
- this._comparisonFunction = value;
- }
- get useMipMaps() {
- return this._useMipMaps;
- }
- set useMipMaps(value) {
- this._useMipMaps = value;
- }
- constructor() {
- this.samplingMode = -1;
- this._useMipMaps = true;
- this._cachedWrapU = null;
- this._cachedWrapV = null;
- this._cachedWrapR = null;
- this._cachedAnisotropicFilteringLevel = null;
- this._comparisonFunction = 0;
- }
- 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;
- }
- 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;
- }
-}
-
-// node_modules/@babylonjs/core/Materials/Textures/internalTexture.js
-var InternalTextureSource, InternalTexture;
-var init_internalTexture = __esm(() => {
- init_observable();
- (function(InternalTextureSource2) {
- InternalTextureSource2[InternalTextureSource2["Unknown"] = 0] = "Unknown";
- InternalTextureSource2[InternalTextureSource2["Url"] = 1] = "Url";
- InternalTextureSource2[InternalTextureSource2["Temp"] = 2] = "Temp";
- InternalTextureSource2[InternalTextureSource2["Raw"] = 3] = "Raw";
- InternalTextureSource2[InternalTextureSource2["Dynamic"] = 4] = "Dynamic";
- InternalTextureSource2[InternalTextureSource2["RenderTarget"] = 5] = "RenderTarget";
- InternalTextureSource2[InternalTextureSource2["MultiRenderTarget"] = 6] = "MultiRenderTarget";
- InternalTextureSource2[InternalTextureSource2["Cube"] = 7] = "Cube";
- InternalTextureSource2[InternalTextureSource2["CubeRaw"] = 8] = "CubeRaw";
- InternalTextureSource2[InternalTextureSource2["CubePrefiltered"] = 9] = "CubePrefiltered";
- InternalTextureSource2[InternalTextureSource2["Raw3D"] = 10] = "Raw3D";
- InternalTextureSource2[InternalTextureSource2["Raw2DArray"] = 11] = "Raw2DArray";
- InternalTextureSource2[InternalTextureSource2["DepthStencil"] = 12] = "DepthStencil";
- InternalTextureSource2[InternalTextureSource2["CubeRawRGBD"] = 13] = "CubeRawRGBD";
- InternalTextureSource2[InternalTextureSource2["Depth"] = 14] = "Depth";
- })(InternalTextureSource || (InternalTextureSource = {}));
- InternalTexture = class InternalTexture extends TextureSampler {
- get useMipMaps() {
- return this.generateMipMaps;
- }
- set useMipMaps(value) {
- this.generateMipMaps = value;
- }
- get uniqueId() {
- return this._uniqueId;
- }
- _setUniqueId(id) {
- this._uniqueId = id;
- }
- getEngine() {
- return this._engine;
- }
- get source() {
- return this._source;
- }
- constructor(engine, source, delayAllocation = false) {
- super();
- this.isReady = false;
- this.isCube = false;
- this.is3D = false;
- this.is2DArray = false;
- this.isMultiview = false;
- this.url = "";
- this.generateMipMaps = false;
- this.samples = 0;
- this.type = -1;
- this.format = -1;
- this.onLoadedObservable = new Observable;
- this.onErrorObservable = new Observable;
- this.onRebuildCallback = null;
- this.width = 0;
- this.height = 0;
- this.depth = 0;
- this.baseWidth = 0;
- this.baseHeight = 0;
- this.baseDepth = 0;
- this.invertY = false;
- this._invertVScale = false;
- this._associatedChannel = -1;
- this._source = 0;
- this._buffer = null;
- this._bufferView = null;
- this._bufferViewArray = null;
- this._bufferViewArrayArray = null;
- this._size = 0;
- this._extension = "";
- this._files = null;
- this._workingCanvas = null;
- this._workingContext = null;
- this._cachedCoordinatesMode = null;
- this._isDisabled = false;
- this._compression = null;
- this._sphericalPolynomial = null;
- this._sphericalPolynomialPromise = null;
- this._sphericalPolynomialComputed = false;
- this._lodGenerationScale = 0;
- this._lodGenerationOffset = 0;
- this._useSRGBBuffer = false;
- this._creationFlags = 0;
- this._lodTextureHigh = null;
- this._lodTextureMid = null;
- this._lodTextureLow = null;
- this._isRGBD = false;
- this._linearSpecularLOD = false;
- this._irradianceTexture = null;
- this._hardwareTexture = null;
- this._maxLodLevel = null;
- this._references = 1;
- this._gammaSpace = null;
- this._premulAlpha = false;
- this._dynamicTextureSource = null;
- this._autoMSAAManagement = false;
- this._engine = engine;
- this._source = source;
- this._uniqueId = InternalTexture._Counter++;
- if (!delayAllocation) {
- this._hardwareTexture = engine._createHardwareTexture();
- }
- }
- incrementReferences() {
- this._references++;
- }
- 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;
- }
- _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:
- break;
- case 1:
- proxy = this._engine.createTexture(this._originalUrl ?? this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, (temp) => {
- temp._swapAndDie(this, false);
- this.isReady = true;
- }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer);
- return;
- case 3:
- 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:
- 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:
- 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:
- 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);
- }
- break;
- case 7:
- 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:
- 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:
- return;
- case 9:
- proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy2) => {
- if (proxy2) {
- proxy2._swapAndDie(this, false);
- }
- this.isReady = true;
- }, null, this.format, this._extension);
- proxy._sphericalPolynomial = this._sphericalPolynomial;
- return;
- case 12:
- case 14: {
- break;
- }
- }
- }
- _swapAndDie(target, swapAll = true) {
- 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() {
- this._references--;
- if (this._references === 0) {
- this.onLoadedObservable.clear();
- this.onErrorObservable.clear();
- this._engine._releaseTexture(this);
- this._hardwareTexture = null;
- this._dynamicTextureSource = null;
- }
- }
- };
- InternalTexture._Counter = 0;
-});
-
-// node_modules/@babylonjs/core/Lights/IES/iesLoader.js
-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;
- 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;
- }
- 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;
-}
-function LoadIESData(uint8Array) {
- const decoder = new TextDecoder("utf-8");
- const source = decoder.decode(uint8Array);
- const dataPointer = {
- lines: source.split(`
-`),
- index: 0
- };
- const data = { version: dataPointer.lines[0], candelaValues: [], horizontalAngles: [], verticalAngles: [], numberOfHorizontalAngles: 0, numberOfVerticalAngles: 0 };
- dataPointer.index = 1;
- while (dataPointer.lines.length > 0 && !dataPointer.lines[dataPointer.index].includes("TILT=")) {
- dataPointer.index++;
- }
- if (dataPointer.lines[dataPointer.index].includes("INCLUDE")) {}
- dataPointer.index++;
- 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];
- data.unitsType = header[6];
- data.width = header[7];
- data.length = header[8];
- data.height = header[9];
- const additionalData = lineToArray(dataPointer.lines[dataPointer.index++]);
- data.ballastFactor = additionalData[0];
- data.fileGenerationType = additionalData[1];
- data.inputWatts = additionalData[2];
- for (let index = 0;index < data.numberOfHorizontalAngles; index++) {
- data.candelaValues[index] = [];
- }
- readArray(dataPointer, data.numberOfVerticalAngles, data.verticalAngles);
- readArray(dataPointer, data.numberOfHorizontalAngles, data.horizontalAngles);
- for (let index = 0;index < data.numberOfHorizontalAngles; index++) {
- readArray(dataPointer, data.numberOfVerticalAngles, data.candelaValues[index]);
- }
- 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]);
- }
- }
- if (maxCandela > 0) {
- for (let index = 0;index < data.numberOfHorizontalAngles; index++) {
- for (let subIndex = 0;subIndex < data.numberOfVerticalAngles; subIndex++) {
- data.candelaValues[index][subIndex] /= maxCandela;
- }
- }
- }
- const height = 180;
- const width = height * 2;
- const size = width * height;
- const arrayBuffer = new Float32Array(width * height);
- 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);
- 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);
- }
- return {
- width: width / 2,
- height: 1,
- data: arrayBuffer
- };
-}
-var init_iesLoader = () => {};
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/iesTextureLoader.js
-var exports_iesTextureLoader = {};
-__export(exports_iesTextureLoader, {
- _IESTextureLoader: () => _IESTextureLoader
-});
-
-class _IESTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- loadCubeData() {
- throw ".ies not supported in Cube.";
- }
- 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);
- });
- }
-}
-var init_iesTextureLoader = __esm(() => {
- init_iesLoader();
-});
-
-// node_modules/@babylonjs/core/Maths/math.axis.js
-class Axis {
-}
-var Space, Coordinate;
-var init_math_axis = __esm(() => {
- init_math_vector();
- (function(Space2) {
- Space2[Space2["LOCAL"] = 0] = "LOCAL";
- Space2[Space2["WORLD"] = 1] = "WORLD";
- Space2[Space2["BONE"] = 2] = "BONE";
- })(Space || (Space = {}));
- Axis.X = new Vector3(1, 0, 0);
- Axis.Y = new Vector3(0, 1, 0);
- Axis.Z = new Vector3(0, 0, 1);
- (function(Coordinate2) {
- Coordinate2[Coordinate2["X"] = 0] = "X";
- Coordinate2[Coordinate2["Y"] = 1] = "Y";
- Coordinate2[Coordinate2["Z"] = 2] = "Z";
- })(Coordinate || (Coordinate = {}));
-});
-
-// node_modules/@babylonjs/core/Maths/math.plane.js
-class Plane {
- constructor(a, b, c, d) {
- this.normal = new Vector3(a, b, c);
- this.d = d;
- }
- asArray() {
- return [this.normal.x, this.normal.y, this.normal.z, this.d];
- }
- clone() {
- return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
- }
- getClassName() {
- return "Plane";
- }
- getHashCode() {
- let hash2 = this.normal.getHashCode();
- hash2 = hash2 * 397 ^ (this.d | 0);
- return hash2;
- }
- 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;
- if (norm !== 0) {
- magnitude = 1 / norm;
- }
- this.normal.x *= magnitude;
- this.normal.y *= magnitude;
- this.normal.z *= magnitude;
- this.d *= magnitude;
- return this;
- }
- 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);
- }
- dotCoordinate(point) {
- return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d;
- }
- 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 / pyth;
- } else {
- invPyth = 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;
- }
- isFrontFacingTo(direction, epsilon) {
- const dot = Vector3.Dot(this.normal, direction);
- return dot <= epsilon;
- }
- signedDistanceTo(point) {
- return Vector3.Dot(point, this.normal) + this.d;
- }
- static FromArray(array) {
- return new Plane(array[0], array[1], array[2], array[3]);
- }
- static FromPoints(point1, point2, point3) {
- const result = new Plane(0, 0, 0, 0);
- result.copyFromPoints(point1, point2, point3);
- return result;
- }
- static FromPositionAndNormal(origin, normal) {
- const plane = new Plane(0, 0, 0, 0);
- return this.FromPositionAndNormalToRef(origin, normal, plane);
- }
- static FromPositionAndNormalToRef(origin, normal, result) {
- result.normal.copyFrom(normal);
- result.normal.normalize();
- result.d = -origin.dot(result.normal);
- return result;
- }
- 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;
- }
-}
-var init_math_plane = __esm(() => {
- init_math_vector();
- Plane._TmpMatrix = Matrix.Identity();
-});
-
-// node_modules/@babylonjs/core/Maths/math.frustum.js
-class Frustum {
- static GetPlanes(transform) {
- const frustumPlanes = [];
- for (let index = 0;index < 6; index++) {
- frustumPlanes.push(new Plane(0, 0, 0, 0));
- }
- Frustum.GetPlanesToRef(transform, frustumPlanes);
- return frustumPlanes;
- }
- 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();
- }
- 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();
- }
- 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();
- }
- 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();
- }
- 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();
- }
- 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();
- }
- static GetPlanesToRef(transform, frustumPlanes) {
- Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
- Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
- Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
- Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
- Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
- Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
- }
- static IsPointInFrustum(point, frustumPlanes) {
- for (let i = 0;i < 6; i++) {
- if (frustumPlanes[i].dotCoordinate(point) < 0) {
- return false;
- }
- }
- return true;
- }
-}
-var init_math_frustum = __esm(() => {
- init_math_plane();
-});
-
-// node_modules/@babylonjs/core/Maths/math.path.js
-class BezierCurve {
- static Interpolate(t, x1, y1, x2, y2) {
- if (t === 0) {
- return 0;
- }
- 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 / (3 * f0 * refinedT2 + 2 * f1 * refinedT + f2);
- refinedT -= (x - t) * slope;
- refinedT = Math.min(1, Math.max(0, refinedT));
- }
- return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
- }
-}
-
-class Angle {
- constructor(radians) {
- this._radians = radians;
- if (this._radians < 0) {
- this._radians += 2 * Math.PI;
- }
- }
- degrees() {
- return this._radians * 180 / Math.PI;
- }
- radians() {
- return this._radians;
- }
- static BetweenTwoPoints(a, b) {
- const delta = b.subtract(a);
- const theta = Math.atan2(delta.y, delta.x);
- return new Angle(theta);
- }
- 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);
- }
- static FromRadians(radians) {
- return new Angle(radians);
- }
- static FromDegrees(degrees) {
- return new Angle(degrees * Math.PI / 180);
- }
-}
-
-class Arc2 {
- constructor(startPoint, midPoint, 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();
- if (a2 - a1 > 180) {
- a2 -= 360;
- }
- if (a2 - a1 < -180) {
- a2 += 360;
- }
- if (a3 - a2 > 180) {
- a3 -= 360;
- }
- if (a3 - a2 < -180) {
- a3 += 360;
- }
- this.orientation = a2 - a1 < 0 ? 0 : 1;
- this.angle = Angle.FromDegrees(this.orientation === 0 ? a1 - a3 : a3 - a1);
- }
-}
-
-class Path2 {
- constructor(x, y) {
- this._points = new Array;
- this._length = 0;
- this.closed = false;
- this._points.push(new Vector2(x, y));
- }
- 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;
- }
- 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) {
- 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;
- }
- addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) {
- if (this.closed) {
- return this;
- }
- const equation = (t, val0, val1, val2) => {
- const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - 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;
- }
- addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) {
- if (this.closed) {
- return this;
- }
- const equation = (t, val0, val1, val2, val3) => {
- const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - 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;
- }
- 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) {
- 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 {
- 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;
- }
- close() {
- this.closed = true;
- return this;
- }
- 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;
- }
- area() {
- const n = this._points.length;
- let value = 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;
- }
- getPoints() {
- return this._points;
- }
- 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();
- }
- static StartingAt(x, y) {
- return new Path2(x, y);
- }
-}
-
-class Path3D {
- constructor(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;
- 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();
- }
- this._raw = raw || false;
- this._alignTangentsWithPath = alignTangentsWithPath;
- this._compute(firstNormal, alignTangentsWithPath);
- }
- getCurve() {
- return this._curve;
- }
- getPoints() {
- return this._curve;
- }
- length() {
- return this._distances[this._distances.length - 1];
- }
- getTangents() {
- return this._tangents;
- }
- getNormals() {
- return this._normals;
- }
- getBinormals() {
- return this._binormals;
- }
- getDistances() {
- return this._distances;
- }
- getPointAt(position) {
- return this._updatePointAtData(position).point;
- }
- getTangentAt(position, interpolated = false) {
- this._updatePointAtData(position, interpolated);
- return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex];
- }
- getNormalAt(position, interpolated = false) {
- this._updatePointAtData(position, interpolated);
- return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex];
- }
- getBinormalAt(position, interpolated = false) {
- this._updatePointAtData(position, interpolated);
- return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex];
- }
- getDistanceAt(position) {
- return this.length() * position;
- }
- getPreviousPointIndexAt(position) {
- this._updatePointAtData(position);
- return this._pointAtData.previousPointArrayIndex;
- }
- getSubPositionAt(position) {
- this._updatePointAtData(position);
- return this._pointAtData.subPosition;
- }
- getClosestPositionTo(target) {
- let smallestDistance = Number.MAX_VALUE;
- let closestPosition = 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) * Vector3.Distance(point, target) / subLength, 1);
- 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;
- }
- slice(start = 0, end = 1) {
- if (start < 0) {
- start = 1 - start * -1 % 1;
- }
- if (end < 0) {
- end = 1 - end * -1 % 1;
- }
- 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) {
- startIndex++;
- slicePoints.push(startPoint);
- }
- slicePoints.push(...curvePoints.slice(startIndex, endIndex));
- if (end !== 1 || start === 1) {
- slicePoints.push(endPoint);
- }
- return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath);
- }
- 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;
- }
- _compute(firstNormal, alignTangentsWithPath = false) {
- const l = this._curve.length;
- if (l < 2) {
- return;
- }
- 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();
- }
- 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;
- let prev;
- let cur;
- let curTang;
- let prevNor;
- let prevBinor;
- for (let i = 1;i < l; i++) {
- 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();
- 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;
- }
- _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;
- }
- _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;
- }
- _normalVector(vt, va) {
- let normal0;
- let tgl = vt.length();
- if (tgl === 0) {
- tgl = 1;
- }
- if (va === undefined || va === null) {
- let point;
- if (!WithinEpsilon(Math.abs(vt.y) / tgl, 1, Epsilon)) {
- point = new Vector3(0, -1, 0);
- } else if (!WithinEpsilon(Math.abs(vt.x) / tgl, 1, Epsilon)) {
- point = new Vector3(1, 0, 0);
- } else if (!WithinEpsilon(Math.abs(vt.z) / tgl, 1, Epsilon)) {
- point = new Vector3(0, 0, 1);
- } else {
- point = Vector3.Zero();
- }
- normal0 = Vector3.Cross(vt, point);
- } else {
- normal0 = Vector3.Cross(vt, va);
- Vector3.CrossToRef(normal0, vt, normal0);
- }
- normal0.normalize();
- return normal0;
- }
- _updatePointAtData(position, interpolateTNB = false) {
- if (this._pointAtData.id === position) {
- if (!this._pointAtData.interpolateReady) {
- this._updateInterpolationMatrix();
- }
- return this._pointAtData;
- } else {
- this._pointAtData.id = position;
- }
- const curvePoints = this.getPoints();
- if (position <= 0) {
- return this._setPointAtData(0, 0, curvePoints[0], 0, interpolateTNB);
- } else if (position >= 1) {
- return this._setPointAtData(1, 1, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB);
- }
- let previousPoint = curvePoints[0];
- let currentPoint;
- let currentLength = 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, 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;
- }
- _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;
- }
- _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);
- }
- }
-}
-
-class Curve3 {
- static CreateQuadraticBezier(v0, v1, v2, nbPoints) {
- nbPoints = nbPoints > 2 ? nbPoints : 3;
- const bez = [];
- const equation = (t, val0, val1, val2) => {
- const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - 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);
- }
- static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {
- nbPoints = nbPoints > 3 ? nbPoints : 4;
- const bez = [];
- const equation = (t, val0, val1, val2, val3) => {
- const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - 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);
- }
- static CreateHermiteSpline(p1, t1, p2, t2, nSeg) {
- const hermite = [];
- const step = 1 / nSeg;
- for (let i = 0;i <= nSeg; i++) {
- hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
- }
- return new Curve3(hermite);
- }
- static CreateCatmullRomSpline(points, nbPoints, closed) {
- const catmullRom = [];
- const step = 1 / nbPoints;
- let amount = 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);
- }
- 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);
- }
- 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);
- }
- constructor(points) {
- this._length = 0;
- this._points = points;
- this._length = this._computeLength(points);
- }
- getPoints() {
- return this._points;
- }
- length() {
- return this._length;
- }
- 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;
- }
-}
-var Orientation;
-var init_math_path = __esm(() => {
- init_math_vector();
- init_math_constants();
- (function(Orientation2) {
- Orientation2[Orientation2["CW"] = 0] = "CW";
- Orientation2[Orientation2["CCW"] = 1] = "CCW";
- })(Orientation || (Orientation = {}));
-});
-
-// node_modules/@babylonjs/core/Maths/math.vertexFormat.js
-var init_math_vertexFormat = __esm(() => {
- init_math_vector();
-});
-
-// node_modules/@babylonjs/core/Maths/math.viewport.js
-class Viewport {
- constructor(x, y, width, height) {
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- }
- toGlobal(renderWidth, renderHeight) {
- return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
- }
- 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;
- }
- clone() {
- return new Viewport(this.x, this.y, this.width, this.height);
- }
-}
-
-// node_modules/@babylonjs/core/Maths/math.js
-var init_math = __esm(() => {
- init_math_axis();
- init_math_color();
- init_math_constants();
- init_math_frustum();
- init_math_path();
- init_math_plane();
- init_math_vector();
- init_math_vertexFormat();
-});
-
-// node_modules/@babylonjs/core/Maths/sphericalPolynomial.js
-class SphericalHarmonics {
- constructor() {
- this.preScaled = false;
- this.l00 = Vector3.Zero();
- this.l1_1 = Vector3.Zero();
- this.l10 = Vector3.Zero();
- this.l11 = Vector3.Zero();
- this.l2_2 = Vector3.Zero();
- this.l2_1 = Vector3.Zero();
- this.l20 = Vector3.Zero();
- this.l21 = Vector3.Zero();
- this.l22 = Vector3.Zero();
- }
- 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]);
- }
- 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);
- }
- convertIncidentRadianceToIrradiance() {
- this.l00.scaleInPlace(SHCosKernelConvolution[0]);
- this.l1_1.scaleInPlace(SHCosKernelConvolution[1]);
- this.l10.scaleInPlace(SHCosKernelConvolution[2]);
- this.l11.scaleInPlace(SHCosKernelConvolution[3]);
- 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]);
- }
- convertIrradianceToLambertianRadiance() {
- this.scaleInPlace(1 / Math.PI);
- }
- 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]);
- }
- 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;
- }
- 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;
- }
- static FromArray(data) {
- const sh = new SphericalHarmonics;
- return sh.updateFromArray(data);
- }
- 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 SphericalPolynomial {
- constructor() {
- this.x = Vector3.Zero();
- this.y = Vector3.Zero();
- this.z = Vector3.Zero();
- this.xx = Vector3.Zero();
- this.yy = Vector3.Zero();
- this.zz = Vector3.Zero();
- this.xy = Vector3.Zero();
- this.yz = Vector3.Zero();
- this.zx = Vector3.Zero();
- }
- get preScaledHarmonics() {
- if (!this._harmonics) {
- this._harmonics = SphericalHarmonics.FromPolynomial(this);
- }
- if (!this._harmonics.preScaled) {
- this._harmonics.preScaleForRendering();
- }
- return this._harmonics;
- }
- 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);
- }
- 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);
- }
- 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 / Math.PI);
- return this;
- }
- static FromHarmonics(harmonics) {
- const result = new SphericalPolynomial;
- return result.updateFromHarmonics(harmonics);
- }
- 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;
- }
-}
-var SH3ylmBasisConstants, SH3ylmBasisTrigonometricTerms, applySH3 = (lm, direction) => {
- return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction);
-}, SHCosKernelConvolution;
-var init_sphericalPolynomial = __esm(() => {
- init_math_vector();
- init_math();
- SH3ylmBasisConstants = [
- Math.sqrt(1 / (4 * Math.PI)),
- -Math.sqrt(3 / (4 * Math.PI)),
- Math.sqrt(3 / (4 * Math.PI)),
- -Math.sqrt(3 / (4 * Math.PI)),
- Math.sqrt(15 / (4 * Math.PI)),
- -Math.sqrt(15 / (4 * Math.PI)),
- Math.sqrt(5 / (16 * Math.PI)),
- -Math.sqrt(15 / (4 * Math.PI)),
- Math.sqrt(15 / (16 * Math.PI))
- ];
- SH3ylmBasisTrigonometricTerms = [
- () => 1,
- (direction) => direction.y,
- (direction) => direction.z,
- (direction) => direction.x,
- (direction) => direction.x * direction.y,
- (direction) => direction.y * direction.z,
- (direction) => 3 * direction.z * direction.z - 1,
- (direction) => direction.x * direction.z,
- (direction) => direction.x * direction.x - direction.y * direction.y
- ];
- 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];
-});
-
-// node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js
-class FileFaceOrientation {
- constructor(name2, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
- this.name = name2;
- this.worldAxisForNormal = worldAxisForNormal;
- this.worldAxisForFileX = worldAxisForFileX;
- this.worldAxisForFileY = worldAxisForFileY;
- }
-}
-
-class CubeMapToSphericalPolynomialTools {
- static ConvertCubeMapTextureToSphericalPolynomial(texture) {
- if (!texture.isCube) {
- 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;
- const format = 5;
- let type = 0;
- if (texture.textureType == 1 || texture.textureType == 2) {
- type = 1;
- }
- return new Promise((resolve3) => {
- 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
- };
- resolve3(this.ConvertCubeMapToSphericalPolynomial(cubeInfo));
- });
- });
- }
- static _AreaElement(x, y) {
- return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
- }
- static ConvertCubeMapToSphericalPolynomial(cubeInfo) {
- const sphericalHarmonics = new SphericalHarmonics;
- let totalSolidAngle = 0;
- const du = 2 / cubeInfo.size;
- const dv = du;
- const halfTexel = 0.5 * du;
- const minUV = halfTexel - 1;
- for (let faceIndex = 0;faceIndex < 6; faceIndex++) {
- const fileFace = this._FileFaces[faceIndex];
- const dataArray = cubeInfo[fileFace.name];
- let v = minUV;
- 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++) {
- 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];
- if (isNaN(r)) {
- r = 0;
- }
- if (isNaN(g)) {
- g = 0;
- }
- if (isNaN(b)) {
- b = 0;
- }
- if (cubeInfo.type === 0) {
- r /= 255;
- g /= 255;
- b /= 255;
- }
- if (cubeInfo.gammaSpace) {
- r = Math.pow(Clamp(r), ToLinearSpace);
- g = Math.pow(Clamp(g), ToLinearSpace);
- b = Math.pow(Clamp(b), ToLinearSpace);
- }
- 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;
- }
- }
- const sphereSolidAngle = 4 * Math.PI;
- const facesProcessed = 6;
- const expectedSolidAngle = sphereSolidAngle * facesProcessed / 6;
- const correctionFactor = expectedSolidAngle / totalSolidAngle;
- sphericalHarmonics.scaleInPlace(correctionFactor);
- sphericalHarmonics.convertIncidentRadianceToIrradiance();
- sphericalHarmonics.convertIrradianceToLambertianRadiance();
- return SphericalPolynomial.FromHarmonics(sphericalHarmonics);
- }
-}
-var init_cubemapToSphericalPolynomial = __esm(() => {
- init_math_vector();
- init_sphericalPolynomial();
- init_math_constants();
- init_math_color();
- CubeMapToSphericalPolynomialTools._FileFaces = [
- new FileFaceOrientation("right", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)),
- new FileFaceOrientation("left", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)),
- new FileFaceOrientation("up", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)),
- new FileFaceOrientation("down", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)),
- new FileFaceOrientation("front", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)),
- new FileFaceOrientation("back", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0))
- ];
- CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096;
- CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false;
-});
-
-// node_modules/@babylonjs/core/Misc/guid.js
-function RandomGUID() {
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
- const r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8;
- return v.toString(16);
- });
-}
-var init_guid = () => {};
-
-// node_modules/@babylonjs/core/Materials/Textures/thinTexture.js
-class ThinTexture {
- get wrapU() {
- return this._wrapU;
- }
- set wrapU(value) {
- this._wrapU = value;
- }
- get wrapV() {
- return this._wrapV;
- }
- set wrapV(value) {
- this._wrapV = value;
- }
- get coordinatesMode() {
- return 0;
- }
- get isCube() {
- if (!this._texture) {
- return false;
- }
- return this._texture.isCube;
- }
- set isCube(value) {
- if (!this._texture) {
- return;
- }
- this._texture.isCube = value;
- }
- get is3D() {
- if (!this._texture) {
- return false;
- }
- return this._texture.is3D;
- }
- set is3D(value) {
- if (!this._texture) {
- return;
- }
- this._texture.is3D = value;
- }
- get is2DArray() {
- if (!this._texture) {
- return false;
- }
- return this._texture.is2DArray;
- }
- set is2DArray(value) {
- if (!this._texture) {
- return;
- }
- this._texture.is2DArray = value;
- }
- getClassName() {
- return "ThinTexture";
- }
- static _IsRenderTargetWrapper(texture) {
- return texture?.shareDepth !== undefined;
- }
- constructor(internalTexture) {
- this._wrapU = 1;
- this._wrapV = 1;
- this.wrapR = 1;
- this.anisotropicFilteringLevel = 4;
- this.delayLoadState = 0;
- this._texture = null;
- this._engine = null;
- this._cachedSize = Size.Zero();
- this._cachedBaseSize = Size.Zero();
- this._initialSamplingMode = 2;
- this._texture = ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture;
- if (this._texture) {
- this._engine = this._texture.getEngine();
- }
- }
- isReady() {
- if (this.delayLoadState === 4) {
- this.delayLoad();
- return false;
- }
- if (this._texture) {
- return this._texture.isReady;
- }
- return false;
- }
- delayLoad() {}
- getInternalTexture() {
- return this._texture;
- }
- 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;
- }
- 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 samplingMode() {
- if (!this._texture) {
- return this._initialSamplingMode;
- }
- return this._texture.samplingMode;
- }
- updateSamplingMode(samplingMode) {
- if (this._texture && this._engine) {
- this._engine.updateTextureSamplingMode(samplingMode, this._texture);
- }
- }
- releaseInternalTexture() {
- if (this._texture) {
- this._texture.dispose();
- this._texture = null;
- }
- }
- dispose() {
- if (this._texture) {
- this.releaseInternalTexture();
- this._engine = null;
- }
- }
-}
-var init_thinTexture = () => {};
-
-// node_modules/@babylonjs/core/Materials/Textures/baseTexture.js
-var BaseTexture;
-var init_baseTexture = __esm(() => {
- init_tslib_es6();
- init_decorators();
- init_observable();
- init_math_vector();
- init_engineStore();
- init_guid();
- init_fileTools();
- init_thinTexture();
- init_decorators_serialization();
- BaseTexture = class BaseTexture extends ThinTexture {
- 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;
- }
- 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;
- }
- 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;
- }
- 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;
- }
- get wrapU() {
- return this._wrapU;
- }
- set wrapU(value) {
- this._wrapU = value;
- }
- get wrapV() {
- return this._wrapV;
- }
- set wrapV(value) {
- this._wrapV = value;
- }
- get isCube() {
- if (!this._texture) {
- return this._isCube;
- }
- return this._texture.isCube;
- }
- set isCube(value) {
- if (!this._texture) {
- this._isCube = value;
- } else {
- this._texture.isCube = value;
- }
- }
- get is3D() {
- if (!this._texture) {
- return false;
- }
- return this._texture.is3D;
- }
- set is3D(value) {
- if (!this._texture) {
- return;
- }
- this._texture.is3D = value;
- }
- get is2DArray() {
- if (!this._texture) {
- return false;
- }
- return this._texture.is2DArray;
- }
- set is2DArray(value) {
- if (!this._texture) {
- return;
- }
- this._texture.is2DArray = value;
- }
- 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);
- });
- }
- 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);
- });
- }
- get noMipmap() {
- return false;
- }
- get lodGenerationOffset() {
- if (this._texture) {
- return this._texture._lodGenerationOffset;
- }
- return 0;
- }
- set lodGenerationOffset(value) {
- if (this._texture) {
- this._texture._lodGenerationOffset = value;
- }
- }
- get lodGenerationScale() {
- if (this._texture) {
- return this._texture._lodGenerationScale;
- }
- return 0;
- }
- set lodGenerationScale(value) {
- if (this._texture) {
- this._texture._lodGenerationScale = value;
- }
- }
- get linearSpecularLOD() {
- if (this._texture) {
- return this._texture._linearSpecularLOD;
- }
- return false;
- }
- set linearSpecularLOD(value) {
- if (this._texture) {
- this._texture._linearSpecularLOD = value;
- }
- }
- get irradianceTexture() {
- if (this._texture) {
- return this._texture._irradianceTexture;
- }
- return null;
- }
- set irradianceTexture(value) {
- if (this._texture) {
- this._texture._irradianceTexture = value;
- }
- }
- get uid() {
- if (!this._uid) {
- this._uid = RandomGUID();
- }
- return this._uid;
- }
- toString() {
- return this.name;
- }
- getClassName() {
- return "BaseTexture";
- }
- set onDispose(callback) {
- if (this._onDisposeObserver) {
- this.onDisposeObservable.remove(this._onDisposeObserver);
- }
- this._onDisposeObserver = this.onDisposeObservable.add(callback);
- }
- get isBlocking() {
- return true;
- }
- get loadingError() {
- return this._loadingError;
- }
- get errorObject() {
- return this._errorObject;
- }
- constructor(sceneOrEngine, internalTexture = null) {
- super(null);
- this.metadata = null;
- this.reservedDataStore = null;
- this._hasAlpha = false;
- this._getAlphaFromRGB = false;
- this.level = 1;
- this._coordinatesIndex = 0;
- this.optimizeUVAllocation = true;
- this._coordinatesMode = 0;
- this.wrapR = 1;
- this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
- this._isCube = false;
- this._gammaSpace = true;
- this.invertZ = false;
- this.lodLevelInAlpha = false;
- this.isRenderTarget = false;
- this._prefiltered = false;
- this._forceSerialize = false;
- this.animations = [];
- this.onDisposeObservable = new Observable;
- this._onDisposeObserver = null;
- this._scene = null;
- this._uid = null;
- 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;
- }
- getScene() {
- return this._scene;
- }
- _getEngine() {
- return this._engine;
- }
- getTextureMatrix() {
- return Matrix.IdentityReadOnly;
- }
- getReflectionTextureMatrix() {
- return Matrix.IdentityReadOnly;
- }
- getRefractionTextureMatrix() {
- return this.getReflectionTextureMatrix();
- }
- isReadyOrNotBlocking() {
- return !this.isBlocking || this.isReady() || this.loadingError;
- }
- scale(ratio) {}
- get canRescale() {
- return false;
- }
- _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;
- }
- _rebuild(_fromContextLost = false) {}
- clone() {
- return null;
- }
- get textureType() {
- if (!this._texture) {
- return 0;
- }
- return this._texture.type !== undefined ? this._texture.type : 0;
- }
- get textureFormat() {
- if (!this._texture) {
- return 5;
- }
- return this._texture.format !== undefined ? this._texture.format : 5;
- }
- _markAllSubMeshesAsTexturesDirty() {
- const scene = this.getScene();
- if (!scene) {
- return;
- }
- scene.markAllMaterialsAsDirty(1);
- }
- 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;
- }
- }
- _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;
- }
- }
- get _lodTextureHigh() {
- if (this._texture) {
- return this._texture._lodTextureHigh;
- }
- return null;
- }
- get _lodTextureMid() {
- if (this._texture) {
- return this._texture._lodTextureMid;
- }
- return null;
- }
- get _lodTextureLow() {
- if (this._texture) {
- return this._texture._lodTextureLow;
- }
- return null;
- }
- dispose() {
- if (this._scene) {
- if (this._scene.stopAnimation) {
- this._scene.stopAnimation(this);
- }
- 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 index2 = this._parentContainer.textures.indexOf(this);
- if (index2 > -1) {
- this._parentContainer.textures.splice(index2, 1);
- }
- this._parentContainer = null;
- }
- }
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- this.metadata = null;
- super.dispose();
- }
- serialize(allowEmptyName = false) {
- if (!this.name && !allowEmptyName) {
- return null;
- }
- const serializationObject = SerializationHelper.Serialize(this);
- SerializationHelper.AppendSerializedAnimations(this, serializationObject);
- return serializationObject;
- }
- 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";
- }
- };
- BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
- __decorate([
- serialize()
- ], BaseTexture.prototype, "uniqueId", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "name", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "displayName", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "metadata", undefined);
- __decorate([
- serialize("hasAlpha")
- ], BaseTexture.prototype, "_hasAlpha", undefined);
- __decorate([
- serialize("getAlphaFromRGB")
- ], BaseTexture.prototype, "_getAlphaFromRGB", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "level", undefined);
- __decorate([
- serialize("coordinatesIndex")
- ], BaseTexture.prototype, "_coordinatesIndex", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "optimizeUVAllocation", undefined);
- __decorate([
- serialize("coordinatesMode")
- ], BaseTexture.prototype, "_coordinatesMode", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "wrapU", null);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "wrapV", null);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "wrapR", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "anisotropicFilteringLevel", undefined);
- __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", undefined);
- __decorate([
- serialize()
- ], BaseTexture.prototype, "lodLevelInAlpha", undefined);
- __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", undefined);
-});
-
-// node_modules/@babylonjs/core/Misc/instantiationTools.js
-class InstantiationTools {
- 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;
- }
-}
-var init_instantiationTools = __esm(() => {
- init_logger();
- init_typeStore();
- InstantiationTools.RegisteredExternalClasses = {};
-});
-
-// node_modules/@babylonjs/core/Misc/copyTools.js
-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");
-}
-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);
-}
-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);
-}
-var init_copyTools = () => {};
-
-// node_modules/@babylonjs/core/Compat/compatibilityOptions.js
-var useOpenGLOrientationForUV = false;
-var init_compatibilityOptions = () => {};
-
-// node_modules/@babylonjs/core/Materials/Textures/texture.js
-var Texture;
-var init_texture = __esm(() => {
- init_tslib_es6();
- init_decorators();
- init_observable();
- init_math_vector();
- init_baseTexture();
- init_typeStore();
- init_devTools();
- init_timingTools();
- init_instantiationTools();
- init_math_plane();
- init_stringTools();
- init_copyTools();
- init_compatibilityOptions();
- init_decorators_serialization();
- Texture = class Texture extends BaseTexture {
- static _CreateVideoTexture(name2, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) {
- throw _WarnImport("VideoTexture");
- }
- get noMipmap() {
- return this._noMipmap;
- }
- get mimeType() {
- return this._mimeType;
- }
- set isBlocking(value) {
- this._isBlocking = value;
- }
- get isBlocking() {
- return this._isBlocking;
- }
- get invertY() {
- return this._invertY;
- }
- constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) {
- super(sceneOrEngine);
- this.url = null;
- this.uOffset = 0;
- this.vOffset = 0;
- this.uScale = 1;
- this.vScale = 1;
- this.uAng = 0;
- this.vAng = 0;
- this.wAng = 0;
- this.uRotationCenter = 0.5;
- this.vRotationCenter = 0.5;
- this.wRotationCenter = 0.5;
- this.homogeneousRotationInUVTransform = false;
- this.inspectableCustomProperties = null;
- this._noMipmap = false;
- 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;
- this._buffer = null;
- this._deleteBuffer = false;
- this._format = null;
- this._delayedOnLoad = null;
- this._delayedOnError = null;
- 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 ?? !useOpenGLOrientationForUV;
- 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 ? !useOpenGLOrientationForUV : 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;
- }
- 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);
- });
- }
- }
- }
- 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();
- }
- 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;
- }
- 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);
- 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, this._t1);
- this._prepareRowForTextureGeneration(0, 1, 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, this._t2.x, this._t2.y, this._t2.z, 0, this._t0.x, this._t0.y, this._t0.z, 0, 0, 0, 0, 1, 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) {
- scene.markAllMaterialsAsDirty(1, (mat) => {
- return mat.hasTexture(this);
- });
- }
- return this._cachedTextureMatrix;
- }
- 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.5, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 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) {
- scene.markAllMaterialsAsDirty(1, (mat) => {
- return mat.hasTexture(this);
- });
- }
- return this._cachedReflectionTextureMatrix;
- }
- 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() {
- 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;
- }
- getClassName() {
- return "Texture";
- }
- dispose() {
- super.dispose();
- this.onLoadObservable.clear();
- this._delayedOnLoad = null;
- this._delayedOnError = null;
- this._buffer = null;
- }
- static Parse(parsedTexture, scene, rootUrl) {
- if (parsedTexture.customType) {
- const customTexture = InstantiationTools.Instantiate(parsedTexture.customType);
- 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 texture2 of cache) {
- if (texture2.uniqueId === parsedTexture.internalTextureUniqueId) {
- internalTexture = texture2;
- break;
- }
- }
- }
- const onLoaded = (texture2) => {
- if (texture2 && texture2._texture) {
- texture2._texture._cachedWrapU = null;
- texture2._texture._cachedWrapV = null;
- texture2._texture._cachedWrapR = null;
- }
- if (parsedTexture.samplingMode) {
- const sampling = parsedTexture.samplingMode;
- if (texture2 && texture2.samplingMode !== sampling) {
- texture2.updateSamplingMode(sampling);
- }
- }
- if (texture2 && parsedTexture.animations) {
- for (let animationIndex = 0;animationIndex < parsedTexture.animations.length; animationIndex++) {
- const parsedAnimation = parsedTexture.animations[animationIndex];
- const internalClass = GetClass("BABYLON.Animation");
- if (internalClass) {
- texture2.animations.push(internalClass.Parse(parsedAnimation));
- }
- }
- }
- if (texture2 && texture2._texture) {
- if (hasInternalTextureUniqueId && !internalTexture) {
- texture2._texture._setUniqueId(parsedTexture.internalTextureUniqueId);
- }
- texture2._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) {
- 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 texture2 = Texture._CreateVideoTexture(rootUrl + (parsedTexture.url || parsedTexture.name), rootUrl + (parsedTexture.src || parsedTexture.url), scene, generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, parsedTexture.settings || {});
- onLoaded(texture2);
- return texture2;
- } else {
- let texture2;
- if (parsedTexture.base64String && !internalTexture) {
- texture2 = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => {
- onLoaded(texture2);
- }, parsedTexture._creationFlags ?? 0, parsedTexture._useSRGBBuffer ?? false);
- texture2.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(texture2);
- },
- internalTexture
- };
- texture2 = new Texture(url, scene, options);
- }
- return texture2;
- }
- }, parsedTexture, scene);
- return texture;
- }
- static CreateFromBase64String(data, name2, scene, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
- return new Texture("data:" + name2, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags, forcedExtension);
- }
- static LoadFromDataString(name2, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) {
- if (name2.substring(0, 5) !== "data:") {
- name2 = "data:" + name2;
- }
- return new Texture(name2, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags, forcedExtension);
- }
- };
- Texture.SerializeBuffers = true;
- Texture.ForceSerializeBuffers = false;
- Texture.OnTextureLoadErrorObservable = new Observable;
- Texture._SerializeInternalTextureUniqueId = false;
- Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => {
- throw _WarnImport("CubeTexture");
- };
- Texture._CreateMirror = (name2, renderTargetSize, scene, generateMipMaps) => {
- throw _WarnImport("MirrorTexture");
- };
- Texture._CreateRenderTargetTexture = (name2, renderTargetSize, scene, generateMipMaps, creationFlags) => {
- throw _WarnImport("RenderTargetTexture");
- };
- Texture.NEAREST_SAMPLINGMODE = 1;
- Texture.NEAREST_NEAREST_MIPLINEAR = 8;
- Texture.BILINEAR_SAMPLINGMODE = 2;
- Texture.LINEAR_LINEAR_MIPNEAREST = 11;
- Texture.TRILINEAR_SAMPLINGMODE = 3;
- Texture.LINEAR_LINEAR_MIPLINEAR = 3;
- Texture.NEAREST_NEAREST_MIPNEAREST = 4;
- Texture.NEAREST_LINEAR_MIPNEAREST = 5;
- Texture.NEAREST_LINEAR_MIPLINEAR = 6;
- Texture.NEAREST_LINEAR = 7;
- Texture.NEAREST_NEAREST = 1;
- Texture.LINEAR_NEAREST_MIPNEAREST = 9;
- Texture.LINEAR_NEAREST_MIPLINEAR = 10;
- Texture.LINEAR_LINEAR = 2;
- Texture.LINEAR_NEAREST = 12;
- Texture.EXPLICIT_MODE = 0;
- Texture.SPHERICAL_MODE = 1;
- Texture.PLANAR_MODE = 2;
- Texture.CUBIC_MODE = 3;
- Texture.PROJECTION_MODE = 4;
- Texture.SKYBOX_MODE = 5;
- Texture.INVCUBIC_MODE = 6;
- Texture.EQUIRECTANGULAR_MODE = 7;
- Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
- Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
- Texture.CLAMP_ADDRESSMODE = 0;
- Texture.WRAP_ADDRESSMODE = 1;
- Texture.MIRROR_ADDRESSMODE = 2;
- Texture.UseSerializedUrlIfAny = false;
- __decorate([
- serialize()
- ], Texture.prototype, "url", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "uOffset", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "vOffset", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "uScale", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "vScale", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "uAng", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "vAng", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "wAng", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "uRotationCenter", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "vRotationCenter", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "wRotationCenter", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "homogeneousRotationInUVTransform", undefined);
- __decorate([
- serialize()
- ], Texture.prototype, "isBlocking", null);
- RegisterClass("BABYLON.Texture", Texture);
- SerializationHelper._TextureParser = Texture.Parse;
-});
-
-// node_modules/@babylonjs/core/Buffers/dataBuffer.js
-class DataBuffer {
- get underlyingResource() {
- return null;
- }
- constructor() {
- this.references = 0;
- this.capacity = 0;
- this.is32Bits = false;
- this.uniqueId = DataBuffer._Counter++;
- }
-}
-var init_dataBuffer = __esm(() => {
- DataBuffer._Counter = 0;
-});
-
-// node_modules/@babylonjs/core/Buffers/bufferUtils.js
-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);
- }
- 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}`);
- }
- }
-}
-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}'`);
- }
-}
-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}'`);
- }
-}
-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;
- }
- }
-}
-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;
-}
-function GetTypedArrayData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) {
- const typeByteLength = GetTypeByteLength(type);
- const constructor = GetTypedArrayConstructor(type);
- const count = totalVertices * size;
- 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));
- }
- 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);
-}
-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);
- }
-}
-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;
-}
-var init_bufferUtils = __esm(() => {
- init_logger();
-});
-
-// node_modules/@babylonjs/core/Buffers/buffer.js
-class Buffer2 {
- get isDisposed() {
- return this._isDisposed;
- }
- constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor, label) {
- this._isAlreadyOwned = false;
- this._isDisposed = false;
- if (engine && engine.getScene) {
- 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) {
- this.create();
- }
- }
- 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;
- return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor);
- }
- isUpdatable() {
- return this._updatable;
- }
- getData() {
- return this._data;
- }
- getBuffer() {
- return this._buffer;
- }
- getStrideSize() {
- return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
- }
- create(data = null) {
- if (!data && this._buffer) {
- return;
- }
- data = data || this._data;
- if (!data) {
- return;
- }
- if (!this._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) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data);
- this._data = data;
- }
- }
- _rebuild() {
- if (!this._data) {
- if (!this._buffer) {
- return;
- }
- if (this._buffer.capacity > 0) {
- 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(data) {
- this.create(data);
- }
- updateDirectly(data, offset, vertexCount, useBytes = false) {
- if (!this._buffer) {
- return;
- }
- if (this._updatable) {
- this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined);
- if (offset === 0 && vertexCount === undefined) {
- this._data = data;
- } else {
- this._data = null;
- }
- }
- }
- _increaseReferences() {
- if (!this._buffer) {
- return;
- }
- if (!this._isAlreadyOwned) {
- this._isAlreadyOwned = true;
- return;
- }
- this._buffer.references++;
- }
- dispose() {
- if (!this._buffer) {
- return;
- }
- if (this._engine._releaseBuffer(this._buffer)) {
- this._isDisposed = true;
- this._data = null;
- this._buffer = null;
- }
- }
-}
-
-class VertexBuffer {
- get isDisposed() {
- return this._isDisposed;
- }
- get instanceDivisor() {
- return this._instanceDivisor;
- }
- set instanceDivisor(value) {
- const isInstanced = value != 0;
- this._instanceDivisor = value;
- if (isInstanced !== this._instanced) {
- this._instanced = isInstanced;
- this._computeHashCode();
- }
- }
- get _maxVerticesCount() {
- const data = this.getData();
- if (!data) {
- return 0;
- }
- if (Array.isArray(data)) {
- return data.length / (this.byteStride / 4) - this.byteOffset / 4;
- }
- return (data.byteLength - this.byteOffset) / this.byteStride;
- }
- constructor(engine, data, kind, updatableOrOptions, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) {
- 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 Buffer2) {
- this._buffer = data;
- this._ownsBuffer = takeBufferOwnership;
- } else {
- this._buffer = new Buffer2(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() {
- this.hashCode = (this.type - 5120 << 0) + ((this.normalized ? 1 : 0) << 3) + (this._size << 4) + ((this._instanced ? 1 : 0) << 6) + (this.byteStride << 12);
- }
- _rebuild() {
- this._buffer?._rebuild();
- }
- getKind() {
- return this._kind;
- }
- isUpdatable() {
- return this._buffer.isUpdatable();
- }
- getData() {
- return this._buffer.getData();
- }
- 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);
- }
- getBuffer() {
- return this._buffer.getBuffer();
- }
- getWrapperBuffer() {
- return this._buffer;
- }
- getStrideSize() {
- return this.byteStride / GetTypeByteLength(this.type);
- }
- getOffset() {
- return this.byteOffset / GetTypeByteLength(this.type);
- }
- getSize(sizeInBytes = false) {
- return sizeInBytes ? this._size * GetTypeByteLength(this.type) : this._size;
- }
- getIsInstanced() {
- return this._instanced;
- }
- getInstanceDivisor() {
- return this._instanceDivisor;
- }
- create(data) {
- this._buffer.create(data);
- this._alignBuffer();
- }
- update(data) {
- this._buffer.update(data);
- this._alignBuffer();
- }
- updateDirectly(data, offset, useBytes = false) {
- this._buffer.updateDirectly(data, offset, undefined, useBytes);
- this._alignBuffer();
- }
- dispose() {
- if (this._ownsBuffer) {
- this._buffer.dispose();
- }
- this._isDisposed = true;
- }
- 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);
- }
- });
- }
- _alignBuffer() {}
- 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 + "'");
- }
- }
- 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;
- }
- }
- static GetTypeByteLength(type) {
- return GetTypeByteLength(type);
- }
- 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);
- }
- });
- }
- static GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) {
- return GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy);
- }
-}
-var init_buffer = __esm(() => {
- init_dataBuffer();
- init_logger();
- init_bufferUtils();
- VertexBuffer._Counter = 0;
- VertexBuffer.BYTE = 5120;
- VertexBuffer.UNSIGNED_BYTE = 5121;
- VertexBuffer.SHORT = 5122;
- VertexBuffer.UNSIGNED_SHORT = 5123;
- VertexBuffer.INT = 5124;
- VertexBuffer.UNSIGNED_INT = 5125;
- VertexBuffer.FLOAT = 5126;
- VertexBuffer.PositionKind = `position`;
- VertexBuffer.NormalKind = `normal`;
- VertexBuffer.TangentKind = `tangent`;
- VertexBuffer.UVKind = `uv`;
- VertexBuffer.UV2Kind = `uv2`;
- VertexBuffer.UV3Kind = `uv3`;
- VertexBuffer.UV4Kind = `uv4`;
- VertexBuffer.UV5Kind = `uv5`;
- VertexBuffer.UV6Kind = `uv6`;
- VertexBuffer.ColorKind = `color`;
- VertexBuffer.ColorInstanceKind = `instanceColor`;
- VertexBuffer.MatricesIndicesKind = `matricesIndices`;
- VertexBuffer.MatricesWeightsKind = `matricesWeights`;
- VertexBuffer.MatricesIndicesExtraKind = `matricesIndicesExtra`;
- VertexBuffer.MatricesWeightsExtraKind = `matricesWeightsExtra`;
-});
-
-// node_modules/@babylonjs/core/PostProcesses/postProcessManager.js
-class PostProcessManager {
- constructor(scene) {
- this._vertexBuffers = {};
- this.onBeforeRenderObservable = new Observable;
- this._scene = scene;
- }
- _prepareBuffers() {
- if (this._vertexBuffers[VertexBuffer.PositionKind]) {
- return;
- }
- 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() {
- 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);
- }
- _rebuild() {
- const vb = this._vertexBuffers[VertexBuffer.PositionKind];
- if (!vb) {
- return;
- }
- vb._rebuild();
- this._buildIndexBuffer();
- }
- _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;
- }
- 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);
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
- engine.drawElementsType(0, 0, 6);
- pp.onAfterRenderObservable.notifyObservers(effect);
- }
- }
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- }
- _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);
- this._prepareBuffers();
- engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
- engine.drawElementsType(0, 0, 6);
- pp.onAfterRenderObservable.notifyObservers(effect);
- }
- }
- engine.setDepthBuffer(true);
- engine.setDepthWrite(true);
- engine.setAlphaMode(0);
- }
- 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;
- }
- }
-}
-var init_postProcessManager = __esm(() => {
- init_buffer();
- init_observable();
-});
-
-// node_modules/@babylonjs/core/Misc/tools.functions.js
-function IsExponentOfTwo(value) {
- let count = 1;
- do {
- count *= 2;
- } while (count < value);
- return count === value;
-}
-function Mix(a, b, alpha) {
- return a * (1 - alpha) + b * alpha;
-}
-function NearestPOT(x) {
- const c = CeilingPOT(x);
- const f = FloorPOT(x);
- return c - x > x - f ? f : c;
-}
-function CeilingPOT(x) {
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x++;
- return x;
-}
-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);
-}
-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);
-}
-
-// node_modules/@babylonjs/core/Misc/smartArray.js
-class SmartArray {
- constructor(capacity) {
- this.length = 0;
- this.data = new Array(capacity);
- this._id = SmartArray._GlobalId++;
- }
- push(value) {
- this.data[this.length++] = value;
- if (this.length > this.data.length) {
- this.data.length *= 2;
- }
- }
- forEach(func) {
- for (let index = 0;index < this.length; index++) {
- func(this.data[index]);
- }
- }
- sort(compareFn) {
- this.data.sort(compareFn);
- }
- reset() {
- this.length = 0;
- }
- dispose() {
- this.reset();
- if (this.data) {
- this.data.length = 0;
- }
- }
- 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];
- }
- }
- indexOf(value) {
- const position = this.data.indexOf(value);
- if (position >= this.length) {
- return -1;
- }
- return position;
- }
- contains(value) {
- return this.indexOf(value) !== -1;
- }
-}
-var SmartArrayNoDuplicate;
-var init_smartArray = __esm(() => {
- SmartArray._GlobalId = 0;
- SmartArrayNoDuplicate = class SmartArrayNoDuplicate extends SmartArray {
- constructor() {
- super(...arguments);
- this._duplicateId = 0;
- }
- push(value) {
- super.push(value);
- if (!value.__smartArrayFlags) {
- value.__smartArrayFlags = {};
- }
- value.__smartArrayFlags[this._id] = this._duplicateId;
- }
- pushNoDuplicate(value) {
- if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
- return false;
- }
- this.push(value);
- return true;
- }
- reset() {
- super.reset();
- this._duplicateId++;
- }
- 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);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/Rendering/renderingGroup.js
-class RenderingGroup {
- set opaqueSortCompareFn(value) {
- if (value) {
- this._opaqueSortCompareFn = value;
- } else {
- this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare;
- }
- this._renderOpaque = this._renderOpaqueSorted;
- }
- set alphaTestSortCompareFn(value) {
- if (value) {
- this._alphaTestSortCompareFn = value;
- } else {
- this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare;
- }
- this._renderAlphaTest = this._renderAlphaTestSorted;
- }
- set transparentSortCompareFn(value) {
- if (value) {
- this._transparentSortCompareFn = value;
- } else {
- this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
- }
- this._renderTransparent = this._renderTransparentSorted;
- }
- 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);
- this._empty = true;
- this._edgesRenderers = new SmartArrayNoDuplicate(16);
- this._scene = scene;
- this.opaqueSortCompareFn = opaqueSortCompareFn;
- this.alphaTestSortCompareFn = alphaTestSortCompareFn;
- this.transparentSortCompareFn = transparentSortCompareFn;
- }
- render(customRenderFunction, renderSprites, renderParticles, activeMeshes) {
- if (customRenderFunction) {
- customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
- return;
- }
- const engine = this._scene.getEngine();
- if (this._depthOnlySubMeshes.length !== 0) {
- engine.setColorWrite(false);
- this._renderAlphaTest(this._depthOnlySubMeshes);
- engine.setColorWrite(true);
- }
- if (this._opaqueSubMeshes.length !== 0) {
- this._renderOpaque(this._opaqueSubMeshes);
- }
- if (this._alphaTestSubMeshes.length !== 0) {
- this._renderAlphaTest(this._alphaTestSubMeshes);
- }
- const stencilState = engine.getStencilBuffer();
- engine.setStencilBuffer(false);
- if (renderSprites) {
- this._renderSprites();
- }
- if (renderParticles) {
- this._renderParticles(activeMeshes);
- }
- if (this.onBeforeTransparentRendering) {
- this.onBeforeTransparentRendering();
- }
- 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) {
- this._renderTransparent(excludedMeshes);
- }
- } else {
- this._renderTransparent(this._transparentSubMeshes);
- }
- engine.setAlphaMode(0);
- }
- engine.setStencilBuffer(false);
- if (this._edgesRenderers.length) {
- for (let edgesRendererIndex = 0;edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
- this._edgesRenderers.data[edgesRendererIndex].render();
- }
- engine.setAlphaMode(0);
- }
- engine.setStencilBuffer(stencilState);
- }
- _renderOpaqueSorted(subMeshes) {
- RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
- }
- _renderAlphaTestSorted(subMeshes) {
- RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
- }
- _renderTransparentSorted(subMeshes) {
- RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, 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);
- }
- }
- static defaultTransparentSortCompare(a, b) {
- if (a._alphaIndex > b._alphaIndex) {
- return 1;
- }
- if (a._alphaIndex < b._alphaIndex) {
- return -1;
- }
- return RenderingGroup.backToFrontSortCompare(a, b);
- }
- static backToFrontSortCompare(a, b) {
- if (a._distanceToCamera < b._distanceToCamera) {
- return 1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return -1;
- }
- return 0;
- }
- static frontToBackSortCompare(a, b) {
- if (a._distanceToCamera < b._distanceToCamera) {
- return -1;
- }
- if (a._distanceToCamera > b._distanceToCamera) {
- return 1;
- }
- return 0;
- }
- 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;
- }
- prepare() {
- this._opaqueSubMeshes.reset();
- this._transparentSubMeshes.reset();
- this._alphaTestSubMeshes.reset();
- this._depthOnlySubMeshes.reset();
- this._particleSystems.reset();
- this.prepareSprites();
- this._edgesRenderers.reset();
- this._empty = true;
- }
- 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();
- }
- dispatch(subMesh, mesh, material) {
- if (mesh === undefined) {
- mesh = subMesh.getMesh();
- }
- if (material === undefined) {
- material = subMesh.getMaterial();
- }
- if (material === null || material === undefined) {
- return;
- }
- if (material.needAlphaBlendingForMesh(mesh)) {
- this._transparentSubMeshes.push(subMesh);
- } else if (material.needAlphaTestingForMesh(mesh)) {
- if (material.needDepthPrePass) {
- this._depthOnlySubMeshes.push(subMesh);
- }
- this._alphaTestSubMeshes.push(subMesh);
- } else {
- if (material.needDepthPrePass) {
- this._depthOnlySubMeshes.push(subMesh);
- }
- this._opaqueSubMeshes.push(subMesh);
- }
- 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;
- }
- 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;
- }
- 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);
- }
-}
-var init_renderingGroup = __esm(() => {
- init_smartArray();
- init_math_vector();
- RenderingGroup._ZeroVector = Vector3.Zero();
-});
-
-// node_modules/@babylonjs/core/Rendering/renderingManager.js
-class RenderingGroupInfo {
-}
-
-class RenderingManager {
- get maintainStateBetweenFrames() {
- return this._maintainStateBetweenFrames;
- }
- set maintainStateBetweenFrames(value) {
- if (value === this._maintainStateBetweenFrames) {
- return;
- }
- this._maintainStateBetweenFrames = value;
- if (!this._maintainStateBetweenFrames) {
- this.restoreDispachedFlags();
- }
- }
- 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;
- }
- }
- constructor(scene) {
- 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 };
- }
- }
- 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;
- }
- render(customRenderFunction, activeMeshes, renderParticles, renderSprites) {
- const info = this._renderingGroupInfo;
- info.scene = this._scene;
- info.camera = this._scene.activeCamera;
- info.renderingManager = this;
- if (this._scene.spriteManagers && renderSprites) {
- for (let index = 0;index < this._scene.spriteManagers.length; index++) {
- const manager = this._scene.spriteManagers[index];
- this.dispatchSprites(manager);
- }
- }
- 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;
- this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
- if (RenderingManager.AUTOCLEAR) {
- const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];
- if (autoClear && autoClear.autoClear) {
- this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
- }
- }
- 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);
- }
- this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
- }
- }
- 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();
- }
- }
- }
- 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() {
- this.freeRenderingGroups();
- this._renderingGroups.length = 0;
- this._renderingGroupInfo = null;
- }
- 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]);
- }
- }
- dispatchSprites(spriteManager) {
- if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) {
- return;
- }
- spriteManager._wasDispatched = true;
- this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager);
- }
- dispatchParticles(particleSystem) {
- if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) {
- return;
- }
- particleSystem._wasDispatched = true;
- this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem);
- }
- 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);
- }
- 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];
- }
- }
- setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
- this._autoClearDepthStencil[renderingGroupId] = {
- autoClear: autoClearDepthStencil,
- depth,
- stencil
- };
- }
- getAutoClearDepthStencilSetup(index) {
- return this._autoClearDepthStencil[index];
- }
-}
-var init_renderingManager = __esm(() => {
- init_renderingGroup();
- RenderingManager.MAX_RENDERINGGROUPS = 4;
- RenderingManager.MIN_RENDERINGGROUPS = 0;
- RenderingManager.AUTOCLEAR = true;
-});
-
-// node_modules/@babylonjs/core/Rendering/objectRenderer.js
-class ObjectRenderer {
- 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;
- }
- get renderInLinearSpace() {
- return this._renderInLinearSpace;
- }
- set renderInLinearSpace(value) {
- if (value === this._renderInLinearSpace) {
- return;
- }
- this._renderInLinearSpace = value;
- this._scene.markAllMaterialsAsDirty(64);
- }
- 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}`;
- }
- }
- get renderPassIds() {
- return this._renderPassIds;
- }
- get currentRefreshId() {
- return this._currentRefreshId;
- }
- 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);
- }
- }
- }
- constructor(name2, 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();
- });
- }
- };
- this.particleSystemList = null;
- this.getCustomRenderList = null;
- this.renderParticles = true;
- this.renderSprites = false;
- this.forceLayerMaskCheck = false;
- this._renderInLinearSpace = false;
- this.onBeforeRenderObservable = new Observable;
- this.onAfterRenderObservable = new Observable;
- this.onBeforeRenderingManagerRenderObservable = new Observable;
- this.onAfterRenderingManagerRenderObservable = new Observable;
- this.onFastPathRenderObservable = new Observable;
- this._currentRefreshId = -1;
- this._refreshRate = 1;
- this._currentApplyByPostProcessSetting = false;
- this._currentSceneCamera = null;
- this.name = name2;
- this._scene = scene;
- this.renderList = [];
- this._renderPassIds = [];
- this.options = {
- numPasses: 1,
- doNotChangeAspectRatio: true,
- ...options
- };
- this._createRenderPassId();
- this.renderPassId = this._renderPassIds[0];
- 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}`);
- }
- }
- resetRefreshCounter() {
- this._currentRefreshId = -1;
- }
- get refreshRate() {
- return this._refreshRate;
- }
- set refreshRate(value) {
- this._refreshRate = value;
- this.resetRefreshCounter();
- }
- shouldRender() {
- if (this._currentRefreshId === -1) {
- this._currentRefreshId = 1;
- return true;
- }
- if (this.refreshRate === this._currentRefreshId) {
- this._currentRefreshId = 1;
- return true;
- }
- this._currentRefreshId++;
- return false;
- }
- isReadyForRendering(viewportWidth, viewportHeight) {
- this.prepareRenderList();
- this.initRender(viewportWidth, viewportHeight);
- const isReady = this._checkReadiness();
- this.finishRender();
- return isReady;
- }
- 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;
- }
- if (this.renderListPredicate) {
- if (this.renderList) {
- this.renderList.length = 0;
- } 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;
- this._scene.imageProcessingConfiguration._applyByPostProcess = !!this._renderInLinearSpace;
- }
- 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;
- }
- 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();
- }
- 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) {
- 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) {
- if (!this._defaultRenderListPrepared) {
- this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, !this.renderList || this.forceLayerMaskCheck);
- this._defaultRenderListPrepared = true;
- }
- currentRenderList = defaultRenderList;
- } else {
- 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;
- }
- _checkReadiness() {
- const scene = this._scene;
- const engine = scene.getEngine();
- const currentRenderPassId = engine.currentRenderPassId;
- let returnValue = true;
- if (!scene.getViewMatrix()) {
- 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;
- 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();
- }
- 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);
- }
- }
- setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
- this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
- }
- setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
- this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
- this._renderingManager._useSceneAutoClearSetup = false;
- }
- clone() {
- const newRenderer = new ObjectRenderer(this.name, this._scene, this.options);
- if (this.renderList) {
- newRenderer.renderList = this.renderList.slice(0);
- }
- return newRenderer;
- }
- 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;
- }
- _rebuild() {
- if (this.refreshRate === ObjectRenderer.REFRESHRATE_RENDER_ONCE) {
- this.refreshRate = ObjectRenderer.REFRESHRATE_RENDER_ONCE;
- }
- }
- freeRenderingGroups() {
- if (this._renderingManager) {
- this._renderingManager.freeRenderingGroups();
- }
- }
-}
-var init_objectRenderer = __esm(() => {
- init_observable();
- init_renderingManager();
- init_arrayTools();
- ObjectRenderer.REFRESHRATE_RENDER_ONCE = 0;
- ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
- ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
-});
-
-// node_modules/@babylonjs/core/Materials/drawWrapper.js
-class DrawWrapper {
- static GetEffect(effect) {
- return effect.getPipelineContext === undefined ? effect.effect : effect;
- }
- constructor(engine, createMaterialContext = true) {
- this._wasPreviouslyReady = false;
- this._forceRebindOnNextCall = true;
- 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(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();
- }
-}
-var init_drawWrapper = __esm(() => {
- init_timingTools();
-});
-
-// node_modules/@babylonjs/core/Shaders/postprocess.vertex.js
-var exports_postprocess_vertex = {};
-__export(exports_postprocess_vertex, {
- postprocessVertexShader: () => postprocessVertexShader
-});
-var name2 = "postprocessVertexShader", shader = `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
-}`, postprocessVertexShader;
-var init_postprocess_vertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name2]) {
- ShaderStore.ShadersStore[name2] = shader;
- }
- postprocessVertexShader = { name: name2, shader };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js
-var exports_postprocess_vertex2 = {};
-__export(exports_postprocess_vertex2, {
- postprocessVertexShaderWGSL: () => postprocessVertexShaderWGSL
-});
-var name3 = "postprocessVertexShader", shader2 = `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
-}
-`, postprocessVertexShaderWGSL;
-var init_postprocess_vertex2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name3]) {
- ShaderStore.ShadersStoreWGSL[name3] = shader2;
- }
- postprocessVertexShaderWGSL = { name: name3, shader: shader2 };
-});
-
-// node_modules/@babylonjs/core/Materials/effectRenderer.js
-class EffectRenderer {
- constructor(engine, options = defaultOptions5) {
- this._fullscreenViewport = new Viewport(0, 0, 1, 1);
- const positions = options.positions ?? defaultOptions5.positions;
- const indices = options.indices ?? defaultOptions5.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();
- }
- });
- }
- setViewport(viewport = this._fullscreenViewport) {
- this.engine.setViewport(viewport);
- }
- bindBuffers(effect) {
- this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
- }
- 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({});
- }
- saveStates() {
- this._savedStateDepthTest = this.engine.depthCullingState.depthTest;
- this._savedStateStencilTest = this.engine.stencilState.stencilTest;
- }
- restoreStates() {
- this.engine.depthCullingState.depthTest = this._savedStateDepthTest;
- this.engine.stencilState.stencilTest = this._savedStateStencilTest;
- }
- draw() {
- this.engine.drawElementsType(0, 0, 6);
- }
- _isRenderTargetTexture(texture) {
- return texture.renderTarget !== undefined;
- }
- render(effectWrapper, outputTexture = null) {
- if (!effectWrapper.effect.isReady()) {
- return;
- }
- this.saveStates();
- 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();
- }
- 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;
- }
- }
-}
-
-class EffectWrapper {
- static RegisterShaderCodeProcessing(effectWrapperName, customShaderCodeProcessing) {
- if (!customShaderCodeProcessing) {
- delete EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""];
- return;
- }
- EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""] = customShaderCodeProcessing;
- }
- static _GetShaderCodeProcessing(effectWrapperName) {
- return EffectWrapper._CustomShaderCodeProcessing[effectWrapperName] ?? EffectWrapper._CustomShaderCodeProcessing[""];
- }
- get name() {
- return this.options.name;
- }
- set name(value) {
- this.options.name = value;
- }
- isReady() {
- return this._drawWrapper.effect?.isReady() ?? false;
- }
- get drawWrapper() {
- return this._drawWrapper;
- }
- get effect() {
- return this._drawWrapper.effect;
- }
- set effect(effect) {
- this._drawWrapper.effect = effect;
- }
- constructor(creationOptions) {
- this.alphaMode = 0;
- this.onEffectCreatedObservable = new Observable(undefined, true);
- this.onApplyObservable = new Observable;
- this._shadersLoaded = false;
- 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,
- 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;
- this.effect._prepareEffect();
- });
- }
- this._drawWrapper = new DrawWrapper(this.options.engine);
- this._webGPUReady = this.options.shaderLanguage === 1;
- const defines = Array.isArray(this.options.defines) ? this.options.defines.join(`
-`) : this.options.defines;
- this._postConstructor(this.options.blockCompilation, defines, this.options.extraInitializations);
- }
- _gatherImports(useWebGPU = false, list) {
- if (!this.options.useAsPostProcess) {
- return;
- }
- if (useWebGPU && this._webGPUReady) {
- list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), exports_postprocess_vertex2))]));
- } else {
- list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), exports_postprocess_vertex))]));
- }
- }
- _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;
- }
- if (!blockCompilation) {
- this.updateEffect(defines);
- }
- }
- 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);
- }
- 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);
- }
- dispose(_ignored = false) {
- if (this._onContextRestoredObserver) {
- this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
- this._onContextRestoredObserver = null;
- }
- this.onEffectCreatedObservable.clear();
- this._drawWrapper.dispose(true);
- }
-}
-var defaultOptions5;
-var init_effectRenderer = __esm(() => {
- init_buffer();
- init_observable();
- init_effect();
- init_drawWrapper();
- init_postprocess_vertex();
- defaultOptions5 = {
- positions: [1, 1, -1, 1, -1, -1, 1, -1],
- indices: [0, 1, 2, 0, 2, 3]
- };
- EffectWrapper.ForceGLSL = false;
- EffectWrapper._CustomShaderCodeProcessing = {};
-});
-
-// node_modules/@babylonjs/core/Materials/drawWrapper.functions.js
-function IsWrapper(effect) {
- return effect.getPipelineContext === undefined;
-}
-
-// node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js
-class WebGLShaderProcessor {
- constructor() {
- this.shaderLanguage = 0;
- }
- postProcessor(code, defines, isFragment, processingContext, parameters) {
- if (parameters.drawBuffersExtensionDisabled) {
- const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;
- code = code.replace(regex, "");
- }
- return code;
- }
-}
-
-// node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js
-class WebGL2ShaderProcessor {
- constructor() {
- this.shaderLanguage = 0;
- }
- attributeProcessor(attribute) {
- return attribute.replace("attribute", "in");
- }
- 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;
- 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, "");
- 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;
-`) + "void main(");
- } else {
- const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
- if (hasMultiviewExtension) {
- return `#extension GL_OVR_multiview2 : require
-layout (num_views = 2) in;
-` + code;
- }
- }
- return code;
- }
-}
-var varyingRegex;
-var init_webGL2ShaderProcessors = __esm(() => {
- varyingRegex = /(flat\s)?\s*varying\s*.*/;
-});
-
-// node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js
-var WebGLDataBuffer;
-var init_webGLDataBuffer = __esm(() => {
- init_dataBuffer();
- WebGLDataBuffer = class WebGLDataBuffer extends DataBuffer {
- constructor(resource) {
- super();
- this._buffer = resource;
- }
- get underlyingResource() {
- return this._buffer;
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js
-class WebGLHardwareTexture {
- get underlyingResource() {
- return this._webGLTexture;
- }
- constructor(existingTexture = null, context) {
- 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();
- }
-}
-
-// node_modules/@babylonjs/core/Materials/Textures/textureHelper.functions.js
-function IsDepthTexture(format) {
- return format === 13 || format === 14 || format === 15 || format === 16 || format === 17 || format === 18 || format === 19;
-}
-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;
-}
-function HasStencilAspect(format) {
- return format === 13 || format === 17 || format === 18 || format === 19;
-}
-
-// node_modules/@babylonjs/core/Engines/thinEngine.js
-var exports_thinEngine = {};
-__export(exports_thinEngine, {
- ThinEngine: () => ThinEngine
-});
-
-class BufferPointer {
-}
-var ThinEngine;
-var init_thinEngine = __esm(() => {
- init_thinEngine_functions();
- init_logger();
- init_domManagement();
- init_webGL2ShaderProcessors();
- init_webGLDataBuffer();
- init_abstractEngine();
- init_internalTexture();
- init_effect();
- init_abstractEngine_functions();
- init_effect_functions();
- ThinEngine = class ThinEngine extends AbstractEngine {
- get name() {
- return this._name;
- }
- set name(value) {
- this._name = value;
- }
- get version() {
- return this._webGLVersion;
- }
- static get ShadersRepository() {
- return Effect.ShadersRepository;
- }
- static set ShadersRepository(value) {
- Effect.ShadersRepository = value;
- }
- get supportsUniformBuffers() {
- return this.webGLVersion > 1 && !this.disableUniformBuffers;
- }
- get needPOTTextures() {
- return this._webGLVersion < 2 || this.forcePOTTextures;
- }
- get _supportsHardwareTextureRescaling() {
- return false;
- }
- set framebufferDimensionsObject(dimensions) {
- this._framebufferDimensionsObject = dimensions;
- }
- snapshotRenderingReset() {
- this.snapshotRendering = false;
- }
- constructor(canvasOrContext, antialias, options, adaptToDeviceRatio) {
- options = options || {};
- super(antialias ?? options.antialias, options, adaptToDeviceRatio);
- this._name = "WebGL";
- this.forcePOTTextures = false;
- this.validateShaderPrograms = false;
- this.disableUniformBuffers = false;
- this._webGLVersion = 1;
- this._vertexAttribArraysEnabled = [];
- this._uintIndicesCurrentlySet = false;
- this._currentBoundBuffer = new Array;
- this._currentFramebuffer = null;
- 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;
- this.enableUnpackFlipYCached = true;
- 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;
- }
- 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;
- }
- }
- }
- }
- }
- 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;
- }
- if (!options.disableWebGL2Support) {
- try {
- this._gl = canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options);
- if (this._gl) {
- this._webGLVersion = 2;
- this._shaderPlatformName = "WEBGL2";
- if (!this._gl.deleteQuery) {
- this._webGLVersion = 1;
- this._shaderPlatformName = "WEBGL1";
- }
- }
- } catch (e) {}
- }
- 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;
- this._shaderPlatformName = "WEBGL2";
- } else {
- this._shaderPlatformName = "WEBGL1";
- }
- const attributes = this._gl.getContextAttributes();
- if (attributes) {
- options.stencil = attributes.stencil;
- }
- }
- this._sharedInit(canvas);
- 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();
- for (let i = 0;i < this._caps.maxVertexAttribs; i++) {
- this._currentBufferPointers[i] = new BufferPointer;
- }
- this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor : new WebGLShaderProcessor;
- const versionToLog = `Babylon.js v${ThinEngine.Version}`;
- Logger.Log(versionToLog + ` - ${this.description}`);
- if (this._renderingCanvas && this._renderingCanvas.setAttribute) {
- this._renderingCanvas.setAttribute("data-engine", versionToLog);
- }
- const stateObject = getStateObject(this._gl);
- stateObject.validateShaderPrograms = this.validateShaderPrograms;
- stateObject.parallelShaderCompile = this._caps.parallelShaderCompile;
- }
- _clearEmptyResources() {
- this._dummyFramebuffer = null;
- super._clearEmptyResources();
- }
- _getShaderProcessingContext(shaderLanguage) {
- return null;
- }
- areAllEffectsReady() {
- for (const key in this._compiledEffects) {
- const effect = this._compiledEffects[key];
- if (!effect.isReady()) {
- return false;
- }
- }
- return true;
- }
- _initGLContext() {
- 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"),
- 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"),
- 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;
- 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";
- }
- if (this._gl.HALF_FLOAT_OES !== 36193) {
- this._gl.HALF_FLOAT_OES = 36193;
- }
- if (this._gl.RGBA16F !== 34842) {
- this._gl.RGBA16F = 34842;
- }
- if (this._gl.RGBA32F !== 34836) {
- this._gl.RGBA32F = 34836;
- }
- if (this._gl.DEPTH24_STENCIL8 !== 35056) {
- this._gl.DEPTH24_STENCIL8 = 35056;
- }
- if (this._caps.timerQuery) {
- if (this._webGLVersion === 1) {
- this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
- }
- 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 = 33322;
- this._gl.RG16_EXT = 33324;
- this._gl.RGB16_EXT = 32852;
- this._gl.RGBA16_EXT = 32859;
- this._gl.R16_SNORM_EXT = 36760;
- this._gl.RG16_SNORM_EXT = 36761;
- this._gl.RGB16_SNORM_EXT = 36762;
- this._gl.RGBA16_SNORM_EXT = 36763;
- }
- 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;
- }
- if (this._webGLVersion > 1) {
- if (this._gl.HALF_FLOAT_OES !== 5131) {
- this._gl.HALF_FLOAT_OES = 5131;
- }
- }
- this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
- 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"];
- }
- }
- }
- 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;
- }
- }
- 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);
- }
- }
- 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;
- }
- }
- 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
- };
- }
- }
- if (this._creationOptions) {
- const forceSRGBBufferSupportState = this._creationOptions.forceSRGBBufferSupportState;
- if (forceSRGBBufferSupportState !== undefined) {
- this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState;
- }
- }
- }
- this._depthCullingState.depthTest = true;
- this._depthCullingState.depthFunc = this._gl.LEQUAL;
- this._depthCullingState.depthMask = true;
- this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
- for (let slot = 0;slot < this._maxSimultaneousTextures; slot++) {
- this._nextFreeTextureSlots.push(slot);
- }
- if (this._glRenderer === "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
- };
- }
- get webGLVersion() {
- return this._webGLVersion;
- }
- getClassName() {
- return "ThinEngine";
- }
- _prepareWorkingCanvas() {
- if (this._workingCanvas) {
- return;
- }
- this._workingCanvas = this.createCanvas(1, 1);
- const context = this._workingCanvas.getContext("2d");
- if (context) {
- this._workingContext = context;
- }
- }
- getInfo() {
- return this.getGlInfo();
- }
- getGlInfo() {
- return {
- vendor: this._glVendor,
- renderer: this._glRenderer,
- version: this._glVersion
- };
- }
- extractDriverInfo() {
- const glInfo = this.getGlInfo();
- if (glInfo && glInfo.renderer) {
- return glInfo.renderer;
- }
- return "";
- }
- getRenderWidth(useScreen = false) {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget.width;
- }
- return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth;
- }
- getRenderHeight(useScreen = false) {
- if (!useScreen && this._currentRenderTarget) {
- return this._currentRenderTarget.height;
- }
- return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
- }
- clear(color, backBuffer, depth, stencil = false) {
- const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly;
- this.stencilStateComposer.useStencilGlobalOnly = true;
- 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);
- mode |= this._gl.COLOR_BUFFER_BIT;
- }
- }
- if (depth) {
- if (this.useReverseDepthBuffer) {
- this._depthCullingState.depthFunc = this._gl.GEQUAL;
- this._gl.clearDepth(0);
- } else {
- this._gl.clearDepth(1);
- }
- mode |= this._gl.DEPTH_BUFFER_BIT;
- }
- if (stencil) {
- this._gl.clearStencil(0);
- mode |= this._gl.STENCIL_BUFFER_BIT;
- }
- this._gl.clear(mode);
- }
- _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);
- }
- }
- endFrame() {
- super.endFrame();
- if (this._badOS) {
- this.flushFramebuffer();
- }
- }
- get performanceMonitor() {
- throw new Error("Not Supported by ThinEngine");
- }
- 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;
- }
- }
- setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {
- if (this._depthCullingState.cull !== culling || force) {
- this._depthCullingState.cull = culling;
- }
- this.setStateCullFaceType(cullBackFaces, force);
- this.setZOffset(zOffset);
- this.setZOffsetUnits(zOffsetUnits);
- const frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
- if (this._depthCullingState.frontFace !== frontFace || force) {
- this._depthCullingState.frontFace = frontFace;
- }
- this._stencilStateComposer.stencilMaterial = stencil;
- }
- _bindUnboundFramebuffer(framebuffer) {
- if (this._currentFramebuffer !== framebuffer) {
- this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
- this._currentFramebuffer = framebuffer;
- }
- }
- _currentFrameBufferIsDefaultFrameBuffer() {
- return this._currentFramebuffer === null;
- }
- generateMipmaps(texture) {
- const target = this._getTextureTarget(texture);
- this._bindTextureDirectly(target, texture, true);
- this._gl.generateMipmap(target);
- this._bindTextureDirectly(target, null);
- }
- 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) {
- this._bindUnboundFramebuffer(webglRTWrapper._framebuffer);
- }
- onBeforeUnbind();
- }
- this._bindUnboundFramebuffer(null);
- }
- generateMipMapsFramebuffer(texture) {
- if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) {
- this.generateMipmaps(texture.texture);
- }
- }
- 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);
- }
- flushFramebuffer() {
- this._gl.flush();
- }
- restoreDefaultFramebuffer() {
- if (this._currentRenderTarget) {
- this.unBindFramebuffer(this._currentRenderTarget);
- } else {
- this._bindUnboundFramebuffer(null);
- }
- if (this._cachedViewport) {
- this.setViewport(this._cachedViewport);
- }
- this.wipeCaches();
- }
- _resetVertexBufferBinding() {
- this.bindArrayBuffer(null);
- this._cachedVertexBuffers = null;
- }
- 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;
- }
- createDynamicVertexBuffer(data, _label) {
- return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
- }
- _resetIndexBufferBinding() {
- this.bindIndexBuffer(null);
- this._cachedIndexBuffer = null;
- }
- 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;
- }
- if (this._caps.uintIndices) {
- if (indices instanceof Uint32Array) {
- return indices;
- } else {
- for (let index = 0;index < indices.length; index++) {
- if (indices[index] >= 65535) {
- return new Uint32Array(indices);
- }
- }
- return new Uint16Array(indices);
- }
- }
- return new Uint16Array(indices);
- }
- bindArrayBuffer(buffer) {
- if (!this._vaoRecordInProgress) {
- this._unbindVertexArrayObject();
- }
- this._bindBuffer(buffer, this._gl.ARRAY_BUFFER);
- }
- bindUniformBlock(pipelineContext, blockName, index) {
- const program = pipelineContext.program;
- const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
- this._gl.uniformBlockBinding(program, uniformLocation, index);
- }
- 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;
- }
- }
- 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);
- }
- }
- }
- _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);
- }
- }
- }
- }
- }
- }
- 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;
- }
- 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;
- }
- }
- 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);
- }
- 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);
- }
- 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;
- }
- releaseVertexArrayObject(vao) {
- this._gl.deleteVertexArray(vao);
- }
- _releaseBuffer(buffer) {
- buffer.references--;
- if (buffer.references === 0) {
- this._deleteBuffer(buffer);
- return true;
- }
- return false;
- }
- _deleteBuffer(buffer) {
- this._gl.deleteBuffer(buffer.underlyingResource);
- }
- 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);
- }
- }
- }
- 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);
- }
- }
- disableInstanceAttributeByName(name4) {
- if (!this._currentEffect) {
- return;
- }
- const attributeLocation = this._currentEffect.getAttributeLocationByName(name4);
- this.disableInstanceAttribute(attributeLocation);
- }
- 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);
- }
- }
- disableAttributeByIndex(attributeLocation) {
- this._gl.disableVertexAttribArray(attributeLocation);
- this._vertexAttribArraysEnabled[attributeLocation] = false;
- this._currentBufferPointers[attributeLocation].active = false;
- }
- draw(useTriangles, indexStart, indexCount, instancesCount) {
- this.drawElementsType(useTriangles ? 0 : 1, indexStart, indexCount, instancesCount);
- }
- drawPointClouds(verticesStart, verticesCount, instancesCount) {
- this.drawArraysType(2, verticesStart, verticesCount, instancesCount);
- }
- drawUnIndexed(useTriangles, verticesStart, verticesCount, instancesCount) {
- this.drawArraysType(useTriangles ? 0 : 1, verticesStart, verticesCount, instancesCount);
- }
- drawElementsType(fillMode, indexStart, indexCount, instancesCount) {
- this.applyStates();
- this._reportDrawCall();
- 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);
- }
- }
- drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {
- 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) {
- case 0:
- return this._gl.TRIANGLES;
- case 2:
- return this._gl.POINTS;
- case 1:
- return this._gl.LINES;
- 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;
- }
- }
- _releaseEffect(effect) {
- if (this._compiledEffects[effect._key]) {
- delete this._compiledEffects[effect._key];
- }
- const pipelineContext = effect.getPipelineContext();
- if (pipelineContext) {
- this._deletePipelineContext(pipelineContext);
- }
- }
- _deletePipelineContext(pipelineContext) {
- const webGLPipelineContext = pipelineContext;
- if (webGLPipelineContext && webGLPipelineContext.program) {
- webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
- resetCachedPipeline(webGLPipelineContext);
- if (this._gl) {
- this._gl.deleteProgram(webGLPipelineContext.program);
- }
- }
- }
- _getGlobalDefines(defines) {
- return _getGlobalDefines(defines, this.isNDCHalfZRange, this.useReverseDepthBuffer, this.useExactSrgbConversions);
- }
- createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = 0, 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 name4 = vertex + "+" + fragment + "@" + fullDefines;
- if (this._compiledEffects[name4]) {
- const compiledEffect = this._compiledEffects[name4];
- 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, name4, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync);
- this._compiledEffects[name4] = effect;
- return effect;
- }
- _getShaderSource(shader3) {
- return this._gl.getShaderSource(shader3);
- }
- 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);
- }
- createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) {
- const stateObject = getStateObject(this._gl);
- stateObject._contextWasLost = this._contextWasLost;
- stateObject.validateShaderPrograms = this.validateShaderPrograms;
- return createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context || this._gl, transformFeedbackVaryings);
- }
- inlineShaderCode(code) {
- return code;
- }
- createPipelineContext(shaderProcessingContext) {
- if (this._gl) {
- const stateObject = getStateObject(this._gl);
- stateObject.parallelShaderCompile = this._caps.parallelShaderCompile;
- }
- const context = createPipelineContext(this._gl, shaderProcessingContext);
- context.engine = this;
- return context;
- }
- createMaterialContext() {
- return;
- }
- createDrawContext() {
- return;
- }
- _finalizePipelineContext(pipelineContext) {
- return _finalizePipelineContext(pipelineContext, this._gl, this.validateShaderPrograms);
- }
- _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);
- }
- _isRenderingStateCompiled(pipelineContext) {
- if (this._isDisposed) {
- return false;
- }
- return _isRenderingStateCompiled(pipelineContext, this._gl, this.validateShaderPrograms);
- }
- _executeWhenRenderingStateIsCompiled(pipelineContext, action2) {
- _executeWhenRenderingStateIsCompiled(pipelineContext, action2);
- }
- 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;
- }
- 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;
- }
- enableEffect(effect) {
- effect = effect !== null && IsWrapper(effect) ? effect.effect : effect;
- if (!effect || effect === this._currentEffect) {
- return;
- }
- this._stencilStateComposer.stencilMaterial = undefined;
- effect = effect;
- this.bindSamplers(effect);
- this._currentEffect = effect;
- if (effect.onBind) {
- effect.onBind(effect);
- }
- if (effect._onBindObservable) {
- effect._onBindObservable.notifyObservers(effect);
- }
- }
- setInt(uniform, value) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform1i(uniform, value);
- return true;
- }
- setInt2(uniform, x, y) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform2i(uniform, x, y);
- return true;
- }
- setInt3(uniform, x, y, z) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform3i(uniform, x, y, z);
- return true;
- }
- setInt4(uniform, x, y, z, w) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform4i(uniform, x, y, z, w);
- return true;
- }
- setIntArray(uniform, array) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform1iv(uniform, array);
- return true;
- }
- setIntArray2(uniform, array) {
- if (!uniform || array.length % 2 !== 0) {
- return false;
- }
- this._gl.uniform2iv(uniform, array);
- return true;
- }
- setIntArray3(uniform, array) {
- if (!uniform || array.length % 3 !== 0) {
- return false;
- }
- this._gl.uniform3iv(uniform, array);
- return true;
- }
- setIntArray4(uniform, array) {
- if (!uniform || array.length % 4 !== 0) {
- return false;
- }
- this._gl.uniform4iv(uniform, array);
- return true;
- }
- setUInt(uniform, value) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform1ui(uniform, value);
- return true;
- }
- setUInt2(uniform, x, y) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform2ui(uniform, x, y);
- return true;
- }
- setUInt3(uniform, x, y, z) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform3ui(uniform, x, y, z);
- return true;
- }
- setUInt4(uniform, x, y, z, w) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform4ui(uniform, x, y, z, w);
- return true;
- }
- setUIntArray(uniform, array) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform1uiv(uniform, array);
- return true;
- }
- setUIntArray2(uniform, array) {
- if (!uniform || array.length % 2 !== 0) {
- return false;
- }
- this._gl.uniform2uiv(uniform, array);
- return true;
- }
- setUIntArray3(uniform, array) {
- if (!uniform || array.length % 3 !== 0) {
- return false;
- }
- this._gl.uniform3uiv(uniform, array);
- return true;
- }
- setUIntArray4(uniform, array) {
- if (!uniform || array.length % 4 !== 0) {
- return false;
- }
- this._gl.uniform4uiv(uniform, array);
- return true;
- }
- setArray(uniform, array) {
- if (!uniform) {
- return false;
- }
- if (array.length < 1) {
- return false;
- }
- this._gl.uniform1fv(uniform, array);
- return true;
- }
- setArray2(uniform, array) {
- if (!uniform || array.length % 2 !== 0) {
- return false;
- }
- this._gl.uniform2fv(uniform, array);
- return true;
- }
- setArray3(uniform, array) {
- if (!uniform || array.length % 3 !== 0) {
- return false;
- }
- this._gl.uniform3fv(uniform, array);
- return true;
- }
- setArray4(uniform, array) {
- if (!uniform || array.length % 4 !== 0) {
- return false;
- }
- this._gl.uniform4fv(uniform, array);
- return true;
- }
- setMatrices(uniform, matrices) {
- if (!uniform) {
- return false;
- }
- this._gl.uniformMatrix4fv(uniform, false, matrices);
- return true;
- }
- setMatrix3x3(uniform, matrix) {
- if (!uniform) {
- return false;
- }
- this._gl.uniformMatrix3fv(uniform, false, matrix);
- return true;
- }
- setMatrix2x2(uniform, matrix) {
- if (!uniform) {
- return false;
- }
- this._gl.uniformMatrix2fv(uniform, false, matrix);
- return true;
- }
- setFloat(uniform, value) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform1f(uniform, value);
- return true;
- }
- setFloat2(uniform, x, y) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform2f(uniform, x, y);
- return true;
- }
- setFloat3(uniform, x, y, z) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform3f(uniform, x, y, z);
- return true;
- }
- setFloat4(uniform, x, y, z, w) {
- if (!uniform) {
- return false;
- }
- this._gl.uniform4f(uniform, x, y, z, w);
- return true;
- }
- 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);
- }
- }
- 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;
- 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);
- }
- _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
- };
- }
- _createTexture() {
- const texture = this._gl.createTexture();
- if (!texture) {
- throw new Error("Unable to create texture");
- }
- return texture;
- }
- _createHardwareTexture() {
- return new WebGLHardwareTexture(this._createTexture(), this._gl);
- }
- _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0) {
- 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) {
- samplingMode = 1;
- } else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
- 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);
- 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);
- }
- }
- 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, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), -1);
- }
- 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;
- }
- _getUseSRGBBuffer(useSRGBBuffer, noMipmap) {
- return useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || noMipmap);
- }
- 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 {
- const source = new InternalTexture(this, 2);
- 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);
- }
- _getTexImageParametersForCreateTexture(babylonFormat, useSRGBBuffer) {
- let format, internalFormat;
- if (this.webGLVersion === 1) {
- format = this._getInternalFormat(babylonFormat, useSRGBBuffer);
- internalFormat = format;
- } else {
- format = this._getInternalFormat(babylonFormat, false);
- internalFormat = this._getRGBABufferInternalSizedFormat(0, babylonFormat, useSRGBBuffer);
- }
- return {
- internalFormat,
- format,
- type: this._gl.UNSIGNED_BYTE
- };
- }
- _rescaleTexture(source, destination, scene, internalFormat, onComplete) {}
- _unpackFlipY(value) {
- if (this._unpackFlipYCached !== value) {
- this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
- if (this.enableUnpackFlipYCached) {
- this._unpackFlipYCached = value;
- }
- }
- }
- _getUnpackAlignement() {
- return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
- }
- _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;
- }
- 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;
- }
- updateTextureDimensions(texture, width, height, depth = 1) {}
- 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);
- }
- _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:
- 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 {
- texture._useSRGBBuffer = false;
- }
- break;
- case 33777:
- if (this._caps.s3tc_srgb) {
- internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
- } else {
- texture._useSRGBBuffer = false;
- }
- break;
- case 33779:
- if (this._caps.s3tc_srgb) {
- internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
- } else {
- texture._useSRGBBuffer = false;
- }
- break;
- default:
- texture._useSRGBBuffer = false;
- break;
- }
- }
- this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
- }
- _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);
- }
- 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);
- }
- _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);
- 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) {
- 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);
- })) {
- 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;
- }
- _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);
- 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;
- }
- _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;
- }
- _releaseTexture(texture) {
- this._deleteTexture(texture._hardwareTexture);
- this.unbindAllTextures();
- const index = this._internalTexturesCache.indexOf(texture);
- if (index !== -1) {
- this._internalTexturesCache.splice(index, 1);
- }
- if (texture._lodTextureHigh) {
- texture._lodTextureHigh.dispose();
- }
- if (texture._lodTextureMid) {
- texture._lodTextureMid.dispose();
- }
- if (texture._lodTextureLow) {
- texture._lodTextureLow.dispose();
- }
- if (texture._irradianceTexture) {
- texture._irradianceTexture.dispose();
- }
- }
- _deleteTexture(texture) {
- texture?.release();
- }
- _setProgram(program) {
- if (this._currentProgram !== program) {
- _setProgram(program, this._gl);
- this._currentProgram = program;
- }
- }
- 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;
- }
- }
- _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) {
- Logger.Error(["_bindTextureDirectly called with a multiview texture!", target, texture]);
- 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;
- }
- _bindTexture(channel, texture, name4) {
- 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);
- }
- 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);
- }
- }
- }
- setTexture(channel, uniform, texture, name4) {
- 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, name4 = "") {
- 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;
- }
- if (texture.video) {
- this._activeChannel = channel;
- const videoInternalTexture = texture.getInternalTexture();
- if (videoInternalTexture) {
- videoInternalTexture._associatedChannel = channel;
- }
- texture.update();
- } else if (texture.delayLoadState === 4) {
- 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) {
- 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;
- }
- setTextureArray(channel, uniform, textures, name4) {
- 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);
- }
- }
- _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) {
- const anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
- if (internalTexture.samplingMode !== 11 && internalTexture.samplingMode !== 3 && internalTexture.samplingMode !== 2) {
- anisotropicFilteringLevel = 1;
- }
- 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);
- }
- 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);
- }
- }
- releaseEffects() {
- this._compiledEffects = {};
- this.onReleaseEffectsObservable.notifyObservers(this);
- }
- dispose() {
- if (IsWindowObjectExist()) {
- if (this._renderingCanvas) {
- this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
- if (this._onContextRestored) {
- this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
- }
- }
- }
- super.dispose();
- if (this._dummyFramebuffer) {
- this._gl.deleteFramebuffer(this._dummyFramebuffer);
- }
- 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();
- }
- deleteStateObject(this._gl);
- }
- attachContextLostEvent(callback) {
- if (this._renderingCanvas) {
- this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
- }
- }
- attachContextRestoredEvent(callback) {
- if (this._renderingCanvas) {
- this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
- }
- }
- 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);
- }
- _canRenderToFramebuffer(type) {
- const gl = this._gl;
- 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;
- if (successful) {
- gl.clear(gl.COLOR_BUFFER_BIT);
- successful = successful && gl.getError() === gl.NO_ERROR;
- }
- if (successful) {
- 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;
- }
- gl.deleteTexture(texture);
- gl.deleteFramebuffer(fb);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- while (!successful && gl.getError() !== gl.NO_ERROR) {}
- return successful;
- }
- _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:
- 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;
- }
- _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;
- }
- _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;
- case 5:
- return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8;
- 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:
- 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;
- case 7:
- return this._gl.RG32F;
- case 4:
- return this._gl.RGB32F;
- case 5:
- return this._gl.RGBA32F;
- 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;
- 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;
- case 11:
- return this._gl.RGB10_A2UI;
- default:
- return this._gl.RGB10_A2;
- }
- }
- return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8;
- }
- 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);
- }
- static get IsSupportedAsync() {
- return Promise.resolve(this.isSupported());
- }
- static get IsSupported() {
- return this.isSupported();
- }
- static isSupported() {
- if (this._HasMajorPerformanceCaveat !== null) {
- return !this._HasMajorPerformanceCaveat;
- }
- 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;
- }
- 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);
- 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"] },
- { key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] },
- { key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }
- ];
- ThinEngine._ConcatenateShader = _ConcatenateShader;
- ThinEngine._IsSupported = null;
- ThinEngine._HasMajorPerformanceCaveat = null;
-});
-
-// node_modules/@babylonjs/core/Shaders/pass.fragment.js
-var exports_pass_fragment = {};
-__export(exports_pass_fragment, {
- passPixelShader: () => passPixelShader
-});
-var name4 = "passPixelShader", shader3 = `varying vec2 vUV;uniform sampler2D textureSampler;
-#define CUSTOM_FRAGMENT_DEFINITIONS
-void main(void)
-{gl_FragColor=texture2D(textureSampler,vUV);}`, passPixelShader;
-var init_pass_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name4]) {
- ShaderStore.ShadersStore[name4] = shader3;
- }
- passPixelShader = { name: name4, shader: shader3 };
-});
-
-// node_modules/@babylonjs/core/Misc/dumpTools.js
-var exports_dumpTools = {};
-__export(exports_dumpTools, {
- DumpTools: () => DumpTools,
- DumpFramebuffer: () => DumpFramebuffer,
- DumpDataAsync: () => DumpDataAsync,
- DumpData: () => DumpData,
- Dispose: () => Dispose
-});
-async function _CreateDumpRenderer() {
- if (!_enginePromise) {
- _enginePromise = new Promise((resolve3, 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(() => (init_thinEngine(), exports_thinEngine)).then(({ ThinEngine: thinEngineClass }) => {
- const engineInstanceCount = EngineStore.Instances.length;
- try {
- canvas = new OffscreenCanvas(100, 100);
- engine = new thinEngineClass(canvas, false, options);
- } catch (e) {
- if (engineInstanceCount < EngineStore.Instances.length) {
- EngineStore.Instances.pop()?.dispose();
- }
- canvas = document.createElement("canvas");
- engine = new thinEngineClass(canvas, false, options);
- }
- EngineStore.Instances.pop();
- EngineStore.OnEnginesDisposedObservable.add((e) => {
- if (engine && e !== engine && !engine.isDisposed && EngineStore.Instances.length === 0) {
- Dispose();
- }
- });
- engine.getCaps().parallelShaderCompile = undefined;
- const renderer = new EffectRenderer(engine);
- Promise.resolve().then(() => (init_pass_fragment(), exports_pass_fragment)).then(({ passPixelShader: passPixelShader2 }) => {
- if (!engine) {
- reject("Engine is not defined");
- return;
- }
- const wrapper = new EffectWrapper({
- engine,
- name: passPixelShader2.name,
- fragmentShader: passPixelShader2.shader,
- samplerNames: ["textureSampler"]
- });
- _dumpToolsEngine = {
- canvas,
- engine,
- renderer,
- wrapper
- };
- resolve3(_dumpToolsEngine);
- });
- }).catch(reject);
- });
- }
- return await _enginePromise;
-}
-async function DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) {
- 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);
-}
-function DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer3 = false, quality) {
- return new Promise((resolve3) => {
- DumpData(width, height, data, (result) => resolve3(result), mimeType, fileName, invertY, toArrayBuffer3, quality);
- });
-}
-function DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer3 = false, quality) {
- _CreateDumpRenderer().then((renderer) => {
- renderer.engine.setSize(width, height, true);
- 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;
- }
- 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 (toArrayBuffer3) {
- 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();
- });
-}
-function Dispose() {
- if (_dumpToolsEngine) {
- _dumpToolsEngine.wrapper.dispose();
- _dumpToolsEngine.renderer.dispose();
- _dumpToolsEngine.engine.dispose();
- } else {
- _enginePromise?.then((dumpToolsEngine) => {
- dumpToolsEngine.wrapper.dispose();
- dumpToolsEngine.renderer.dispose();
- dumpToolsEngine.engine.dispose();
- });
- }
- _enginePromise = null;
- _dumpToolsEngine = null;
-}
-var _dumpToolsEngine, _enginePromise = null, DumpTools, initSideEffects = () => {
- Tools.DumpData = DumpData;
- Tools.DumpDataAsync = DumpDataAsync;
- Tools.DumpFramebuffer = DumpFramebuffer;
-};
-var init_dumpTools = __esm(() => {
- init_effectRenderer();
- init_tools();
- init_engineStore();
- DumpTools = {
- DumpData,
- DumpDataAsync,
- DumpFramebuffer,
- Dispose
- };
- initSideEffects();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js
-var RenderTargetTexture;
-var init_renderTargetTexture = __esm(() => {
- init_observable();
- init_math_vector();
- init_texture();
- init_postProcessManager();
- init_effect();
- init_logger();
- init_objectRenderer();
- Effect.prototype.setDepthStencilTexture = function(channel, texture) {
- this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel);
- };
- RenderTargetTexture = class RenderTargetTexture extends Texture {
- get renderListPredicate() {
- return this._objectRenderer.renderListPredicate;
- }
- set renderListPredicate(value) {
- this._objectRenderer.renderListPredicate = value;
- }
- get renderList() {
- return this._objectRenderer.renderList;
- }
- set renderList(value) {
- this._objectRenderer.renderList = value;
- }
- get particleSystemList() {
- return this._objectRenderer.particleSystemList;
- }
- set particleSystemList(value) {
- this._objectRenderer.particleSystemList = value;
- }
- get getCustomRenderList() {
- return this._objectRenderer.getCustomRenderList;
- }
- set getCustomRenderList(value) {
- this._objectRenderer.getCustomRenderList = value;
- }
- get renderParticles() {
- return this._objectRenderer.renderParticles;
- }
- set renderParticles(value) {
- this._objectRenderer.renderParticles = value;
- }
- get renderSprites() {
- return this._objectRenderer.renderSprites;
- }
- set renderSprites(value) {
- this._objectRenderer.renderSprites = value;
- }
- get forceLayerMaskCheck() {
- return this._objectRenderer.forceLayerMaskCheck;
- }
- set forceLayerMaskCheck(value) {
- this._objectRenderer.forceLayerMaskCheck = value;
- }
- get activeCamera() {
- return this._objectRenderer.activeCamera;
- }
- set activeCamera(value) {
- this._objectRenderer.activeCamera = value;
- }
- get cameraForLOD() {
- return this._objectRenderer.cameraForLOD;
- }
- set cameraForLOD(value) {
- this._objectRenderer.cameraForLOD = value;
- }
- get renderInLinearSpace() {
- return this._objectRenderer.renderInLinearSpace;
- }
- set renderInLinearSpace(value) {
- this._objectRenderer.renderInLinearSpace = value;
- }
- get customIsReadyFunction() {
- return this._objectRenderer.customIsReadyFunction;
- }
- set customIsReadyFunction(value) {
- this._objectRenderer.customIsReadyFunction = value;
- }
- get customRenderFunction() {
- return this._objectRenderer.customRenderFunction;
- }
- set customRenderFunction(value) {
- this._objectRenderer.customRenderFunction = value;
- }
- get postProcesses() {
- return this._postProcesses;
- }
- get _prePassEnabled() {
- return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled;
- }
- set onAfterUnbind(callback) {
- if (this._onAfterUnbindObserver) {
- this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
- }
- this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
- }
- get onBeforeRenderObservable() {
- return this._objectRenderer.onBeforeRenderObservable;
- }
- set onBeforeRender(callback) {
- if (this._onBeforeRenderObserver) {
- this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
- }
- this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
- }
- get onAfterRenderObservable() {
- return this._objectRenderer.onAfterRenderObservable;
- }
- set onAfterRender(callback) {
- if (this._onAfterRenderObserver) {
- this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
- }
- this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
- }
- set onClear(callback) {
- if (this._onClearObserver) {
- this.onClearObservable.remove(this._onClearObserver);
- }
- this._onClearObserver = this.onClearObservable.add(callback);
- }
- get _waitingRenderList() {
- return this._objectRenderer._waitingRenderList;
- }
- set _waitingRenderList(value) {
- this._objectRenderer._waitingRenderList = value;
- }
- get renderPassId() {
- return this._objectRenderer.renderPassId;
- }
- get renderPassIds() {
- return this._objectRenderer.renderPassIds;
- }
- get currentRefreshId() {
- return this._objectRenderer.currentRefreshId;
- }
- setMaterialForRendering(mesh, material) {
- this._objectRenderer.setMaterialForRendering(mesh, material);
- }
- get isMulti() {
- return this._renderTarget?.isMulti ?? false;
- }
- get renderTargetOptions() {
- return this._renderTargetOptions;
- }
- get renderTarget() {
- return this._renderTarget;
- }
- _onRatioRescale() {
- if (this._sizeRatio) {
- this.resize(this._initialSizeParameter);
- }
- }
- 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;
- }
- get depthStencilTexture() {
- return this._renderTarget?._depthStencilTexture ?? null;
- }
- constructor(name5, 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);
- this.ignoreCameraViewport = false;
- this.onBeforeBindObservable = new Observable;
- this.onAfterUnbindObservable = new Observable;
- this.onClearObservable = new Observable;
- this.onResizeObservable = new Observable;
- this._cleared = false;
- this.skipInitialClear = false;
- this._samples = 1;
- this._canRescale = true;
- this._renderTarget = null;
- this._dontDisposeObjectRenderer = false;
- this.boundingBoxPosition = Vector3.Zero();
- this._disableEngineStages = false;
- this._dumpToolsLoading = false;
- scene = this.getScene();
- if (!scene) {
- return;
- }
- const engine = this.getScene().getEngine();
- this._gammaSpace = gammaSpace;
- this._coordinatesMode = Texture.PROJECTION_MODE;
- this.name = name5;
- this.isRenderTarget = true;
- this._initialSizeParameter = size;
- this._dontDisposeObjectRenderer = !!existingObjectRenderer;
- this._processSizeParameter(size);
- this._objectRenderer = existingObjectRenderer ?? new ObjectRenderer(name5, scene, {
- numPasses: isCube ? 6 : this.getRenderLayers() || 1,
- doNotChangeAspectRatio
- });
- this._onBeforeRenderingManagerRenderObserver = this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(() => {
- if (!this._disableEngineStages) {
- for (const step of this._scene._beforeRenderTargetClearStage) {
- step.action(this, this._currentFaceIndex, this._currentLayer);
- }
- }
- 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);
- }
- if (!this._disableEngineStages) {
- for (const step of this._scene._beforeRenderTargetDrawStage) {
- step.action(this, this._currentFaceIndex, this._currentLayer);
- }
- }
- });
- this._onAfterRenderingManagerRenderObserver = this._objectRenderer.onAfterRenderingManagerRenderObservable.add(() => {
- 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 (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);
- }
- 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,
- type,
- format: this._format ?? undefined,
- samplingMode: this.samplingMode,
- generateDepthBuffer,
- generateStencilBuffer,
- samples,
- creationFlags,
- noColorAttachment,
- useSRGBBuffer,
- 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;
- }
- }
- }
- 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;
- }
- }
- get samples() {
- return this._renderTarget?.samples ?? this._samples;
- }
- set samples(value) {
- if (this._renderTarget) {
- this._samples = this._renderTarget.setSamples(value);
- }
- }
- 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;
- }
- clearPostProcesses(dispose = false) {
- if (!this._postProcesses) {
- return;
- }
- if (dispose) {
- for (const postProcess of this._postProcesses) {
- postProcess.dispose();
- }
- }
- this._postProcesses = [];
- }
- 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;
- }
- }
- resetRefreshCounter() {
- this._objectRenderer.resetRefreshCounter();
- }
- get refreshRate() {
- return this._objectRenderer.refreshRate;
- }
- set refreshRate(value) {
- this._objectRenderer.refreshRate = value;
- }
- _shouldRender() {
- return this._objectRenderer.shouldRender();
- }
- getRenderSize() {
- return this.getRenderWidth();
- }
- getRenderWidth() {
- if (this._size.width) {
- return this._size.width;
- }
- return this._size;
- }
- getRenderHeight() {
- if (this._size.width) {
- return this._size.height;
- }
- return this._size;
- }
- getRenderLayers() {
- const layers = this._size.layers;
- if (layers) {
- return layers;
- }
- const depth = this._size.depth;
- if (depth) {
- return depth;
- }
- return 0;
- }
- disableRescaling() {
- this._canRescale = false;
- }
- get canRescale() {
- return this._canRescale;
- }
- scale(ratio) {
- const newSize = Math.max(1, this.getRenderSize() * ratio);
- this.resize(newSize);
- }
- getReflectionTextureMatrix() {
- if (this.isCube) {
- return this._textureMatrix;
- }
- return super.getReflectionTextureMatrix();
- }
- 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);
- }
- }
- render(useCameraPostProcess = false, dumpForDebug = false) {
- this._render(useCameraPostProcess, dumpForDebug);
- }
- isReadyForRendering() {
- if (!this._dumpToolsLoading) {
- this._dumpToolsLoading = true;
- Promise.resolve().then(() => (init_dumpTools(), exports_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));
- return Math.min(FloorPOT(renderDimension), curved);
- }
- _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);
- });
- }
- _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);
- engine._debugPopGroup?.(2);
- this._unbindFrameBuffer(engine, faceIndex);
- if (this._texture && this.isCube && faceIndex === 5) {
- engine.generateMipMapsForCubemap(this._texture, true);
- }
- }
- setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
- this._objectRenderer.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
- }
- setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {
- this._objectRenderer.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
- }
- 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);
- newTexture.hasAlpha = this.hasAlpha;
- newTexture.level = this.level;
- newTexture.coordinatesMode = this.coordinatesMode;
- if (this.renderList) {
- newTexture.renderList = this.renderList.slice(0);
- }
- return newTexture;
- }
- 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;
- }
- disposeFramebufferObjects() {
- this._renderTarget?.dispose(true);
- }
- releaseInternalTexture() {
- this._renderTarget?.releaseTextures();
- this._texture = null;
- }
- 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;
- }
- 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();
- }
- _rebuild() {
- this._objectRenderer._rebuild();
- if (this._postProcessManager) {
- this._postProcessManager._rebuild();
- }
- }
- freeRenderingGroups() {
- this._objectRenderer.freeRenderingGroups();
- }
- getViewCount() {
- return 1;
- }
- };
- RenderTargetTexture.REFRESHRATE_RENDER_ONCE = ObjectRenderer.REFRESHRATE_RENDER_ONCE;
- RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME;
- RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
- Texture._CreateRenderTargetTexture = (name5, renderTargetSize, scene, generateMipMaps, creationFlags) => {
- return new RenderTargetTexture(name5, renderTargetSize, scene, generateMipMaps);
- };
-});
-
-// node_modules/@babylonjs/core/PostProcesses/postProcess.js
-class PostProcess {
- static get ForceGLSL() {
- return EffectWrapper.ForceGLSL;
- }
- static set ForceGLSL(force) {
- EffectWrapper.ForceGLSL = force;
- }
- static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) {
- EffectWrapper.RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing);
- }
- get name() {
- return this._effectWrapper.name;
- }
- set name(value) {
- this._effectWrapper.name = value;
- }
- get alphaMode() {
- return this._effectWrapper.alphaMode;
- }
- set alphaMode(value) {
- this._effectWrapper.alphaMode = value;
- }
- 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);
- });
- }
- get shaderLanguage() {
- return this._shaderLanguage;
- }
- getEffectName() {
- return this._fragmentUrl;
- }
- set onActivate(callback) {
- if (this._onActivateObserver) {
- this.onActivateObservable.remove(this._onActivateObserver);
- }
- if (callback) {
- this._onActivateObserver = this.onActivateObservable.add(callback);
- }
- }
- set onSizeChanged(callback) {
- if (this._onSizeChangedObserver) {
- this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
- }
- this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
- }
- set onApply(callback) {
- if (this._onApplyObserver) {
- this.onApplyObservable.remove(this._onApplyObserver);
- }
- this._onApplyObserver = this.onApplyObservable.add(callback);
- }
- set onBeforeRender(callback) {
- if (this._onBeforeRenderObserver) {
- this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
- }
- this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
- }
- set onAfterRender(callback) {
- if (this._onAfterRenderObserver) {
- this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
- }
- this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
- }
- get inputTexture() {
- return this._textures.data[this._currentRenderTextureInd];
- }
- set inputTexture(value) {
- this._forcedOutputTexture = value;
- }
- restoreDefaultInputTexture() {
- if (this._forcedOutputTexture) {
- this._forcedOutputTexture = null;
- this.markTextureDirty();
- }
- }
- getCamera() {
- return this._camera;
- }
- get texelSize() {
- if (this._shareOutputWithPostProcess) {
- return this._shareOutputWithPostProcess.texelSize;
- }
- if (this._forcedOutputTexture) {
- this._texelSize.copyFromFloats(1 / this._forcedOutputTexture.width, 1 / this._forcedOutputTexture.height);
- }
- return this._texelSize;
- }
- constructor(name5, fragmentUrl, parameters, samplers, _size, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = "postprocess", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage, extraInitializations) {
- this._parentContainer = null;
- this.width = -1;
- this.height = -1;
- this.nodeMaterialSource = null;
- this._outputTexture = null;
- this.autoClear = true;
- this.forceAutoClearInAlphaMode = false;
- this.animations = [];
- this.enablePixelPerfectMode = false;
- this.forceFullscreenViewport = true;
- this.scaleMode = 1;
- this.alwaysForcePOT = false;
- this._samples = 1;
- this.adaptScaleToCurrentViewport = false;
- this._webGPUReady = false;
- this._reusable = false;
- this._renderId = 0;
- this.externalTextureSamplerBinding = false;
- this._textures = new SmartArray(2);
- this._textureCache = [];
- this._currentRenderTextureInd = 0;
- this._scaleRatio = new Vector2(1, 1);
- this._texelSize = Vector2.Zero();
- this.onActivateObservable = new Observable;
- this.onSizeChangedObservable = new Observable;
- this.onApplyObservable = new Observable;
- this.onBeforeRenderObservable = new Observable;
- this.onAfterRenderObservable = new Observable;
- 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(`
-`) : 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;
- 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: name5,
- 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 = name5;
- 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;
- 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;
- 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) {
- if (useWebGPU && this._webGPUReady) {
- list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), exports_postprocess_vertex2))]));
- } else {
- list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), exports_postprocess_vertex))]));
- }
- }
- getClassName() {
- return "PostProcess";
- }
- getEngine() {
- return this._engine;
- }
- getEffect() {
- return this._effectWrapper.drawWrapper.effect;
- }
- shareOutputWith(postProcess) {
- this._disposeTextures();
- this._shareOutputWithPostProcess = postProcess;
- return this;
- }
- useOwnOutput() {
- if (this._textures.length == 0) {
- this._textures = new SmartArray(2);
- }
- this._shareOutputWithPostProcess = null;
- }
- 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(`
-`) : this._effectWrapper.options.defines;
- }
- isReusable() {
- return this._reusable;
- }
- 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);
- }
- }
- }
- }
- 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 / this.width, 1 / 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;
- }
- 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();
- }
- 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);
- 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;
- }
- get isSupported() {
- return this._effectWrapper.drawWrapper.effect.isSupported;
- }
- get aspectRatio() {
- if (this._shareOutputWithPostProcess) {
- return this._shareOutputWithPostProcess.aspectRatio;
- }
- if (this._forcedOutputTexture) {
- return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
- }
- return this.width / this.height;
- }
- isReady() {
- return this._effectWrapper.isReady();
- }
- apply() {
- if (!this._effectWrapper.isReady()) {
- return null;
- }
- this._engine.enableEffect(this._effectWrapper.drawWrapper);
- this._engine.setState(false);
- this._engine.setDepthBuffer(false);
- this._engine.setDepthWrite(false);
- if (this.alphaConstants) {
- this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
- }
- 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);
- }
- 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;
- }
- setPrePassRenderer(prePassRenderer) {
- if (this._prePassEffectConfiguration) {
- this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);
- this._prePassEffectConfiguration.enabled = true;
- return true;
- }
- return false;
- }
- 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 index2 = this._parentContainer.postProcesses.indexOf(this);
- if (index2 > -1) {
- this._parentContainer.postProcesses.splice(index2, 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();
- }
- 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;
- }
- 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;
- }
- 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);
- }
- 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);
- }
-}
-var init_postProcess = __esm(() => {
- init_tslib_es6();
- init_smartArray();
- init_observable();
- init_math_vector();
- init_effect();
- init_decorators();
- init_decorators_serialization();
- init_typeStore();
- init_abstractEngine();
- init_effectRenderer();
- AbstractEngine.prototype.setTextureFromPostProcess = function(channel, postProcess, name5) {
- 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, name5);
- };
- AbstractEngine.prototype.setTextureFromPostProcessOutput = function(channel, postProcess, name5) {
- this._bindTexture(channel, postProcess?._outputTexture?.texture ?? null, name5);
- };
- Effect.prototype.setTextureFromPostProcess = function(channel, postProcess) {
- this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel);
- };
- Effect.prototype.setTextureFromPostProcessOutput = function(channel, postProcess) {
- this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel);
- };
- __decorate([
- serialize()
- ], PostProcess.prototype, "uniqueId", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "name", null);
- __decorate([
- serialize()
- ], PostProcess.prototype, "width", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "height", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "renderTargetSamplingMode", undefined);
- __decorate([
- serializeAsColor4()
- ], PostProcess.prototype, "clearColor", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "autoClear", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "forceAutoClearInAlphaMode", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "alphaMode", null);
- __decorate([
- serialize()
- ], PostProcess.prototype, "alphaConstants", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "enablePixelPerfectMode", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "forceFullscreenViewport", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "scaleMode", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "alwaysForcePOT", undefined);
- __decorate([
- serialize("samples")
- ], PostProcess.prototype, "_samples", undefined);
- __decorate([
- serialize()
- ], PostProcess.prototype, "adaptScaleToCurrentViewport", undefined);
- RegisterClass("BABYLON.PostProcess", PostProcess);
-});
-
-// node_modules/@babylonjs/core/Misc/performanceMonitor.js
-class PerformanceMonitor {
- constructor(frameSampleSize = 30) {
- this._enabled = true;
- this._rollingFrameTime = new RollingAverage(frameSampleSize);
- }
- sampleFrame(timeMs = PrecisionDate.Now) {
- if (!this._enabled) {
- return;
- }
- if (this._lastFrameTimeMs != null) {
- const dt = timeMs - this._lastFrameTimeMs;
- this._rollingFrameTime.add(dt);
- }
- this._lastFrameTimeMs = timeMs;
- }
- get averageFrameTime() {
- return this._rollingFrameTime.average;
- }
- get averageFrameTimeVariance() {
- return this._rollingFrameTime.variance;
- }
- get instantaneousFrameTime() {
- return this._rollingFrameTime.history(0);
- }
- get averageFPS() {
- return 1000 / this._rollingFrameTime.average;
- }
- get instantaneousFPS() {
- const history = this._rollingFrameTime.history(0);
- if (history === 0) {
- return 0;
- }
- return 1000 / history;
- }
- get isSaturated() {
- return this._rollingFrameTime.isSaturated();
- }
- enable() {
- this._enabled = true;
- }
- disable() {
- this._enabled = false;
- this._lastFrameTimeMs = null;
- }
- get isEnabled() {
- return this._enabled;
- }
- reset() {
- this._lastFrameTimeMs = null;
- this._rollingFrameTime.reset();
- }
-}
-
-class RollingAverage {
- constructor(length) {
- this._samples = new Array(length);
- this.reset();
- }
- add(v) {
- let delta;
- if (this.isSaturated()) {
- 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++;
- }
- delta = v - this.average;
- this.average += delta / this._sampleCount;
- this._m2 += delta * (v - this.average);
- this.variance = this._m2 / (this._sampleCount - 1);
- this._samples[this._pos] = v;
- this._pos++;
- this._pos %= this._samples.length;
- }
- history(i) {
- if (i >= this._sampleCount || i >= this._samples.length) {
- return 0;
- }
- const i0 = this._wrapPosition(this._pos - 1);
- return this._samples[this._wrapPosition(i0 - i)];
- }
- isSaturated() {
- return this._sampleCount >= this._samples.length;
- }
- reset() {
- this.average = 0;
- this.variance = 0;
- this._sampleCount = 0;
- this._pos = 0;
- this._m2 = 0;
- }
- _wrapPosition(i) {
- const max = this._samples.length;
- return (i % max + max) % max;
- }
-}
-var init_performanceMonitor = __esm(() => {
- init_precisionDate();
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js
-var init_engine_alpha = __esm(() => {
- init_thinEngine();
- ThinEngine.prototype.setAlphaMode = function(mode, noDepthWriteChange = false) {
- if (this._alphaMode === mode) {
- if (!noDepthWriteChange) {
- 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:
- 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;
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js
-function _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {
- 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;
- } else if (textureType === 7) {
- rgbaData = new Uint32Array(width * height * 4);
- } else {
- rgbaData = new Uint8Array(width * height * 4);
- }
- 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;
- rgbaData[newIndex + 0] = rgbData[index + 0];
- rgbaData[newIndex + 1] = rgbData[index + 1];
- rgbaData[newIndex + 2] = rgbData[index + 2];
- rgbaData[newIndex + 3] = val1;
- }
- }
- return rgbaData;
-}
-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 : 11;
- 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);
- 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;
- };
-}
-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);
- texture.isReady = true;
- };
-}
-var init_engine_rawTexture = __esm(() => {
- init_internalTexture();
- init_logger();
- init_thinEngine();
- ThinEngine.prototype.updateRawTexture = function(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
- if (!texture) {
- return;
- }
- const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);
- 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);
- texture.isReady = true;
- };
- ThinEngine.prototype.createRawTexture = function(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {
- const texture = new InternalTexture(this, 3);
- 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);
- 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);
- 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;
- }
- 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;
- const isPot = !this.needPOTTextures || IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height);
- if (!isPot) {
- generateMipMaps = false;
- }
- 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);
- 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);
- }
- 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(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);
- 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 (!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(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;
- 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;
- };
- ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false);
- ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true);
- ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false);
- ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true);
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js
-var init_engine_readTexture = __esm(() => {
- init_thinEngine();
- init_abstractEngine_functions();
- 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));
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js
-var init_engine_dynamicBuffer = __esm(() => {
- init_thinEngine();
- ThinEngine.prototype.updateDynamicIndexBuffer = function(indexBuffer, indices, offset = 0) {
- this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
- this.bindIndexBuffer(indexBuffer);
- let view;
- if (indexBuffer.is32Bits) {
- view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);
- } else {
- 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();
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js
-var init_engine_cubeTexture = __esm(() => {
- init_thinEngine();
- init_internalTexture();
- init_logger();
- ThinEngine.prototype._createDepthStencilCubeTexture = function(size, options) {
- const internalTexture = new InternalTexture(this, 12);
- 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);
- 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);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/renderTargetWrapper.js
-class RenderTargetWrapper {
- get depthStencilTexture() {
- return this._depthStencilTexture;
- }
- 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);
- }
- }
- get depthStencilTextureWithStencil() {
- return this._depthStencilTextureWithStencil;
- }
- get isCube() {
- return this._isCube;
- }
- get isMulti() {
- return this._isMulti;
- }
- get is2DArray() {
- return this.layers > 0;
- }
- get is3D() {
- return this.depth > 0;
- }
- get size() {
- return this.width;
- }
- get width() {
- return this._size.width ?? this._size;
- }
- get height() {
- return this._size.height ?? this._size;
- }
- get layers() {
- return this._size.layers || 0;
- }
- get depth() {
- return this._size.depth || 0;
- }
- get texture() {
- return this._textures?.[0] ?? null;
- }
- get textures() {
- return this._textures;
- }
- get faceIndices() {
- return this._faceIndices;
- }
- get layerIndices() {
- return this._layerIndices;
- }
- 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;
- }
- get samples() {
- return this._samples;
- }
- 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;
- }
- resolveMSAATextures() {
- if (this.isMulti) {
- this._engine.resolveMultiFramebuffer(this);
- } else {
- this._engine.resolveFramebuffer(this);
- }
- }
- generateMipMaps() {
- if (this._engine._currentRenderTarget === this) {
- this._engine.unBindFramebuffer(this, true);
- }
- if (this.isMulti) {
- this._engine.generateMipMapsMultiFramebuffer(this);
- } else {
- this._engine.generateMipMapsFramebuffer(this);
- }
- }
- constructor(isMulti, isCube, size, engine, label) {
- this._textures = null;
- this._faceIndices = null;
- this._layerIndices = null;
- this._samples = 1;
- this._attachments = null;
- this._generateStencilBuffer = false;
- this._generateDepthBuffer = false;
- this._depthStencilTextureWithStencil = false;
- this.disableAutomaticMSAAResolve = false;
- this.resolveMSAAColors = true;
- this.resolveMSAADepth = false;
- this.resolveMSAAStencil = false;
- this._isMulti = isMulti;
- this._isCube = isCube;
- this._size = size;
- this._engine = engine;
- this._depthStencilTexture = null;
- this.label = label;
- }
- setTextures(textures) {
- if (Array.isArray(textures)) {
- this._textures = textures;
- } else if (textures) {
- this._textures = [textures];
- } else {
- this._textures = null;
- }
- }
- 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;
- }
- setLayerAndFaceIndices(layers, faces) {
- this._layerIndices = layers;
- this._faceIndices = faces;
- }
- 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;
- }
- }
- 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;
- }
- _shareDepth(renderTarget) {
- this.shareDepth(renderTarget);
- }
- shareDepth(renderTarget) {
- if (this._depthStencilTexture) {
- if (renderTarget._depthStencilTexture) {
- renderTarget._depthStencilTexture.dispose();
- }
- renderTarget._depthStencilTexture = this._depthStencilTexture;
- renderTarget._depthStencilTextureWithStencil = this._depthStencilTextureWithStencil;
- this._depthStencilTexture.incrementReferences();
- }
- }
- _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 || lastTextureSource === 12) {
- 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.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;
- }
- _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();
- }
- releaseTextures() {
- if (this._textures) {
- for (let i = 0;i < this._textures.length; ++i) {
- this._textures[i].dispose();
- }
- }
- this._textures = null;
- }
- dispose(disposeOnlyFramebuffers = false) {
- if (!disposeOnlyFramebuffers) {
- this._depthStencilTexture?.dispose();
- this._depthStencilTexture = null;
- this.releaseTextures();
- }
- this._engine._releaseRenderTargetWrapper(this);
- }
-}
-var init_renderTargetWrapper = () => {};
-
-// node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js
-var WebGLRenderTargetWrapper;
-var init_webGLRenderTargetWrapper = __esm(() => {
- init_renderTargetWrapper();
- WebGLRenderTargetWrapper = 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);
- this._framebuffer = null;
- this._depthStencilBuffer = null;
- this._MSAAFramebuffer = null;
- this._colorTextureArray = null;
- this._depthStencilTextureArray = null;
- this._disposeOnlyFramebuffers = false;
- 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;
- }
- createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {
- if (this._depthStencilBuffer) {
- const engine = this._engine;
- 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);
- }
- 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);
- }
- _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) {
- 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 {
- 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);
- }
- setTexture(texture, index = 0, disposePrevious = true) {
- super.setTexture(texture, index, disposePrevious);
- this._bindTextureRenderTarget(texture, index);
- }
- setLayerAndFaceIndices(layers, faces) {
- super.setLayerAndFaceIndices(layers, faces);
- if (!this.textures || !this.layerIndices || !this.faceIndices) {
- return;
- }
- const textureCount = this._attachments?.length ?? this.textures.length;
- for (let index = 0;index < textureCount; index++) {
- const texture = this.textures[index];
- if (!texture) {
- 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);
- }
- }
- }
- 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);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.texture.js
-var init_abstractEngine_texture = __esm(() => {
- init_abstractEngine();
- 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);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js
-var init_engine_renderTarget = __esm(() => {
- init_internalTexture();
- init_logger();
- init_thinEngine();
- init_webGLRenderTargetWrapper();
- init_abstractEngine_texture();
- 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));
- const width = size.width || size;
- const height = size.height || size;
- const currentFrameBuffer = this._currentFramebuffer;
- const gl = this._gl;
- const framebuffer = gl.createFramebuffer();
- this._bindUnboundFramebuffer(framebuffer);
- rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
- 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);
- 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);
- 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, 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);
- 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);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetTexture.js
-var init_engine_renderTargetTexture = __esm(() => {
- init_thinEngine();
- ThinEngine.prototype.setDepthStencilTexture = function(channel, uniform, texture, name5) {
- if (channel === undefined) {
- return;
- }
- if (uniform) {
- this._boundUniforms[channel] = uniform;
- }
- if (!texture || !texture.depthStencilTexture) {
- this._setTexture(channel, null, undefined, undefined, name5);
- } else {
- this._setTexture(channel, texture, false, true, name5);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js
-var init_engine_renderTargetCube = __esm(() => {
- init_internalTexture();
- init_logger();
- init_thinEngine();
- 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) {
- fullOptions.samplingMode = 1;
- } else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
- fullOptions.samplingMode = 1;
- }
- const gl = this._gl;
- const texture = new InternalTexture(this, 5);
- 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);
- }
- const framebuffer = gl.createFramebuffer();
- this._bindUnboundFramebuffer(framebuffer);
- rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
- if (fullOptions.generateMipMaps) {
- gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
- }
- 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;
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.prefilteredCubeTexture.js
-var init_engine_prefilteredCubeTexture = __esm(() => {
- init_thinEngine();
- init_internalTexture();
- init_logger();
- init_sphericalPolynomial();
- init_baseTexture();
- 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;
- if (this.getCaps().textureLOD) {
- if (onLoad) {
- onLoad(texture);
- }
- return;
- }
- const mipSlices = 3;
- const gl = this._gl;
- const width = loadData.width;
- if (!width) {
- return;
- }
- const { DDSTools } = await Promise.resolve().then(() => (init_dds(), exports_dds));
- const textures = [];
- for (let i = 0;i < mipSlices; i++) {
- const smoothness = i / (mipSlices - 1);
- const roughness = 1 - smoothness;
- const minLODIndex = lodOffset;
- const maxLODIndex = Math.log2(width) * lodScale + lodOffset;
- const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
- const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
- const glTextureFromLod = new InternalTexture(this, 2);
- 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);
- 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);
- };
-});
-
-// node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js
-var init_engine_uniformBuffer = __esm(() => {
- init_thinEngine();
- init_webGLDataBuffer();
- 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);
- };
- ThinEngine.prototype.bindUniformBufferBase = function(buffer, location2, name5) {
- this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location2, buffer ? buffer.underlyingResource : null);
- };
- ThinEngine.prototype.bindUniformBlock = function(pipelineContext, blockName, index) {
- const program = pipelineContext.program;
- const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
- if (uniformLocation !== 4294967295) {
- this._gl.uniformBlockBinding(program, uniformLocation, index);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.loadingScreen.js
-var init_abstractEngine_loadingScreen = __esm(() => {
- init_domManagement();
- init_abstractEngine();
- 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
- });
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.dom.js
-var init_abstractEngine_dom = __esm(() => {
- init_abstractEngine();
- 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?.();
- };
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.alpha.js
-var init_abstractEngine_alpha = __esm(() => {
- init_abstractEngine();
- 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;
- };
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.states.js
-var init_abstractEngine_states = __esm(() => {
- init_abstractEngine();
- init_abstractEngine_alpha();
- 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;
- };
-});
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.renderPass.js
-var init_abstractEngine_renderPass = __esm(() => {
- init_abstractEngine();
- AbstractEngine.prototype.getRenderPassNames = function() {
- return this._renderPassNames;
- };
- AbstractEngine.prototype.getCurrentRenderPassName = function() {
- return this._renderPassNames[this.currentRenderPassId];
- };
- AbstractEngine.prototype.createRenderPassId = function(name5) {
- const id = ++AbstractEngine._RenderPassIdCounter;
- this._renderPassNames[id] = name5 ?? "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);
- }
- }
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/Engines/engine.common.js
-function _DisableTouchAction(canvas) {
- if (!canvas || !canvas.setAttribute) {
- return;
- }
- canvas.setAttribute("touch-action", "none");
- canvas.style.touchAction = "none";
- canvas.style.webkitTapHighlightColor = "transparent";
-}
-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) => {
- if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) {
- commonEngine.onCanvasPointerOutObservable.notifyObservers(ev);
- }
- };
- const hostWindow = commonEngine.getHostWindow();
- 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);
- }
- if (!AbstractEngine.audioEngine && creationOptions.audioEngine && AbstractEngine.AudioEngineFactory) {
- AbstractEngine.audioEngine = AbstractEngine.AudioEngineFactory(commonEngine.getRenderingCanvas(), commonEngine.getAudioContext(), commonEngine.getAudioDestination());
- }
- if (IsDocumentAvailable()) {
- commonEngine._onFullscreenChange = () => {
- commonEngine.isFullscreen = !!document.fullscreenElement;
- if (commonEngine.isFullscreen && commonEngine._pointerLockRequested && canvas) {
- RequestPointerlock(canvas);
- }
- };
- document.addEventListener("fullscreenchange", commonEngine._onFullscreenChange, false);
- document.addEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange, false);
- 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;
-}
-function _CommonDispose(commonEngine, canvas) {
- if (EngineStore.Instances.length === 1 && AbstractEngine.audioEngine) {
- AbstractEngine.audioEngine.dispose();
- AbstractEngine.audioEngine = null;
- }
- const hostWindow = commonEngine.getHostWindow();
- 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);
- }
-}
-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 };
-}
-function CreateImageBitmapFromSource(engine, imageSource, options) {
- const promise = new Promise((resolve3, reject) => {
- const image = new Image;
- image.onload = () => {
- image.decode().then(() => {
- engine.createImageBitmap(image, options).then((imageBitmap) => {
- resolve3(imageBitmap);
- });
- });
- };
- image.onerror = () => {
- reject(`Error loading image ${image.src}`);
- };
- image.src = imageSource;
- });
- return promise;
-}
-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);
- const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
- return buffer;
-}
-function RequestFullscreen(element) {
- const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen;
- if (!requestFunction) {
- return;
- }
- requestFunction.call(element);
-}
-function ExitFullscreen() {
- const anyDoc = document;
- if (document.exitFullscreen) {
- document.exitFullscreen();
- } else if (anyDoc.webkitCancelFullScreen) {
- anyDoc.webkitCancelFullScreen();
- }
-}
-function RequestPointerlock(element) {
- if (element.requestPointerLock) {
- const promise = element.requestPointerLock();
- if (promise instanceof Promise)
- promise.then(() => {
- element.focus();
- }).catch(() => {});
- else
- element.focus();
- }
-}
-function ExitPointerlock() {
- if (document.exitPointerLock) {
- document.exitPointerLock();
- }
-}
-var init_engine_common = __esm(() => {
- init_domManagement();
- init_abstractEngine();
- init_engineStore();
-});
-
-// node_modules/@babylonjs/core/Misc/perfCounter.js
-class PerfCounter {
- get min() {
- return this._min;
- }
- get max() {
- return this._max;
- }
- get average() {
- return this._average;
- }
- get lastSecAverage() {
- return this._lastSecAverage;
- }
- get current() {
- return this._current;
- }
- get total() {
- return this._totalAccumulated;
- }
- get count() {
- return this._totalValueCount;
- }
- 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;
- }
- fetchNewFrame() {
- this._totalValueCount++;
- this._current = 0;
- this._lastSecValueCount++;
- }
- addCount(newCount, fetchResult) {
- if (!PerfCounter.Enabled) {
- return;
- }
- this._current += newCount;
- if (fetchResult) {
- this._fetchResult();
- }
- }
- beginMonitoring() {
- if (!PerfCounter.Enabled) {
- return;
- }
- this._startMonitoringTime = PrecisionDate.Now;
- }
- endMonitoring(newFrame = true) {
- if (!PerfCounter.Enabled) {
- return;
- }
- if (newFrame) {
- this.fetchNewFrame();
- }
- const currentTime = PrecisionDate.Now;
- this._current = currentTime - this._startMonitoringTime;
- if (newFrame) {
- this._fetchResult();
- }
- }
- endFrame() {
- this._fetchResult();
- }
- _fetchResult() {
- this._totalAccumulated += this._current;
- this._lastSecAccumulated += this._current;
- this._min = Math.min(this._min, this._current);
- this._max = Math.max(this._max, this._current);
- this._average = this._totalAccumulated / this._totalValueCount;
- const now = PrecisionDate.Now;
- if (now - this._lastSecTime > 1000) {
- this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
- this._lastSecTime = now;
- this._lastSecAccumulated = 0;
- this._lastSecValueCount = 0;
- }
- }
-}
-var init_perfCounter = __esm(() => {
- init_precisionDate();
- PerfCounter.Enabled = true;
-});
-
-// node_modules/@babylonjs/core/Engines/engine.js
-var Engine;
-var init_engine = __esm(() => {
- init_internalTexture();
- init_engineStore();
- init_thinEngine();
- init_performanceMonitor();
- init_webGLDataBuffer();
- init_logger();
- init_engine_alpha();
- init_engine_rawTexture();
- init_engine_readTexture();
- init_engine_dynamicBuffer();
- init_engine_cubeTexture();
- init_engine_renderTarget();
- init_engine_renderTargetTexture();
- init_engine_renderTargetCube();
- init_engine_prefilteredCubeTexture();
- init_engine_uniformBuffer();
- init_abstractEngine_loadingScreen();
- init_abstractEngine_dom();
- init_abstractEngine_states();
- init_abstractEngine_renderPass();
- init_abstractEngine_texture();
- init_abstractEngine();
- init_engine_common();
- init_perfCounter();
- init_timingTools();
- Engine = class Engine extends ThinEngine {
- static get NpmPackage() {
- return AbstractEngine.NpmPackage;
- }
- static get Version() {
- return AbstractEngine.Version;
- }
- static get Instances() {
- return EngineStore.Instances;
- }
- static get LastCreatedEngine() {
- return EngineStore.LastCreatedEngine;
- }
- static get LastCreatedScene() {
- return EngineStore.LastCreatedScene;
- }
- 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;
- }
- get performanceMonitor() {
- return this._performanceMonitor;
- }
- constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) {
- super(canvasOrContext, antialias, options, adaptToDeviceRatio);
- 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;
- }
- _sharedInit(canvas) {
- super._sharedInit(canvas);
- _CommonInit(this, canvas, this._creationOptions);
- }
- resizeImageBitmap(image, bufferWidth, bufferHeight) {
- return ResizeImageBitmap(this, image, bufferWidth, bufferHeight);
- }
- _createImageBitmapFromSource(imageSource, options) {
- return CreateImageBitmapFromSource(this, imageSource, options);
- }
- switchFullscreen(requestPointerLock) {
- if (this.isFullscreen) {
- this.exitFullscreen();
- } else {
- this.enterFullscreen(requestPointerLock);
- }
- }
- enterFullscreen(requestPointerLock) {
- if (!this.isFullscreen) {
- this._pointerLockRequested = requestPointerLock;
- if (this._renderingCanvas) {
- RequestFullscreen(this._renderingCanvas);
- }
- }
- }
- exitFullscreen() {
- if (this.isFullscreen) {
- ExitFullscreen();
- }
- }
- setDitheringState(value) {
- if (value) {
- this._gl.enable(this._gl.DITHER);
- } else {
- this._gl.disable(this._gl.DITHER);
- }
- }
- setRasterizerState(value) {
- if (value) {
- this._gl.disable(this._gl.RASTERIZER_DISCARD);
- } else {
- this._gl.enable(this._gl.RASTERIZER_DISCARD);
- }
- }
- setDirectViewport(x, y, width, height) {
- const currentViewport = this._cachedViewport;
- this._cachedViewport = null;
- this._viewport(x, y, width, height);
- return currentViewport;
- }
- scissorClear(x, y, width, height, clearColor) {
- this.enableScissor(x, y, width, height);
- this.clear(clearColor, true, true, true);
- this.disableScissor();
- }
- enableScissor(x, y, width, height) {
- const gl = this._gl;
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(x, y, width, height);
- }
- disableScissor() {
- const gl = this._gl;
- gl.disable(gl.SCISSOR_TEST);
- }
- _loadFileAsync(url, offlineProvider, useArrayBuffer) {
- return new Promise((resolve3, reject) => {
- this._loadFile(url, (data) => {
- resolve3(data);
- }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {
- reject(exception);
- });
- });
- }
- getVertexShaderSource(program) {
- const shaders = this._gl.getAttachedShaders(program);
- if (!shaders) {
- return null;
- }
- return this._gl.getShaderSource(shaders[0]);
- }
- getFragmentShaderSource(program) {
- const shaders = this._gl.getAttachedShaders(program);
- if (!shaders) {
- return null;
- }
- return this._gl.getShaderSource(shaders[1]);
- }
- set framebufferDimensionsObject(dimensions) {
- this._framebufferDimensionsObject = dimensions;
- if (this._framebufferDimensionsObject) {
- this.onResizeObservable.notifyObservers(this);
- }
- }
- _rebuildBuffers() {
- for (const scene of this.scenes) {
- scene.resetCachedMaterial();
- scene._rebuildGeometries();
- }
- for (const scene of this._virtualScenes) {
- scene.resetCachedMaterial();
- scene._rebuildGeometries();
- }
- super._rebuildBuffers();
- }
- getFontOffset(font) {
- return GetFontOffset(font);
- }
- _cancelFrame() {
- if (this.customAnimationFrameRequester) {
- if (this._frameHandler !== 0) {
- this._frameHandler = 0;
- const { cancelAnimationFrame: cancelAnimationFrame2 } = this.customAnimationFrameRequester;
- if (cancelAnimationFrame2) {
- cancelAnimationFrame2(this.customAnimationFrameRequester.requestID);
- }
- }
- } else {
- super._cancelFrame();
- }
- }
- _renderLoop(timestamp) {
- this._processFrame(timestamp);
- 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());
- }
- }
- }
- enterPointerlock() {
- if (this._renderingCanvas) {
- RequestPointerlock(this._renderingCanvas);
- }
- }
- exitPointerlock() {
- ExitPointerlock();
- }
- 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;
- }
- _releaseTexture(texture) {
- super._releaseTexture(texture);
- }
- _releaseRenderTargetWrapper(rtWrapper) {
- super._releaseRenderTargetWrapper(rtWrapper);
- 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;
- }
- }
- });
- });
- });
- }
- _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(effect2) {
- effect2._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((effect2) => {
- effect2.executeWhenCompiled(onCompiled);
- });
- }
- }
- }
- wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3, width = 0, height = 0) {
- const hardwareTexture = new WebGLHardwareTexture(texture, this._gl);
- const internalTexture = new InternalTexture(this, 0, 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;
- }
- _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);
- }
- 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;
- }
- 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;
- }
- deleteInstancesBuffer(buffer) {
- this._gl.deleteBuffer(buffer);
- }
- _clientWaitAsync(sync, flags = 0, intervalms = 10) {
- const gl = this._gl;
- return new Promise((resolve3, 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;
- }, resolve3, reject, intervalms);
- });
- }
- _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();
- if (this._rescalePostProcess) {
- this._rescalePostProcess.dispose();
- }
- _CommonDispose(this, this._renderingCanvas);
- super.dispose();
- }
- };
- Engine.ALPHA_DISABLE = 0;
- Engine.ALPHA_ADD = 1;
- Engine.ALPHA_COMBINE = 2;
- Engine.ALPHA_SUBTRACT = 3;
- Engine.ALPHA_MULTIPLY = 4;
- Engine.ALPHA_MAXIMIZED = 5;
- Engine.ALPHA_ONEONE = 6;
- Engine.ALPHA_PREMULTIPLIED = 7;
- Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
- Engine.ALPHA_INTERPOLATE = 9;
- Engine.ALPHA_SCREENMODE = 10;
- Engine.DELAYLOADSTATE_NONE = 0;
- Engine.DELAYLOADSTATE_LOADED = 1;
- Engine.DELAYLOADSTATE_LOADING = 2;
- Engine.DELAYLOADSTATE_NOTLOADED = 4;
- Engine.NEVER = 512;
- Engine.ALWAYS = 519;
- Engine.LESS = 513;
- Engine.EQUAL = 514;
- Engine.LEQUAL = 515;
- Engine.GREATER = 516;
- Engine.GEQUAL = 518;
- Engine.NOTEQUAL = 517;
- Engine.KEEP = 7680;
- Engine.REPLACE = 7681;
- Engine.INCR = 7682;
- Engine.DECR = 7683;
- Engine.INVERT = 5386;
- Engine.INCR_WRAP = 34055;
- Engine.DECR_WRAP = 34056;
- Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
- Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
- Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
- Engine.TEXTUREFORMAT_ALPHA = 0;
- Engine.TEXTUREFORMAT_LUMINANCE = 1;
- Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
- Engine.TEXTUREFORMAT_RGB = 4;
- Engine.TEXTUREFORMAT_RGBA = 5;
- Engine.TEXTUREFORMAT_RED = 6;
- Engine.TEXTUREFORMAT_R = 6;
- Engine.TEXTUREFORMAT_R16_UNORM = 33322;
- Engine.TEXTUREFORMAT_RG16_UNORM = 33324;
- Engine.TEXTUREFORMAT_RGB16_UNORM = 32852;
- Engine.TEXTUREFORMAT_RGBA16_UNORM = 32859;
- Engine.TEXTUREFORMAT_R16_SNORM = 36760;
- Engine.TEXTUREFORMAT_RG16_SNORM = 36761;
- Engine.TEXTUREFORMAT_RGB16_SNORM = 36762;
- Engine.TEXTUREFORMAT_RGBA16_SNORM = 36763;
- Engine.TEXTUREFORMAT_RG = 7;
- Engine.TEXTUREFORMAT_RED_INTEGER = 8;
- Engine.TEXTUREFORMAT_R_INTEGER = 8;
- Engine.TEXTUREFORMAT_RG_INTEGER = 9;
- Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
- Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
- Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
- Engine.TEXTURETYPE_UNSIGNED_INT = 0;
- Engine.TEXTURETYPE_FLOAT = 1;
- Engine.TEXTURETYPE_HALF_FLOAT = 2;
- Engine.TEXTURETYPE_BYTE = 3;
- Engine.TEXTURETYPE_SHORT = 4;
- Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
- Engine.TEXTURETYPE_INT = 6;
- Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
- Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
- Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
- Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
- Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
- Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
- Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
- Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
- Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
- Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
- Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
- Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
- Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
- Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
- Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
- Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
- Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
- Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
- Engine.TEXTURE_NEAREST_LINEAR = 7;
- Engine.TEXTURE_NEAREST_NEAREST = 1;
- Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
- Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
- Engine.TEXTURE_LINEAR_LINEAR = 2;
- Engine.TEXTURE_LINEAR_NEAREST = 12;
- Engine.TEXTURE_EXPLICIT_MODE = 0;
- Engine.TEXTURE_SPHERICAL_MODE = 1;
- Engine.TEXTURE_PLANAR_MODE = 2;
- Engine.TEXTURE_CUBIC_MODE = 3;
- Engine.TEXTURE_PROJECTION_MODE = 4;
- Engine.TEXTURE_SKYBOX_MODE = 5;
- Engine.TEXTURE_INVCUBIC_MODE = 6;
- Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
- Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
- Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
- Engine.SCALEMODE_FLOOR = 1;
- Engine.SCALEMODE_NEAREST = 2;
- Engine.SCALEMODE_CEILING = 3;
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/pass.fragment.js
-var exports_pass_fragment2 = {};
-__export(exports_pass_fragment2, {
- passPixelShaderWGSL: () => passPixelShaderWGSL
-});
-var name5 = "passPixelShader", shader4 = `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);}`, passPixelShaderWGSL;
-var init_pass_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name5]) {
- ShaderStore.ShadersStoreWGSL[name5] = shader4;
- }
- passPixelShaderWGSL = { name: name5, shader: shader4 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/passCube.fragment.js
-var exports_passCube_fragment = {};
-__export(exports_passCube_fragment, {
- passCubePixelShaderWGSL: () => passCubePixelShaderWGSL
-});
-var name6 = "passCubePixelShader", shader5 = `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
-}`, passCubePixelShaderWGSL;
-var init_passCube_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name6]) {
- ShaderStore.ShadersStoreWGSL[name6] = shader5;
- }
- passCubePixelShaderWGSL = { name: name6, shader: shader5 };
-});
-
-// node_modules/@babylonjs/core/Shaders/passCube.fragment.js
-var exports_passCube_fragment2 = {};
-__export(exports_passCube_fragment2, {
- passCubePixelShader: () => passCubePixelShader
-});
-var name7 = "passCubePixelShader", shader6 = `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
-}`, passCubePixelShader;
-var init_passCube_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name7]) {
- ShaderStore.ShadersStore[name7] = shader6;
- }
- passCubePixelShader = { name: name7, shader: shader6 };
-});
-
-// node_modules/@babylonjs/core/PostProcesses/thinPassPostProcess.js
-var ThinPassPostProcess, ThinPassCubePostProcess;
-var init_thinPassPostProcess = __esm(() => {
- init_effectRenderer();
- init_engine();
- ThinPassPostProcess = class ThinPassPostProcess extends EffectWrapper {
- _gatherImports(useWebGPU, list) {
- if (useWebGPU) {
- this._webGPUReady = true;
- list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment2(), exports_pass_fragment2))]));
- } else {
- list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment(), exports_pass_fragment))]));
- }
- super._gatherImports(useWebGPU, list);
- }
- constructor(name8, engine = null, options) {
- super({
- ...options,
- name: name8,
- engine: engine || Engine.LastCreatedEngine,
- useShaderStore: true,
- useAsPostProcess: true,
- fragmentShader: ThinPassPostProcess.FragmentUrl
- });
- }
- };
- ThinPassPostProcess.FragmentUrl = "pass";
- ThinPassCubePostProcess = class ThinPassCubePostProcess extends EffectWrapper {
- _gatherImports(useWebGPU, list) {
- if (useWebGPU) {
- this._webGPUReady = true;
- list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment(), exports_passCube_fragment))]));
- } else {
- list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment2(), exports_passCube_fragment2))]));
- }
- super._gatherImports(useWebGPU, list);
- }
- constructor(name8, engine = null, options) {
- super({
- ...options,
- name: name8,
- engine: engine || Engine.LastCreatedEngine,
- useShaderStore: true,
- useAsPostProcess: true,
- fragmentShader: ThinPassCubePostProcess.FragmentUrl,
- defines: "#define POSITIVEX"
- });
- this._face = 0;
- }
- 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;
- }
- }
- };
- ThinPassCubePostProcess.FragmentUrl = "passCube";
-});
-
-// node_modules/@babylonjs/core/PostProcesses/passPostProcess.js
-var PassPostProcess, PassCubePostProcess;
-var init_passPostProcess = __esm(() => {
- init_tslib_es6();
- init_postProcess();
- init_abstractEngine();
- init_typeStore();
- init_decorators_serialization();
- init_thinPassPostProcess();
- init_decorators();
- PassPostProcess = class PassPostProcess extends PostProcess {
- getClassName() {
- return "PassPostProcess";
- }
- constructor(name8, 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(name8, ThinPassPostProcess.FragmentUrl, {
- effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassPostProcess(name8, engine, localOptions) : undefined,
- ...localOptions
- });
- }
- 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 = class PassCubePostProcess extends PostProcess {
- get face() {
- return this._effectWrapper.face;
- }
- set face(value) {
- this._effectWrapper.face = value;
- }
- getClassName() {
- return "PassCubePostProcess";
- }
- constructor(name8, 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(name8, ThinPassPostProcess.FragmentUrl, {
- effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassCubePostProcess(name8, engine, localOptions) : undefined,
- ...localOptions
- });
- }
- 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);
- };
-});
-
-// node_modules/@babylonjs/core/Shaders/lodCube.fragment.js
-var exports_lodCube_fragment = {};
-__export(exports_lodCube_fragment, {
- lodCubePixelShader: () => lodCubePixelShader
-});
-var name8 = "lodCubePixelShader", shader7 = `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));}}
-`, lodCubePixelShader;
-var init_lodCube_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name8]) {
- ShaderStore.ShadersStore[name8] = shader7;
- }
- lodCubePixelShader = { name: name8, shader: shader7 };
-});
-
-// node_modules/@babylonjs/core/Shaders/lod.fragment.js
-var exports_lod_fragment = {};
-__export(exports_lod_fragment, {
- lodPixelShader: () => lodPixelShader
-});
-var name9 = "lodPixelShader", shader8 = `#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));}}
-`, lodPixelShader;
-var init_lod_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name9]) {
- ShaderStore.ShadersStore[name9] = shader8;
- }
- lodPixelShader = { name: name9, shader: shader8 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/lodCube.fragment.js
-var exports_lodCube_fragment2 = {};
-__export(exports_lodCube_fragment2, {
- lodCubePixelShaderWGSL: () => lodCubePixelShaderWGSL
-});
-var name10 = "lodCubePixelShader", shader9 = `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);}}
-`, lodCubePixelShaderWGSL;
-var init_lodCube_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name10]) {
- ShaderStore.ShadersStoreWGSL[name10] = shader9;
- }
- lodCubePixelShaderWGSL = { name: name10, shader: shader9 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/lod.fragment.js
-var exports_lod_fragment2 = {};
-__export(exports_lod_fragment2, {
- lodPixelShaderWGSL: () => lodPixelShaderWGSL
-});
-var name11 = "lodPixelShader", shader10 = `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);}}
-`, lodPixelShaderWGSL;
-var init_lod_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name11]) {
- ShaderStore.ShadersStoreWGSL[name11] = shader10;
- }
- lodPixelShaderWGSL = { name: name11, shader: shader10 };
-});
-
-// node_modules/@babylonjs/core/Misc/textureTools.js
-function CreateResizedCopy(texture, width, height, useBilinearMode = true) {
- const scene = texture.getScene();
- const engine = scene.getEngine();
- const rtt = new RenderTargetTexture("resized" + texture.name, { width, 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;
-}
-function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) {
- 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((resolve3) => {
- const postProcess = new PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, undefined, type, undefined, null, false, format);
- postProcess.externalTextureSamplerBinding = true;
- const encodedTexture = engine.createRenderTargetTexture({ width, height }, {
- generateDepthBuffer: false,
- generateMipMaps: false,
- generateStencilBuffer: false,
- samplingMode,
- type,
- format
- });
- postProcess.onEffectCreatedObservable.addOnce((e) => {
- e.executeWhenCompiled(() => {
- postProcess.onApply = (effect) => {
- effect._bindTexture("textureSampler", internalTexture);
- effect.setFloat2("scale", 1, 1);
- };
- scene.postProcessManager.directRender([postProcess], encodedTexture, true);
- engine.restoreDefaultFramebuffer();
- engine._releaseTexture(internalTexture);
- if (postProcess) {
- postProcess.dispose();
- }
- encodedTexture._swapAndDie(internalTexture);
- internalTexture.type = type;
- internalTexture.format = 5;
- internalTexture.isReady = true;
- resolve3(internalTexture);
- });
- });
- });
-}
-function ToHalfFloat(value) {
- if (!floatView) {
- floatView = new Float32Array(1);
- int32View = new Int32Array(floatView.buffer);
- }
- floatView[0] = value;
- const x = int32View[0];
- let bits = x >> 16 & 32768;
- let m = x >> 12 & 2047;
- const e = x >> 23 & 255;
- if (e < 103) {
- return bits;
- }
- if (e > 142) {
- bits |= 31744;
- bits |= (e == 255 ? 0 : 1) && x & 8388607;
- return bits;
- }
- if (e < 113) {
- m |= 2048;
- bits |= (m >> 114 - e) + (m >> 113 - e & 1);
- return bits;
- }
- bits |= e - 112 << 10 | m >> 1;
- bits += m & 1;
- return bits;
-}
-function FromHalfFloat(value) {
- const s = (value & 32768) >> 15;
- const e = (value & 31744) >> 10;
- const f = value & 1023;
- if (e === 0) {
- return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
- } else if (e == 31) {
- return f ? NaN : (s ? -1 : 1) * Infinity;
- }
- return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10));
-}
-async function GetTextureDataAsync(texture, width, height, face = 0, lod = 0) {
- if (!texture.isReady() && texture._texture) {
- await new Promise((resolve3, reject) => {
- if (texture._texture === null) {
- reject(0);
- return;
- }
- texture._texture.onLoadedObservable.addOnce(() => {
- resolve3(0);
- });
- });
- }
- return await ProcessAsync(texture, width, height, face, lod);
-}
-var floatView, int32View, 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(() => (init_lodCube_fragment(), exports_lodCube_fragment));
- } else {
- await Promise.resolve().then(() => (init_lod_fragment(), exports_lod_fragment));
- }
- } else {
- if (texture.isCube) {
- await Promise.resolve().then(() => (init_lodCube_fragment2(), exports_lodCube_fragment2));
- } else {
- await Promise.resolve().then(() => (init_lod_fragment2(), exports_lod_fragment2));
- }
- }
- let lodPostProcess;
- if (!texture.isCube) {
- lodPostProcess = new PostProcess("lod", "lod", {
- uniforms: ["lod", "gamma"],
- samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST,
- engine,
- shaderLanguage: engine.isWebGPU ? 1 : 0
- });
- } 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 : 0
- });
- }
- await new Promise((resolve3) => {
- lodPostProcess.onEffectCreatedObservable.addOnce((e) => {
- e.executeWhenCompiled(() => {
- resolve3(0);
- });
- });
- });
- const rtt = new RenderTargetTexture("temp", { width, 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);
- const bufferView = await engine.readPixels(0, 0, width, height);
- const data = new Uint8Array(bufferView.buffer, 0, bufferView.byteLength);
- engine.unBindFramebuffer(rtt.renderTarget);
- return data;
- } else {
- throw Error("Render to texture failed.");
- }
- } finally {
- rtt.dispose();
- lodPostProcess.dispose();
- }
-}, TextureTools;
-var init_textureTools = __esm(() => {
- init_texture();
- init_renderTargetTexture();
- init_passPostProcess();
- init_postProcess();
- TextureTools = {
- CreateResizedCopy,
- ApplyPostProcess,
- ToHalfFloat,
- FromHalfFloat,
- GetTextureDataAsync
- };
-});
-
-// node_modules/@babylonjs/core/Misc/urlTools.js
-function GetExtensionFromUrl(url) {
- const urlWithoutUriParams = url.split("?")[0];
- const lastDot = urlWithoutUriParams.lastIndexOf(".");
- const extension = lastDot > -1 ? urlWithoutUriParams.substring(lastDot).toLowerCase() : "";
- return extension;
-}
-
-// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.cubeTexture.js
-var init_abstractEngine_cubeTexture = __esm(() => {
- init_internalTexture();
- init_logger();
- init_fileTools();
- init_guid();
- init_abstractEngine();
- init_textureLoaderManager();
- 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);
- 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);
- }
- 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 {
- 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, (texture2, imgs) => {
- if (imageHandler) {
- imageHandler(texture2, imgs);
- }
- }, files, onError);
- }
- this._internalTexturesCache.push(texture);
- return texture;
- };
-});
-
-// node_modules/@babylonjs/core/Misc/dds.js
-var exports_dds = {};
-__export(exports_dds, {
- DDSTools: () => DDSTools
-});
-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 & 255, value >> 8 & 255, value >> 16 & 255, value >> 24 & 255);
-}
-
-class DDSTools {
- 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,
- 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,
- 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(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(srcData[index]);
- destArray[index + 1] = ToHalfFloat(srcData[index + 1]);
- destArray[index + 2] = ToHalfFloat(srcData[index + 2]);
- if (DDSTools.StoreLODInAlphaChannel) {
- destArray[index + 3] = ToHalfFloat(lod);
- } else {
- destArray[index + 3] = ToHalfFloat(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;
- }
- 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;
- 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: {
- dataOffset += 5 * 4;
- 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;
- }
- }
- 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) {
- 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) {
- 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: {
- 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 {
- 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, width);
- height = Math.max(1, height);
- }
- if (currentFace !== undefined) {
- 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;
- }
- }
-}
-var DDS_MAGIC = 542327876, DDSD_MIPMAPCOUNT = 131072, DDSCAPS2_CUBEMAP = 512, DDPF_FOURCC = 4, DDPF_RGB = 64, DDPF_LUMINANCE = 131072, FOURCC_DXT1, FOURCC_DXT3, FOURCC_DXT5, FOURCC_DX10, FOURCC_D3DFMT_R16G16B16A16F = 113, FOURCC_D3DFMT_R32G32B32A32F = 116, DXGI_FORMAT_R32G32B32A32_FLOAT = 2, DXGI_FORMAT_R16G16B16A16_FLOAT = 10, DXGI_FORMAT_B8G8R8X8_UNORM = 88, headerLengthInt = 31, off_magic = 0, off_size = 1, off_flags = 2, off_height = 3, off_width = 4, off_mipmapCount = 7, off_pfFlags = 20, off_pfFourCC = 21, off_RGBbpp = 22, off_RMask = 23, off_GMask = 24, off_BMask = 25, off_AMask = 26, off_caps2 = 28, off_dxgiFormat = 32;
-var init_dds = __esm(() => {
- init_logger();
- init_cubemapToSphericalPolynomial();
- init_textureTools();
- init_abstractEngine_cubeTexture();
- FOURCC_DXT1 = FourCCToInt32("DXT1");
- FOURCC_DXT3 = FourCCToInt32("DXT3");
- FOURCC_DXT5 = FourCCToInt32("DXT5");
- FOURCC_DX10 = FourCCToInt32("DX10");
- DDSTools.StoreLODInAlphaChannel = false;
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js
-var exports_ddsTextureLoader = {};
-__export(exports_ddsTextureLoader, {
- _DDSTextureLoader: () => _DDSTextureLoader
-});
-
-class _DDSTextureLoader {
- constructor() {
- this.supportCascades = true;
- }
- 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) {
- 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 });
- }
- }
- 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);
- });
- }
-}
-var init_ddsTextureLoader = __esm(() => {
- init_sphericalPolynomial();
- init_dds();
-});
-
-// node_modules/@babylonjs/core/Misc/basisWorker.js
-function workerFunction() {
- const _BASIS_FORMAT = {
- cTFETC1: 0,
- cTFETC2: 1,
- cTFBC1: 2,
- cTFBC3: 3,
- cTFBC4: 4,
- cTFBC5: 5,
- cTFBC7: 6,
- cTFPVRTC1_4_RGB: 8,
- cTFPVRTC1_4_RGBA: 9,
- cTFASTC_4x4: 10,
- cTFATC_RGB: 11,
- cTFATC_RGBA_INTERPOLATED_ALPHA: 12,
- cTFRGBA32: 13,
- cTFRGB565: 14,
- cTFBGR565: 15,
- cTFRGBA4444: 16,
- cTFFXT1_RGB: 17,
- cTFPVRTC2_4_RGB: 18,
- cTFPVRTC2_4_RGBA: 19,
- cTFETC2_EAC_R11: 20,
- cTFETC2_EAC_RG11: 21
- };
- let transcoderModulePromise = null;
- onmessage = (event) => {
- if (event.data.action === "init") {
- if (event.data.url) {
- try {
- importScripts(event.data.url);
- } catch (e) {
- postMessage({ action: "error", error: e });
- }
- }
- if (!transcoderModulePromise) {
- transcoderModulePromise = BASIS({
- wasmBinary: event.data.wasmBinary
- });
- }
- if (transcoderModulePromise !== null) {
- transcoderModulePromise.then((m) => {
- BASIS = m;
- m.initializeBasis();
- postMessage({ action: "init" });
- });
- }
- } else if (event.data.action === "transcode") {
- 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;
- }
- 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);
- }
- }
- }
- loadedFile.close();
- loadedFile.delete();
- if (needsConversion) {
- format = -1;
- }
- if (!success) {
- postMessage({ action: "transcode", success, id: event.data.id });
- } else {
- postMessage({ action: "transcode", success, id: event.data.id, fileInfo, format }, buffers);
- }
- }
- };
- 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;
- }
- 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 (convertToRgb565) {
- const alignedWidth = loadedFile.getImageWidth(imageIndex, levelIndex) + 3 & ~3;
- const alignedHeight = loadedFile.getImageHeight(imageIndex, levelIndex) + 3 & ~3;
- dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight);
- }
- return dst;
- }
- 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] & 31) + 1 * (c[1] & 31)) / 3 | (2 * (c[0] & 2016) + 1 * (c[1] & 2016)) / 3 & 2016 | (2 * (c[0] & 63488) + 1 * (c[1] & 63488)) / 3 & 63488;
- c[3] = (2 * (c[1] & 31) + 1 * (c[0] & 31)) / 3 | (2 * (c[1] & 2016) + 1 * (c[0] & 2016)) / 3 & 2016 | (2 * (c[1] & 63488) + 1 * (c[0] & 63488)) / 3 & 63488;
- 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 & 3];
- dst[dstI++] = c[m >> 2 & 3];
- dst[dstI++] = c[m >> 4 & 3];
- dst[dstI++] = c[m >> 6 & 3];
- }
- }
- }
- return dst;
- }
-}
-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);
- worker.postMessage({ action: "init", url: moduleUrl ? Tools.GetBabylonScriptURL(moduleUrl) : undefined, wasmBinary }, [wasmBinary]);
- });
-}
-var init_basisWorker = __esm(() => {
- init_tools();
-});
-
-// node_modules/@babylonjs/core/Misc/basis.js
-var BASIS_FORMATS, BasisToolsOptions, 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) {
- throw "The chosen Basis transcoder format is not currently supported";
- }
- return format;
-}, _WorkerPromise = null, _Worker = null, _actionId = 0, _IgnoreSupportedFormats = false, _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;
-}, 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, ignoreSupportedFormats: _IgnoreSupportedFormats }, [
- dataViewCopy.buffer
- ]);
- }, (error) => {
- rej(error);
- });
- });
-}, BindTexture = (texture, engine) => {
- let target = engine._gl?.TEXTURE_2D;
- if (texture.isCube) {
- target = engine._gl?.TEXTURE_CUBE_MAP;
- }
- engine._bindTextureDirectly(target, texture, true);
-}, 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) {
- texture.type = 10;
- texture.format = 4;
- if (engine._features.basisNeedsPOT && (Math.log2(rootImage.width) % 1 !== 0 || Math.log2(rootImage.height) % 1 !== 0)) {
- const source = new InternalTexture(engine, 2);
- texture._invertVScale = texture.invertY;
- source.type = 10;
- source.format = 4;
- source.width = rootImage.width + 3 & ~3;
- source.height = rootImage.height + 3 & ~3;
- BindTexture(source, engine);
- engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);
- engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => {
- engine._releaseTexture(source);
- BindTexture(texture, engine);
- });
- } else {
- texture._invertVScale = !texture.invertY;
- texture.width = rootImage.width + 3 & ~3;
- texture.height = rootImage.height + 3 & ~3;
- 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);
- 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;
- }
- }
- }
-}, BasisTools;
-var init_basis = __esm(() => {
- init_tools();
- init_texture();
- init_internalTexture();
- init_basisWorker();
- (function(BASIS_FORMATS2) {
- BASIS_FORMATS2[BASIS_FORMATS2["cTFETC1"] = 0] = "cTFETC1";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2"] = 1] = "cTFETC2";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBC1"] = 2] = "cTFBC1";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBC3"] = 3] = "cTFBC3";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBC4"] = 4] = "cTFBC4";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBC5"] = 5] = "cTFBC5";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBC7"] = 6] = "cTFBC7";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGB"] = 8] = "cTFPVRTC1_4_RGB";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGBA"] = 9] = "cTFPVRTC1_4_RGBA";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFASTC_4x4"] = 10] = "cTFASTC_4x4";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGB"] = 11] = "cTFATC_RGB";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGBA_INTERPOLATED_ALPHA"] = 12] = "cTFATC_RGBA_INTERPOLATED_ALPHA";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA32"] = 13] = "cTFRGBA32";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFRGB565"] = 14] = "cTFRGB565";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFBGR565"] = 15] = "cTFBGR565";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA4444"] = 16] = "cTFRGBA4444";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFFXT1_RGB"] = 17] = "cTFFXT1_RGB";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGB"] = 18] = "cTFPVRTC2_4_RGB";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGBA"] = 19] = "cTFPVRTC2_4_RGBA";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_R11"] = 20] = "cTFETC2_EAC_R11";
- BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_RG11"] = 21] = "cTFETC2_EAC_RG11";
- })(BASIS_FORMATS || (BASIS_FORMATS = {}));
- BasisToolsOptions = {
- JSModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,
- WasmModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`
- };
- BasisTools = {
- JSModuleURL: BasisToolsOptions.JSModuleURL,
- WasmModuleURL: BasisToolsOptions.WasmModuleURL,
- GetInternalFormatFromBasisFormat,
- TranscodeAsync,
- 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;
- }
- });
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js
-var exports_basisTextureLoader = {};
-__export(exports_basisTextureLoader, {
- _BasisTextureLoader: () => _BasisTextureLoader
-});
-
-class _BasisTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- 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);
- }
- });
- }
- 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);
- });
- }
-}
-var init_basisTextureLoader = __esm(() => {
- init_basis();
- init_tools();
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js
-var exports_helperFunctions = {};
-__export(exports_helperFunctions, {
- helperFunctionsWGSL: () => helperFunctionsWGSL
-});
-var name12 = "helperFunctions", shader11 = `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));}
-`, helperFunctionsWGSL;
-var init_helperFunctions = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name12]) {
- ShaderStore.IncludesShadersStoreWGSL[name12] = shader11;
- }
- helperFunctionsWGSL = { name: name12, shader: shader11 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/rgbdDecode.fragment.js
-var exports_rgbdDecode_fragment = {};
-__export(exports_rgbdDecode_fragment, {
- rgbdDecodePixelShaderWGSL: () => rgbdDecodePixelShaderWGSL
-});
-var name13 = "rgbdDecodePixelShader", shader12 = `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);}`, rgbdDecodePixelShaderWGSL;
-var init_rgbdDecode_fragment = __esm(() => {
- init_shaderStore();
- init_helperFunctions();
- if (!ShaderStore.ShadersStoreWGSL[name13]) {
- ShaderStore.ShadersStoreWGSL[name13] = shader12;
- }
- rgbdDecodePixelShaderWGSL = { name: name13, shader: shader12 };
-});
-
-// node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js
-var exports_helperFunctions2 = {};
-__export(exports_helperFunctions2, {
- helperFunctions: () => helperFunctions
-});
-var name14 = "helperFunctions", shader13 = `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));}`, helperFunctions;
-var init_helperFunctions2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStore[name14]) {
- ShaderStore.IncludesShadersStore[name14] = shader13;
- }
- helperFunctions = { name: name14, shader: shader13 };
-});
-
-// node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js
-var exports_rgbdDecode_fragment2 = {};
-__export(exports_rgbdDecode_fragment2, {
- rgbdDecodePixelShader: () => rgbdDecodePixelShader
-});
-var name15 = "rgbdDecodePixelShader", shader14 = `varying vec2 vUV;uniform sampler2D textureSampler;
-#include
-#define CUSTOM_FRAGMENT_DEFINITIONS
-void main(void)
-{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`, rgbdDecodePixelShader;
-var init_rgbdDecode_fragment2 = __esm(() => {
- init_shaderStore();
- init_helperFunctions2();
- if (!ShaderStore.ShadersStore[name15]) {
- ShaderStore.ShadersStore[name15] = shader14;
- }
- rgbdDecodePixelShader = { name: name15, shader: shader14 };
-});
-
-// node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js
-var exports_rgbdEncode_fragment = {};
-__export(exports_rgbdEncode_fragment, {
- rgbdEncodePixelShader: () => rgbdEncodePixelShader
-});
-var name16 = "rgbdEncodePixelShader", shader15 = `varying vec2 vUV;uniform sampler2D textureSampler;
-#include
-#define CUSTOM_FRAGMENT_DEFINITIONS
-void main(void)
-{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`, rgbdEncodePixelShader;
-var init_rgbdEncode_fragment = __esm(() => {
- init_shaderStore();
- init_helperFunctions2();
- if (!ShaderStore.ShadersStore[name16]) {
- ShaderStore.ShadersStore[name16] = shader15;
- }
- rgbdEncodePixelShader = { name: name16, shader: shader15 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/rgbdEncode.fragment.js
-var exports_rgbdEncode_fragment2 = {};
-__export(exports_rgbdEncode_fragment2, {
- rgbdEncodePixelShaderWGSL: () => rgbdEncodePixelShaderWGSL
-});
-var name17 = "rgbdEncodePixelShader", shader16 = `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);}`, rgbdEncodePixelShaderWGSL;
-var init_rgbdEncode_fragment2 = __esm(() => {
- init_shaderStore();
- init_helperFunctions();
- if (!ShaderStore.ShadersStoreWGSL[name17]) {
- ShaderStore.ShadersStoreWGSL[name17] = shader16;
- }
- rgbdEncodePixelShaderWGSL = { name: name17, shader: shader16 };
-});
-
-// node_modules/@babylonjs/core/Misc/rgbdTextureTools.js
-class RGBDTextureTools {
- static ExpandRGBDTexture(texture) {
- const internalTexture = texture._texture;
- if (!internalTexture || !texture.isRGBD) {
- return;
- }
- const engine = internalTexture.getEngine();
- const caps = engine.getCaps();
- const isReady = internalTexture.isReady;
- let expandTexture = false;
- if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
- expandTexture = true;
- internalTexture.type = 2;
- } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
- expandTexture = true;
- internalTexture.type = 1;
- }
- if (expandTexture) {
- internalTexture.isReady = false;
- internalTexture._isRGBD = false;
- internalTexture.invertY = false;
- }
- const expandRGBDTexture = async () => {
- const isWebGPU = engine.isWebGPU;
- const shaderLanguage = isWebGPU ? 1 : 0;
- internalTexture.isReady = false;
- if (isWebGPU) {
- await Promise.resolve().then(() => (init_rgbdDecode_fragment(), exports_rgbdDecode_fragment));
- } else {
- await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), exports_rgbdDecode_fragment2));
- }
- const rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false, undefined, shaderLanguage);
- rgbdPostProcess.externalTextureSamplerBinding = true;
- 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(() => {
- rgbdPostProcess.onApply = (effect) => {
- effect._bindTexture("textureSampler", internalTexture);
- effect.setFloat2("scale", 1, 1);
- };
- texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true);
- engine.restoreDefaultFramebuffer();
- engine._releaseTexture(internalTexture);
- if (rgbdPostProcess) {
- rgbdPostProcess.dispose();
- }
- expandedTexture._swapAndDie(internalTexture);
- internalTexture.isReady = true;
- });
- });
- };
- if (expandTexture) {
- if (isReady) {
- expandRGBDTexture();
- } else {
- texture.onLoadObservable.addOnce(expandRGBDTexture);
- }
- }
- }
- static async EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) {
- if (!scene.getEngine().isWebGPU) {
- await Promise.resolve().then(() => (init_rgbdEncode_fragment(), exports_rgbdEncode_fragment));
- } else {
- await Promise.resolve().then(() => (init_rgbdEncode_fragment2(), exports_rgbdEncode_fragment2));
- }
- return ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5);
- }
-}
-var init_rgbdTextureTools = __esm(() => {
- init_postProcess();
- init_textureTools();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js
-var init_baseTexture_polynomial = __esm(() => {
- init_cubemapToSphericalPolynomial();
- init_baseTexture();
- 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
- });
-});
-
-// node_modules/@babylonjs/core/Misc/environmentTextureTools.js
-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;
- }
- }
- let manifestString = "";
- let charCode = 0;
- while (charCode = dataView.getUint8(pos++)) {
- manifestString += String.fromCharCode(charCode);
- }
- let manifest = JSON.parse(manifestString);
- manifest = normalizeEnvInfo(manifest);
- manifest.binaryDataPosition = pos;
- if (manifest.specular) {
- manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
- }
- return manifest;
-}
-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;
- }
- info = { ...info, version: 2, imageType: DefaultEnvironmentTextureImageType };
- return info;
-}
-function CreateRadianceImageDataArrayBufferViews(data, info) {
- info = normalizeEnvInfo(info);
- const specularInfo = info.specular;
- 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;
-}
-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;
-}
-function UploadEnvLevelsAsync(texture, data, info) {
- info = normalizeEnvInfo(info);
- const specularInfo = info.specular;
- if (!specularInfo) {
- 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((resolve3, reject) => {
- if (expandTexture) {
- const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => {
- reject(message);
- }, image);
- rgbdPostProcess?.onEffectCreatedObservable.addOnce((effect) => {
- effect.executeWhenCompiled(() => {
- rgbdPostProcess.externalTextureSamplerBinding = true;
- rgbdPostProcess.onApply = (effect2) => {
- effect2._bindTexture("textureSampler", tempTexture);
- effect2.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);
- engine.restoreDefaultFramebuffer();
- tempTexture.dispose();
- URL.revokeObjectURL(url);
- resolve3();
- });
- });
- } else {
- engine._uploadImageToTexture(texture, image, face, i);
- if (generateNonLODTextures) {
- const lodTexture = lodTextures[i];
- if (lodTexture) {
- engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
- }
- }
- resolve3();
- }
- });
-}
-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);
- texture.isReady = true;
-}
-async function UploadIrradianceLevelsAsync(mainTexture, imageData, size, imageType = DefaultEnvironmentTextureImageType) {
- const engine = mainTexture.getEngine();
- const texture = new InternalTexture(engine, 5);
- 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);
- texture.isReady = true;
-}
-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;
- 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;
- } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
- expandTexture = true;
- texture.type = 2;
- } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
- expandTexture = true;
- texture.type = 1;
- }
- let shaderLanguage = 0;
- if (expandTexture) {
- if (engine.isWebGPU) {
- shaderLanguage = 1;
- await Promise.resolve().then(() => (init_rgbdDecode_fragment(), exports_rgbdDecode_fragment));
- } else {
- await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), exports_rgbdDecode_fragment2));
- }
- 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;
- if (generateNonLODTextures) {
- const mipSlices = 3;
- lodTextures = {};
- const scale = texture._lodGenerationScale;
- const offset = texture._lodGenerationOffset;
- for (let i = 0;i < mipSlices; i++) {
- const smoothness = i / (mipSlices - 1);
- const roughness = 1 - smoothness;
- const minLODIndex = offset;
- const maxLODIndex = (mipmapsCount - 1) * scale + offset;
- const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
- const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
- const glTextureFromLod = new InternalTexture(engine, 2);
- glTextureFromLod.isCube = true;
- glTextureFromLod.invertY = true;
- glTextureFromLod.generateMipMaps = false;
- engine.updateTextureSamplingMode(2, glTextureFromLod);
- 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 = [];
- for (let i = 0;i < imageData.length; i++) {
- for (let face = 0;face < 6; face++) {
- 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;
- promise = new Promise((resolve3, reject) => {
- image.onload = () => {
- _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture).then(() => resolve3()).catch((reason) => {
- reject(reason);
- });
- };
- image.onerror = (error) => {
- reject(error);
- };
- });
- }
- promises.push(promise);
- }
- }
- await Promise.all(promises);
- 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);
- }
- }
- }
- if (cubeRtt) {
- const irradiance = texture._irradianceTexture;
- texture._irradianceTexture = null;
- engine._releaseTexture(texture);
- cubeRtt._swapAndDie(texture);
- texture._irradianceTexture = irradiance;
- }
- if (rgbdPostProcess) {
- rgbdPostProcess.dispose();
- }
- 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;
- }
- }
-}
-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;
-}
-var DefaultEnvironmentTextureImageType = "image/png", CurrentVersion = 2, MagicBytes;
-var init_environmentTextureTools = __esm(() => {
- init_tools();
- init_math_vector();
- init_sphericalPolynomial();
- init_internalTexture();
- init_baseTexture();
- init_scene();
- init_postProcess();
- init_logger();
- init_rgbdTextureTools();
- init_dumpTools();
- init_baseTexture_polynomial();
- MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54];
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js
-var exports_envTextureLoader = {};
-__export(exports_envTextureLoader, {
- _ENVTextureLoader: () => _ENVTextureLoader
-});
-
-class _ENVTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- 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);
- }
- }
- loadData() {
- throw ".env not supported in 2d.";
- }
-}
-var init_envTextureLoader = __esm(() => {
- init_environmentTextureTools();
-});
-
-// node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js
-class PanoramaToCubeMapTools {
- static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false) {
- if (!float32Array) {
- throw "ConvertPanoramaToCubemap: input cannot be null";
- }
- if (float32Array.length != inputWidth * inputHeight * 3) {
- 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,
- 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);
- 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);
- 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;
- 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,
- g,
- b
- };
- }
-}
-var init_panoramaToCubemap = __esm(() => {
- init_math_vector();
- PanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1, -1, -1), new Vector3(1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1)];
- PanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(1, 1, 1), new Vector3(-1, 1, 1)];
- PanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1, -1, -1), new Vector3(1, -1, 1), new Vector3(1, 1, -1), new Vector3(1, 1, 1)];
- PanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(-1, 1, 1), new Vector3(-1, 1, -1)];
- PanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1)];
- PanoramaToCubeMapTools.FACE_UP = [new Vector3(-1, -1, -1), new Vector3(-1, -1, 1), new Vector3(1, -1, -1), new Vector3(1, -1, 1)];
-});
-
-// node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js
-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) {
- exponent = ldexp(1, 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 == `
-`) {
- break;
- }
- line += character;
- }
- return line;
-}
-function RGBE_ReadHeader(uint8array) {
- let height = 0;
- let width = 0;
- let line = readStringLine(uint8array, 0);
- if (line[0] != "#" || line[1] != "?") {
- 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) {
- 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);
- if (!match || match.length < 3) {
- throw "HDR Bad header format, no size";
- }
- width = parseInt(match[2]);
- height = parseInt(match[1]);
- if (width < 8 || width > 32767) {
- throw "HDR Bad header format, unsupported size";
- }
- lineIndex += line.length + 1;
- return {
- height,
- width,
- dataPosition: lineIndex
- };
-}
-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;
-}
-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);
- const scanLineArray = new Uint8Array(scanLineArrayBuffer);
- const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
- const resultArray = new Float32Array(resultBuffer);
- while (num_scanlines > 0) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- c = uint8array[dataIndex++];
- d = uint8array[dataIndex++];
- if (a != 2 || b != 2 || c & 128 || hdrInfo.width < 8 || hdrInfo.width > 32767) {
- return readRGBEPixelsNotRLE(uint8array, hdrInfo);
- }
- if ((c << 8 | d) != scanline_width) {
- throw "HDR Bad header format, wrong scan line width";
- }
- index = 0;
- for (i = 0;i < 4; i++) {
- endIndex = (i + 1) * scanline_width;
- while (index < endIndex) {
- a = uint8array[dataIndex++];
- b = uint8array[dataIndex++];
- if (a > 128) {
- count = a - 128;
- if (count == 0 || count > endIndex - index) {
- throw "HDR Bad Format, bad scanline data (run)";
- }
- while (count-- > 0) {
- scanLineArray[index++] = b;
- }
- } else {
- count = a;
- if (count == 0 || count > endIndex - index) {
- 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++];
- }
- }
- }
- }
- }
- 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) {
- let num_scanlines = hdrInfo.height;
- const scanline_width = hdrInfo.width;
- let a, b, c, d, i;
- let dataIndex = hdrInfo.dataPosition;
- const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
- const resultArray = new Float32Array(resultBuffer);
- 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;
-}
-var init_hdr = __esm(() => {
- init_panoramaToCubemap();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js
-var exports_hdrTextureLoader = {};
-__export(exports_hdrTextureLoader, {
- _HDRTextureLoader: () => _HDRTextureLoader
-});
-
-class _HDRTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- loadCubeData() {
- throw ".hdr not supported in Cube.";
- }
- 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);
- });
- }
-}
-var init_hdrTextureLoader = __esm(() => {
- init_hdr();
-});
-
-// node_modules/@babylonjs/core/Misc/khronosTextureContainer.js
-class KhronosTextureContainer {
- constructor(data, facesExpected) {
- this.data = data;
- this.isInvalid = false;
- if (!KhronosTextureContainer.IsValid(data)) {
- this.isInvalid = true;
- Logger.Error("texture missing KTX identifier");
- return;
- }
- 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 === 67305985;
- this.glType = headerDataView.getUint32(1 * dataSize, littleEndian);
- this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian);
- this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian);
- this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian);
- this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian);
- this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian);
- this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian);
- this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian);
- this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian);
- this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian);
- this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian);
- this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian);
- if (this.glType !== 0) {
- Logger.Error("only compressed formats currently supported");
- this.isInvalid = true;
- return;
- } else {
- 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;
- }
- this.loadType = KhronosTextureContainer.COMPRESSED_2D;
- }
- uploadLevels(texture, loadMipmaps) {
- switch (this.loadType) {
- case KhronosTextureContainer.COMPRESSED_2D:
- this._upload2DCompressedLevels(texture, loadMipmaps);
- break;
- case KhronosTextureContainer.TEX_2D:
- case KhronosTextureContainer.COMPRESSED_3D:
- case KhronosTextureContainer.TEX_3D:
- }
- }
- _upload2DCompressedLevels(texture, loadMipmaps) {
- 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];
- dataOffset += 4;
- 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;
- dataOffset += 3 - (imageSize + 3) % 4;
- }
- width = Math.max(1, width * 0.5);
- height = Math.max(1, height * 0.5);
- }
- }
- static IsValid(data) {
- if (data.byteLength >= 12) {
- const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);
- if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 49 && identifier[6] === 49 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) {
- return true;
- }
- }
- return false;
- }
-}
-var init_khronosTextureContainer = __esm(() => {
- init_logger();
- KhronosTextureContainer.HEADER_LEN = 12 + 13 * 4;
- KhronosTextureContainer.COMPRESSED_2D = 0;
- KhronosTextureContainer.COMPRESSED_3D = 1;
- KhronosTextureContainer.TEX_2D = 2;
- KhronosTextureContainer.TEX_3D = 3;
-});
-
-// node_modules/@babylonjs/core/Misc/workerPool.js
-class WorkerPool {
- constructor(workers) {
- this._pendingActions = new Array;
- this._workerInfos = workers.map((worker) => ({
- workerPromise: Promise.resolve(worker),
- idle: true
- }));
- }
- dispose() {
- for (const workerInfo of this._workerInfos) {
- workerInfo.workerPromise.then((worker) => {
- worker.terminate();
- });
- }
- this._workerInfos.length = 0;
- this._pendingActions.length = 0;
- }
- push(action2) {
- if (!this._executeOnIdleWorker(action2)) {
- this._pendingActions.push(action2);
- }
- }
- _executeOnIdleWorker(action2) {
- for (const workerInfo of this._workerInfos) {
- if (workerInfo.idle) {
- this._execute(workerInfo, action2);
- return true;
- }
- }
- return false;
- }
- _execute(workerInfo, action2) {
- workerInfo.idle = false;
- workerInfo.workerPromise.then((worker) => {
- action2(worker, () => {
- const nextAction = this._pendingActions.shift();
- if (nextAction) {
- this._execute(workerInfo, nextAction);
- } else {
- workerInfo.idle = true;
- }
- });
- });
- }
-}
-var AutoReleaseWorkerPool;
-var init_workerPool = __esm(() => {
- AutoReleaseWorkerPool = class AutoReleaseWorkerPool extends WorkerPool {
- constructor(maxWorkers, createWorkerAsync, options = AutoReleaseWorkerPool.DefaultOptions) {
- super([]);
- this._maxWorkers = maxWorkers;
- this._createWorkerAsync = createWorkerAsync;
- this._options = options;
- }
- push(action2) {
- if (!this._executeOnIdleWorker(action2)) {
- if (this._workerInfos.length < this._maxWorkers) {
- const workerInfo = {
- workerPromise: this._createWorkerAsync(),
- idle: false
- };
- this._workerInfos.push(workerInfo);
- this._execute(workerInfo, action2);
- } else {
- this._pendingActions.push(action2);
- }
- }
- }
- _execute(workerInfo, action2) {
- if (workerInfo.timeoutId) {
- clearTimeout(workerInfo.timeoutId);
- delete workerInfo.timeoutId;
- }
- super._execute(workerInfo, (worker, onComplete) => {
- action2(worker, () => {
- onComplete();
- if (workerInfo.idle) {
- workerInfo.timeoutId = setTimeout(() => {
- workerInfo.workerPromise.then((worker2) => {
- worker2.terminate();
- });
- const indexOf = this._workerInfos.indexOf(workerInfo);
- if (indexOf !== -1) {
- this._workerInfos.splice(indexOf, 1);
- }
- }, this._options.idleTimeElapsedBeforeRelease);
- }
- });
- });
- }
- };
- AutoReleaseWorkerPool.DefaultOptions = {
- idleTimeElapsedBeforeRelease: 1000
- };
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js
-var SourceTextureFormat, TranscodeTarget, EngineFormat;
-var init_ktx2decoderTypes = __esm(() => {
- (function(SourceTextureFormat2) {
- SourceTextureFormat2[SourceTextureFormat2["ETC1S"] = 0] = "ETC1S";
- SourceTextureFormat2[SourceTextureFormat2["UASTC4x4"] = 1] = "UASTC4x4";
- })(SourceTextureFormat || (SourceTextureFormat = {}));
- (function(TranscodeTarget2) {
- TranscodeTarget2[TranscodeTarget2["ASTC_4X4_RGBA"] = 0] = "ASTC_4X4_RGBA";
- TranscodeTarget2[TranscodeTarget2["BC7_RGBA"] = 1] = "BC7_RGBA";
- TranscodeTarget2[TranscodeTarget2["BC3_RGBA"] = 2] = "BC3_RGBA";
- TranscodeTarget2[TranscodeTarget2["BC1_RGB"] = 3] = "BC1_RGB";
- TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGBA"] = 4] = "PVRTC1_4_RGBA";
- TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGB"] = 5] = "PVRTC1_4_RGB";
- TranscodeTarget2[TranscodeTarget2["ETC2_RGBA"] = 6] = "ETC2_RGBA";
- TranscodeTarget2[TranscodeTarget2["ETC1_RGB"] = 7] = "ETC1_RGB";
- TranscodeTarget2[TranscodeTarget2["RGBA32"] = 8] = "RGBA32";
- TranscodeTarget2[TranscodeTarget2["R8"] = 9] = "R8";
- TranscodeTarget2[TranscodeTarget2["RG8"] = 10] = "RG8";
- })(TranscodeTarget || (TranscodeTarget = {}));
- (function(EngineFormat2) {
- EngineFormat2[EngineFormat2["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT";
- EngineFormat2[EngineFormat2["COMPRESSED_RGBA_ASTC_4X4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4X4_KHR";
- EngineFormat2[EngineFormat2["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
- EngineFormat2[EngineFormat2["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
- EngineFormat2[EngineFormat2["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
- EngineFormat2[EngineFormat2["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
- EngineFormat2[EngineFormat2["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
- EngineFormat2[EngineFormat2["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
- EngineFormat2[EngineFormat2["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
- EngineFormat2[EngineFormat2["RGBA8Format"] = 32856] = "RGBA8Format";
- EngineFormat2[EngineFormat2["R8Format"] = 33321] = "R8Format";
- EngineFormat2[EngineFormat2["RG8Format"] = 33323] = "RG8Format";
- })(EngineFormat || (EngineFormat = {}));
-});
-
-// node_modules/@babylonjs/core/Misc/khronosTextureContainer2Worker.js
-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 workerFunction2(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);
- 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 initializeWebWorker2(worker, wasmBinaries, urls) {
- return new Promise((resolve3, 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);
- resolve3(worker);
- }
- };
- worker.addEventListener("error", onError);
- worker.addEventListener("message", onMessage);
- worker.postMessage({
- action: "init",
- urls,
- wasmBinaries
- });
- });
-}
-
-// node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js
-class DefaultKTX2DecoderOptions {
- constructor() {
- this._isDirty = true;
- this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true;
- this._ktx2DecoderOptions = {};
- }
- get isDirty() {
- return this._isDirty;
- }
- get useRGBAIfASTCBC7NotAvailableWhenUASTC() {
- return this._useRGBAIfASTCBC7NotAvailableWhenUASTC;
- }
- set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) {
- if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) {
- return;
- }
- this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value;
- this._isDirty = true;
- }
- get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() {
- return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC;
- }
- set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) {
- if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) {
- return;
- }
- this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value;
- this._isDirty = true;
- }
- get forceRGBA() {
- return this._forceRGBA;
- }
- set forceRGBA(value) {
- if (this._forceRGBA === value) {
- return;
- }
- this._forceRGBA = value;
- this._isDirty = true;
- }
- get forceR8() {
- return this._forceR8;
- }
- set forceR8(value) {
- if (this._forceR8 === value) {
- return;
- }
- this._forceR8 = value;
- this._isDirty = true;
- }
- get forceRG8() {
- return this._forceRG8;
- }
- set forceRG8(value) {
- if (this._forceRG8 === value) {
- return;
- }
- this._forceRG8 = value;
- this._isDirty = true;
- }
- get bypassTranscoders() {
- return this._bypassTranscoders;
- }
- set bypassTranscoders(value) {
- if (this._bypassTranscoders === value) {
- return;
- }
- this._bypassTranscoders = value;
- this._isDirty = true;
- }
- _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,
- roundToMultiple4: false
- }
- }
- };
- }
- this._ktx2DecoderOptions = options;
- return options;
- }
-}
-
-class KhronosTextureContainer2 {
- static GetDefaultNumWorkers() {
- if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
- return 1;
- }
- 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((resolve3) => {
- const workerContent = `${applyConfig}(${workerFunction2})()`;
- const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
- resolve3(new AutoReleaseWorkerPool(numWorkers, () => initializeWebWorker2(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(engine, numWorkersOrOptions = KhronosTextureContainer2.DefaultNumWorkers) {
- this._engine = engine;
- const workerPoolOption = typeof numWorkersOrOptions === "object" && numWorkersOrOptions.workerPool || KhronosTextureContainer2.WorkerPool;
- if (workerPoolOption) {
- KhronosTextureContainer2._WorkerPoolPromise = Promise.resolve(workerPoolOption);
- } else {
- 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);
- }
- }
- _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((resolve3, 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);
- resolve3();
- } 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((resolve3, reject) => {
- decoder.decode(data, caps).then((data2) => {
- this._createTexture(data2, internalTexture);
- resolve3();
- }).catch((reason) => {
- reject({ message: reason });
- });
- });
- });
- }
- throw new Error("KTX2 decoder module is not available");
- }
- _createTexture(data, internalTexture, options) {
- const oglTexture2D = 3553;
- this._engine._bindTextureDirectly(oglTexture2D, internalTexture);
- if (options) {
- options.transcodedFormat = data.transcodedFormat;
- options.isInGammaSpace = data.isInGammaSpace;
- options.hasAlpha = data.hasAlpha;
- options.transcoderName = data.transcoderName;
- }
- let isUncompressedFormat = true;
- switch (data.transcodedFormat) {
- case 32856:
- internalTexture.type = 0;
- internalTexture.format = 5;
- break;
- case 33321:
- internalTexture.type = 0;
- internalTexture.format = 6;
- break;
- case 33323:
- 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) {
- internalTexture.width = mipmap.width;
- 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);
- }
- static IsValid(data) {
- if (data.byteLength >= 12) {
- const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);
- if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 50 && identifier[6] === 48 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) {
- return true;
- }
- }
- return false;
- }
-}
-var init_khronosTextureContainer2 = __esm(() => {
- init_workerPool();
- init_tools();
- init_ktx2decoderTypes();
- 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
- };
- KhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers();
- KhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions;
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js
-var exports_ktxTextureLoader = {};
-__export(exports_ktxTextureLoader, {
- _KTXTextureLoader: () => _KTXTextureLoader
-});
-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;
-}
-
-class _KTXTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- loadCubeData(data, texture, createPolynomials, onLoad) {
- if (Array.isArray(data)) {
- return;
- }
- 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();
- }
- }
- loadData(data, texture, callback, options) {
- if (KhronosTextureContainer.IsValid(data)) {
- 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);
- }
- }
-}
-var init_ktxTextureLoader = __esm(() => {
- init_khronosTextureContainer();
- init_khronosTextureContainer2();
- init_logger();
-});
-
-// node_modules/@babylonjs/core/Misc/tga.js
-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;
-}
-function UploadContent(texture, data) {
- if (data.length < 19) {
- Logger.Error("Unable to load TGA file - Not enough data to contain header");
- return;
- }
- let offset = 18;
- const header = GetTGAHeader(data);
- if (header.id_length + offset > data.length) {
- Logger.Error("Unable to load TGA file - Not enough data");
- return;
- }
- offset += header.id_length;
- let use_rle = false;
- let use_pal = false;
- let use_grey = false;
- switch (header.image_type) {
- case _TYPE_RLE_INDEXED:
- use_rle = true;
- case _TYPE_INDEXED:
- use_pal = true;
- break;
- case _TYPE_RLE_RGB:
- use_rle = true;
- case _TYPE_RGB:
- break;
- case _TYPE_RLE_GREY:
- use_rle = true;
- case _TYPE_GREY:
- use_grey = true;
- break;
- }
- let pixel_data;
- const pixel_size = header.pixel_size >> 3;
- const pixel_total = header.width * header.height * pixel_size;
- let palettes;
- if (use_pal) {
- palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
- }
- 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 & 127) + 1;
- if (c & 128) {
- for (i = 0;i < pixel_size; ++i) {
- pixels[i] = data[offset++];
- }
- for (i = 0;i < count; ++i) {
- pixel_data.set(pixels, localOffset + i * pixel_size);
- }
- localOffset += pixel_size * count;
- } else {
- count *= pixel_size;
- for (i = 0;i < count; ++i) {
- pixel_data[localOffset + i] = data[offset++];
- }
- localOffset += count;
- }
- }
- } else {
- pixel_data = data.subarray(offset, offset += use_pal ? header.width * header.height : pixel_total);
- }
- 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;
- }
- 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);
-}
-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, height } = header;
- 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;
-}
-function _getImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- const image = pixel_data;
- const { width, height } = header;
- 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);
- const r = ((color & 31744) >> 10) * 255 / 31 | 0;
- const g = ((color & 992) >> 5) * 255 / 31 | 0;
- const b = (color & 31) * 255 / 31 | 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 & 32768 ? 0 : 255;
- }
- }
- return imageData;
-}
-function _getImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- const image = pixel_data;
- const { width, height } = header;
- 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;
-}
-function _getImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- const image = pixel_data;
- const { width, height } = header;
- 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;
-}
-function _getImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- const image = pixel_data;
- const { width, height } = header;
- 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;
-}
-function _getImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
- const image = pixel_data;
- const { width, height } = header;
- 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;
-}
-var _TYPE_INDEXED = 1, _TYPE_RGB = 2, _TYPE_GREY = 3, _TYPE_RLE_INDEXED = 9, _TYPE_RLE_RGB = 10, _TYPE_RLE_GREY = 11, _ORIGIN_MASK = 48, _ORIGIN_SHIFT = 4, _ORIGIN_BL = 0, _ORIGIN_BR = 1, _ORIGIN_UL = 2, _ORIGIN_UR = 3, TGATools;
-var init_tga = __esm(() => {
- init_logger();
- TGATools = {
- GetTGAHeader,
- UploadContent,
- _getImageData8bits,
- _getImageData16bits,
- _getImageData24bits,
- _getImageData32bits,
- _getImageDataGrey8bits,
- _getImageDataGrey16bits
- };
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js
-var exports_tgaTextureLoader = {};
-__export(exports_tgaTextureLoader, {
- _TGATextureLoader: () => _TGATextureLoader
-});
-
-class _TGATextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- loadCubeData() {
- throw ".env not supported in Cube.";
- }
- 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);
- });
- }
-}
-var init_tgaTextureLoader = __esm(() => {
- init_tga();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.interfaces.js
-var INT32_SIZE = 4, FLOAT32_SIZE = 4, INT8_SIZE = 1, INT16_SIZE = 2, ULONG_SIZE = 8, USHORT_RANGE, BITMAP_SIZE, HUF_ENCBITS = 16, HUF_DECBITS = 14, HUF_ENCSIZE, HUF_DECSIZE, HUF_DECMASK, SHORT_ZEROCODE_RUN = 59, LONG_ZEROCODE_RUN = 63, SHORTEST_LONG_RUN;
-var init_exrLoader_interfaces = __esm(() => {
- USHORT_RANGE = 1 << 16;
- BITMAP_SIZE = USHORT_RANGE >> 3;
- HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1;
- HUF_DECSIZE = 1 << HUF_DECBITS;
- HUF_DECMASK = HUF_DECSIZE - 1;
- SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.core.js
-function _GenerateTables() {
- const buffer = new ArrayBuffer(4);
- const floatView2 = 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;
- if (e < -27) {
- baseTable[i] = 0;
- baseTable[i | 256] = 32768;
- shiftTable[i] = 24;
- shiftTable[i | 256] = 24;
- } else if (e < -14) {
- baseTable[i] = 1024 >> -e - 14;
- baseTable[i | 256] = 1024 >> -e - 14 | 32768;
- shiftTable[i] = -e - 1;
- shiftTable[i | 256] = -e - 1;
- } else if (e <= 15) {
- baseTable[i] = e + 15 << 10;
- baseTable[i | 256] = e + 15 << 10 | 32768;
- shiftTable[i] = 13;
- shiftTable[i | 256] = 13;
- } else if (e < 128) {
- baseTable[i] = 31744;
- baseTable[i | 256] = 64512;
- shiftTable[i] = 24;
- shiftTable[i | 256] = 24;
- } else {
- baseTable[i] = 31744;
- baseTable[i | 256] = 64512;
- shiftTable[i] = 13;
- shiftTable[i | 256] = 13;
- }
- }
- 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;
- let e = 0;
- while ((m & 8388608) === 0) {
- m <<= 1;
- e -= 8388608;
- }
- m &= ~8388608;
- e += 947912704;
- mantissaTable[i] = m | e;
- }
- for (let i = 1024;i < 2048; ++i) {
- mantissaTable[i] = 939524096 + (i - 1024 << 13);
- }
- for (let i = 1;i < 31; ++i) {
- exponentTable[i] = i << 23;
- }
- exponentTable[31] = 1199570944;
- exponentTable[32] = 2147483648;
- for (let i = 33;i < 63; ++i) {
- exponentTable[i] = 2147483648 + (i - 32 << 23);
- }
- exponentTable[63] = 3347054592;
- for (let i = 1;i < 64; ++i) {
- if (i !== 32) {
- offsetTable[i] = 1024;
- }
- }
- return {
- floatView: floatView2,
- uint32View,
- baseTable,
- shiftTable,
- mantissaTable,
- exponentTable,
- offsetTable
- };
-}
-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;
-}
-function ParseInt32(dataView, offset) {
- const value = dataView.getInt32(offset.value, true);
- offset.value += INT32_SIZE;
- return value;
-}
-function ParseUint32(dataView, offset) {
- const value = dataView.getUint32(offset.value, true);
- offset.value += INT32_SIZE;
- return value;
-}
-function ParseUint8(dataView, offset) {
- const value = dataView.getUint8(offset.value);
- offset.value += INT8_SIZE;
- return value;
-}
-function ParseUint16(dataView, offset) {
- const value = dataView.getUint16(offset.value, true);
- offset.value += INT16_SIZE;
- return value;
-}
-function ParseUint8Array(array, offset) {
- const value = array[offset.value];
- offset.value += INT8_SIZE;
- return value;
-}
-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;
-}
-function ParseFloat32(dataView, offset) {
- const value = dataView.getFloat32(offset.value, true);
- offset.value += FLOAT32_SIZE;
- return value;
-}
-function ParseFloat16(dataView, offset) {
- return DecodeFloat16(ParseUint16(dataView, offset));
-}
-function DecodeFloat16(binary) {
- const exponent = (binary & 31744) >> 10;
- const fraction = binary & 1023;
- return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 0.00006103515625 * (fraction / 1024));
-}
-function ToHalfFloat2(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 & 511;
- return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]);
-}
-function DecodeFloat32(dataView, offset) {
- return ToHalfFloat2(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 name18 = ParseNullTerminatedString(dataView.buffer, offset);
- const pixelType = ParseInt32(dataView, offset);
- const pLinear = ParseUint8(dataView, offset);
- offset.value += 3;
- const xSampling = ParseInt32(dataView, offset);
- const ySampling = ParseInt32(dataView, offset);
- channels.push({
- name: name18,
- pixelType,
- pLinear,
- xSampling,
- 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, redY, greenX, greenY, blueX, blueY, whiteX, 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, yMin, xMax, yMax };
-}
-function ParseLineOrder(dataView, offset) {
- const lineOrder = ParseUint8(dataView, offset);
- return LineOrders[lineOrder];
-}
-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;
- }
-}
-function Predictor(source) {
- for (let t = 1;t < source.length; t++) {
- const d = source[t - 1] + source[t] - 128;
- source[t] = d;
- }
-}
-function InterleaveScalar(source, out) {
- let t1 = 0;
- let t2 = Math.floor((source.length + 1) / 2);
- let s = 0;
- const stop = source.length - 1;
- while (true) {
- if (s > stop) {
- break;
- }
- out[s++] = source[t1++];
- if (s > stop) {
- break;
- }
- out[s++] = source[t2++];
- }
-}
-var CompressionCodes, LineOrders, _tables;
-var init_exrLoader_core = __esm(() => {
- init_exrLoader_interfaces();
- (function(CompressionCodes2) {
- CompressionCodes2[CompressionCodes2["NO_COMPRESSION"] = 0] = "NO_COMPRESSION";
- CompressionCodes2[CompressionCodes2["RLE_COMPRESSION"] = 1] = "RLE_COMPRESSION";
- CompressionCodes2[CompressionCodes2["ZIPS_COMPRESSION"] = 2] = "ZIPS_COMPRESSION";
- CompressionCodes2[CompressionCodes2["ZIP_COMPRESSION"] = 3] = "ZIP_COMPRESSION";
- CompressionCodes2[CompressionCodes2["PIZ_COMPRESSION"] = 4] = "PIZ_COMPRESSION";
- CompressionCodes2[CompressionCodes2["PXR24_COMPRESSION"] = 5] = "PXR24_COMPRESSION";
- })(CompressionCodes || (CompressionCodes = {}));
- (function(LineOrders2) {
- LineOrders2[LineOrders2["INCREASING_Y"] = 0] = "INCREASING_Y";
- LineOrders2[LineOrders2["DECREASING_Y"] = 1] = "DECREASING_Y";
- })(LineOrders || (LineOrders = {}));
- _tables = _GenerateTables();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.header.js
-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);
- 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 & ~4) != 0) {
- throw new Error("Unsupported file format");
- }
- return { version, spec, ...headerData };
-}
-var EXR_MAGIC = 20000630;
-var init_exrLoader_header = __esm(() => {
- init_logger();
- init_exrLoader_core();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.huf.js
-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 };
-}
-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;
-}
-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 & 65535;
-}
-function Int16(value) {
- const ref = UInt16(value);
- return ref > 32767 ? ref - 65536 : 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 };
-}
-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;
-}
-function ApplyLut(lut, data, nData) {
- for (let i = 0;i < nData; ++i) {
- data[i] = lut[data[i]];
- }
-}
-var NBITS = 16, A_OFFSET, MOD_MASK, HufTableBuffer;
-var init_exrLoader_compression_huf = __esm(() => {
- init_exrLoader_core();
- init_exrLoader_interfaces();
- A_OFFSET = 1 << NBITS - 1;
- MOD_MASK = (1 << NBITS) - 1;
- HufTableBuffer = new Array(59);
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.rle.js
-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;
-}
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.js
-function UncompressRAW(decoder) {
- return new DataView(decoder.array.buffer, decoder.offset.value, decoder.size);
-}
-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);
-}
-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);
-}
-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 writePtr2 = 0;
- const ptr3 = 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:
- ptr3[0] = tmpBufferEnd;
- ptr3[1] = ptr3[0] + decoder.width;
- tmpBufferEnd = ptr3[1] + decoder.width;
- for (let j = 0;j < decoder.width; ++j) {
- const diff = rawBuffer[ptr3[0]++] << 8 | rawBuffer[ptr3[1]++];
- pixel += diff;
- tmpBuffer[writePtr2] = pixel;
- writePtr2++;
- }
- break;
- case 2:
- ptr3[0] = tmpBufferEnd;
- ptr3[1] = ptr3[0] + decoder.width;
- ptr3[2] = ptr3[1] + decoder.width;
- tmpBufferEnd = ptr3[2] + decoder.width;
- for (let j = 0;j < decoder.width; ++j) {
- const diff = rawBuffer[ptr3[0]++] << 24 | rawBuffer[ptr3[1]++] << 16 | rawBuffer[ptr3[2]++] << 8;
- pixel += diff;
- tmpBuffer[writePtr2] = pixel;
- writePtr2++;
- }
- break;
- }
- }
- }
- return new DataView(tmpBuffer.buffer);
-}
-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);
- 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;
- }
- 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);
- }
- }
- const lut = new Uint16Array(USHORT_RANGE);
- const maxValue = ReverseLutFromBitmap(bitmap, lut);
- const length = ParseUint32(inDataView, inOffset);
- HufUncompress(decoder.array, inDataView, inOffset, length, outBuffer, outBufferEnd);
- 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);
- }
- }
- ApplyLut(lut, outBuffer, outBufferEnd);
- 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 init_exrLoader_compression = __esm(() => {
- init_exrLoader_compression_huf();
- init_exrLoader_core();
- init_exrLoader_interfaces();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.configuration.js
-class ExrLoaderGlobalConfiguration {
-}
-var EXROutputType;
-var init_exrLoader_configuration = __esm(() => {
- (function(EXROutputType2) {
- EXROutputType2[EXROutputType2["Float"] = 0] = "Float";
- EXROutputType2[EXROutputType2["HalfFloat"] = 1] = "HalfFloat";
- })(EXROutputType || (EXROutputType = {}));
- ExrLoaderGlobalConfiguration.DefaultOutputType = EXROutputType.HalfFloat;
- ExrLoaderGlobalConfiguration.FFLATEUrl = "https://unpkg.com/fflate@0.8.2";
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.decoder.js
-async function CreateDecoderAsync(header, dataView, offset, outputType) {
- const decoder = {
- size: 0,
- viewer: dataView,
- array: new Uint8Array(dataView.buffer),
- 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;
- }
- }
- 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) {
- 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) {
- 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);
- }
- const size = decoder.width * decoder.height * decoder.outputChannels;
- switch (outputType) {
- case EXROutputType.Float:
- decoder.byteArray = new Float32Array(size);
- decoder.textureType = 1;
- 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(15360, 0, size);
- }
- 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;
-}
-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;
- decoder.size = ParseUint32(dataView, offset);
- 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 name18 = header.channels[channelID].name;
- const lOff = decoder.channelLineOffsets[name18];
- const cOff = decoder.decodeChannels[name18];
- 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);
- }
- }
- }
- }
- }
-}
-var init_exrLoader_decoder = __esm(() => {
- init_exrLoader_core();
- init_exrLoader_compression();
- init_exrLoader_interfaces();
- init_tools();
- init_exrLoader_configuration();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/exrTextureLoader.js
-var exports_exrTextureLoader = {};
-__export(exports_exrTextureLoader, {
- _ExrTextureLoader: () => _ExrTextureLoader
-});
-
-class _ExrTextureLoader {
- constructor() {
- this.supportCascades = false;
- }
- loadCubeData(_data, _texture, _createPolynomials, _onLoad, _onError) {
- throw ".exr not supported in Cube.";
- }
- 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);
- 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);
- }
- });
- }
-}
-var init_exrTextureLoader = __esm(() => {
- init_exrLoader_header();
- init_exrLoader_decoder();
- init_exrLoader_configuration();
-});
-
-// node_modules/@babylonjs/core/Materials/Textures/Loaders/textureLoaderManager.js
-function registerTextureLoader(extension, loaderFactory) {
- if (unregisterTextureLoader(extension)) {
- Logger.Warn(`Extension with the name '${name}' already exists`);
- }
- _registeredTextureLoaders.set(extension, loaderFactory);
-}
-function unregisterTextureLoader(extension) {
- return _registeredTextureLoaders.delete(extension);
-}
-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(() => (init_iesTextureLoader(), exports_iesTextureLoader)).then((module) => new module._IESTextureLoader));
- }
- if (extension.endsWith(".dds")) {
- registerTextureLoader(".dds", () => Promise.resolve().then(() => (init_ddsTextureLoader(), exports_ddsTextureLoader)).then((module) => new module._DDSTextureLoader));
- }
- if (extension.endsWith(".basis")) {
- registerTextureLoader(".basis", () => Promise.resolve().then(() => (init_basisTextureLoader(), exports_basisTextureLoader)).then((module) => new module._BasisTextureLoader));
- }
- if (extension.endsWith(".env")) {
- registerTextureLoader(".env", () => Promise.resolve().then(() => (init_envTextureLoader(), exports_envTextureLoader)).then((module) => new module._ENVTextureLoader));
- }
- if (extension.endsWith(".hdr")) {
- registerTextureLoader(".hdr", () => Promise.resolve().then(() => (init_hdrTextureLoader(), exports_hdrTextureLoader)).then((module) => new module._HDRTextureLoader));
- }
- if (extension.endsWith(".ktx") || extension.endsWith(".ktx2")) {
- registerTextureLoader(".ktx", () => Promise.resolve().then(() => (init_ktxTextureLoader(), exports_ktxTextureLoader)).then((module) => new module._KTXTextureLoader));
- registerTextureLoader(".ktx2", () => Promise.resolve().then(() => (init_ktxTextureLoader(), exports_ktxTextureLoader)).then((module) => new module._KTXTextureLoader));
- }
- if (extension.endsWith(".tga")) {
- registerTextureLoader(".tga", () => Promise.resolve().then(() => (init_tgaTextureLoader(), exports_tgaTextureLoader)).then((module) => new module._TGATextureLoader));
- }
- if (extension.endsWith(".exr")) {
- registerTextureLoader(".exr", () => Promise.resolve().then(() => (init_exrTextureLoader(), exports_exrTextureLoader)).then((module) => new module._ExrTextureLoader));
- }
- }
- const registered = _registeredTextureLoaders.get(extension);
- return registered ? Promise.resolve(registered(mimeType)) : null;
-}
-var _registeredTextureLoaders;
-var init_textureLoaderManager = __esm(() => {
- init_logger();
- _registeredTextureLoaders = new Map;
-});
-
-// node_modules/@babylonjs/core/Engines/abstractEngine.js
-function QueueNewFrame(func, requester) {
- if (!IsWindowObjectExist()) {
- if (typeof requestAnimationFrame === "function") {
- return requestAnimationFrame(func);
- }
- } else {
- const { requestAnimationFrame: requestAnimationFrame2 } = requester || window;
- if (typeof requestAnimationFrame2 === "function") {
- return requestAnimationFrame2(func);
- }
- }
- return setTimeout(func, 16);
-}
-
-class AbstractEngine {
- get frameId() {
- return this._frameId;
- }
- get isWebGPU() {
- return this._isWebGPU;
- }
- _getShaderProcessor(shaderLanguage) {
- return this._shaderProcessor;
- }
- get shaderPlatformName() {
- return this._shaderPlatformName;
- }
- _clearEmptyResources() {
- this._emptyTexture = null;
- this._emptyCubeTexture = null;
- this._emptyTexture3D = null;
- this._emptyTexture2DArray = null;
- }
- 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;
- }
- }
- setColorWrite(enable) {
- if (enable !== this._colorWrite) {
- this._colorWriteChanged = true;
- this._colorWrite = enable;
- }
- }
- getColorWrite() {
- return this._colorWrite;
- }
- get depthCullingState() {
- return this._depthCullingState;
- }
- get alphaState() {
- return this._alphaState;
- }
- get stencilState() {
- return this._stencilState;
- }
- get stencilStateComposer() {
- return this._stencilStateComposer;
- }
- _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 += `
-`;
- }
- s += "#define USE_REVERSE_DEPTHBUFFER";
- }
- if (this.useExactSrgbConversions) {
- if (s) {
- s += `
-`;
- }
- s += "#define USE_EXACT_SRGB_CONVERSIONS";
- }
- return s;
- }
- }
- _rebuildInternalTextures() {
- const currentState = this._internalTexturesCache.slice();
- for (const internalTexture of currentState) {
- internalTexture._rebuild();
- }
- }
- _rebuildRenderTargetWrappers() {
- const currentState = this._renderTargetWrapperCache.slice();
- for (const renderTargetWrapper of currentState) {
- renderTargetWrapper._rebuild();
- }
- }
- _rebuildEffects() {
- for (const key in this._compiledEffects) {
- const effect = this._compiledEffects[key];
- effect._pipelineContext = null;
- effect._prepareEffect();
- }
- Effect.ResetCache();
- }
- _rebuildGraphicsResources() {
- this.wipeCaches(true);
- this._rebuildEffects();
- this._rebuildComputeEffects?.();
- this._rebuildBuffers();
- this._rebuildInternalTextures();
- this._rebuildTextures();
- this._rebuildRenderTargetWrappers();
- this.wipeCaches(true);
- }
- _flagContextRestored() {
- Logger.Warn(this.name + " context successfully restored.");
- this.onContextRestoredObservable.notifyObservers(this);
- this._contextWasLost = false;
- }
- _restoreEngineAfterContextLost(initEngine) {
- setTimeout(async () => {
- this._clearEmptyResources();
- const depthTest = this._depthCullingState.depthTest;
- const depthFunc = this._depthCullingState.depthFunc;
- const depthMask = this._depthCullingState.depthMask;
- const stencilTest = this._stencilState.stencilTest;
- await initEngine();
- this._rebuildGraphicsResources();
- this._depthCullingState.depthTest = depthTest;
- this._depthCullingState.depthFunc = depthFunc;
- this._depthCullingState.depthMask = depthMask;
- this._stencilState.stencilTest = stencilTest;
- this._flagContextRestored();
- }, 0);
- }
- get isDisposed() {
- return this._isDisposed;
- }
- get snapshotRendering() {
- return false;
- }
- set snapshotRendering(activate) {}
- get snapshotRenderingMode() {
- return 0;
- }
- set snapshotRenderingMode(mode) {}
- getClassName() {
- return "AbstractEngine";
- }
- get emptyTexture() {
- if (!this._emptyTexture) {
- this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, false, false, 1);
- }
- return this._emptyTexture;
- }
- get emptyTexture3D() {
- if (!this._emptyTexture3D) {
- this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, false, false, 1);
- }
- return this._emptyTexture3D;
- }
- get emptyTexture2DArray() {
- if (!this._emptyTexture2DArray) {
- this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, false, false, 1);
- }
- return this._emptyTexture2DArray;
- }
- 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;
- }
- get activeRenderLoops() {
- return this._activeRenderLoops;
- }
- 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: cancelAnimationFrame2 } = this.getHostWindow() || window;
- if (typeof cancelAnimationFrame2 === "function") {
- return cancelAnimationFrame2(handlerToCancel);
- }
- }
- return clearTimeout(handlerToCancel);
- }
- }
- beginFrame() {
- this.onBeginFrameObservable.notifyObservers(this);
- }
- endFrame() {
- this._frameId++;
- this.onEndFrameObservable.notifyObservers(this);
- }
- 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);
- }
- _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) {
- this.beginFrame();
- if (!this.skipFrameRender && !this._renderViews()) {
- this._renderFrame();
- }
- this.endFrame();
- }
- }
- }
- _renderLoop(timestamp) {
- this._processFrame(timestamp);
- if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) {
- this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
- }
- }
- _renderFrame() {
- for (let index = 0;index < this._activeRenderLoops.length; index++) {
- const renderFunction = this._activeRenderLoops[index];
- renderFunction();
- }
- }
- _renderViews() {
- return false;
- }
- _queueNewFrame(bindedRenderFunction, requester) {
- return QueueNewFrame(bindedRenderFunction, requester);
- }
- runRenderLoop(renderFunction) {
- if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
- return;
- }
- this._activeRenderLoops.push(renderFunction);
- if (this._activeRenderLoops.length === 1 && this._frameHandler === 0) {
- this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
- }
- }
- getDepthBuffer() {
- return this._depthCullingState.depthTest;
- }
- setDepthBuffer(enable) {
- this._depthCullingState.depthTest = enable;
- }
- setZOffset(value) {
- this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -value : value;
- }
- getZOffset() {
- const zOffset = this._depthCullingState.zOffset;
- return this.useReverseDepthBuffer ? -zOffset : zOffset;
- }
- setZOffsetUnits(value) {
- this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -value : value;
- }
- getZOffsetUnits() {
- const zOffsetUnits = this._depthCullingState.zOffsetUnits;
- return this.useReverseDepthBuffer ? -zOffsetUnits : zOffsetUnits;
- }
- getHostWindow() {
- if (!IsWindowObjectExist()) {
- return null;
- }
- if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
- return this._renderingCanvas.ownerDocument.defaultView;
- }
- return window;
- }
- get compatibilityMode() {
- return this._compatibilityMode;
- }
- set compatibilityMode(mode) {
- this._compatibilityMode = true;
- }
- _rebuildTextures() {
- for (const scene of this.scenes) {
- scene._rebuildTextures();
- }
- for (const scene of this._virtualScenes) {
- scene._rebuildTextures();
- }
- }
- _releaseRenderTargetWrapper(rtWrapper) {
- const index = this._renderTargetWrapperCache.indexOf(rtWrapper);
- if (index !== -1) {
- this._renderTargetWrapperCache.splice(index, 1);
- }
- }
- get currentViewport() {
- return this._cachedViewport;
- }
- 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);
- }
- createCanvasImage() {
- return document.createElement("img");
- }
- createCanvasPath2D(d) {
- return new Path2D(d);
- }
- 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);
- if (texture !== fallback) {
- texture.label = url.substring(0, 60);
- }
- const originalUrl = url;
- if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
- url = this._transformTextureUrl(url);
- }
- if (originalUrl !== url) {
- texture._originalUrl = originalUrl;
- }
- const lastDot = url.lastIndexOf(".");
- let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
- 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) {
- 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 {
- 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);
- }
- };
- 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) {
- texture._buffer = img;
- }
- prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcess, samplingMode);
- };
- 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() {
- for (const uniformBuffer of this._uniformBuffers) {
- uniformBuffer._rebuildAfterContextLost();
- }
- }
- get _shouldUseHighPrecisionShader() {
- return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
- }
- getHostDocument() {
- if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
- return this._renderingCanvas.ownerDocument;
- }
- return IsDocumentAvailable() ? document : null;
- }
- getLoadedTexturesCache() {
- return this._internalTexturesCache;
- }
- clearInternalTexturesCache() {
- this._internalTexturesCache.length = 0;
- }
- getCaps() {
- return this._caps;
- }
- resetTextureCache() {
- for (const key in this._boundTexturesCache) {
- if (!Object.prototype.hasOwnProperty.call(this._boundTexturesCache, key)) {
- continue;
- }
- this._boundTexturesCache[key] = null;
- }
- this._currentTextureChannel = -1;
- }
- get name() {
- return this._name;
- }
- set name(value) {
- this._name = value;
- }
- static get NpmPackage() {
- return "babylonjs@7.54.3";
- }
- static get Version() {
- return "7.54.3";
- }
- getRenderingCanvas() {
- return this._renderingCanvas;
- }
- getAudioContext() {
- return this._audioContext;
- }
- getAudioDestination() {
- return this._audioDestination;
- }
- setHardwareScalingLevel(level) {
- this._hardwareScalingLevel = level;
- this.resize();
- }
- getHardwareScalingLevel() {
- return this._hardwareScalingLevel;
- }
- get doNotHandleContextLost() {
- return this._doNotHandleContextLost;
- }
- set doNotHandleContextLost(value) {
- this._doNotHandleContextLost = value;
- }
- get isStencilEnable() {
- return this._isStencilEnable;
- }
- getCreationOptions() {
- return this._creationOptions;
- }
- constructor(antialias, options, adaptToDeviceRatio) {
- this._colorWrite = true;
- this._colorWriteChanged = true;
- this._depthCullingState = new DepthCullingState;
- this._stencilStateComposer = new StencilStateComposer;
- this._stencilState = new StencilState;
- this._alphaState = new AlphaState;
- this._alphaMode = 1;
- this._alphaEquation = 0;
- this._activeRequests = [];
- this._badOS = false;
- this._badDesktopOS = false;
- this._compatibilityMode = true;
- this._internalTexturesCache = new Array;
- this._currentRenderTarget = null;
- this._boundTexturesCache = {};
- this._activeChannel = 0;
- this._currentTextureChannel = -1;
- this._viewportCached = { x: 0, y: 0, z: 0, w: 0 };
- this._isWebGPU = false;
- this.onCanvasBlurObservable = new Observable;
- this.onCanvasFocusObservable = new Observable;
- this.onNewSceneAddedObservable = new Observable;
- this.onResizeObservable = new Observable;
- this.onCanvasPointerOutObservable = new Observable;
- this.onEffectErrorObservable = new Observable;
- this.disablePerformanceMonitorInBackground = false;
- this.disableVertexArrayObjects = false;
- this._frameId = 0;
- this.hostInformation = {
- isMobile: false
- };
- this.isFullscreen = false;
- this.enableOfflineSupport = false;
- this.disableManifestCheck = false;
- this.disableContextMenu = true;
- this.currentRenderPassId = 0;
- this.isPointerLock = false;
- this.postProcesses = [];
- this.canvasTabIndex = 1;
- this._contextWasLost = false;
- this._useReverseDepthBuffer = false;
- this.isNDCHalfZRange = false;
- this.hasOriginBottomLeft = true;
- this._renderTargetWrapperCache = new Array;
- this._compiledEffects = {};
- this._isDisposed = false;
- this.scenes = [];
- this._virtualScenes = new Array;
- this.onBeforeTextureInitObservable = new Observable;
- this.renderEvenInBackground = true;
- this.preventCacheWipeBetweenFrames = false;
- this._frameHandler = 0;
- this._activeRenderLoops = new Array;
- this._windowIsBackground = false;
- this._boundRenderFunction = (timestamp) => this._renderLoop(timestamp);
- this._lastFrameTime = 0;
- this.skipFrameRender = false;
- this.onBeforeShaderCompilationObservable = new Observable;
- this.onAfterShaderCompilationObservable = new Observable;
- this.onBeginFrameObservable = new Observable;
- this.onEndFrameObservable = new Observable;
- this._transformTextureUrl = null;
- this._uniformBuffers = new Array;
- this._storageBuffers = new Array;
- this._highPrecisionShadersAllowed = true;
- this.onContextLostObservable = new Observable;
- this.onContextRestoredObservable = new Observable;
- this._name = "";
- this.premultipliedAlpha = true;
- this.adaptToDeviceRatio = false;
- this._lastDevicePixelRatio = 1;
- this._doNotHandleContextLost = false;
- this.cullBackFaces = null;
- this._renderPassNames = ["main"];
- this._fps = 60;
- this._deltaTime = 0;
- this._deterministicLockstep = false;
- this._lockstepMaxSteps = 4;
- this._timeStep = 1 / 60;
- this.onDisposeObservable = new Observable;
- 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) {
- this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
- this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
- }
- 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 : 1;
- const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
- adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false;
- this._hardwareScalingLevel = adaptToDeviceRatio ? 1 / Math.min(limitDeviceRatio, devicePixelRatio) : 1;
- this._lastDevicePixelRatio = devicePixelRatio;
- this._creationOptions = options;
- }
- resize(forceSetSize = false) {
- let width;
- let height;
- if (this.adaptToDeviceRatio) {
- const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1 : 1;
- const changeRatio = this._lastDevicePixelRatio / devicePixelRatio;
- this._lastDevicePixelRatio = devicePixelRatio;
- this._hardwareScalingLevel *= changeRatio;
- }
- if (IsWindowObjectExist() && IsDocumentAvailable()) {
- 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);
- }
- 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;
- }
- createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type, creationFlags, useSRGBBuffer) {
- throw _WarnImport("engine.rawTexture");
- }
- createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
- throw _WarnImport("engine.rawTexture");
- }
- createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) {
- throw _WarnImport("engine.rawTexture");
- }
- createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) {
- throw _WarnImport("engine.rawTexture");
- }
- _sharedInit(canvas) {
- this._renderingCanvas = canvas;
- }
- _setupMobileChecks() {
- if (!(navigator && navigator.userAgent)) {
- return;
- }
- this._checkForMobile = () => {
- const currentUA = navigator.userAgent;
- this.hostInformation.isMobile = currentUA.indexOf("Mobile") !== -1 || currentUA.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend" in document;
- };
- this._checkForMobile();
- if (IsWindowObjectExist()) {
- window.addEventListener("resize", this._checkForMobile);
- }
- }
- createVideoElement(constraints) {
- return document.createElement("video");
- }
- _reportDrawCall(numDrawCalls = 1) {
- this._drawCalls?.addCount(numDrawCalls, false);
- }
- getFps() {
- return this._fps;
- }
- getDeltaTime() {
- return this._deltaTime;
- }
- isDeterministicLockStep() {
- return this._deterministicLockstep;
- }
- getLockstepMaxSteps() {
- return this._lockstepMaxSteps;
- }
- getTimeStep() {
- return this._timeStep * 1000;
- }
- _createImageBitmapFromSource(imageSource, options) {
- throw new Error("createImageBitmapFromSource is not implemented");
- }
- createImageBitmap(image, options) {
- return createImageBitmap(image, options);
- }
- resizeImageBitmap(image, bufferWidth, bufferHeight) {
- throw new Error("resizeImageBitmap is not implemented");
- }
- 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;
- }
- createCanvas(width, height) {
- return AbstractEngine._CreateCanvas(width, height);
- }
- static _FileToolsLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions, engine) {
- throw _WarnImport("FileTools");
- }
- _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;
- }
- static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
- if (EngineFunctionContext.loadFile) {
- return EngineFunctionContext.loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
- }
- throw _WarnImport("FileTools");
- }
- dispose() {
- this.releaseEffects();
- this._isDisposed = true;
- this.stopRenderLoop();
- if (this._emptyTexture) {
- this._releaseTexture(this._emptyTexture);
- this._emptyTexture = null;
- }
- if (this._emptyCubeTexture) {
- this._releaseTexture(this._emptyCubeTexture);
- this._emptyCubeTexture = null;
- }
- this._renderingCanvas = null;
- if (this.onBeforeTextureInitObservable) {
- this.onBeforeTextureInitObservable.clear();
- }
- while (this.postProcesses.length) {
- this.postProcesses[0].dispose();
- }
- while (this.scenes.length) {
- this.scenes[0].dispose();
- }
- while (this._virtualScenes.length) {
- this._virtualScenes[0].dispose();
- }
- this.releaseComputeEffects?.();
- Effect.ResetCache();
- 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);
- }
- const index = EngineStore.Instances.indexOf(this);
- if (index >= 0) {
- EngineStore.Instances.splice(index, 1);
- }
- if (!EngineStore.Instances.length) {
- EngineStore.OnEnginesDisposedObservable.notifyObservers(this);
- EngineStore.OnEnginesDisposedObservable.clear();
- }
- this.onBeginFrameObservable.clear();
- this.onEndFrameObservable.clear();
- }
- static DefaultLoadingScreenFactory(canvas) {
- throw _WarnImport("LoadingScreen");
- }
- 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);
- }
- }
- }
-}
-var init_abstractEngine = __esm(() => {
- init_engineStore();
- init_logger();
- init_effect();
- init_performanceConfigurator();
- init_precisionDate();
- init_stencilState();
- init_devTools();
- init_internalTexture();
- init_domManagement();
- init_observable();
- init_abstractEngine_functions();
- init_textureLoaderManager();
- AbstractEngine._RenderPassIdCounter = 0;
- AbstractEngine._RescalePostProcessFactory = null;
- AbstractEngine.CollisionsEpsilon = 0.001;
- AbstractEngine.QueueNewFrame = QueueNewFrame;
-});
-
-// node_modules/@babylonjs/core/Misc/fileTools.js
-function DecodeBase64UrlToBinary(uri) {
- return DecodeBase64ToBinary(uri.split(",")[1]);
-}
-var Base64DataUrlRegEx, LoadFileError, RequestFileError, ReadFileError, CleanUrl = (url) => {
- url = url.replace(/#/gm, "%23");
- return url;
-}, FileToolsOptions, 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;
- }
- }
- }
-}, LoadImageConfiguration, 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;
- if (LoadImageConfiguration.getRequiredSize) {
- const size = LoadImageConfiguration.getRequiredSize(input);
- if (size.width) {
- img.width = size.width;
- }
- if (size.height) {
- img.height = size.height;
- }
- }
- 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);
- 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 url2 = URL.createObjectURL(blob);
- usingObjectURL = true;
- img.src = url2;
- }, 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) {
- blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
- }
- img.src = blobURL;
- usingObjectURL = true;
- } catch (e) {
- img.src = "";
- }
- return img;
- }
- }
- noOfflineSupport();
- }
- return img;
-}, 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) => {
- onSuccess(e.target["result"]);
- };
- if (onProgress) {
- reader.onprogress = onProgress;
- }
- if (!useArrayBuffer) {
- reader.readAsText(file);
- } else {
- reader.readAsArrayBuffer(file);
- }
- return fileRequest;
-}, 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 (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);
- }
- }
- 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);
-}, 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;
- }
- if (request.readyState === (XMLHttpRequest.DONE || 4)) {
- if (onReadyStateChange) {
- request.removeEventListener("readystatechange", onReadyStateChange);
- }
- if (request.status >= 200 && request.status < 300 || request.status === 0 && (!IsWindowObjectExist() || IsFileURL())) {
- 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) {
- 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);
- };
- if (offlineProvider && offlineProvider.enableSceneOffline) {
- const noOfflineSupport = (request) => {
- if (request && request.status > 400) {
- if (onError) {
- onError(request);
- }
- } else {
- requestFile();
- }
- };
- const loadFromOfflineSupport = () => {
- 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;
-}, IsFileURL = () => {
- return typeof location !== "undefined" && location.protocol === "file:";
-}, IsBase64DataUrl = (uri) => {
- return Base64DataUrlRegEx.test(uri);
-}, 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 };
- }
-}, DecodeBase64UrlToString = (uri) => {
- return DecodeBase64ToString(uri.split(",")[1]);
-}, initSideEffects2 = () => {
- AbstractEngine._FileToolsLoadImage = LoadImage;
- EngineFunctionContext.loadFile = LoadFile;
- _functionContainer.loadFile = LoadFile;
-}, FileTools, _injectLTSFileTools = (DecodeBase64UrlToBinary2, DecodeBase64UrlToString2, FileToolsOptions2, IsBase64DataUrl2, IsFileURL2, LoadFile2, LoadImage2, ReadFile2, RequestFile2, SetCorsBehavior2) => {
- FileTools = {
- DecodeBase64UrlToBinary: DecodeBase64UrlToBinary2,
- DecodeBase64UrlToString: DecodeBase64UrlToString2,
- DefaultRetryStrategy: FileToolsOptions2.DefaultRetryStrategy,
- BaseUrl: FileToolsOptions2.BaseUrl,
- CorsBehavior: FileToolsOptions2.CorsBehavior,
- PreprocessUrl: FileToolsOptions2.PreprocessUrl,
- IsBase64DataUrl: IsBase64DataUrl2,
- IsFileURL: IsFileURL2,
- LoadFile: LoadFile2,
- LoadImage: LoadImage2,
- ReadFile: ReadFile2,
- RequestFile: RequestFile2,
- SetCorsBehavior: SetCorsBehavior2
- };
- Object.defineProperty(FileTools, "DefaultRetryStrategy", {
- get: function() {
- return FileToolsOptions2.DefaultRetryStrategy;
- },
- set: function(value) {
- FileToolsOptions2.DefaultRetryStrategy = value;
- }
- });
- Object.defineProperty(FileTools, "BaseUrl", {
- get: function() {
- return FileToolsOptions2.BaseUrl;
- },
- set: function(value) {
- FileToolsOptions2.BaseUrl = value;
- }
- });
- Object.defineProperty(FileTools, "PreprocessUrl", {
- get: function() {
- return FileToolsOptions2.PreprocessUrl;
- },
- set: function(value) {
- FileToolsOptions2.PreprocessUrl = value;
- }
- });
- Object.defineProperty(FileTools, "CorsBehavior", {
- get: function() {
- return FileToolsOptions2.CorsBehavior;
- },
- set: function(value) {
- FileToolsOptions2.CorsBehavior = value;
- }
- });
-};
-var init_fileTools = __esm(() => {
- init_webRequest();
- init_domManagement();
- init_observable();
- init_filesInputStore();
- init_error();
- init_stringTools();
- init_shaderProcessor();
- init_engineStore();
- init_logger();
- init_timingTools();
- init_abstractEngine_functions();
- init_abstractEngine();
- Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);
- LoadFileError = class LoadFileError extends RuntimeError {
- 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;
- }
- }
- };
- RequestFileError = class RequestFileError extends RuntimeError {
- constructor(message, request) {
- super(message, ErrorCodes.RequestFileError);
- this.request = request;
- this.name = "RequestFileError";
- BaseError._setPrototypeOf(this, RequestFileError.prototype);
- }
- };
- ReadFileError = class ReadFileError extends RuntimeError {
- constructor(message, file) {
- super(message, ErrorCodes.ReadFileError);
- this.file = file;
- this.name = "ReadFileError";
- BaseError._setPrototypeOf(this, ReadFileError.prototype);
- }
- };
- FileToolsOptions = {
- DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),
- BaseUrl: "",
- CorsBehavior: "anonymous",
- PreprocessUrl: (url) => url,
- ScriptBaseUrl: "",
- ScriptPreprocessUrl: (url) => url,
- CleanUrl
- };
- LoadImageConfiguration = {
- getRequiredSize: null
- };
- initSideEffects2();
- _injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);
-});
-
-// node_modules/@babylonjs/core/Misc/tools.js
-class Tools {
- static get BaseUrl() {
- return FileToolsOptions.BaseUrl;
- }
- static set BaseUrl(value) {
- FileToolsOptions.BaseUrl = value;
- }
- static get CleanUrl() {
- return FileToolsOptions.CleanUrl;
- }
- static set CleanUrl(value) {
- FileToolsOptions.CleanUrl = value;
- }
- static IsAbsoluteUrl(url) {
- if (url.indexOf("//") === 0) {
- return true;
- }
- if (url.indexOf("://") === -1) {
- return false;
- }
- if (url.indexOf(".") === -1) {
- return false;
- }
- if (url.indexOf("/") === -1) {
- return false;
- }
- if (url.indexOf(":") > url.indexOf("/")) {
- return false;
- }
- if (url.indexOf("://") < url.indexOf(".")) {
- return true;
- }
- if (url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) {
- return true;
- }
- return false;
- }
- static set ScriptBaseUrl(value) {
- FileToolsOptions.ScriptBaseUrl = value;
- }
- static get ScriptBaseUrl() {
- return FileToolsOptions.ScriptBaseUrl;
- }
- static set CDNBaseUrl(value) {
- Tools.ScriptBaseUrl = value;
- Tools.AssetBaseUrl = value;
- }
- static set ScriptPreprocessUrl(func) {
- FileToolsOptions.ScriptPreprocessUrl = func;
- }
- static get ScriptPreprocessUrl() {
- return FileToolsOptions.ScriptPreprocessUrl;
- }
- static get DefaultRetryStrategy() {
- return FileToolsOptions.DefaultRetryStrategy;
- }
- static set DefaultRetryStrategy(strategy) {
- FileToolsOptions.DefaultRetryStrategy = strategy;
- }
- static get CorsBehavior() {
- return FileToolsOptions.CorsBehavior;
- }
- static set CorsBehavior(value) {
- FileToolsOptions.CorsBehavior = value;
- }
- static get UseFallbackTexture() {
- return EngineStore.UseFallbackTexture;
- }
- static set UseFallbackTexture(value) {
- EngineStore.UseFallbackTexture = value;
- }
- static get RegisteredExternalClasses() {
- return InstantiationTools.RegisteredExternalClasses;
- }
- static set RegisteredExternalClasses(classes) {
- InstantiationTools.RegisteredExternalClasses = classes;
- }
- static get fallbackTexture() {
- return EngineStore.FallbackTexture;
- }
- static set fallbackTexture(value) {
- EngineStore.FallbackTexture = value;
- }
- 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;
- }
- static Mix(a, b, alpha) {
- return 0;
- }
- static Instantiate(className) {
- return InstantiationTools.Instantiate(className);
- }
- static SetImmediate(action2) {
- TimingTools.SetImmediate(action2);
- }
- static IsExponentOfTwo(value) {
- return true;
- }
- static FloatRound(value) {
- return Math.fround(value);
- }
- static GetFilename(path) {
- const index = path.lastIndexOf("/");
- if (index < 0) {
- return path;
- }
- return path.substring(index + 1);
- }
- static GetFolderPath(uri, returnUnchangedIfNoSlash = false) {
- const index = uri.lastIndexOf("/");
- if (index < 0) {
- if (returnUnchangedIfNoSlash) {
- return uri;
- }
- return "";
- }
- return uri.substring(0, index + 1);
- }
- static ToDegrees(angle) {
- return angle * 180 / Math.PI;
- }
- static ToRadians(angle) {
- return angle * Math.PI / 180;
- }
- 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)));
- }
- static MakeArray(obj, allowsNullUndefined) {
- if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
- return null;
- }
- return Array.isArray(obj) ? obj : [obj];
- }
- static GetPointerPrefix(engine) {
- return IsWindowObjectExist() && !window.PointerEvent ? "mouse" : "pointer";
- }
- static SetCorsBehavior(url, element) {
- SetCorsBehavior(url, element);
- }
- static SetReferrerPolicyBehavior(referrerPolicy, element) {
- element.referrerPolicy = referrerPolicy;
- }
- static get PreprocessUrl() {
- return FileToolsOptions.PreprocessUrl;
- }
- static set PreprocessUrl(processor) {
- FileToolsOptions.PreprocessUrl = processor;
- }
- static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) {
- return LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions);
- }
- static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
- return LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
- }
- static LoadFileAsync(url, useArrayBuffer = true) {
- return new Promise((resolve3, reject) => {
- LoadFile(url, (data) => {
- resolve3(data);
- }, undefined, undefined, useArrayBuffer, (request, exception) => {
- reject(exception);
- });
- });
- }
- static GetAssetUrl(url) {
- if (!url) {
- return "";
- }
- if (Tools.AssetBaseUrl && url.startsWith(Tools._DefaultAssetsUrl)) {
- 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;
- }
- static GetBabylonScriptURL(scriptUrl, forceAbsoluteUrl) {
- if (!scriptUrl) {
- return "";
- }
- if (Tools.ScriptBaseUrl && scriptUrl.startsWith(Tools._DefaultCdnUrl)) {
- const baseUrl = Tools.ScriptBaseUrl[Tools.ScriptBaseUrl.length - 1] === "/" ? Tools.ScriptBaseUrl.substring(0, Tools.ScriptBaseUrl.length - 1) : Tools.ScriptBaseUrl;
- scriptUrl = scriptUrl.replace(Tools._DefaultCdnUrl, baseUrl);
- }
- scriptUrl = Tools.ScriptPreprocessUrl(scriptUrl);
- if (forceAbsoluteUrl) {
- scriptUrl = Tools.GetAbsoluteUrl(scriptUrl);
- }
- return scriptUrl;
- }
- static LoadBabylonScript(scriptUrl, onSuccess, onError, scriptId) {
- scriptUrl = Tools.GetBabylonScriptURL(scriptUrl);
- Tools.LoadScript(scriptUrl, onSuccess, onError);
- }
- static LoadBabylonScriptAsync(scriptUrl) {
- scriptUrl = Tools.GetBabylonScriptURL(scriptUrl);
- return Tools.LoadScriptAsync(scriptUrl);
- }
- 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);
- }
- static LoadScriptAsync(scriptUrl, scriptId) {
- return new Promise((resolve3, reject) => {
- this.LoadScript(scriptUrl, () => {
- resolve3();
- }, (message, exception) => {
- reject(exception || new Error(message));
- }, scriptId);
- });
- }
- 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) => {
- callback(e.target["result"]);
- };
- reader.onprogress = progressCallback;
- reader.readAsDataURL(fileToLoad);
- return request;
- }
- static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) {
- return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
- }
- static FileAsURL(content) {
- const fileBlob = new Blob([content]);
- const url = window.URL;
- const link = url.createObjectURL(fileBlob);
- return link;
- }
- static Format(value, decimals = 2) {
- return value.toFixed(decimals);
- }
- static DeepCopy(source, destination, doNotCopyList, mustCopyList) {
- DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
- }
- static IsEmpty(obj) {
- for (const i in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, i)) {
- return false;
- }
- }
- return true;
- }
- 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) {}
- }
- }
- 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) {}
- }
- }
- static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) {
- throw _WarnImport("DumpTools");
- }
- static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer3 = false, quality) {
- throw _WarnImport("DumpTools");
- }
- static DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer3 = false, quality) {
- throw _WarnImport("DumpTools");
- }
- static _IsOffScreenCanvas(canvas) {
- return canvas.convertToBlob !== undefined;
- }
- static ToBlob(canvas, successCallback, mimeType = "image/png", quality) {
- if (!Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) {
- canvas.toBlob = function(callback, type, quality2) {
- setTimeout(() => {
- const binStr = atob(this.toDataURL(type, quality2).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);
- }
- }
- static DownloadBlob(blob, fileName) {
- 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() {
- URL.revokeObjectURL(url);
- };
- img.src = url;
- newWindow.document.body.appendChild(img);
- }
- }
- }
- 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);
- }
- }
- 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);
- }
- static BackCompatCameraNoPreventDefault(args) {
- if (typeof args[0] === "boolean") {
- return args[0];
- } else if (typeof args[1] === "boolean") {
- return args[1];
- }
- return false;
- }
- static CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) {
- throw _WarnImport("ScreenshotTools");
- }
- static CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) {
- throw _WarnImport("ScreenshotTools");
- }
- 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");
- }
- static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) {
- throw _WarnImport("ScreenshotTools");
- }
- static RandomId() {
- return RandomGUID();
- }
- static IsBase64(uri) {
- return IsBase64DataUrl(uri);
- }
- static DecodeBase64(uri) {
- return DecodeBase64UrlToBinary(uri);
- }
- static get errorsCount() {
- return Logger.errorsCount;
- }
- static Log(message) {
- Logger.Log(message);
- }
- static Warn(message) {
- Logger.Warn(message);
- }
- static Error(message) {
- Logger.Error(message);
- }
- static get LogCache() {
- return Logger.LogCache;
- }
- static ClearLogCache() {
- Logger.ClearLogCache();
- }
- static set LogLevels(level) {
- Logger.LogLevels = 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;
- }
- static _StartPerformanceCounterDisabled(counterName, condition2) {}
- static _EndPerformanceCounterDisabled(counterName, condition2) {}
- static _StartUserMark(counterName, condition2 = true) {
- if (!Tools._Performance) {
- if (!IsWindowObjectExist()) {
- return;
- }
- Tools._Performance = window.performance;
- }
- if (!condition2 || !Tools._Performance.mark) {
- return;
- }
- Tools._Performance.mark(counterName + "-Begin");
- }
- static _EndUserMark(counterName, condition2 = true) {
- if (!condition2 || !Tools._Performance.mark) {
- return;
- }
- Tools._Performance.mark(counterName + "-End");
- Tools._Performance.measure(counterName, counterName + "-Begin", counterName + "-End");
- }
- static _StartPerformanceConsole(counterName, condition2 = true) {
- if (!condition2) {
- return;
- }
- Tools._StartUserMark(counterName, condition2);
- if (console.time) {
- console.time(counterName);
- }
- }
- static _EndPerformanceConsole(counterName, condition2 = true) {
- if (!condition2) {
- return;
- }
- Tools._EndUserMark(counterName, condition2);
- console.timeEnd(counterName);
- }
- static get Now() {
- return PrecisionDate.Now;
- }
- static GetClassName(object, isType = false) {
- let name18 = null;
- if (!isType && object.getClassName) {
- name18 = object.getClassName();
- } else {
- if (object instanceof Object) {
- const classObj = isType ? object : Object.getPrototypeOf(object);
- name18 = classObj.constructor["__bjsclassName__"];
- }
- if (!name18) {
- name18 = typeof object;
- }
- }
- return name18;
- }
- static First(array, predicate) {
- for (const el of array) {
- if (predicate(el)) {
- return el;
- }
- }
- return null;
- }
- 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;
- }
- static DelayAsync(delay) {
- return new Promise((resolve3) => {
- setTimeout(() => {
- resolve3();
- }, delay);
- });
- }
- static IsSafari() {
- if (!IsNavigatorAvailable()) {
- return false;
- }
- return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
- }
-}
-
-class AsyncLoop {
- constructor(iterations, func, successCallback, offset = 0) {
- this.iterations = iterations;
- this.index = offset - 1;
- this._done = false;
- this._fn = func;
- this._successCallback = successCallback;
- }
- executeNext() {
- if (!this._done) {
- if (this.index + 1 < this.iterations) {
- ++this.index;
- this._fn(this);
- } else {
- this.breakLoop();
- }
- }
- }
- breakLoop() {
- this._done = true;
- this._successCallback();
- }
- static Run(iterations, fn, successCallback, offset = 0) {
- const loop = new AsyncLoop(iterations, fn, successCallback, offset);
- loop.executeNext();
- return loop;
- }
- 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);
- }
-}
-var init_tools = __esm(() => {
- init_observable();
- init_domManagement();
- init_logger();
- init_deepCopier();
- init_precisionDate();
- init_devTools();
- init_webRequest();
- init_engineStore();
- init_fileTools();
- init_timingTools();
- init_instantiationTools();
- init_guid();
- Tools.AssetBaseUrl = "";
- Tools.UseCustomRequestHeaders = false;
- Tools.CustomRequestHeaders = WebRequest.CustomRequestHeaders;
- Tools.GetDOMTextContent = GetDOMTextContent;
- Tools._DefaultCdnUrl = "https://cdn.babylonjs.com";
- Tools._DefaultAssetsUrl = "https://assets.babylonjs.com/core";
- 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.");
- };
- Tools.NoneLogLevel = Logger.NoneLogLevel;
- Tools.MessageLogLevel = Logger.MessageLogLevel;
- Tools.WarningLogLevel = Logger.WarningLogLevel;
- Tools.ErrorLogLevel = Logger.ErrorLogLevel;
- Tools.AllLogLevel = Logger.AllLogLevel;
- Tools.IsWindowObjectExist = IsWindowObjectExist;
- Tools.PerformanceNoneLogLevel = 0;
- Tools.PerformanceUserMarkLogLevel = 1;
- Tools.PerformanceConsoleLogLevel = 2;
- Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
- Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
- Tools.Mix = Mix;
- Tools.IsExponentOfTwo = IsExponentOfTwo;
- 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";
-});
-
-// node_modules/@babylonjs/core/Misc/stringDictionary.js
-class StringDictionary {
- constructor() {
- this._count = 0;
- this._data = {};
- }
- copyFrom(source) {
- this.clear();
- source.forEach((t, v) => this.add(t, v));
- }
- get(key) {
- const val = this._data[key];
- if (val !== undefined) {
- return val;
- }
- return;
- }
- getOrAddWithFactory(key, factory) {
- let val = this.get(key);
- if (val !== undefined) {
- return val;
- }
- val = factory(key);
- if (val) {
- this.add(key, val);
- }
- return val;
- }
- getOrAdd(key, val) {
- const curVal = this.get(key);
- if (curVal !== undefined) {
- return curVal;
- }
- this.add(key, val);
- return val;
- }
- contains(key) {
- return this._data[key] !== undefined;
- }
- add(key, value) {
- if (this._data[key] !== undefined) {
- return false;
- }
- this._data[key] = value;
- ++this._count;
- return true;
- }
- set(key, value) {
- if (this._data[key] === undefined) {
- return false;
- }
- this._data[key] = value;
- return true;
- }
- getAndRemove(key) {
- const val = this.get(key);
- if (val !== undefined) {
- delete this._data[key];
- --this._count;
- return val;
- }
- return null;
- }
- remove(key) {
- if (this.contains(key)) {
- delete this._data[key];
- --this._count;
- return true;
- }
- return false;
- }
- clear() {
- this._data = {};
- this._count = 0;
- }
- get count() {
- return this._count;
- }
- forEach(callback) {
- for (const cur in this._data) {
- const val = this._data[cur];
- callback(cur, val);
- }
- }
- first(callback) {
- for (const cur in this._data) {
- const val = this._data[cur];
- const res = callback(cur, val);
- if (res) {
- return res;
- }
- }
- return null;
- }
-}
-
-// node_modules/@babylonjs/core/Materials/colorCurves.functions.js
-function PrepareUniformsForColorCurves(uniformsList) {
- uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
-}
-
-// node_modules/@babylonjs/core/Materials/colorCurves.js
-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;
- }
- get globalHue() {
- return this._globalHue;
- }
- set globalHue(value) {
- this._globalHue = value;
- this._dirty = true;
- }
- get globalDensity() {
- return this._globalDensity;
- }
- set globalDensity(value) {
- this._globalDensity = value;
- this._dirty = true;
- }
- get globalSaturation() {
- return this._globalSaturation;
- }
- set globalSaturation(value) {
- this._globalSaturation = value;
- this._dirty = true;
- }
- get globalExposure() {
- return this._globalExposure;
- }
- set globalExposure(value) {
- this._globalExposure = value;
- this._dirty = true;
- }
- get highlightsHue() {
- return this._highlightsHue;
- }
- set highlightsHue(value) {
- this._highlightsHue = value;
- this._dirty = true;
- }
- get highlightsDensity() {
- return this._highlightsDensity;
- }
- set highlightsDensity(value) {
- this._highlightsDensity = value;
- this._dirty = true;
- }
- get highlightsSaturation() {
- return this._highlightsSaturation;
- }
- set highlightsSaturation(value) {
- this._highlightsSaturation = value;
- this._dirty = true;
- }
- get highlightsExposure() {
- return this._highlightsExposure;
- }
- set highlightsExposure(value) {
- this._highlightsExposure = value;
- this._dirty = true;
- }
- get midtonesHue() {
- return this._midtonesHue;
- }
- set midtonesHue(value) {
- this._midtonesHue = value;
- this._dirty = true;
- }
- get midtonesDensity() {
- return this._midtonesDensity;
- }
- set midtonesDensity(value) {
- this._midtonesDensity = value;
- this._dirty = true;
- }
- get midtonesSaturation() {
- return this._midtonesSaturation;
- }
- set midtonesSaturation(value) {
- this._midtonesSaturation = value;
- this._dirty = true;
- }
- get midtonesExposure() {
- return this._midtonesExposure;
- }
- set midtonesExposure(value) {
- this._midtonesExposure = value;
- this._dirty = true;
- }
- get shadowsHue() {
- return this._shadowsHue;
- }
- set shadowsHue(value) {
- this._shadowsHue = value;
- this._dirty = true;
- }
- get shadowsDensity() {
- return this._shadowsDensity;
- }
- set shadowsDensity(value) {
- this._shadowsDensity = value;
- this._dirty = true;
- }
- get shadowsSaturation() {
- return this._shadowsSaturation;
- }
- set shadowsSaturation(value) {
- this._shadowsSaturation = value;
- this._dirty = true;
- }
- get shadowsExposure() {
- return this._shadowsExposure;
- }
- set shadowsExposure(value) {
- this._shadowsExposure = value;
- this._dirty = true;
- }
- getClassName() {
- return "ColorCurves";
- }
- static Bind(colorCurves, effect, positiveUniform = "vCameraColorCurvePositive", neutralUniform = "vCameraColorCurveNeutral", negativeUniform = "vCameraColorCurveNegative") {
- if (colorCurves._dirty) {
- colorCurves._dirty = false;
- colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
- colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
- colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
- colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
- colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
- 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);
- }
- }
- _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);
- 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;
- }
- static _ApplyColorGradingSliderNonlinear(value) {
- value /= 100;
- let x = Math.abs(value);
- x = Math.pow(x, 2);
- if (value < 0) {
- x *= -1;
- }
- x *= 100;
- return x;
- }
- 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 {
- h /= 60;
- const i = Math.floor(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:
- result.r = v;
- result.g = p;
- result.b = q;
- break;
- }
- }
- result.a = 1;
- }
- static _Clamp(value, min, max) {
- return Math.min(Math.max(value, min), max);
- }
- clone() {
- return SerializationHelper.Clone(() => new ColorCurves, this);
- }
- serialize() {
- return SerializationHelper.Serialize(this);
- }
- static Parse(source) {
- return SerializationHelper.Parse(() => new ColorCurves, source, null, null);
- }
-}
-var init_colorCurves = __esm(() => {
- init_tslib_es6();
- init_decorators();
- init_math_color();
- init_decorators_serialization();
- ColorCurves.PrepareUniforms = PrepareUniformsForColorCurves;
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_globalHue", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_globalDensity", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_globalSaturation", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_globalExposure", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_highlightsHue", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_highlightsDensity", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_highlightsSaturation", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_highlightsExposure", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_midtonesHue", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_midtonesDensity", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_midtonesSaturation", undefined);
- __decorate([
- serialize()
- ], ColorCurves.prototype, "_midtonesExposure", undefined);
- SerializationHelper._ColorCurvesParser = ColorCurves.Parse;
-});
-
-// node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.functions.js
-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");
- }
-}
-function PrepareSamplersForImageProcessing(samplersList, defines) {
- if (defines.COLORGRADING) {
- samplersList.push("txColorTransform");
- }
-}
-var init_imageProcessingConfiguration_functions = () => {};
-
-// node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js
-class ImageProcessingConfiguration {
- constructor() {
- this.colorCurves = new ColorCurves;
- this._colorCurvesEnabled = false;
- this._colorGradingEnabled = false;
- this._colorGradingWithGreenDepth = true;
- this._colorGradingBGR = true;
- this._exposure = 1;
- this._toneMappingEnabled = false;
- this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
- this._contrast = 1;
- this.vignetteStretch = 0;
- this.vignetteCenterX = 0;
- this.vignetteCenterY = 0;
- this.vignetteWeight = 1.5;
- this.vignetteColor = new Color4(0, 0, 0, 0);
- this.vignetteCameraFov = 0.5;
- this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
- this._vignetteEnabled = false;
- this._ditheringEnabled = false;
- this._ditheringIntensity = 1 / 255;
- this._skipFinalColorClamp = false;
- this._applyByPostProcess = false;
- this._isEnabled = true;
- this.onUpdateParameters = new Observable;
- }
- get colorCurvesEnabled() {
- return this._colorCurvesEnabled;
- }
- set colorCurvesEnabled(value) {
- if (this._colorCurvesEnabled === value) {
- return;
- }
- this._colorCurvesEnabled = value;
- this._updateParameters();
- }
- get colorGradingTexture() {
- return this._colorGradingTexture;
- }
- set colorGradingTexture(value) {
- if (this._colorGradingTexture === value) {
- return;
- }
- this._colorGradingTexture = value;
- this._updateParameters();
- }
- get colorGradingEnabled() {
- return this._colorGradingEnabled;
- }
- set colorGradingEnabled(value) {
- if (this._colorGradingEnabled === value) {
- return;
- }
- this._colorGradingEnabled = value;
- this._updateParameters();
- }
- get colorGradingWithGreenDepth() {
- return this._colorGradingWithGreenDepth;
- }
- set colorGradingWithGreenDepth(value) {
- if (this._colorGradingWithGreenDepth === value) {
- return;
- }
- this._colorGradingWithGreenDepth = value;
- this._updateParameters();
- }
- get colorGradingBGR() {
- return this._colorGradingBGR;
- }
- set colorGradingBGR(value) {
- if (this._colorGradingBGR === value) {
- return;
- }
- this._colorGradingBGR = value;
- this._updateParameters();
- }
- get exposure() {
- return this._exposure;
- }
- set exposure(value) {
- if (this._exposure === value) {
- return;
- }
- this._exposure = value;
- this._updateParameters();
- }
- get toneMappingEnabled() {
- return this._toneMappingEnabled;
- }
- set toneMappingEnabled(value) {
- if (this._toneMappingEnabled === value) {
- return;
- }
- this._toneMappingEnabled = value;
- this._updateParameters();
- }
- get toneMappingType() {
- return this._toneMappingType;
- }
- set toneMappingType(value) {
- if (this._toneMappingType === value) {
- return;
- }
- this._toneMappingType = value;
- this._updateParameters();
- }
- get contrast() {
- return this._contrast;
- }
- set contrast(value) {
- if (this._contrast === value) {
- return;
- }
- this._contrast = value;
- this._updateParameters();
- }
- get vignetteCentreY() {
- return this.vignetteCenterY;
- }
- set vignetteCentreY(value) {
- this.vignetteCenterY = value;
- }
- get vignetteCentreX() {
- return this.vignetteCenterX;
- }
- set vignetteCentreX(value) {
- this.vignetteCenterX = value;
- }
- get vignetteBlendMode() {
- return this._vignetteBlendMode;
- }
- set vignetteBlendMode(value) {
- if (this._vignetteBlendMode === value) {
- return;
- }
- this._vignetteBlendMode = value;
- this._updateParameters();
- }
- get vignetteEnabled() {
- return this._vignetteEnabled;
- }
- set vignetteEnabled(value) {
- if (this._vignetteEnabled === value) {
- return;
- }
- this._vignetteEnabled = value;
- this._updateParameters();
- }
- get ditheringEnabled() {
- return this._ditheringEnabled;
- }
- set ditheringEnabled(value) {
- if (this._ditheringEnabled === value) {
- return;
- }
- this._ditheringEnabled = value;
- this._updateParameters();
- }
- get ditheringIntensity() {
- return this._ditheringIntensity;
- }
- set ditheringIntensity(value) {
- if (this._ditheringIntensity === value) {
- return;
- }
- this._ditheringIntensity = value;
- this._updateParameters();
- }
- get skipFinalColorClamp() {
- return this._skipFinalColorClamp;
- }
- set skipFinalColorClamp(value) {
- if (this._skipFinalColorClamp === value) {
- return;
- }
- this._skipFinalColorClamp = value;
- this._updateParameters();
- }
- get applyByPostProcess() {
- return this._applyByPostProcess;
- }
- set applyByPostProcess(value) {
- if (this._applyByPostProcess === value) {
- return;
- }
- this._applyByPostProcess = value;
- this._updateParameters();
- }
- get isEnabled() {
- return this._isEnabled;
- }
- set isEnabled(value) {
- if (this._isEnabled === value) {
- return;
- }
- this._isEnabled = value;
- this._updateParameters();
- }
- _updateParameters() {
- this.onUpdateParameters.notifyObservers(this);
- }
- getClassName() {
- return "ImageProcessingConfiguration";
- }
- 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;
- defines.EXPOSURE = this.exposure !== 1;
- 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;
- }
- isReady() {
- return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
- }
- bind(effect, overrideAspectRatio) {
- if (this._colorCurvesEnabled && this.colorCurves) {
- ColorCurves.Bind(this.colorCurves, effect);
- }
- 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);
- }
- }
- effect.setFloat("exposureLinear", this.exposure);
- effect.setFloat("contrast", this.contrast);
- if (this.colorGradingTexture) {
- effect.setTexture("txColorTransform", this.colorGradingTexture);
- const textureSize = this.colorGradingTexture.getSize().height;
- effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, 0.5 / textureSize, textureSize, this.colorGradingTexture.level);
- }
- }
- clone() {
- return SerializationHelper.Clone(() => new ImageProcessingConfiguration, this);
- }
- serialize() {
- return SerializationHelper.Serialize(this);
- }
- static Parse(source) {
- const parsed = SerializationHelper.Parse(() => new ImageProcessingConfiguration, source, null, null);
- if (source.vignetteCentreX !== undefined) {
- parsed.vignetteCenterX = source.vignetteCentreX;
- }
- if (source.vignetteCentreY !== undefined) {
- parsed.vignetteCenterY = source.vignetteCentreY;
- }
- return parsed;
- }
- static get VIGNETTEMODE_MULTIPLY() {
- return this._VIGNETTEMODE_MULTIPLY;
- }
- static get VIGNETTEMODE_OPAQUE() {
- return this._VIGNETTEMODE_OPAQUE;
- }
-}
-var init_imageProcessingConfiguration = __esm(() => {
- init_tslib_es6();
- init_decorators();
- init_observable();
- init_math_color();
- init_colorCurves();
- init_decorators_serialization();
- init_imageProcessingConfiguration_functions();
- init_typeStore();
- ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
- ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
- ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL = 2;
- ImageProcessingConfiguration.PrepareUniforms = PrepareUniformsForImageProcessing;
- ImageProcessingConfiguration.PrepareSamplers = PrepareSamplersForImageProcessing;
- ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
- ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
- __decorate([
- serializeAsColorCurves()
- ], ImageProcessingConfiguration.prototype, "colorCurves", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", undefined);
- __decorate([
- serializeAsTexture("colorGradingTexture")
- ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_exposure", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_toneMappingType", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_contrast", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteStretch", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCenterX", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCenterY", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteWeight", undefined);
- __decorate([
- serializeAsColor4()
- ], ImageProcessingConfiguration.prototype, "vignetteColor", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_ditheringEnabled", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_ditheringIntensity", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_skipFinalColorClamp", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", undefined);
- __decorate([
- serialize()
- ], ImageProcessingConfiguration.prototype, "_isEnabled", undefined);
- SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;
- RegisterClass("BABYLON.ImageProcessingConfiguration", ImageProcessingConfiguration);
-});
-
-// node_modules/@babylonjs/core/Materials/uniformBuffer.js
-class UniformBuffer {
- constructor(engine, data, dynamic, name18, forceNoUniformBuffer = false) {
- this._valueCache = {};
- this._engine = engine;
- this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer;
- this._dynamic = dynamic;
- this._name = name18 ?? "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;
- }
- }
- get useUbo() {
- return !this._noUBO;
- }
- get isSync() {
- return !this._needSync;
- }
- isDynamic() {
- return this._dynamic !== undefined;
- }
- getData() {
- return this._bufferData;
- }
- getBuffer() {
- return this._buffer;
- }
- _fillAlignment(size) {
- 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);
- }
- }
- }
- addUniform(name18, size, arraySize = 0) {
- if (this._noUBO) {
- return;
- }
- if (this._uniformLocations[name18] !== undefined) {
- return;
- }
- let data;
- if (arraySize > 0) {
- if (size instanceof Array) {
- throw "addUniform should not be use with Array in UBO: " + name18;
- }
- this._fillAlignment(4);
- this._uniformArraySizes[name18] = { strideSize: size, arraySize };
- if (size == 16) {
- size = size * arraySize;
- } else {
- const perElementPadding = 4 - size;
- const totalPadding = perElementPadding * arraySize;
- size = size * arraySize + totalPadding;
- }
- data = [];
- for (let i = 0;i < size; i++) {
- data.push(0);
- }
- } else {
- if (size instanceof Array) {
- data = size;
- size = data.length;
- } else {
- size = size;
- data = [];
- for (let i = 0;i < size; i++) {
- data.push(0);
- }
- }
- this._fillAlignment(size);
- }
- this._uniformSizes[name18] = size;
- this._uniformLocations[name18] = this._uniformLocationPointer;
- this._uniformLocationPointer += size;
- for (let i = 0;i < size; i++) {
- this._data.push(data[i]);
- }
- this._needSync = true;
- }
- addMatrix(name18, mat) {
- this.addUniform(name18, Array.prototype.slice.call(mat.asArray()));
- }
- addFloat2(name18, x, y) {
- const temp = [x, y];
- this.addUniform(name18, temp);
- }
- addFloat3(name18, x, y, z) {
- const temp = [x, y, z];
- this.addUniform(name18, temp);
- }
- addColor3(name18, color) {
- const temp = [color.r, color.g, color.b];
- this.addUniform(name18, temp);
- }
- addColor4(name18, color, alpha) {
- const temp = [color.r, color.g, color.b, alpha];
- this.addUniform(name18, temp);
- }
- addVector3(name18, vector) {
- const temp = [vector.x, vector.y, vector.z];
- this.addUniform(name18, temp);
- }
- addMatrix3x3(name18) {
- this.addUniform(name18, 12);
- }
- addMatrix2x2(name18) {
- this.addUniform(name18, 8);
- }
- create() {
- if (this._noUBO) {
- return;
- }
- if (this._buffer) {
- return;
- }
- this._fillAlignment(4);
- this._bufferData = new Float32Array(this._data);
- this._rebuild();
- this._needSync = true;
- }
- _getNames() {
- const names = [];
- let i = 0;
- for (const name18 in this._uniformLocations) {
- names.push(name18);
- if (++i === 10) {
- break;
- }
- }
- return names.join(",");
- }
- _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;
- }
- }
- _rebuildAfterContextLost() {
- if (this._engine._features.trackUbosInFrame) {
- this._buffers = [];
- this._currentFrameId = 0;
- }
- this._rebuild();
- }
- get _numBuffers() {
- return this._buffers.length;
- }
- get _indexBuffer() {
- return this._bufferIndex;
- }
- get name() {
- return this._name;
- }
- 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];
- }
- }
- 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;
- }
- }
- }
- updateUniform(uniformName, data, size) {
- this._checkNewFrame();
- let location2 = this._uniformLocations[uniformName];
- if (location2 === undefined) {
- if (this._buffer) {
- Logger.Error("Cannot add an uniform after UBO has been created. uniformName=" + uniformName);
- return;
- }
- this.addUniform(uniformName, size);
- location2 = this._uniformLocations[uniformName];
- }
- if (!this._buffer) {
- this.create();
- }
- if (!this._dynamic) {
- let changed = false;
- for (let i = 0;i < size; i++) {
- if (size === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[location2 + i] !== Math.fround(data[i])) {
- changed = true;
- if (this._createBufferOnWrite) {
- this._createNewBuffer();
- }
- this._bufferData[location2 + i] = data[i];
- }
- }
- this._needSync = this._needSync || changed;
- } else {
- for (let i = 0;i < size; i++) {
- this._bufferData[location2 + i] = data[i];
- }
- }
- }
- updateUniformArray(uniformName, data, size) {
- this._checkNewFrame();
- const location2 = this._uniformLocations[uniformName];
- if (location2 === 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) {
- let changed = false;
- let countToFour = 0;
- let baseStride = 0;
- for (let i = 0;i < size; i++) {
- if (this._bufferData[location2 + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) {
- changed = true;
- if (this._createBufferOnWrite) {
- this._createNewBuffer();
- }
- this._bufferData[location2 + baseStride * 4 + countToFour] = data[i];
- }
- countToFour++;
- if (countToFour === arraySizes.strideSize) {
- for (;countToFour < 4; countToFour++) {
- this._bufferData[location2 + baseStride * 4 + countToFour] = 0;
- }
- countToFour = 0;
- baseStride++;
- }
- }
- this._needSync = this._needSync || changed;
- } else {
- for (let i = 0;i < size; i++) {
- this._bufferData[location2 + i] = data[i];
- }
- }
- }
- _cacheMatrix(name18, matrix) {
- this._checkNewFrame();
- const cache = this._valueCache[name18];
- const flag = matrix.updateFlag;
- if (cache !== undefined && cache === flag) {
- return false;
- }
- this._valueCache[name18] = flag;
- return true;
- }
- _updateMatrix3x3ForUniform(name18, matrix) {
- 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;
- }
- this.updateUniform(name18, UniformBuffer._TempBuffer, 12);
- }
- _updateMatrix3x3ForEffect(name18, matrix) {
- this._currentEffect.setMatrix3x3(name18, matrix);
- }
- _updateMatrix2x2ForEffect(name18, matrix) {
- this._currentEffect.setMatrix2x2(name18, matrix);
- }
- _updateMatrix2x2ForUniform(name18, matrix) {
- 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;
- UniformBuffer._TempBuffer[i * 4 + 3] = 0;
- }
- this.updateUniform(name18, UniformBuffer._TempBuffer, 8);
- }
- _updateFloatForEffect(name18, x) {
- this._currentEffect.setFloat(name18, x);
- }
- _updateFloatForUniform(name18, x) {
- UniformBuffer._TempBuffer[0] = x;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 1);
- }
- _updateFloat2ForEffect(name18, x, y, suffix3 = "") {
- this._currentEffect.setFloat2(name18 + suffix3, x, y);
- }
- _updateFloat2ForUniform(name18, x, y) {
- UniformBuffer._TempBuffer[0] = x;
- UniformBuffer._TempBuffer[1] = y;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 2);
- }
- _updateFloat3ForEffect(name18, x, y, z, suffix3 = "") {
- this._currentEffect.setFloat3(name18 + suffix3, x, y, z);
- }
- _updateFloat3ForUniform(name18, x, y, z) {
- UniformBuffer._TempBuffer[0] = x;
- UniformBuffer._TempBuffer[1] = y;
- UniformBuffer._TempBuffer[2] = z;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 3);
- }
- _updateFloat4ForEffect(name18, x, y, z, w, suffix3 = "") {
- this._currentEffect.setFloat4(name18 + suffix3, x, y, z, w);
- }
- _updateFloat4ForUniform(name18, x, y, z, w) {
- UniformBuffer._TempBuffer[0] = x;
- UniformBuffer._TempBuffer[1] = y;
- UniformBuffer._TempBuffer[2] = z;
- UniformBuffer._TempBuffer[3] = w;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- _updateFloatArrayForEffect(name18, array) {
- this._currentEffect.setFloatArray(name18, array);
- }
- _updateFloatArrayForUniform(name18, array) {
- this.updateUniformArray(name18, array, array.length);
- }
- _updateArrayForEffect(name18, array) {
- this._currentEffect.setArray(name18, array);
- }
- _updateArrayForUniform(name18, array) {
- this.updateUniformArray(name18, array, array.length);
- }
- _updateIntArrayForEffect(name18, array) {
- this._currentEffect.setIntArray(name18, array);
- }
- _updateIntArrayForUniform(name18, array) {
- UniformBuffer._TempBufferInt32View.set(array);
- this.updateUniformArray(name18, UniformBuffer._TempBuffer, array.length);
- }
- _updateUIntArrayForEffect(name18, array) {
- this._currentEffect.setUIntArray(name18, array);
- }
- _updateUIntArrayForUniform(name18, array) {
- UniformBuffer._TempBufferUInt32View.set(array);
- this.updateUniformArray(name18, UniformBuffer._TempBuffer, array.length);
- }
- _updateMatrixForEffect(name18, mat) {
- this._currentEffect.setMatrix(name18, mat);
- }
- _updateMatrixForUniform(name18, mat) {
- if (this._cacheMatrix(name18, mat)) {
- this.updateUniform(name18, mat.asArray(), 16);
- }
- }
- _updateMatricesForEffect(name18, mat) {
- this._currentEffect.setMatrices(name18, mat);
- }
- _updateMatricesForUniform(name18, mat) {
- this.updateUniform(name18, mat, mat.length);
- }
- _updateVector3ForEffect(name18, vector) {
- this._currentEffect.setVector3(name18, vector);
- }
- _updateVector3ForUniform(name18, vector) {
- UniformBuffer._TempBuffer[0] = vector.x;
- UniformBuffer._TempBuffer[1] = vector.y;
- UniformBuffer._TempBuffer[2] = vector.z;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 3);
- }
- _updateVector4ForEffect(name18, vector) {
- this._currentEffect.setVector4(name18, vector);
- }
- _updateVector4ForUniform(name18, vector) {
- UniformBuffer._TempBuffer[0] = vector.x;
- UniformBuffer._TempBuffer[1] = vector.y;
- UniformBuffer._TempBuffer[2] = vector.z;
- UniformBuffer._TempBuffer[3] = vector.w;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- _updateColor3ForEffect(name18, color, suffix3 = "") {
- this._currentEffect.setColor3(name18 + suffix3, color);
- }
- _updateColor3ForUniform(name18, color) {
- UniformBuffer._TempBuffer[0] = color.r;
- UniformBuffer._TempBuffer[1] = color.g;
- UniformBuffer._TempBuffer[2] = color.b;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 3);
- }
- _updateColor4ForEffect(name18, color, alpha, suffix3 = "") {
- this._currentEffect.setColor4(name18 + suffix3, color, alpha);
- }
- _updateDirectColor4ForEffect(name18, color, suffix3 = "") {
- this._currentEffect.setDirectColor4(name18 + suffix3, color);
- }
- _updateColor4ForUniform(name18, color, alpha) {
- UniformBuffer._TempBuffer[0] = color.r;
- UniformBuffer._TempBuffer[1] = color.g;
- UniformBuffer._TempBuffer[2] = color.b;
- UniformBuffer._TempBuffer[3] = alpha;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- _updateDirectColor4ForUniform(name18, color) {
- UniformBuffer._TempBuffer[0] = color.r;
- UniformBuffer._TempBuffer[1] = color.g;
- UniformBuffer._TempBuffer[2] = color.b;
- UniformBuffer._TempBuffer[3] = color.a;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- _updateIntForEffect(name18, x, suffix3 = "") {
- this._currentEffect.setInt(name18 + suffix3, x);
- }
- _updateIntForUniform(name18, x) {
- UniformBuffer._TempBufferInt32View[0] = x;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 1);
- }
- _updateInt2ForEffect(name18, x, y, suffix3 = "") {
- this._currentEffect.setInt2(name18 + suffix3, x, y);
- }
- _updateInt2ForUniform(name18, x, y) {
- UniformBuffer._TempBufferInt32View[0] = x;
- UniformBuffer._TempBufferInt32View[1] = y;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 2);
- }
- _updateInt3ForEffect(name18, x, y, z, suffix3 = "") {
- this._currentEffect.setInt3(name18 + suffix3, x, y, z);
- }
- _updateInt3ForUniform(name18, x, y, z) {
- UniformBuffer._TempBufferInt32View[0] = x;
- UniformBuffer._TempBufferInt32View[1] = y;
- UniformBuffer._TempBufferInt32View[2] = z;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 3);
- }
- _updateInt4ForEffect(name18, x, y, z, w, suffix3 = "") {
- this._currentEffect.setInt4(name18 + suffix3, x, y, z, w);
- }
- _updateInt4ForUniform(name18, x, y, z, w) {
- UniformBuffer._TempBufferInt32View[0] = x;
- UniformBuffer._TempBufferInt32View[1] = y;
- UniformBuffer._TempBufferInt32View[2] = z;
- UniformBuffer._TempBufferInt32View[3] = w;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- _updateUIntForEffect(name18, x, suffix3 = "") {
- this._currentEffect.setUInt(name18 + suffix3, x);
- }
- _updateUIntForUniform(name18, x) {
- UniformBuffer._TempBufferUInt32View[0] = x;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 1);
- }
- _updateUInt2ForEffect(name18, x, y, suffix3 = "") {
- this._currentEffect.setUInt2(name18 + suffix3, x, y);
- }
- _updateUInt2ForUniform(name18, x, y) {
- UniformBuffer._TempBufferUInt32View[0] = x;
- UniformBuffer._TempBufferUInt32View[1] = y;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 2);
- }
- _updateUInt3ForEffect(name18, x, y, z, suffix3 = "") {
- this._currentEffect.setUInt3(name18 + suffix3, x, y, z);
- }
- _updateUInt3ForUniform(name18, x, y, z) {
- UniformBuffer._TempBufferUInt32View[0] = x;
- UniformBuffer._TempBufferUInt32View[1] = y;
- UniformBuffer._TempBufferUInt32View[2] = z;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 3);
- }
- _updateUInt4ForEffect(name18, x, y, z, w, suffix3 = "") {
- this._currentEffect.setUInt4(name18 + suffix3, x, y, z, w);
- }
- _updateUInt4ForUniform(name18, x, y, z, w) {
- UniformBuffer._TempBufferUInt32View[0] = x;
- UniformBuffer._TempBufferUInt32View[1] = y;
- UniformBuffer._TempBufferUInt32View[2] = z;
- UniformBuffer._TempBufferUInt32View[3] = w;
- this.updateUniform(name18, UniformBuffer._TempBuffer, 4);
- }
- setTexture(name18, texture) {
- this._currentEffect.setTexture(name18, texture);
- }
- setTextureArray(name18, textures) {
- this._currentEffect.setTextureArray(name18, textures);
- }
- bindTexture(name18, texture) {
- this._currentEffect._bindTexture(name18, texture);
- }
- updateUniformDirectly(uniformName, data) {
- this.updateUniform(uniformName, data, data.length);
- this.update();
- }
- bindToEffect(effect, name18) {
- this._currentEffect = effect;
- this._currentEffectName = name18;
- }
- bindUniformBuffer() {
- if (!this._noUBO && this._buffer && this._currentEffect) {
- this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName);
- }
- }
- unbindEffect() {
- this._currentEffect = undefined;
- this._currentEffectName = undefined;
- }
- 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;
- }
- 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;
- }
- }
-}
-var init_uniformBuffer = __esm(() => {
- init_logger();
- init_tools();
- UniformBuffer._UpdatedUbosInFrame = {};
- 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);
-});
-
-// node_modules/@babylonjs/core/Collisions/pickingInfo.js
-class PickingInfo {
- constructor() {
- this.hit = false;
- this.distance = 0;
- this.pickedPoint = null;
- this.pickedMesh = null;
- this.bu = 0;
- this.bv = 0;
- this.faceId = -1;
- this.subMeshFaceId = -1;
- this.subMeshId = 0;
- this.pickedSprite = null;
- this.thinInstanceIndex = -1;
- this.ray = null;
- this.originMesh = null;
- this.aimTransform = null;
- this.gripTransform = null;
- }
- 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 - 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) {
- transformNormalToWorld(this.pickedMesh, normalForDirectionChecking);
- }
- if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) {
- result.negateInPlace();
- }
- }
- result.normalize();
- return result;
- }
- 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 - this.bu - this.bv);
- return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
- }
-}
-var init_pickingInfo = __esm(() => {
- init_math_vector();
- init_buffer();
-});
-
-// node_modules/@babylonjs/core/sceneComponent.js
-class SceneComponentConstants {
-}
-var Stage;
-var init_sceneComponent = __esm(() => {
- 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;
- Stage = class Stage extends Array {
- constructor(items) {
- super(...items);
- }
- static Create() {
- return Object.create(Stage.prototype);
- }
- registerStep(index, component, action2) {
- 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: action2.bind(component) });
- }
- clear() {
- this.length = 0;
- }
- };
-});
-
-// node_modules/@babylonjs/core/Events/pointerEvents.js
-class PointerEventTypes {
-}
-
-class PointerInfoBase {
- constructor(type, event) {
- this.type = type;
- this.event = event;
- }
-}
-var PointerInfoPre, PointerInfo;
-var init_pointerEvents = __esm(() => {
- init_math_vector();
- PointerEventTypes.POINTERDOWN = 1;
- PointerEventTypes.POINTERUP = 2;
- PointerEventTypes.POINTERMOVE = 4;
- PointerEventTypes.POINTERWHEEL = 8;
- PointerEventTypes.POINTERPICK = 16;
- PointerEventTypes.POINTERTAP = 32;
- PointerEventTypes.POINTERDOUBLETAP = 64;
- PointerInfoPre = class PointerInfoPre extends PointerInfoBase {
- constructor(type, event, localX, localY) {
- super(type, event);
- this.ray = null;
- this.originalPickingInfo = null;
- this.skipOnPointerObservable = false;
- this.localPosition = new Vector2(localX, localY);
- }
- };
- PointerInfo = class PointerInfo extends PointerInfoBase {
- get pickInfo() {
- if (!this._pickInfo) {
- this._generatePickInfo();
- }
- return this._pickInfo;
- }
- constructor(type, event, pickInfo, inputManager = null) {
- super(type, event);
- this._pickInfo = pickInfo;
- this._inputManager = inputManager;
- }
- _generatePickInfo() {
- if (this._inputManager) {
- this._pickInfo = this._inputManager._pickMove(this.event);
- this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event);
- this._inputManager = null;
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/Events/keyboardEvents.js
-class KeyboardEventTypes {
-}
-
-class KeyboardInfo {
- constructor(type, event) {
- this.type = type;
- this.event = event;
- }
-}
-var KeyboardInfoPre;
-var init_keyboardEvents = __esm(() => {
- KeyboardEventTypes.KEYDOWN = 1;
- KeyboardEventTypes.KEYUP = 2;
- KeyboardInfoPre = class KeyboardInfoPre extends KeyboardInfo {
- get skipOnPointerObservable() {
- return this.skipOnKeyboardObservable;
- }
- set skipOnPointerObservable(value) {
- this.skipOnKeyboardObservable = value;
- }
- constructor(type, event) {
- super(type, event);
- this.type = type;
- this.event = event;
- this.skipOnKeyboardObservable = false;
- }
- };
-});
-
-// node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js
-var DeviceType, PointerInput, NativePointerInput, DualShockInput, DualSenseInput, XboxInput, SwitchInput;
-var init_deviceEnums = __esm(() => {
- (function(DeviceType2) {
- DeviceType2[DeviceType2["Generic"] = 0] = "Generic";
- DeviceType2[DeviceType2["Keyboard"] = 1] = "Keyboard";
- DeviceType2[DeviceType2["Mouse"] = 2] = "Mouse";
- DeviceType2[DeviceType2["Touch"] = 3] = "Touch";
- DeviceType2[DeviceType2["DualShock"] = 4] = "DualShock";
- DeviceType2[DeviceType2["Xbox"] = 5] = "Xbox";
- DeviceType2[DeviceType2["Switch"] = 6] = "Switch";
- DeviceType2[DeviceType2["DualSense"] = 7] = "DualSense";
- })(DeviceType || (DeviceType = {}));
- (function(PointerInput2) {
- PointerInput2[PointerInput2["Horizontal"] = 0] = "Horizontal";
- PointerInput2[PointerInput2["Vertical"] = 1] = "Vertical";
- PointerInput2[PointerInput2["LeftClick"] = 2] = "LeftClick";
- PointerInput2[PointerInput2["MiddleClick"] = 3] = "MiddleClick";
- PointerInput2[PointerInput2["RightClick"] = 4] = "RightClick";
- PointerInput2[PointerInput2["BrowserBack"] = 5] = "BrowserBack";
- PointerInput2[PointerInput2["BrowserForward"] = 6] = "BrowserForward";
- PointerInput2[PointerInput2["MouseWheelX"] = 7] = "MouseWheelX";
- PointerInput2[PointerInput2["MouseWheelY"] = 8] = "MouseWheelY";
- PointerInput2[PointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ";
- PointerInput2[PointerInput2["Move"] = 12] = "Move";
- })(PointerInput || (PointerInput = {}));
- (function(NativePointerInput2) {
- NativePointerInput2[NativePointerInput2["Horizontal"] = 0] = "Horizontal";
- NativePointerInput2[NativePointerInput2["Vertical"] = 1] = "Vertical";
- NativePointerInput2[NativePointerInput2["LeftClick"] = 2] = "LeftClick";
- NativePointerInput2[NativePointerInput2["MiddleClick"] = 3] = "MiddleClick";
- NativePointerInput2[NativePointerInput2["RightClick"] = 4] = "RightClick";
- NativePointerInput2[NativePointerInput2["BrowserBack"] = 5] = "BrowserBack";
- NativePointerInput2[NativePointerInput2["BrowserForward"] = 6] = "BrowserForward";
- NativePointerInput2[NativePointerInput2["MouseWheelX"] = 7] = "MouseWheelX";
- NativePointerInput2[NativePointerInput2["MouseWheelY"] = 8] = "MouseWheelY";
- NativePointerInput2[NativePointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ";
- NativePointerInput2[NativePointerInput2["DeltaHorizontal"] = 10] = "DeltaHorizontal";
- NativePointerInput2[NativePointerInput2["DeltaVertical"] = 11] = "DeltaVertical";
- })(NativePointerInput || (NativePointerInput = {}));
- (function(DualShockInput2) {
- DualShockInput2[DualShockInput2["Cross"] = 0] = "Cross";
- DualShockInput2[DualShockInput2["Circle"] = 1] = "Circle";
- DualShockInput2[DualShockInput2["Square"] = 2] = "Square";
- DualShockInput2[DualShockInput2["Triangle"] = 3] = "Triangle";
- DualShockInput2[DualShockInput2["L1"] = 4] = "L1";
- DualShockInput2[DualShockInput2["R1"] = 5] = "R1";
- DualShockInput2[DualShockInput2["L2"] = 6] = "L2";
- DualShockInput2[DualShockInput2["R2"] = 7] = "R2";
- DualShockInput2[DualShockInput2["Share"] = 8] = "Share";
- DualShockInput2[DualShockInput2["Options"] = 9] = "Options";
- DualShockInput2[DualShockInput2["L3"] = 10] = "L3";
- DualShockInput2[DualShockInput2["R3"] = 11] = "R3";
- DualShockInput2[DualShockInput2["DPadUp"] = 12] = "DPadUp";
- DualShockInput2[DualShockInput2["DPadDown"] = 13] = "DPadDown";
- DualShockInput2[DualShockInput2["DPadLeft"] = 14] = "DPadLeft";
- DualShockInput2[DualShockInput2["DPadRight"] = 15] = "DPadRight";
- DualShockInput2[DualShockInput2["Home"] = 16] = "Home";
- DualShockInput2[DualShockInput2["TouchPad"] = 17] = "TouchPad";
- DualShockInput2[DualShockInput2["LStickXAxis"] = 18] = "LStickXAxis";
- DualShockInput2[DualShockInput2["LStickYAxis"] = 19] = "LStickYAxis";
- DualShockInput2[DualShockInput2["RStickXAxis"] = 20] = "RStickXAxis";
- DualShockInput2[DualShockInput2["RStickYAxis"] = 21] = "RStickYAxis";
- })(DualShockInput || (DualShockInput = {}));
- (function(DualSenseInput2) {
- DualSenseInput2[DualSenseInput2["Cross"] = 0] = "Cross";
- DualSenseInput2[DualSenseInput2["Circle"] = 1] = "Circle";
- DualSenseInput2[DualSenseInput2["Square"] = 2] = "Square";
- DualSenseInput2[DualSenseInput2["Triangle"] = 3] = "Triangle";
- DualSenseInput2[DualSenseInput2["L1"] = 4] = "L1";
- DualSenseInput2[DualSenseInput2["R1"] = 5] = "R1";
- DualSenseInput2[DualSenseInput2["L2"] = 6] = "L2";
- DualSenseInput2[DualSenseInput2["R2"] = 7] = "R2";
- DualSenseInput2[DualSenseInput2["Create"] = 8] = "Create";
- DualSenseInput2[DualSenseInput2["Options"] = 9] = "Options";
- DualSenseInput2[DualSenseInput2["L3"] = 10] = "L3";
- DualSenseInput2[DualSenseInput2["R3"] = 11] = "R3";
- DualSenseInput2[DualSenseInput2["DPadUp"] = 12] = "DPadUp";
- DualSenseInput2[DualSenseInput2["DPadDown"] = 13] = "DPadDown";
- DualSenseInput2[DualSenseInput2["DPadLeft"] = 14] = "DPadLeft";
- DualSenseInput2[DualSenseInput2["DPadRight"] = 15] = "DPadRight";
- DualSenseInput2[DualSenseInput2["Home"] = 16] = "Home";
- DualSenseInput2[DualSenseInput2["TouchPad"] = 17] = "TouchPad";
- DualSenseInput2[DualSenseInput2["LStickXAxis"] = 18] = "LStickXAxis";
- DualSenseInput2[DualSenseInput2["LStickYAxis"] = 19] = "LStickYAxis";
- DualSenseInput2[DualSenseInput2["RStickXAxis"] = 20] = "RStickXAxis";
- DualSenseInput2[DualSenseInput2["RStickYAxis"] = 21] = "RStickYAxis";
- })(DualSenseInput || (DualSenseInput = {}));
- (function(XboxInput2) {
- XboxInput2[XboxInput2["A"] = 0] = "A";
- XboxInput2[XboxInput2["B"] = 1] = "B";
- XboxInput2[XboxInput2["X"] = 2] = "X";
- XboxInput2[XboxInput2["Y"] = 3] = "Y";
- XboxInput2[XboxInput2["LB"] = 4] = "LB";
- XboxInput2[XboxInput2["RB"] = 5] = "RB";
- XboxInput2[XboxInput2["LT"] = 6] = "LT";
- XboxInput2[XboxInput2["RT"] = 7] = "RT";
- XboxInput2[XboxInput2["Back"] = 8] = "Back";
- XboxInput2[XboxInput2["Start"] = 9] = "Start";
- XboxInput2[XboxInput2["LS"] = 10] = "LS";
- XboxInput2[XboxInput2["RS"] = 11] = "RS";
- XboxInput2[XboxInput2["DPadUp"] = 12] = "DPadUp";
- XboxInput2[XboxInput2["DPadDown"] = 13] = "DPadDown";
- XboxInput2[XboxInput2["DPadLeft"] = 14] = "DPadLeft";
- XboxInput2[XboxInput2["DPadRight"] = 15] = "DPadRight";
- XboxInput2[XboxInput2["Home"] = 16] = "Home";
- XboxInput2[XboxInput2["LStickXAxis"] = 17] = "LStickXAxis";
- XboxInput2[XboxInput2["LStickYAxis"] = 18] = "LStickYAxis";
- XboxInput2[XboxInput2["RStickXAxis"] = 19] = "RStickXAxis";
- XboxInput2[XboxInput2["RStickYAxis"] = 20] = "RStickYAxis";
- })(XboxInput || (XboxInput = {}));
- (function(SwitchInput2) {
- SwitchInput2[SwitchInput2["B"] = 0] = "B";
- SwitchInput2[SwitchInput2["A"] = 1] = "A";
- SwitchInput2[SwitchInput2["Y"] = 2] = "Y";
- SwitchInput2[SwitchInput2["X"] = 3] = "X";
- SwitchInput2[SwitchInput2["L"] = 4] = "L";
- SwitchInput2[SwitchInput2["R"] = 5] = "R";
- SwitchInput2[SwitchInput2["ZL"] = 6] = "ZL";
- SwitchInput2[SwitchInput2["ZR"] = 7] = "ZR";
- SwitchInput2[SwitchInput2["Minus"] = 8] = "Minus";
- SwitchInput2[SwitchInput2["Plus"] = 9] = "Plus";
- SwitchInput2[SwitchInput2["LS"] = 10] = "LS";
- SwitchInput2[SwitchInput2["RS"] = 11] = "RS";
- SwitchInput2[SwitchInput2["DPadUp"] = 12] = "DPadUp";
- SwitchInput2[SwitchInput2["DPadDown"] = 13] = "DPadDown";
- SwitchInput2[SwitchInput2["DPadLeft"] = 14] = "DPadLeft";
- SwitchInput2[SwitchInput2["DPadRight"] = 15] = "DPadRight";
- SwitchInput2[SwitchInput2["Home"] = 16] = "Home";
- SwitchInput2[SwitchInput2["Capture"] = 17] = "Capture";
- SwitchInput2[SwitchInput2["LStickXAxis"] = 18] = "LStickXAxis";
- SwitchInput2[SwitchInput2["LStickYAxis"] = 19] = "LStickYAxis";
- SwitchInput2[SwitchInput2["RStickXAxis"] = 20] = "RStickXAxis";
- SwitchInput2[SwitchInput2["RStickYAxis"] = 21] = "RStickYAxis";
- })(SwitchInput || (SwitchInput = {}));
-});
-
-// node_modules/@babylonjs/core/Events/deviceInputEvents.js
-class EventConstants {
-}
-var DeviceInputEventType;
-var init_deviceInputEvents = __esm(() => {
- (function(DeviceInputEventType2) {
- DeviceInputEventType2[DeviceInputEventType2["PointerMove"] = 0] = "PointerMove";
- DeviceInputEventType2[DeviceInputEventType2["PointerDown"] = 1] = "PointerDown";
- DeviceInputEventType2[DeviceInputEventType2["PointerUp"] = 2] = "PointerUp";
- })(DeviceInputEventType || (DeviceInputEventType = {}));
- EventConstants.DOM_DELTA_PIXEL = 0;
- EventConstants.DOM_DELTA_LINE = 1;
- EventConstants.DOM_DELTA_PAGE = 2;
-});
-
-// node_modules/@babylonjs/core/DeviceInput/eventFactory.js
-class DeviceEventFactory {
- 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);
- }
- case DeviceType.Touch:
- return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId);
- default:
- throw `Unable to generate event for device ${DeviceType[deviceType]}`;
- }
- }
- 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;
- 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;
- }
- static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {
- const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);
- 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;
- }
- 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);
- 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);
- evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, 11);
- 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;
- }
- 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;
- }
- 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;
- }
- static _CreateEvent(elementToAttachTo) {
- const evt = {};
- evt.preventDefault = () => {};
- evt.target = elementToAttachTo;
- return evt;
- }
-}
-var init_eventFactory = __esm(() => {
- init_deviceInputEvents();
- init_deviceEnums();
-});
-
-// node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js
-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();
- }
- pollInput(deviceType, deviceSlot, inputIndex) {
- return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex);
- }
- isDeviceAvailable(deviceType) {
- return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch;
- }
- dispose() {
- this._nativeInput.dispose();
- }
- _createDummyNativeInput() {
- const nativeInput = {
- pollInput: () => {
- return 0;
- },
- isDeviceAvailable: () => {
- return false;
- },
- dispose: () => {}
- };
- return nativeInput;
- }
-}
-var init_nativeDeviceInputSystem = __esm(() => {
- init_eventFactory();
- init_deviceEnums();
-});
-
-// node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js
-class WebDeviceInputSystem {
- constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) {
- this._inputs = [];
- this._keyboardActive = false;
- this._pointerActive = false;
- this._usingSafari = Tools.IsSafari();
- this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
- this._keyboardDownEvent = (evt) => {};
- this._keyboardUpEvent = (evt) => {};
- this._keyboardBlurEvent = (evt) => {};
- this._pointerMoveEvent = (evt) => {};
- this._pointerDownEvent = (evt) => {};
- this._pointerUpEvent = (evt) => {};
- this._pointerCancelEvent = (evt) => {};
- this._pointerCancelTouch = (pointerId) => {};
- this._pointerLeaveEvent = (evt) => {};
- this._pointerWheelEvent = (evt) => {};
- this._pointerBlurEvent = (evt) => {};
- 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;
- this._gamepadConnectedEvent = (evt) => {};
- this._gamepadDisconnectedEvent = (evt) => {};
- this._eventPrefix = Tools.GetPointerPrefix(engine);
- this._engine = engine;
- this._onDeviceConnected = onDeviceConnected;
- this._onDeviceDisconnected = onDeviceDisconnected;
- this._onInputChanged = onInputChanged;
- this._mouseId = this._isUsingFirefox ? 0 : 1;
- this._enableEvents();
- if (this._usingMacOS) {
- this._metaKeys = [];
- }
- if (!this._engine._onEngineViewChanged) {
- this._engine._onEngineViewChanged = () => {
- this._enableEvents();
- };
- }
- }
- pollInput(deviceType, deviceSlot, inputIndex) {
- const device = this._inputs[deviceType][deviceSlot];
- if (!device) {
- 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) {
- 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;
- }
- isDeviceAvailable(deviceType) {
- return this._inputs[deviceType] !== undefined;
- }
- dispose() {
- this._onDeviceConnected = () => {};
- this._onDeviceDisconnected = () => {};
- this._onInputChanged = () => {};
- delete this._engine._onEngineViewChanged;
- if (this._elementToAttachTo) {
- this._disableEvents();
- }
- }
- _enableEvents() {
- const inputElement = this?._engine.getInputElement();
- if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) {
- this._disableEvents();
- 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;
- this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex;
- this._handleKeyActions();
- this._handlePointerActions();
- this._handleGamepadActions();
- this._eventsAttached = true;
- this._checkForConnectedDevices();
- }
- }
- _disableEvents() {
- if (this._elementToAttachTo) {
- this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent);
- this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent);
- this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent);
- this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent);
- 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);
- }
- window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent);
- window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent);
- }
- if (this._pointerInputClearObserver) {
- this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver);
- }
- this._eventsAttached = false;
- }
- _checkForConnectedDevices() {
- if (navigator.getGamepads) {
- const gamepads = navigator.getGamepads();
- for (const gamepad of gamepads) {
- if (gamepad) {
- this._addGamePad(gamepad);
- }
- }
- }
- if (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) {
- this._addPointerDevice(DeviceType.Mouse, 0, 0, 0);
- }
- }
- _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;
- }
- _addPointerDevice(deviceType, deviceSlot, currentX, currentY) {
- if (!this._pointerActive) {
- this._pointerActive = true;
- }
- this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);
- const pointer = this._inputs[deviceType][deviceSlot];
- pointer[0] = currentX;
- pointer[1] = currentY;
- }
- _registerDevice(deviceType, deviceSlot, numberOfInputs) {
- if (deviceSlot === undefined) {
- 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);
- }
- }
- _unregisterDevice(deviceType, deviceSlot) {
- if (this._inputs[deviceType][deviceSlot]) {
- delete this._inputs[deviceType][deviceSlot];
- this._onDeviceDisconnected(deviceType, deviceSlot);
- }
- }
- _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 deviceEvent2 = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo);
- kbKey[keyCode] = 0;
- this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent2);
- }
- 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);
- }
- _handlePointerActions() {
- 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);
- if (deviceType === DeviceType.Touch && deviceSlot === -1) {
- const idx = this._activeTouchIds.indexOf(-1);
- if (idx >= 0) {
- deviceSlot = idx;
- this._activeTouchIds[idx] = evt.pointerId;
- this._onDeviceConnected(deviceType, deviceSlot);
- } else {
- 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;
- 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);
- if (!this._usingSafari && evt.button !== -1) {
- deviceEvent.inputIndex = evt.button + 2;
- pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1;
- 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) {
- let idx = this._activeTouchIds.indexOf(evt.pointerId);
- if (idx === -1) {
- idx = this._activeTouchIds.indexOf(-1);
- }
- if (idx >= 0) {
- deviceSlot = idx;
- this._activeTouchIds[idx] = evt.pointerId;
- } else {
- 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) {
- if (evt.pointerId === undefined) {
- evt.pointerId = this._mouseId;
- }
- if (!document.pointerLockElement) {
- try {
- this._elementToAttachTo.setPointerCapture(this._mouseId);
- } catch (e) {}
- }
- } else {
- if (evt.pointerId && !document.pointerLockElement) {
- try {
- this._elementToAttachTo.setPointerCapture(evt.pointerId);
- } catch (e) {}
- }
- }
- pointer[PointerInput.Horizontal] = evt.clientX;
- pointer[PointerInput.Vertical] = evt.clientY;
- pointer[evt.button + 2] = 1;
- const deviceEvent = evt;
- 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 (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;
- if (!shouldProcessPointerUp && this._isUsingFirefox && this._usingMacOS && pointer) {
- 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);
- }
- 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 (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") {
- this._pointerCancelTouch(evt.pointerId);
- }
- };
- this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll";
- 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 = () => {
- 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);
- }
- }
- }
- 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;
- 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);
- }
- }
- };
- 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);
- 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;
- }
- });
- }
- _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);
- }
- _updateDevice(deviceType, deviceSlot, inputIndex) {
- 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;
- }
- }
- }
- _getGamepadDeviceType(deviceName) {
- if (deviceName.indexOf("054c") !== -1) {
- 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) {
- return DeviceType.Xbox;
- } else if (deviceName.indexOf("057e") !== -1) {
- return DeviceType.Switch;
- }
- return DeviceType.Generic;
- }
- _getPointerType(evt) {
- let deviceType = DeviceType.Mouse;
- if (evt.pointerType === "touch" || evt.pointerType === "pen" || evt.touches) {
- deviceType = DeviceType.Touch;
- }
- return deviceType;
- }
-}
-var MAX_KEYCODES = 255, MAX_POINTER_INPUTS;
-var init_webDeviceInputSystem = __esm(() => {
- init_domManagement();
- init_tools();
- init_eventFactory();
- init_deviceEnums();
- MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2;
-});
-
-// node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js
-class DeviceSource {
- constructor(deviceInputSystem, deviceType, deviceSlot = 0) {
- this.deviceType = deviceType;
- this.deviceSlot = deviceSlot;
- this.onInputChangedObservable = new Observable;
- this._deviceInputSystem = deviceInputSystem;
- }
- getInput(inputIndex) {
- return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex);
- }
-}
-var init_deviceSource = __esm(() => {
- init_observable();
-});
-
-// node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js
-class InternalDeviceSourceManager {
- constructor(engine) {
- this._registeredManagers = new Array;
- this._refCount = 0;
- 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();
- }
-}
-var init_internalDeviceSourceManager = __esm(() => {
- init_deviceEnums();
- init_nativeDeviceInputSystem();
- init_webDeviceInputSystem();
- init_deviceSource();
-});
-
-// node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js
-class DeviceSourceManager {
- 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];
- }
- getDeviceSources(deviceType) {
- if (!this._devices[deviceType]) {
- return [];
- }
- return this._devices[deviceType].filter((source) => {
- return !!source;
- });
- }
- 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++;
- 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() {
- 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);
- }
- _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);
- }
- _removeDevice(deviceType, deviceSlot) {
- const deviceSource = this._devices[deviceType]?.[deviceSlot];
- this.onDeviceDisconnectedObservable.notifyObservers(deviceSource);
- if (this._devices[deviceType]?.[deviceSlot]) {
- delete this._devices[deviceType][deviceSlot];
- }
- this._updateFirstDevices(deviceType);
- }
- _onInputChanged(deviceType, deviceSlot, eventData) {
- this._devices[deviceType]?.[deviceSlot]?.onInputChangedObservable.notifyObservers(eventData);
- }
- _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];
- const devices = this._devices[type];
- if (devices) {
- for (let i = 0;i < devices.length; i++) {
- if (devices[i]) {
- this._firstDevice[type] = i;
- break;
- }
- }
- }
- break;
- }
- }
- }
-}
-var init_deviceSourceManager = __esm(() => {
- init_deviceEnums();
- init_observable();
- init_internalDeviceSourceManager();
-});
-
-// node_modules/@babylonjs/core/import.helper.js
-class _ImportHelper {
-}
-var init_import_helper = __esm(() => {
- _ImportHelper._IsPickingAvailable = false;
-});
-
-// node_modules/@babylonjs/core/Inputs/scene.inputManager.js
-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 InputManager {
- constructor(scene) {
- this._alreadyAttached = false;
- this._meshPickProceed = false;
- this._currentPickResult = null;
- this._previousPickResult = null;
- this._activePointerIds = new Array;
- 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;
- }
- }
- get meshUnderPointer() {
- if (this._movePointerInfo) {
- this._movePointerInfo._generatePickInfo();
- this._movePointerInfo = null;
- }
- return this._pointerOverMesh;
- }
- getMeshUnderPointerByPointerId(pointerId) {
- return this._meshUnderPointerId[pointerId] || null;
- }
- get unTranslatedPointer() {
- return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
- }
- get pointerX() {
- return this._pointerX;
- }
- set pointerX(value) {
- this._pointerX = value;
- }
- 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;
- if (!scene.doNotHandleCursors) {
- canvas.style.cursor = scene.defaultCursor;
- }
- }
- this._setCursorAndPointerOverMesh(pickResult, evt, scene);
- for (const step of scene._pointerMoveStage) {
- 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) {
- 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);
- }
- }
- _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);
- }
- }
- }
- _addCameraPointerObserver(observer, mask) {
- this._cameraObserverCount++;
- return this._scene.onPointerObservable.add(observer, mask);
- }
- _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;
- }
- }
- _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 actionManager2 = this._pointerOverMesh._getActionManagerForTrigger();
- if (actionManager2 && actionManager2.hasPointerTriggers) {
- canvas.style.cursor = actionManager2.hoverCursor || scene.hoverCursor;
- }
- }
- } else {
- this.setPointerOverMesh(null, evt.pointerId, pickResult, evt);
- }
- }
- 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);
- }
- 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 actionManager2 = pickResult.pickedMesh._getActionManagerForTrigger();
- if (actionManager2) {
- if (actionManager2.hasPickTriggers) {
- actionManager2.processTrigger(5, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
- switch (evt.button) {
- case 0:
- actionManager2.processTrigger(2, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
- break;
- case 1:
- actionManager2.processTrigger(4, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
- break;
- case 2:
- actionManager2.processTrigger(3, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult));
- break;
- }
- }
- if (actionManager2.hasSpecificTrigger(8)) {
- window.setTimeout(() => {
- const pickResult2 = 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 (pickResult2?.pickedMesh && actionManager2) {
- if (this._activePointerIdsCount !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) {
- this._startingPointerTime = 0;
- actionManager2.processTrigger(8, ActionEvent.CreateNew(pickResult2.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);
- }
- }
- _isPointerSwiping() {
- return this._isSwiping;
- }
- 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 actionManager2 = pickResult.pickedMesh._getActionManagerForTrigger();
- if (actionManager2 && !clickInfo.ignore) {
- actionManager2.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));
- if (!clickInfo.hasSwiped && clickInfo.singleClick) {
- actionManager2.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);
- 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 pi2 = new PointerInfo(type, evt, pickResult);
- if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {
- scene.onPointerObservable.notifyObservers(pi2, type);
- }
- }
- }
- }
- }
- isPointerCaptured(pointerId = 0) {
- return this._pointerCaptures[pointerId];
- }
- 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);
- 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) => {
- if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured || btn !== this._previousButtonPressed) {
- this._doubleClickOccured = false;
- clickInfo.singleClick = true;
- clickInfo.ignore = false;
- 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);
- }
- 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;
- 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) {
- if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) {
- clickInfo.singleClick = true;
- cb(clickInfo, this._currentPickResult);
- needToIgnoreNext = true;
- }
- } else {
- const delayedClick = {
- evt,
- 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) {
- if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) {
- if (!clickInfo.hasSwiped && !this._isPointerSwiping()) {
- this._previousStartingPointerTime = 0;
- this._doubleClickOccured = true;
- clickInfo.doubleClick = true;
- clickInfo.ignore = false;
- if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) {
- clearTimeout(this._delayedClicks[btn]?.timeoutId);
- this._delayedClicks[btn] = null;
- }
- cb(clickInfo, this._currentPickResult);
- } 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 (this._delayedClicks[btn]) {
- clearTimeout(this._delayedClicks[btn]?.timeoutId);
- this._delayedClicks[btn] = null;
- }
- cb(clickInfo, this._previousPickResult);
- } else {
- cb(clickInfo, this._currentPickResult);
- }
- }
- needToIgnoreNext = true;
- } else {
- this._doubleClickOccured = false;
- this._previousStartingPointerTime = this._startingPointerTime;
- this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
- this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
- this._previousButtonPressed = btn;
- }
- }
- }
- }
- if (!needToIgnoreNext) {
- cb(clickInfo, this._currentPickResult);
- }
- };
- this._onPointerMove = (evt) => {
- this._updatePointerPosition(evt);
- 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;
- }
- if (engine.isPointerLock) {
- engine._verifyPointerLock();
- }
- 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 (InputManager.ExclusiveDoubleClickMode) {
- for (let i = 0;i < this._delayedClicks.length; i++) {
- if (this._delayedClicks[i]) {
- if (evt.button === i) {
- clearTimeout(this._delayedClicks[i]?.timeoutId);
- } else {
- 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);
- }
- 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();
- 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);
- };
- }
- 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) {
- 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) => {
- if (scene.onPrePointerObservable.hasObservers()) {
- this._skipPointerTap = false;
- if (!clickInfo.ignore) {
- if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {
- if (this._swipeButtonPressed === evt.button) {
- this._isSwiping = false;
- this._swipeButtonPressed = -1;
- }
- 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;
- }
- }
- }
- }
- }
- if (!this._pointerCaptures[evt.pointerId]) {
- if (this._swipeButtonPressed === evt.button) {
- this._isSwiping = false;
- this._swipeButtonPressed = -1;
- }
- return;
- }
- 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);
- };
- }
- 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));
- }
- };
- 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;
- }
- detachControl() {
- if (this._alreadyAttached) {
- this._deviceSourceManager.dispose();
- this._deviceSourceManager = null;
- if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) {
- this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor;
- }
- this._alreadyAttached = false;
- this._alreadyAttachedTo = null;
- }
- }
- setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) {
- if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) {
- return;
- }
- const underPointerMesh = this._meshUnderPointerId[pointerId];
- let actionManager2;
- if (underPointerMesh) {
- actionManager2 = underPointerMesh._getActionManagerForTrigger(10);
- if (actionManager2) {
- actionManager2.processTrigger(10, new ActionEvent(underPointerMesh, this._pointerX, this._pointerY, mesh, evt, { pointerId }));
- }
- }
- if (mesh) {
- this._meshUnderPointerId[pointerId] = mesh;
- this._pointerOverMesh = mesh;
- actionManager2 = mesh._getActionManagerForTrigger(9);
- if (actionManager2) {
- actionManager2.processTrigger(9, new ActionEvent(mesh, this._pointerX, this._pointerY, mesh, evt, { pointerId, pickResult }));
- }
- } else {
- delete this._meshUnderPointerId[pointerId];
- this._pointerOverMesh = null;
- }
- if (this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()) {
- this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({
- mesh,
- pointerId
- });
- }
- }
- getPointerOverMesh() {
- return this.meshUnderPointer;
- }
- _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];
- }
- }
- }
-}
-var init_scene_inputManager = __esm(() => {
- init_pointerEvents();
- init_abstractActionManager();
- init_pickingInfo();
- init_math_vector();
- init_keyboardEvents();
- init_deviceEnums();
- init_deviceSourceManager();
- init_engineStore();
- init_import_helper();
- InputManager.DragMovementThreshold = 10;
- InputManager.LongPressDelay = 500;
- InputManager.DoubleClickDelay = 300;
- InputManager.ExclusiveDoubleClickMode = false;
-});
-
-// node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js
-class UniqueIdGenerator {
- static get UniqueId() {
- const result = this._UniqueIdCounter;
- this._UniqueIdCounter++;
- return result;
- }
-}
-var init_uniqueIdGenerator = __esm(() => {
- UniqueIdGenerator._UniqueIdCounter = 1;
-});
-
-// node_modules/@babylonjs/core/Lights/lightConstants.js
-class LightConstants {
- static CompareLightsPriority(a, b) {
- if (a.shadowEnabled !== b.shadowEnabled) {
- return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
- }
- return b.renderPriority - a.renderPriority;
- }
-}
-var init_lightConstants = __esm(() => {
- LightConstants.FALLOFF_DEFAULT = 0;
- LightConstants.FALLOFF_PHYSICAL = 1;
- LightConstants.FALLOFF_GLTF = 2;
- LightConstants.FALLOFF_STANDARD = 3;
- LightConstants.LIGHTMAP_DEFAULT = 0;
- LightConstants.LIGHTMAP_SPECULAR = 1;
- LightConstants.LIGHTMAP_SHADOWSONLY = 2;
- LightConstants.INTENSITYMODE_AUTOMATIC = 0;
- LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1;
- LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2;
- LightConstants.INTENSITYMODE_ILLUMINANCE = 3;
- LightConstants.INTENSITYMODE_LUMINANCE = 4;
- LightConstants.LIGHTTYPEID_POINTLIGHT = 0;
- LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
- LightConstants.LIGHTTYPEID_SPOTLIGHT = 2;
- LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
- LightConstants.LIGHTTYPEID_RECT_AREALIGHT = 4;
-});
-
-// node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js
-class PointerPickingConfiguration {
- constructor() {
- this.pointerDownFastCheck = false;
- this.pointerUpFastCheck = false;
- this.pointerMoveFastCheck = false;
- this.skipPointerMovePicking = false;
- this.skipPointerDownPicking = false;
- this.skipPointerUpPicking = false;
- }
-}
-
-// node_modules/@babylonjs/core/scene.js
-class Scene {
- static DefaultMaterialFactory(scene) {
- throw _WarnImport("StandardMaterial");
- }
- static CollisionCoordinatorFactory() {
- throw _WarnImport("DefaultCollisionCoordinator");
- }
- get clearColor() {
- return this._clearColor;
- }
- set clearColor(value) {
- if (value !== this._clearColor) {
- this._clearColor = value;
- this.onClearColorChangedObservable.notifyObservers(this._clearColor);
- }
- }
- get imageProcessingConfiguration() {
- return this._imageProcessingConfiguration;
- }
- get performancePriority() {
- return this._performancePriority;
- }
- set performancePriority(value) {
- if (value === this._performancePriority) {
- return;
- }
- this._performancePriority = value;
- switch (value) {
- case 0:
- this.skipFrustumClipping = false;
- this._renderingManager.maintainStateBetweenFrames = false;
- this.skipPointerMovePicking = false;
- this.autoClear = true;
- break;
- case 1:
- this.skipFrustumClipping = false;
- this._renderingManager.maintainStateBetweenFrames = false;
- this.skipPointerMovePicking = true;
- this.autoClear = false;
- break;
- case 2:
- this.skipFrustumClipping = true;
- this._renderingManager.maintainStateBetweenFrames = true;
- this.skipPointerMovePicking = true;
- this.autoClear = false;
- break;
- }
- this.onScenePerformancePriorityChangedObservable.notifyObservers(value);
- }
- set forceWireframe(value) {
- if (this._forceWireframe === value) {
- return;
- }
- this._forceWireframe = value;
- this.markAllMaterialsAsDirty(16);
- }
- get forceWireframe() {
- return this._forceWireframe;
- }
- set skipFrustumClipping(value) {
- if (this._skipFrustumClipping === value) {
- return;
- }
- this._skipFrustumClipping = value;
- }
- get skipFrustumClipping() {
- return this._skipFrustumClipping;
- }
- set forcePointsCloud(value) {
- if (this._forcePointsCloud === value) {
- return;
- }
- this._forcePointsCloud = value;
- this.markAllMaterialsAsDirty(16);
- }
- get forcePointsCloud() {
- return this._forcePointsCloud;
- }
- get environmentTexture() {
- return this._environmentTexture;
- }
- set environmentTexture(value) {
- if (this._environmentTexture === value) {
- return;
- }
- this._environmentTexture = value;
- this.onEnvironmentTextureChangedObservable.notifyObservers(value);
- this.markAllMaterialsAsDirty(1);
- }
- getNodes() {
- let nodes = [];
- nodes = nodes.concat(this.meshes);
- nodes = nodes.concat(this.lights);
- nodes = nodes.concat(this.cameras);
- nodes = nodes.concat(this.transformNodes);
- this.skeletons.forEach((skeleton) => nodes = nodes.concat(skeleton.bones));
- return nodes;
- }
- get animationPropertiesOverride() {
- return this._animationPropertiesOverride;
- }
- set animationPropertiesOverride(value) {
- this._animationPropertiesOverride = value;
- }
- set onDispose(callback) {
- if (this._onDisposeObserver) {
- this.onDisposeObservable.remove(this._onDisposeObserver);
- }
- this._onDisposeObserver = this.onDisposeObservable.add(callback);
- }
- set beforeRender(callback) {
- if (this._onBeforeRenderObserver) {
- this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
- }
- if (callback) {
- this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
- }
- }
- set afterRender(callback) {
- if (this._onAfterRenderObserver) {
- this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
- }
- if (callback) {
- this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
- }
- }
- set beforeCameraRender(callback) {
- if (this._onBeforeCameraRenderObserver) {
- this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
- }
- this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
- }
- set afterCameraRender(callback) {
- if (this._onAfterCameraRenderObserver) {
- this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
- }
- this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
- }
- get pointerDownPredicate() {
- return this._pointerPickingConfiguration.pointerDownPredicate;
- }
- set pointerDownPredicate(value) {
- this._pointerPickingConfiguration.pointerDownPredicate = value;
- }
- get pointerUpPredicate() {
- return this._pointerPickingConfiguration.pointerUpPredicate;
- }
- set pointerUpPredicate(value) {
- this._pointerPickingConfiguration.pointerUpPredicate = value;
- }
- get pointerMovePredicate() {
- return this._pointerPickingConfiguration.pointerMovePredicate;
- }
- set pointerMovePredicate(value) {
- this._pointerPickingConfiguration.pointerMovePredicate = value;
- }
- get pointerDownFastCheck() {
- return this._pointerPickingConfiguration.pointerDownFastCheck;
- }
- set pointerDownFastCheck(value) {
- this._pointerPickingConfiguration.pointerDownFastCheck = value;
- }
- get pointerUpFastCheck() {
- return this._pointerPickingConfiguration.pointerUpFastCheck;
- }
- set pointerUpFastCheck(value) {
- this._pointerPickingConfiguration.pointerUpFastCheck = value;
- }
- get pointerMoveFastCheck() {
- return this._pointerPickingConfiguration.pointerMoveFastCheck;
- }
- set pointerMoveFastCheck(value) {
- this._pointerPickingConfiguration.pointerMoveFastCheck = value;
- }
- get skipPointerMovePicking() {
- return this._pointerPickingConfiguration.skipPointerMovePicking;
- }
- set skipPointerMovePicking(value) {
- this._pointerPickingConfiguration.skipPointerMovePicking = value;
- }
- get skipPointerDownPicking() {
- return this._pointerPickingConfiguration.skipPointerDownPicking;
- }
- set skipPointerDownPicking(value) {
- this._pointerPickingConfiguration.skipPointerDownPicking = value;
- }
- get skipPointerUpPicking() {
- return this._pointerPickingConfiguration.skipPointerUpPicking;
- }
- set skipPointerUpPicking(value) {
- this._pointerPickingConfiguration.skipPointerUpPicking = value;
- }
- get unTranslatedPointer() {
- return this._inputManager.unTranslatedPointer;
- }
- static get DragMovementThreshold() {
- return InputManager.DragMovementThreshold;
- }
- static set DragMovementThreshold(value) {
- InputManager.DragMovementThreshold = value;
- }
- static get LongPressDelay() {
- return InputManager.LongPressDelay;
- }
- static set LongPressDelay(value) {
- InputManager.LongPressDelay = value;
- }
- static get DoubleClickDelay() {
- return InputManager.DoubleClickDelay;
- }
- static set DoubleClickDelay(value) {
- InputManager.DoubleClickDelay = value;
- }
- static get ExclusiveDoubleClickMode() {
- return InputManager.ExclusiveDoubleClickMode;
- }
- static set ExclusiveDoubleClickMode(value) {
- InputManager.ExclusiveDoubleClickMode = value;
- }
- 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];
- }
- 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;
- }
- set useRightHandedSystem(value) {
- if (this._useRightHandedSystem === value) {
- return;
- }
- this._useRightHandedSystem = value;
- this.markAllMaterialsAsDirty(16);
- }
- get useRightHandedSystem() {
- return this._useRightHandedSystem;
- }
- setStepId(newStepId) {
- this._currentStepId = newStepId;
- }
- getStepId() {
- return this._currentStepId;
- }
- getInternalStep() {
- return this._currentInternalStep;
- }
- set fogEnabled(value) {
- if (this._fogEnabled === value) {
- return;
- }
- this._fogEnabled = value;
- this.markAllMaterialsAsDirty(16);
- }
- get fogEnabled() {
- return this._fogEnabled;
- }
- set fogMode(value) {
- if (this._fogMode === value) {
- return;
- }
- this._fogMode = value;
- this.markAllMaterialsAsDirty(16);
- }
- get fogMode() {
- return this._fogMode;
- }
- get prePass() {
- return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled;
- }
- set shadowsEnabled(value) {
- if (this._shadowsEnabled === value) {
- return;
- }
- this._shadowsEnabled = value;
- this.markAllMaterialsAsDirty(2);
- }
- get shadowsEnabled() {
- return this._shadowsEnabled;
- }
- set lightsEnabled(value) {
- if (this._lightsEnabled === value) {
- return;
- }
- this._lightsEnabled = value;
- this.markAllMaterialsAsDirty(2);
- }
- get lightsEnabled() {
- return this._lightsEnabled;
- }
- 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;
- }
- get activeCamera() {
- return this._activeCamera;
- }
- set activeCamera(value) {
- if (value === this._activeCamera) {
- return;
- }
- this._activeCamera = value;
- this.onActiveCameraChanged.notifyObservers(this);
- }
- get _hasDefaultMaterial() {
- return Scene.DefaultMaterialFactory !== Scene._OriginalDefaultMaterialFactory;
- }
- get defaultMaterial() {
- if (!this._defaultMaterial) {
- this._defaultMaterial = Scene.DefaultMaterialFactory(this);
- }
- return this._defaultMaterial;
- }
- set defaultMaterial(value) {
- this._defaultMaterial = value;
- }
- set texturesEnabled(value) {
- if (this._texturesEnabled === value) {
- return;
- }
- this._texturesEnabled = value;
- this.markAllMaterialsAsDirty(1);
- }
- get texturesEnabled() {
- return this._texturesEnabled;
- }
- 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;
- }
- }
- set skeletonsEnabled(value) {
- if (this._skeletonsEnabled === value) {
- return;
- }
- this._skeletonsEnabled = value;
- this.markAllMaterialsAsDirty(8);
- }
- get skeletonsEnabled() {
- return this._skeletonsEnabled;
- }
- get collisionCoordinator() {
- if (!this._collisionCoordinator) {
- this._collisionCoordinator = Scene.CollisionCoordinatorFactory();
- this._collisionCoordinator.init(this);
- }
- return this._collisionCoordinator;
- }
- get renderingManager() {
- return this._renderingManager;
- }
- get frustumPlanes() {
- return this._frustumPlanes;
- }
- _registerTransientComponents() {
- if (this._transientComponents.length > 0) {
- for (const component of this._transientComponents) {
- component.register();
- }
- this._transientComponents.length = 0;
- }
- }
- _addComponent(component) {
- this._components.push(component);
- this._transientComponents.push(component);
- const serializableComponent = component;
- if (serializableComponent.addFromContainer && serializableComponent.serialize) {
- this._serializableComponents.push(serializableComponent);
- }
- }
- _getComponent(name18) {
- for (const component of this._components) {
- if (component.name === name18) {
- return component;
- }
- }
- return null;
- }
- constructor(engine, options) {
- this._inputManager = new InputManager(this);
- this.cameraToUseForPointers = null;
- this._isScene = true;
- this._blockEntityCollection = false;
- this.autoClear = true;
- this.autoClearDepthAndStencil = true;
- this._clearColor = new Color4(0.2, 0.2, 0.3, 1);
- this.onClearColorChangedObservable = new Observable;
- this.ambientColor = new Color3(0, 0, 0);
- this.environmentIntensity = 1;
- this.iblIntensity = 1;
- this._performancePriority = 0;
- this.onScenePerformancePriorityChangedObservable = new Observable;
- this._forceWireframe = false;
- this._skipFrustumClipping = false;
- this._forcePointsCloud = false;
- this.rootNodes = [];
- this.cameras = [];
- this.lights = [];
- this.meshes = [];
- this.skeletons = [];
- this.particleSystems = [];
- this.animations = [];
- this.animationGroups = [];
- this.multiMaterials = [];
- this.materials = [];
- this.morphTargetManagers = [];
- this.geometries = [];
- this.transformNodes = [];
- this.actionManagers = [];
- this.textures = [];
- this._environmentTexture = null;
- this.postProcesses = [];
- this.effectLayers = [];
- this.sounds = null;
- this.layers = [];
- this.lensFlareSystems = [];
- this.proceduralTextures = [];
- this.animationsEnabled = true;
- this._animationPropertiesOverride = null;
- this.useConstantAnimationDeltaTime = false;
- this.constantlyUpdateMeshUnderPointer = false;
- this.hoverCursor = "pointer";
- this.defaultCursor = "";
- this.doNotHandleCursors = false;
- this.preventDefaultOnPointerDown = true;
- this.preventDefaultOnPointerUp = true;
- this.metadata = null;
- this.reservedDataStore = null;
- this.disableOfflineSupportExceptionRules = [];
- this.onDisposeObservable = new Observable;
- this._onDisposeObserver = null;
- this.onBeforeRenderObservable = new Observable;
- this._onBeforeRenderObserver = null;
- this.onAfterRenderObservable = new Observable;
- this.onAfterRenderCameraObservable = new Observable;
- this._onAfterRenderObserver = null;
- this.onBeforeAnimationsObservable = new Observable;
- this.onAfterAnimationsObservable = new Observable;
- this.onBeforeDrawPhaseObservable = new Observable;
- this.onAfterDrawPhaseObservable = new Observable;
- this.onReadyObservable = new Observable;
- this.onBeforeCameraRenderObservable = new Observable;
- this._onBeforeCameraRenderObserver = null;
- this.onAfterCameraRenderObservable = new Observable;
- this._onAfterCameraRenderObserver = null;
- this.onBeforeActiveMeshesEvaluationObservable = new Observable;
- this.onAfterActiveMeshesEvaluationObservable = new Observable;
- this.onBeforeParticlesRenderingObservable = new Observable;
- this.onAfterParticlesRenderingObservable = new Observable;
- this.onDataLoadedObservable = new Observable;
- this.onNewCameraAddedObservable = new Observable;
- this.onCameraRemovedObservable = new Observable;
- this.onNewLightAddedObservable = new Observable;
- this.onLightRemovedObservable = new Observable;
- this.onNewGeometryAddedObservable = new Observable;
- this.onGeometryRemovedObservable = new Observable;
- this.onNewTransformNodeAddedObservable = new Observable;
- this.onTransformNodeRemovedObservable = new Observable;
- this.onNewMeshAddedObservable = new Observable;
- this.onMeshRemovedObservable = new Observable;
- this.onNewSkeletonAddedObservable = new Observable;
- this.onSkeletonRemovedObservable = new Observable;
- this.onNewMaterialAddedObservable = new Observable;
- this.onNewMultiMaterialAddedObservable = new Observable;
- this.onMaterialRemovedObservable = new Observable;
- this.onMultiMaterialRemovedObservable = new Observable;
- this.onNewTextureAddedObservable = new Observable;
- this.onTextureRemovedObservable = new Observable;
- this.onBeforeRenderTargetsRenderObservable = new Observable;
- this.onAfterRenderTargetsRenderObservable = new Observable;
- this.onBeforeStepObservable = new Observable;
- this.onAfterStepObservable = new Observable;
- this.onActiveCameraChanged = new Observable;
- this.onActiveCamerasChanged = new Observable;
- this.onBeforeRenderingGroupObservable = new Observable;
- this.onAfterRenderingGroupObservable = new Observable;
- this.onMeshImportedObservable = new Observable;
- this.onAnimationFileImportedObservable = new Observable;
- this.onEnvironmentTextureChangedObservable = new Observable;
- this.onMeshUnderPointerUpdatedObservable = new Observable;
- this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256);
- this._pointerPickingConfiguration = new PointerPickingConfiguration;
- this.onPrePointerObservable = new Observable;
- this.onPointerObservable = new Observable;
- this.onPreKeyboardObservable = new Observable;
- this.onKeyboardObservable = new Observable;
- this._useRightHandedSystem = false;
- this._timeAccumulator = 0;
- this._currentStepId = 0;
- this._currentInternalStep = 0;
- this._fogEnabled = true;
- this._fogMode = Scene.FOGMODE_NONE;
- this.fogColor = new Color3(0.2, 0.2, 0.3);
- this.fogDensity = 0.1;
- this.fogStart = 0;
- this.fogEnd = 1000;
- this.needsPreviousWorldMatrices = false;
- this._shadowsEnabled = true;
- this._lightsEnabled = true;
- this._unObserveActiveCameras = null;
- this._texturesEnabled = true;
- this._frameGraph = null;
- this.frameGraphs = [];
- this.physicsEnabled = true;
- this.particlesEnabled = true;
- this.spritesEnabled = true;
- this._skeletonsEnabled = true;
- this.lensFlaresEnabled = true;
- this.collisionsEnabled = true;
- this.gravity = new Vector3(0, -9.807, 0);
- this.postProcessesEnabled = true;
- this.renderTargetsEnabled = true;
- this.dumpNextRenderTargets = false;
- this.customRenderTargets = [];
- this.importedMeshesFiles = [];
- this.probesEnabled = true;
- this._meshesForIntersections = new SmartArrayNoDuplicate(256);
- this.proceduralTexturesEnabled = true;
- this._totalVertices = new PerfCounter;
- this._activeIndices = new PerfCounter;
- this._activeParticles = new PerfCounter;
- this._activeBones = new PerfCounter;
- this._animationTime = 0;
- this.animationTimeScale = 1;
- this._renderId = 0;
- this._frameId = 0;
- this._executeWhenReadyTimeoutId = null;
- this._intermediateRendering = false;
- this._defaultFrameBufferCleared = false;
- this._viewUpdateFlag = -1;
- this._projectionUpdateFlag = -1;
- this._toBeDisposed = new Array(256);
- this._activeRequests = new Array;
- this._pendingData = new Array;
- this._isDisposed = false;
- this.dispatchAllSubMeshesOfActiveMeshes = false;
- this._activeMeshes = new SmartArray(256);
- this._processedMaterials = new SmartArray(256);
- this._renderTargets = new SmartArrayNoDuplicate(256);
- this._materialsRenderTargets = new SmartArrayNoDuplicate(256);
- this._activeParticleSystems = new SmartArray(256);
- this._activeSkeletons = new SmartArrayNoDuplicate(32);
- this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32);
- this._activeAnimatables = new Array;
- this._transformMatrix = Matrix.Zero();
- this.requireLightSorting = false;
- this._components = [];
- this._serializableComponents = [];
- this._transientComponents = [];
- this._beforeCameraUpdateStage = Stage.Create();
- this._beforeClearStage = Stage.Create();
- this._beforeRenderTargetClearStage = Stage.Create();
- this._gatherRenderTargetsStage = Stage.Create();
- this._gatherActiveCameraRenderTargetsStage = Stage.Create();
- this._isReadyForMeshStage = Stage.Create();
- this._beforeEvaluateActiveMeshStage = Stage.Create();
- this._evaluateSubMeshStage = Stage.Create();
- this._preActiveMeshStage = Stage.Create();
- this._cameraDrawRenderTargetStage = Stage.Create();
- this._beforeCameraDrawStage = Stage.Create();
- this._beforeRenderTargetDrawStage = Stage.Create();
- this._beforeRenderingGroupDrawStage = Stage.Create();
- this._beforeRenderingMeshStage = Stage.Create();
- this._afterRenderingMeshStage = Stage.Create();
- this._afterRenderingGroupDrawStage = Stage.Create();
- this._afterCameraDrawStage = Stage.Create();
- this._afterCameraPostProcessStage = Stage.Create();
- this._afterRenderTargetDrawStage = Stage.Create();
- this._afterRenderTargetPostProcessStage = Stage.Create();
- this._afterRenderStage = Stage.Create();
- this._pointerMoveStage = Stage.Create();
- this._pointerDownStage = Stage.Create();
- this._pointerUpStage = Stage.Create();
- this._geometriesByUniqueId = null;
- this._defaultMeshCandidates = {
- data: [],
- length: 0
- };
- this._defaultSubMeshCandidates = {
- data: [],
- length: 0
- };
- this._preventFreeActiveMeshesAndRenderingGroups = false;
- this._activeMeshesFrozen = false;
- this._activeMeshesFrozenButKeepClipping = false;
- this._skipEvaluateActiveMeshesCompletely = false;
- this._useCurrentFrameBuffer = false;
- this._allowPostProcessClearColor = true;
- this.getDeterministicFrameTime = () => {
- return this._engine.getTimeStep();
- };
- this._registeredActions = 0;
- this._blockMaterialDirtyMechanism = false;
- 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();
- }
- this._createUbo();
- 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);
- }
- }
- getClassName() {
- return "Scene";
- }
- _getDefaultMeshCandidates() {
- this._defaultMeshCandidates.data = this.meshes;
- this._defaultMeshCandidates.length = this.meshes.length;
- return this._defaultMeshCandidates;
- }
- _getDefaultSubMeshCandidates(mesh) {
- this._defaultSubMeshCandidates.data = mesh.subMeshes;
- this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
- return this._defaultSubMeshCandidates;
- }
- 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);
- }
- get meshUnderPointer() {
- return this._inputManager.meshUnderPointer;
- }
- get pointerX() {
- return this._inputManager.pointerX;
- }
- set pointerX(value) {
- this._inputManager.pointerX = value;
- }
- get pointerY() {
- return this._inputManager.pointerY;
- }
- set pointerY(value) {
- this._inputManager.pointerY = value;
- }
- getCachedMaterial() {
- return this._cachedMaterial;
- }
- getCachedEffect() {
- return this._cachedEffect;
- }
- getCachedVisibility() {
- return this._cachedVisibility;
- }
- isCachedMaterialInvalid(material, effect, visibility = 1) {
- return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
- }
- getEngine() {
- return this._engine;
- }
- getTotalVertices() {
- return this._totalVertices.current;
- }
- get totalVerticesPerfCounter() {
- return this._totalVertices;
- }
- getActiveIndices() {
- return this._activeIndices.current;
- }
- get totalActiveIndicesPerfCounter() {
- return this._activeIndices;
- }
- getActiveParticles() {
- return this._activeParticles.current;
- }
- get activeParticlesPerfCounter() {
- return this._activeParticles;
- }
- getActiveBones() {
- return this._activeBones.current;
- }
- get activeBonesPerfCounter() {
- return this._activeBones;
- }
- getActiveMeshes() {
- return this._activeMeshes;
- }
- getAnimationRatio() {
- return this._animationRatio !== undefined ? this._animationRatio : 1;
- }
- getRenderId() {
- return this._renderId;
- }
- getFrameId() {
- return this._frameId;
- }
- incrementRenderId() {
- this._renderId++;
- }
- _createUbo() {
- this.setSceneUniformBuffer(this.createSceneUniformBuffer());
- }
- simulatePointerMove(pickResult, pointerEventInit) {
- this._inputManager.simulatePointerMove(pickResult, pointerEventInit);
- return this;
- }
- simulatePointerDown(pickResult, pointerEventInit) {
- this._inputManager.simulatePointerDown(pickResult, pointerEventInit);
- return this;
- }
- simulatePointerUp(pickResult, pointerEventInit, doubleTap) {
- this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap);
- return this;
- }
- isPointerCaptured(pointerId = 0) {
- return this._inputManager.isPointerCaptured(pointerId);
- }
- attachControl(attachUp = true, attachDown = true, attachMove = true) {
- this._inputManager.attachControl(attachUp, attachDown, attachMove);
- }
- detachControl() {
- this._inputManager.detachControl();
- }
- 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;
- if (this._pendingData.length > 0) {
- isReady = false;
- }
- this.prePassRenderer?.update();
- if (this.useOrderIndependentTransparency && this.depthPeelingRenderer) {
- isReady && (isReady = this.depthPeelingRenderer.isReady());
- }
- 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;
- }
- if (!mesh.isReady(true)) {
- isReady = false;
- continue;
- }
- const hardwareInstancedRendering = mesh.hasThinInstances || mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
- 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());
- }
- }
- }
- }
- }
- if (checkRenderTargets) {
- for (index = 0;index < this._materialsRenderTargets.length; ++index) {
- const rtt = this._materialsRenderTargets.data[index];
- if (!rtt.isReadyForRendering()) {
- isReady = false;
- }
- }
- }
- for (index = 0;index < this.geometries.length; index++) {
- const geometry = this.geometries[index];
- if (geometry.delayLoadState === 2) {
- isReady = false;
- }
- }
- 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;
- }
- }
- for (const particleSystem of this.particleSystems) {
- if (!particleSystem.isReady()) {
- isReady = false;
- }
- }
- if (this.layers) {
- for (const layer of this.layers) {
- if (!layer.isReady()) {
- isReady = false;
- }
- }
- }
- if (this.effectLayers) {
- for (const effectLayer of this.effectLayers) {
- if (!effectLayer.isLayerReady()) {
- isReady = false;
- }
- }
- }
- if (!engine.areAllEffectsReady()) {
- isReady = false;
- }
- engine.currentRenderPassId = currentRenderPassId;
- return isReady;
- }
- resetCachedMaterial() {
- this._cachedMaterial = null;
- this._cachedEffect = null;
- this._cachedVisibility = null;
- }
- registerBeforeRender(func) {
- this.onBeforeRenderObservable.add(func);
- }
- unregisterBeforeRender(func) {
- this.onBeforeRenderObservable.removeCallback(func);
- }
- registerAfterRender(func) {
- this.onAfterRenderObservable.add(func);
- }
- unregisterAfterRender(func) {
- this.onAfterRenderObservable.removeCallback(func);
- }
- _executeOnceBeforeRender(func) {
- const execFunc = () => {
- func();
- setTimeout(() => {
- this.unregisterBeforeRender(execFunc);
- });
- };
- this.registerBeforeRender(execFunc);
- }
- executeOnceBeforeRender(func, timeout) {
- if (timeout !== undefined) {
- setTimeout(() => {
- this._executeOnceBeforeRender(func);
- }, timeout);
- } else {
- this._executeOnceBeforeRender(func);
- }
- }
- addPendingData(data) {
- this._pendingData.push(data);
- }
- 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);
- }
- }
- getWaitingItemsCount() {
- return this._pendingData.length;
- }
- get isLoading() {
- return this._pendingData.length > 0;
- }
- executeWhenReady(func, checkRenderTargets = false) {
- this.onReadyObservable.addOnce(func);
- if (this._executeWhenReadyTimeoutId !== null) {
- return;
- }
- this._checkIsReady(checkRenderTargets);
- }
- whenReadyAsync(checkRenderTargets = false) {
- return new Promise((resolve3) => {
- this.executeWhenReady(() => {
- resolve3();
- }, checkRenderTargets);
- });
- }
- _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(() => {
- this.incrementRenderId();
- this._checkIsReady(checkRenderTargets);
- }, 100);
- }
- get animatables() {
- return this._activeAnimatables;
- }
- resetLastAnimationTimeFrame() {
- this._animationTimeLast = PrecisionDate.Now;
- }
- getViewMatrix() {
- return this._viewMatrix;
- }
- getProjectionMatrix() {
- return this._projectionMatrix;
- }
- getTransformMatrix() {
- return this._transformMatrix;
- }
- setTransformMatrix(viewL, projectionL, viewR, projectionR) {
- 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);
- 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);
- }
- }
- getSceneUniformBuffer() {
- return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo;
- }
- createSceneUniformBuffer(name18) {
- const sceneUbo = new UniformBuffer(this._engine, undefined, false, name18 ?? "scene");
- sceneUbo.addUniform("viewProjection", 16);
- sceneUbo.addUniform("view", 16);
- sceneUbo.addUniform("projection", 16);
- sceneUbo.addUniform("vEyePosition", 4);
- return sceneUbo;
- }
- setSceneUniformBuffer(ubo) {
- this._sceneUbo = ubo;
- this._viewUpdateFlag = -1;
- this._projectionUpdateFlag = -1;
- }
- getUniqueId() {
- return UniqueIdGenerator.UniqueId;
- }
- 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);
- });
- }
- }
- removeMesh(toRemove, recursive = false) {
- const index = this.meshes.indexOf(toRemove);
- if (index !== -1) {
- 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;
- }
- addTransformNode(newTransformNode) {
- if (this._blockEntityCollection) {
- return;
- }
- if (newTransformNode.getScene() === this && newTransformNode._indexInSceneTransformNodesArray !== -1) {
- return;
- }
- newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
- this.transformNodes.push(newTransformNode);
- if (!newTransformNode.parent) {
- newTransformNode._addToSceneRootNodes();
- }
- this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
- }
- 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;
- }
- removeSkeleton(toRemove) {
- const index = this.skeletons.indexOf(toRemove);
- if (index !== -1) {
- this.skeletons.splice(index, 1);
- this.onSkeletonRemovedObservable.notifyObservers(toRemove);
- this._executeActiveContainerCleanup(this._activeSkeletons);
- }
- return index;
- }
- removeMorphTargetManager(toRemove) {
- const index = this.morphTargetManagers.indexOf(toRemove);
- if (index !== -1) {
- this.morphTargetManagers.splice(index, 1);
- }
- return index;
- }
- removeLight(toRemove) {
- const index = this.lights.indexOf(toRemove);
- if (index !== -1) {
- for (const mesh of this.meshes) {
- mesh._removeLightSource(toRemove, false);
- }
- this.lights.splice(index, 1);
- this.sortLightsByPriority();
- if (!toRemove.parent) {
- toRemove._removeFromSceneRootNodes();
- }
- }
- this.onLightRemovedObservable.notifyObservers(toRemove);
- return index;
- }
- removeCamera(toRemove) {
- const index = this.cameras.indexOf(toRemove);
- if (index !== -1) {
- this.cameras.splice(index, 1);
- if (!toRemove.parent) {
- toRemove._removeFromSceneRootNodes();
- }
- }
- if (this.activeCameras) {
- const index2 = this.activeCameras.indexOf(toRemove);
- if (index2 !== -1) {
- this.activeCameras.splice(index2, 1);
- }
- }
- if (this.activeCamera === toRemove) {
- if (this.cameras.length > 0) {
- this.activeCamera = this.cameras[0];
- } else {
- this.activeCamera = null;
- }
- }
- this.onCameraRemovedObservable.notifyObservers(toRemove);
- return index;
- }
- removeParticleSystem(toRemove) {
- const index = this.particleSystems.indexOf(toRemove);
- if (index !== -1) {
- this.particleSystems.splice(index, 1);
- this._executeActiveContainerCleanup(this._activeParticleSystems);
- }
- return index;
- }
- removeAnimation(toRemove) {
- const index = this.animations.indexOf(toRemove);
- if (index !== -1) {
- this.animations.splice(index, 1);
- }
- return index;
- }
- stopAnimation(target, animationName, targetMask) {}
- removeAnimationGroup(toRemove) {
- const index = this.animationGroups.indexOf(toRemove);
- if (index !== -1) {
- this.animationGroups.splice(index, 1);
- }
- return index;
- }
- removeMultiMaterial(toRemove) {
- const index = this.multiMaterials.indexOf(toRemove);
- if (index !== -1) {
- this.multiMaterials.splice(index, 1);
- }
- this.onMultiMaterialRemovedObservable.notifyObservers(toRemove);
- return index;
- }
- 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;
- }
- removeActionManager(toRemove) {
- const index = this.actionManagers.indexOf(toRemove);
- if (index !== -1) {
- this.actionManagers.splice(index, 1);
- }
- return index;
- }
- removeTexture(toRemove) {
- const index = this.textures.indexOf(toRemove);
- if (index !== -1) {
- this.textures.splice(index, 1);
- }
- this.onTextureRemovedObservable.notifyObservers(toRemove);
- return index;
- }
- addLight(newLight) {
- if (this._blockEntityCollection) {
- return;
- }
- this.lights.push(newLight);
- this.sortLightsByPriority();
- if (!newLight.parent) {
- newLight._addToSceneRootNodes();
- }
- for (const mesh of this.meshes) {
- if (mesh.lightSources.indexOf(newLight) === -1) {
- mesh.lightSources.push(newLight);
- mesh._resyncLightSources();
- }
- }
- Tools.SetImmediate(() => {
- this.onNewLightAddedObservable.notifyObservers(newLight);
- });
- }
- sortLightsByPriority() {
- if (this.requireLightSorting) {
- this.lights.sort(LightConstants.CompareLightsPriority);
- }
- }
- addCamera(newCamera) {
- if (this._blockEntityCollection) {
- return;
- }
- this.cameras.push(newCamera);
- Tools.SetImmediate(() => {
- this.onNewCameraAddedObservable.notifyObservers(newCamera);
- });
- if (!newCamera.parent) {
- newCamera._addToSceneRootNodes();
- }
- }
- addSkeleton(newSkeleton) {
- if (this._blockEntityCollection) {
- return;
- }
- this.skeletons.push(newSkeleton);
- Tools.SetImmediate(() => {
- this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton);
- });
- }
- addParticleSystem(newParticleSystem) {
- if (this._blockEntityCollection) {
- return;
- }
- this.particleSystems.push(newParticleSystem);
- }
- addAnimation(newAnimation) {
- if (this._blockEntityCollection) {
- return;
- }
- this.animations.push(newAnimation);
- }
- addAnimationGroup(newAnimationGroup) {
- if (this._blockEntityCollection) {
- return;
- }
- this.animationGroups.push(newAnimationGroup);
- }
- addMultiMaterial(newMultiMaterial) {
- if (this._blockEntityCollection) {
- return;
- }
- this.multiMaterials.push(newMultiMaterial);
- Tools.SetImmediate(() => {
- this.onNewMultiMaterialAddedObservable.notifyObservers(newMultiMaterial);
- });
- }
- addMaterial(newMaterial) {
- if (this._blockEntityCollection) {
- return;
- }
- if (newMaterial.getScene() === this && newMaterial._indexInSceneMaterialArray !== -1) {
- return;
- }
- newMaterial._indexInSceneMaterialArray = this.materials.length;
- this.materials.push(newMaterial);
- Tools.SetImmediate(() => {
- this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
- });
- }
- addMorphTargetManager(newMorphTargetManager) {
- if (this._blockEntityCollection) {
- return;
- }
- this.morphTargetManagers.push(newMorphTargetManager);
- }
- addGeometry(newGeometry) {
- if (this._blockEntityCollection) {
- return;
- }
- if (this._geometriesByUniqueId) {
- this._geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
- }
- this.geometries.push(newGeometry);
- }
- addActionManager(newActionManager) {
- this.actionManagers.push(newActionManager);
- }
- addTexture(newTexture) {
- if (this._blockEntityCollection) {
- return;
- }
- this.textures.push(newTexture);
- this.onNewTextureAddedObservable.notifyObservers(newTexture);
- }
- 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();
- }
- }
- setActiveCameraById(id) {
- const camera = this.getCameraById(id);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- }
- setActiveCameraByName(name18) {
- const camera = this.getCameraByName(name18);
- if (camera) {
- this.activeCamera = camera;
- return camera;
- }
- return null;
- }
- getAnimationGroupByName(name18) {
- for (let index = 0;index < this.animationGroups.length; index++) {
- if (this.animationGroups[index].name === name18) {
- 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;
- }
- getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) {
- return this._getMaterial(allowMultiMaterials, (m) => m.uniqueId === uniqueId);
- }
- getMaterialById(id, allowMultiMaterials = false) {
- return this._getMaterial(allowMultiMaterials, (m) => m.id === id);
- }
- getMaterialByName(name18, allowMultiMaterials = false) {
- return this._getMaterial(allowMultiMaterials, (m) => m.name === name18);
- }
- 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;
- }
- getTextureByUniqueId(uniqueId) {
- for (let index = 0;index < this.textures.length; index++) {
- if (this.textures[index].uniqueId === uniqueId) {
- return this.textures[index];
- }
- }
- return null;
- }
- getTextureByName(name18) {
- for (let index = 0;index < this.textures.length; index++) {
- if (this.textures[index].name === name18) {
- return this.textures[index];
- }
- }
- return null;
- }
- getCameraById(id) {
- for (let index = 0;index < this.cameras.length; index++) {
- if (this.cameras[index].id === id) {
- return this.cameras[index];
- }
- }
- return null;
- }
- getCameraByUniqueId(uniqueId) {
- for (let index = 0;index < this.cameras.length; index++) {
- if (this.cameras[index].uniqueId === uniqueId) {
- return this.cameras[index];
- }
- }
- return null;
- }
- getCameraByName(name18) {
- for (let index = 0;index < this.cameras.length; index++) {
- if (this.cameras[index].name === name18) {
- return this.cameras[index];
- }
- }
- return null;
- }
- 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;
- }
- getBoneByName(name18) {
- 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 === name18) {
- return skeleton.bones[boneIndex];
- }
- }
- }
- return null;
- }
- getLightByName(name18) {
- for (let index = 0;index < this.lights.length; index++) {
- if (this.lights[index].name === name18) {
- return this.lights[index];
- }
- }
- return null;
- }
- getLightById(id) {
- for (let index = 0;index < this.lights.length; index++) {
- if (this.lights[index].id === id) {
- return this.lights[index];
- }
- }
- return null;
- }
- getLightByUniqueId(uniqueId) {
- for (let index = 0;index < this.lights.length; index++) {
- if (this.lights[index].uniqueId === uniqueId) {
- return this.lights[index];
- }
- }
- return null;
- }
- getParticleSystemById(id) {
- for (let index = 0;index < this.particleSystems.length; index++) {
- if (this.particleSystems[index].id === id) {
- return this.particleSystems[index];
- }
- }
- return null;
- }
- 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;
- }
- getFrameGraphByName(name18) {
- for (let index = 0;index < this.frameGraphs.length; index++) {
- if (this.frameGraphs[index].name === name18) {
- return this.frameGraphs[index];
- }
- }
- return null;
- }
- pushGeometry(geometry, force) {
- if (!force && this._getGeometryByUniqueId(geometry.uniqueId)) {
- return false;
- }
- this.addGeometry(geometry);
- Tools.SetImmediate(() => {
- this.onNewGeometryAddedObservable.notifyObservers(geometry);
- });
- return true;
- }
- 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;
- }
- getGeometries() {
- return this.geometries;
- }
- getMeshById(id) {
- for (let index = 0;index < this.meshes.length; index++) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- }
- getMeshesById(id) {
- return this.meshes.filter(function(m) {
- return m.id === id;
- });
- }
- getTransformNodeById(id) {
- for (let index = 0;index < this.transformNodes.length; index++) {
- if (this.transformNodes[index].id === id) {
- return this.transformNodes[index];
- }
- }
- return null;
- }
- getTransformNodeByUniqueId(uniqueId) {
- for (let index = 0;index < this.transformNodes.length; index++) {
- if (this.transformNodes[index].uniqueId === uniqueId) {
- return this.transformNodes[index];
- }
- }
- return null;
- }
- getTransformNodesById(id) {
- return this.transformNodes.filter(function(m) {
- return m.id === id;
- });
- }
- getMeshByUniqueId(uniqueId) {
- for (let index = 0;index < this.meshes.length; index++) {
- if (this.meshes[index].uniqueId === uniqueId) {
- return this.meshes[index];
- }
- }
- return null;
- }
- getLastMeshById(id) {
- for (let index = this.meshes.length - 1;index >= 0; index--) {
- if (this.meshes[index].id === id) {
- return this.meshes[index];
- }
- }
- return null;
- }
- getLastTransformNodeById(id) {
- for (let index = this.transformNodes.length - 1;index >= 0; index--) {
- if (this.transformNodes[index].id === id) {
- return this.transformNodes[index];
- }
- }
- return null;
- }
- 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;
- }
- 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;
- }
- getNodeByName(name18) {
- const mesh = this.getMeshByName(name18);
- if (mesh) {
- return mesh;
- }
- const transformNode = this.getTransformNodeByName(name18);
- if (transformNode) {
- return transformNode;
- }
- const light = this.getLightByName(name18);
- if (light) {
- return light;
- }
- const camera = this.getCameraByName(name18);
- if (camera) {
- return camera;
- }
- const bone = this.getBoneByName(name18);
- if (bone) {
- return bone;
- }
- return null;
- }
- getMeshByName(name18) {
- for (let index = 0;index < this.meshes.length; index++) {
- if (this.meshes[index].name === name18) {
- return this.meshes[index];
- }
- }
- return null;
- }
- getTransformNodeByName(name18) {
- for (let index = 0;index < this.transformNodes.length; index++) {
- if (this.transformNodes[index].name === name18) {
- return this.transformNodes[index];
- }
- }
- return null;
- }
- getLastSkeletonById(id) {
- for (let index = this.skeletons.length - 1;index >= 0; index--) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- }
- getSkeletonByUniqueId(uniqueId) {
- for (let index = 0;index < this.skeletons.length; index++) {
- if (this.skeletons[index].uniqueId === uniqueId) {
- return this.skeletons[index];
- }
- }
- return null;
- }
- getSkeletonById(id) {
- for (let index = 0;index < this.skeletons.length; index++) {
- if (this.skeletons[index].id === id) {
- return this.skeletons[index];
- }
- }
- return null;
- }
- getSkeletonByName(name18) {
- for (let index = 0;index < this.skeletons.length; index++) {
- if (this.skeletons[index].name === name18) {
- return this.skeletons[index];
- }
- }
- return null;
- }
- getMorphTargetManagerById(id) {
- for (let index = 0;index < this.morphTargetManagers.length; index++) {
- if (this.morphTargetManagers[index].uniqueId === id) {
- return this.morphTargetManagers[index];
- }
- }
- return null;
- }
- 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;
- }
- getMorphTargetByName(name18) {
- 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 === name18) {
- return target;
- }
- }
- }
- return null;
- }
- getPostProcessByName(name18) {
- for (let postProcessIndex = 0;postProcessIndex < this.postProcesses.length; ++postProcessIndex) {
- const postProcess = this.postProcesses[postProcessIndex];
- if (postProcess.name === name18) {
- return postProcess;
- }
- }
- return null;
- }
- isActiveMesh(mesh) {
- return this._activeMeshes.indexOf(mesh) !== -1;
- }
- get uid() {
- if (!this._uid) {
- this._uid = Tools.RandomId();
- }
- return this._uid;
- }
- addExternalData(key, data) {
- if (!this._externalData) {
- this._externalData = new StringDictionary;
- }
- return this._externalData.add(key, data);
- }
- getExternalData(key) {
- if (!this._externalData) {
- return null;
- }
- return this._externalData.get(key);
- }
- getOrAddExternalDataWithFactory(key, factory) {
- if (!this._externalData) {
- this._externalData = new StringDictionary;
- }
- return this._externalData.getOrAddWithFactory(key, factory);
- }
- 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) {
- if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) {
- if (this._processedMaterials.indexOf(material) === -1) {
- this._processedMaterials.push(material);
- this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
- }
- }
- this._renderingManager.dispatch(subMesh, mesh, material);
- }
- }
- }
- freeProcessedMaterials() {
- this._processedMaterials.dispose();
- }
- get blockfreeActiveMeshesAndRenderingGroups() {
- return this._preventFreeActiveMeshesAndRenderingGroups;
- }
- set blockfreeActiveMeshesAndRenderingGroups(value) {
- if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
- return;
- }
- if (value) {
- this.freeActiveMeshes();
- this.freeRenderingGroups();
- }
- this._preventFreeActiveMeshesAndRenderingGroups = value;
- }
- 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();
- }
- }
- }
- }
- 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();
- }
- }
- }
- }
- _isInIntermediateRendering() {
- return this._intermediateRendering;
- }
- 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;
- }
- 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;
- }
- 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 len2 = this._activeMeshes.length;
- for (let i = 0;i < len2; 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();
- }
- const meshes = this.getActiveMeshCandidates();
- 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();
- if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) {
- this._meshesForIntersections.pushNoDuplicate(mesh);
- }
- 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;
- }
- 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);
- 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);
- }
- }
- _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);
- }
- }
- }
- 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) {
- 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);
- }
- }
- }
- _renderForCamera(camera, rigParent, bindFrameBuffer = true) {
- if (camera && camera._skipRendering) {
- return;
- }
- const engine = this._engine;
- this._activeCamera = camera;
- if (!this.activeCamera) {
- throw new Error("Active camera not set");
- }
- engine.setViewport(this.activeCamera.viewport);
- 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);
- this._evaluateActiveMeshes();
- for (let softwareSkinnedMeshIndex = 0;softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
- const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
- mesh.applySkeleton(mesh.skeleton);
- }
- 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);
- }
- 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;
- if (needRebind && !this.prePass) {
- this._bindFrameBuffer(this._activeCamera, false);
- this.updateTransformMatrix();
- }
- this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
- if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) {
- this.postProcessManager._prepareFrame();
- }
- for (const step of this._beforeCameraDrawStage) {
- step.action(this.activeCamera);
- }
- this.onBeforeDrawPhaseObservable.notifyObservers(this);
- if (engine.snapshotRendering && engine.snapshotRenderingMode === 1) {
- this.finalizeSceneUbo();
- }
- this._renderingManager.render(null, null, true, true);
- this.onAfterDrawPhaseObservable.notifyObservers(this);
- for (const step of this._afterCameraDrawStage) {
- step.action(this.activeCamera);
- }
- if (this.postProcessManager && !camera._multiviewTexture) {
- const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : undefined;
- this.postProcessManager._finalizeFrame(camera.isIntermediate, texture);
- }
- for (const step of this._afterCameraPostProcessStage) {
- step.action(this.activeCamera);
- }
- 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 {
- this.onBeforeCameraRenderObservable.notifyObservers(camera);
- for (let index = 0;index < camera._rigCameras.length; index++) {
- this._renderForCamera(camera._rigCameras[index], camera);
- }
- }
- 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 action2 = sourceMesh.actionManager.actions[actionIndex];
- if (action2.trigger === 12 || action2.trigger === 13) {
- const parameters = action2.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 (action2.trigger === 12) {
- action2._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
- sourceMesh._intersectionsInProgress.push(otherMesh);
- } else if (action2.trigger === 13) {
- sourceMesh._intersectionsInProgress.push(otherMesh);
- }
- } else if (!areIntersecting && currentIntersectionInProgress > -1) {
- if (action2.trigger === 13) {
- action2._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
- }
- if (!sourceMesh.actionManager.hasSpecificTrigger(13, (parameter) => {
- const parameterMesh = parameter.mesh ? parameter.mesh : parameter;
- return otherMesh === parameterMesh;
- }) || action2.trigger === 13) {
- sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
- }
- }
- }
- }
- }
- }
- _advancePhysicsEngineStep(step) {}
- _animate(customDeltaTime) {}
- 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 / defaultFrameTime / 1000;
- 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);
- this._animationRatio = defaultFrameTime * defaultFPS;
- this._animate(defaultFrameTime);
- this.onAfterAnimationsObservable.notifyObservers(this);
- if (this.physicsEnabled) {
- this._advancePhysicsEngineStep(defaultFrameTime);
- }
- this.onAfterStepObservable.notifyObservers(this);
- this._currentStepId++;
- stepsTaken++;
- deltaTime -= defaultFrameTime;
- }
- this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
- } else {
- const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
- this._animationRatio = deltaTime * (60 / 1000);
- this._animate();
- this.onAfterAnimationsObservable.notifyObservers(this);
- 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;
- }
- }
- }
- }
- 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();
- if (updateCameras) {
- for (const camera of this.cameras) {
- camera.update();
- if (camera.cameraRigMode !== 0) {
- for (let index = 0;index < camera._rigCameras.length; index++) {
- camera._rigCameras[index].update();
- }
- }
- }
- }
- for (const step of this._beforeClearStage) {
- step.action();
- }
- 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);
- }
- }
- 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();
- }
- }
- }
- this.frameGraph?.execute();
- }
- 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);
- }
- this._registerTransientComponents();
- this._activeParticles.fetchNewFrame();
- this._totalVertices.fetchNewFrame();
- this._activeIndices.fetchNewFrame();
- this._activeBones.fetchNewFrame();
- this._meshesForIntersections.reset();
- this.resetCachedMaterial();
- this.onBeforeAnimationsObservable.notifyObservers(this);
- if (this.actionManager) {
- this.actionManager.processTrigger(11);
- }
- if (!ignoreAnimations) {
- this.animate();
- }
- for (const step of this._beforeCameraUpdateStage) {
- step.action();
- }
- 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) {
- 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) {
- for (let index = 0;index < this.activeCamera._rigCameras.length; index++) {
- this.activeCamera._rigCameras[index].update();
- }
- }
- }
- }
- this.onBeforeRenderObservable.notifyObservers(this);
- if (this.customRenderFunction) {
- this._renderId++;
- this._engine.currentRenderPassId = 0;
- this.customRenderFunction(updateCameras, ignoreAnimations);
- } else {
- const engine = this.getEngine();
- 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");
- }
- engine.setViewport(this.activeCamera.viewport);
- 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;
- 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();
- }
- this._clearFrameBuffer(this.activeCamera);
- for (const step of this._gatherRenderTargetsStage) {
- step.action(this._renderTargets);
- }
- 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);
- }
- }
- this._checkIntersections();
- for (const step of this._afterRenderStage) {
- step.action();
- }
- if (this.afterRender) {
- this.afterRender();
- }
- this.onAfterRenderObservable.notifyObservers(this);
- 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();
- }
- freezeMaterials() {
- for (let i = 0;i < this.materials.length; i++) {
- this.materials[i].freeze();
- }
- }
- unfreezeMaterials() {
- for (let i = 0;i < this.materials.length; i++) {
- this.materials[i].unfreeze();
- }
- }
- 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) {
- this._activeAnimatables.forEach((animatable) => {
- animatable.onAnimationEndObservable.clear();
- animatable.onAnimationEnd = null;
- });
- this.stopAllAnimations();
- }
- this.resetCachedMaterial();
- 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;
- const activeRequests = this._activeRequests.slice();
- for (const request of activeRequests) {
- request.abort();
- }
- this._activeRequests.length = 0;
- try {
- this.onDisposeObservable.notifyObservers(this);
- } catch (e) {
- Logger.Error("An error occurred while calling onDisposeObservable!", e);
- }
- this.detachControl();
- const canvas = this._engine.getInputElement();
- if (canvas) {
- for (let index2 = 0;index2 < this.cameras.length; index2++) {
- this.cameras[index2].detachControl();
- }
- }
- this._disposeList(this.animationGroups);
- this._disposeList(this.lights);
- if (this._defaultMaterial) {
- this._defaultMaterial.dispose();
- }
- this._disposeList(this.multiMaterials);
- this._disposeList(this.materials);
- this._disposeList(this.meshes, (item) => item.dispose(true));
- this._disposeList(this.transformNodes, (item) => item.dispose(true));
- const cameras = this.cameras;
- this._disposeList(cameras);
- this._disposeList(this.particleSystems);
- this._disposeList(this.postProcesses);
- this._disposeList(this.textures);
- this._disposeList(this.morphTargetManagers);
- this._sceneUbo.dispose();
- if (this._multiviewSceneUbo) {
- this._multiviewSceneUbo.dispose();
- }
- this.postProcessManager.dispose();
- this._disposeList(this._components);
- 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;
- }
- get isDisposed() {
- return this._isDisposed;
- }
- clearCachedVertexData() {
- for (let meshIndex = 0;meshIndex < this.meshes.length; meshIndex++) {
- const mesh = this.meshes[meshIndex];
- const geometry = mesh.geometry;
- if (geometry) {
- geometry.clearCachedData();
- }
- }
- }
- cleanCachedTextureBuffer() {
- for (const baseTexture of this.textures) {
- const buffer = baseTexture._buffer;
- if (buffer) {
- baseTexture._buffer = null;
- }
- }
- }
- 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,
- max
- };
- }
- createPickingRay(x, y, world, camera, cameraViewSpace = false) {
- throw _WarnImport("Ray");
- }
- createPickingRayToRef(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {
- throw _WarnImport("Ray");
- }
- createPickingRayInCameraSpace(x, y, camera) {
- throw _WarnImport("Ray");
- }
- createPickingRayInCameraSpaceToRef(x, y, result, camera) {
- throw _WarnImport("Ray");
- }
- pick(x, y, predicate, fastCheck, camera, trianglePredicate) {
- const warn = _WarnImport("Ray", true);
- if (warn) {
- Logger.Warn(warn);
- }
- return new PickingInfo;
- }
- pickWithBoundingInfo(x, y, predicate, fastCheck, camera) {
- const warn = _WarnImport("Ray", true);
- if (warn) {
- Logger.Warn(warn);
- }
- return new PickingInfo;
- }
- pickWithRay(ray, predicate, fastCheck, trianglePredicate) {
- throw _WarnImport("Ray");
- }
- multiPick(x, y, predicate, camera, trianglePredicate) {
- throw _WarnImport("Ray");
- }
- multiPickWithRay(ray, predicate, trianglePredicate) {
- throw _WarnImport("Ray");
- }
- setPointerOverMesh(mesh, pointerId, pickResult) {
- this._inputManager.setPointerOverMesh(mesh, pointerId, pickResult);
- }
- getPointerOverMesh() {
- return this._inputManager.getPointerOverMesh();
- }
- _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();
- }
- }
- }
- _rebuildTextures() {
- for (const texture of this.textures) {
- texture._rebuild(true);
- }
- this.markAllMaterialsAsDirty(1);
- }
- _getByTags(list, tagsQuery, filter) {
- if (tagsQuery === undefined) {
- 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;
- }
- getMeshesByTags(tagsQuery, filter) {
- return this._getByTags(this.meshes, tagsQuery, filter);
- }
- getCamerasByTags(tagsQuery, filter) {
- return this._getByTags(this.cameras, tagsQuery, filter);
- }
- getLightsByTags(tagsQuery, filter) {
- return this._getByTags(this.lights, tagsQuery, filter);
- }
- getMaterialByTags(tagsQuery, filter) {
- return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter));
- }
- getTransformNodesByTags(tagsQuery, filter) {
- return this._getByTags(this.transformNodes, tagsQuery, filter);
- }
- setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {
- this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
- }
- setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {
- this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
- }
- getAutoClearDepthStencilSetup(index) {
- return this._renderingManager.getAutoClearDepthStencilSetup(index);
- }
- _forceBlockMaterialDirtyMechanism(value) {
- this._blockMaterialDirtyMechanism = value;
- }
- get blockMaterialDirtyMechanism() {
- return this._blockMaterialDirtyMechanism;
- }
- set blockMaterialDirtyMechanism(value) {
- if (this._blockMaterialDirtyMechanism === value) {
- return;
- }
- this._blockMaterialDirtyMechanism = value;
- if (!value) {
- this.markAllMaterialsAsDirty(127);
- }
- }
- markAllMaterialsAsDirty(flag, predicate) {
- if (this._blockMaterialDirtyMechanism) {
- return;
- }
- for (const material of this.materials) {
- if (predicate && !predicate(material)) {
- continue;
- }
- material.markAsDirty(flag);
- }
- }
- _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((request2) => {
- this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
- });
- return request;
- }
- _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
- return new Promise((resolve3, reject) => {
- this._loadFile(fileOrUrl, (data) => {
- resolve3(data);
- }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => {
- reject(exception);
- }, onOpened);
- });
- }
- _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((request2) => {
- this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
- });
- return request;
- }
- _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) {
- return new Promise((resolve3, reject) => {
- this._requestFile(url, (data) => {
- resolve3(data);
- }, onProgress, useOfflineSupport, useArrayBuffer, (error) => {
- reject(error);
- }, onOpened);
- });
- }
- _readFile(file, onSuccess, onProgress, useArrayBuffer, onError) {
- const request = ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
- this._activeRequests.push(request);
- request.onCompleteObservable.add((request2) => {
- this._activeRequests.splice(this._activeRequests.indexOf(request2), 1);
- });
- return request;
- }
- _readFileAsync(file, onProgress, useArrayBuffer) {
- return new Promise((resolve3, reject) => {
- this._readFile(file, (data) => {
- resolve3(data);
- }, onProgress, useArrayBuffer, (error) => {
- reject(error);
- });
- });
- }
- getPerfCollector() {
- throw _WarnImport("performanceViewerSceneExtension");
- }
- setActiveCameraByID(id) {
- return this.setActiveCameraById(id);
- }
- getMaterialByID(id) {
- return this.getMaterialById(id);
- }
- getLastMaterialByID(id) {
- return this.getLastMaterialById(id);
- }
- getTextureByUniqueID(uniqueId) {
- return this.getTextureByUniqueId(uniqueId);
- }
- getCameraByID(id) {
- return this.getCameraById(id);
- }
- getCameraByUniqueID(uniqueId) {
- return this.getCameraByUniqueId(uniqueId);
- }
- getBoneByID(id) {
- return this.getBoneById(id);
- }
- getLightByID(id) {
- return this.getLightById(id);
- }
- getLightByUniqueID(uniqueId) {
- return this.getLightByUniqueId(uniqueId);
- }
- getParticleSystemByID(id) {
- return this.getParticleSystemById(id);
- }
- getGeometryByID(id) {
- return this.getGeometryById(id);
- }
- getMeshByID(id) {
- return this.getMeshById(id);
- }
- getMeshByUniqueID(uniqueId) {
- return this.getMeshByUniqueId(uniqueId);
- }
- getLastMeshByID(id) {
- return this.getLastMeshById(id);
- }
- getMeshesByID(id) {
- return this.getMeshesById(id);
- }
- getTransformNodeByID(id) {
- return this.getTransformNodeById(id);
- }
- getTransformNodeByUniqueID(uniqueId) {
- return this.getTransformNodeByUniqueId(uniqueId);
- }
- getTransformNodesByID(id) {
- return this.getTransformNodesById(id);
- }
- getNodeByID(id) {
- return this.getNodeById(id);
- }
- getLastEntryByID(id) {
- return this.getLastEntryById(id);
- }
- getLastSkeletonByID(id) {
- return this.getLastSkeletonById(id);
- }
-}
-var ScenePerformancePriority;
-var init_scene = __esm(() => {
- init_tools();
- init_precisionDate();
- init_observable();
- init_smartArray();
- init_tags();
- init_math_vector();
- init_imageProcessingConfiguration();
- init_uniformBuffer();
- init_pickingInfo();
- init_postProcessManager();
- init_renderingManager();
- init_sceneComponent();
- init_domManagement();
- init_engineStore();
- init_devTools();
- init_scene_inputManager();
- init_perfCounter();
- init_math_color();
- init_math_frustum();
- init_uniqueIdGenerator();
- init_fileTools();
- init_lightConstants();
- init_arrayTools();
- init_logger();
- init_typeStore();
- (function(ScenePerformancePriority2) {
- ScenePerformancePriority2[ScenePerformancePriority2["BackwardCompatible"] = 0] = "BackwardCompatible";
- ScenePerformancePriority2[ScenePerformancePriority2["Intermediate"] = 1] = "Intermediate";
- ScenePerformancePriority2[ScenePerformancePriority2["Aggressive"] = 2] = "Aggressive";
- })(ScenePerformancePriority || (ScenePerformancePriority = {}));
- Scene.FOGMODE_NONE = 0;
- Scene.FOGMODE_EXP = 1;
- Scene.FOGMODE_EXP2 = 2;
- Scene.FOGMODE_LINEAR = 3;
- Scene.MinDeltaTime = 1;
- Scene.MaxDeltaTime = 1000;
- Scene._OriginalDefaultMaterialFactory = Scene.DefaultMaterialFactory;
- RegisterClass("BABYLON.Scene", Scene);
-});
-
-// node_modules/@babylonjs/core/Animations/animatable.js
-var init_animatable = __esm(() => {
- init_bone();
- init_animatable_core();
- init_scene();
- init_animatable_core();
- AddAnimationExtensions(Scene, Bone);
-});
-
-// node_modules/@babylonjs/core/Animations/easing.js
-class EasingFunction {
- constructor() {
- this._easingMode = EasingFunction.EASINGMODE_EASEIN;
- }
- setEasingMode(easingMode) {
- const n = Math.min(Math.max(easingMode, 0), 2);
- this._easingMode = n;
- }
- getEasingMode() {
- return this._easingMode;
- }
- easeInCore(gradient) {
- throw new Error("You must implement this method");
- }
- 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;
- }
-}
-var CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase;
-var init_easing = __esm(() => {
- init_math_path();
- EasingFunction.EASINGMODE_EASEIN = 0;
- EasingFunction.EASINGMODE_EASEOUT = 1;
- EasingFunction.EASINGMODE_EASEINOUT = 2;
- CircleEase = class CircleEase extends EasingFunction {
- easeInCore(gradient) {
- gradient = Math.max(0, Math.min(1, gradient));
- return 1 - Math.sqrt(1 - gradient * gradient);
- }
- };
- BackEase = class BackEase extends EasingFunction {
- constructor(amplitude = 1) {
- super();
- this.amplitude = amplitude;
- }
- easeInCore(gradient) {
- const num = Math.max(0, this.amplitude);
- return Math.pow(gradient, 3) - gradient * num * Math.sin(3.141592653589793 * gradient);
- }
- };
- BounceEase = class BounceEase extends EasingFunction {
- constructor(bounces = 3, bounciness = 2) {
- super();
- this.bounces = bounces;
- this.bounciness = bounciness;
- }
- easeInCore(gradient) {
- const y = Math.max(0, this.bounces);
- let bounciness = this.bounciness;
- if (bounciness <= 1) {
- bounciness = 1.001;
- }
- const num9 = Math.pow(bounciness, y);
- const num5 = 1 - bounciness;
- const num4 = (1 - num9) / num5 + num9 * 0.5;
- const num15 = gradient * num4;
- const num65 = Math.log(-num15 * (1 - bounciness) + 1) / Math.log(bounciness);
- const num3 = Math.floor(num65);
- const num13 = num3 + 1;
- const num8 = (1 - Math.pow(bounciness, num3)) / (num5 * num4);
- const num12 = (1 - Math.pow(bounciness, num13)) / (num5 * num4);
- const num7 = (num8 + num12) * 0.5;
- const num6 = gradient - num7;
- const num2 = num7 - num8;
- return -Math.pow(1 / bounciness, y - num3) / (num2 * num2) * (num6 - num2) * (num6 + num2);
- }
- };
- CubicEase = class CubicEase extends EasingFunction {
- easeInCore(gradient) {
- return gradient * gradient * gradient;
- }
- };
- ElasticEase = class ElasticEase extends EasingFunction {
- constructor(oscillations = 3, springiness = 3) {
- super();
- this.oscillations = oscillations;
- this.springiness = springiness;
- }
- easeInCore(gradient) {
- let num2;
- const num3 = Math.max(0, this.oscillations);
- const num = Math.max(0, this.springiness);
- if (num == 0) {
- num2 = gradient;
- } else {
- num2 = (Math.exp(num * gradient) - 1) / (Math.exp(num) - 1);
- }
- return num2 * Math.sin((6.283185307179586 * num3 + 1.5707963267948966) * gradient);
- }
- };
- ExponentialEase = class ExponentialEase extends EasingFunction {
- constructor(exponent = 2) {
- super();
- this.exponent = exponent;
- }
- easeInCore(gradient) {
- if (this.exponent <= 0) {
- return gradient;
- }
- return (Math.exp(this.exponent * gradient) - 1) / (Math.exp(this.exponent) - 1);
- }
- };
- QuadraticEase = class QuadraticEase extends EasingFunction {
- easeInCore(gradient) {
- return gradient * gradient;
- }
- };
- QuarticEase = class QuarticEase extends EasingFunction {
- easeInCore(gradient) {
- return gradient * gradient * gradient * gradient;
- }
- };
- QuinticEase = class QuinticEase extends EasingFunction {
- easeInCore(gradient) {
- return gradient * gradient * gradient * gradient * gradient;
- }
- };
- SineEase = class SineEase extends EasingFunction {
- easeInCore(gradient) {
- return 1 - Math.sin(1.5707963267948966 * (1 - gradient));
- }
- };
- BezierCurveEase = class BezierCurveEase extends EasingFunction {
- constructor(x1 = 0, y1 = 0, x2 = 1, y2 = 1) {
- super();
- this.x1 = x1;
- this.y1 = y1;
- this.x2 = x2;
- this.y2 = y2;
- }
- easeInCore(gradient) {
- return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Animations/animationGroup.js
-class TargetedAnimation {
- getClassName() {
- return "TargetedAnimation";
- }
- serialize() {
- const serializationObject = {};
- serializationObject.animation = this.animation.serialize();
- serializationObject.targetId = this.target.id;
- return serializationObject;
- }
-}
-
-class AnimationGroup {
- get mask() {
- return this._mask;
- }
- set mask(value) {
- if (this._mask === value) {
- return;
- }
- this._mask = value;
- this.syncWithMask(true);
- }
- 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();
- }
- }
- }
- }
- removeUnmaskedAnimations() {
- if (!this.mask || this.mask.disabled) {
- return;
- }
- 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;
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- 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;
- }
- }
- get isStarted() {
- return this._isStarted;
- }
- get isPlaying() {
- return this._isStarted && !this._isPaused;
- }
- get speedRatio() {
- return this._speedRatio;
- }
- 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;
- }
- }
- 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;
- }
- }
- 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;
- }
- }
- get weight() {
- return this._weight;
- }
- set weight(value) {
- if (this._weight === value) {
- return;
- }
- this._weight = value;
- this.setWeightForAllAnimatables(this._weight);
- }
- get targetedAnimations() {
- return this._targetedAnimations;
- }
- get animatables() {
- return this._animatables;
- }
- get children() {
- return this._targetedAnimations;
- }
- 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();
- }
- }
- 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;
- }
- }
- }
- 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;
- }
- }
- }
- getLength(from, to) {
- from = from ?? this._from;
- to = to ?? this._to;
- const fps = this.targetedAnimations[0].animation.framePerSecond * this._speedRatio;
- return (to - from) / fps;
- }
- 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;
- }
- constructor(name18, scene = null, weight = -1, playOrder = 0) {
- this.name = name18;
- 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;
- this._parentContainer = null;
- this.onAnimationEndObservable = new Observable;
- this.onAnimationLoopObservable = new Observable;
- this.onAnimationGroupLoopObservable = new Observable;
- this.onAnimationGroupEndObservable = new Observable;
- this.onAnimationGroupPauseObservable = new Observable;
- this.onAnimationGroupPlayObservable = new Observable;
- 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);
- }
- 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;
- }
- 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);
- }
- }
- }
- 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(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() {
- 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(loop) {
- 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() {
- 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() {
- 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(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);
- }
- 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) {
- this._checkAnimationGroupEnded(animatable, skipOnAnimationEnd);
- }
- }
- this._scene._activeAnimatables.length = curIndex;
- this._isStarted = false;
- return this;
- }
- setWeightForAllAnimatables(weight) {
- for (let index = 0;index < this._animatables.length; index++) {
- const animatable = this._animatables[index];
- animatable.weight = weight;
- }
- return this;
- }
- syncAllAnimationsWith(root) {
- for (let index = 0;index < this._animatables.length; index++) {
- const animatable = this._animatables[index];
- animatable.syncWith(root);
- }
- return this;
- }
- 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;
- }
- getCurrentFrame() {
- return this.animatables[0]?.masterFrame || 0;
- }
- dispose() {
- if (this.isStarted) {
- this.stop();
- }
- this._targetedAnimations.length = 0;
- this._animatables.length = 0;
- const index = this._scene.animationGroups.indexOf(this);
- if (index > -1) {
- this._scene.animationGroups.splice(index, 1);
- }
- if (this._parentContainer) {
- const index2 = this._parentContainer.animationGroups.indexOf(this);
- if (index2 > -1) {
- this._parentContainer.animationGroups.splice(index2, 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) {
- const idx = this._animatables.indexOf(animatable);
- if (idx > -1) {
- this._animatables.splice(idx, 1);
- }
- if (this._animatables.length === this._targetedAnimations.length - this._numActiveAnimatables) {
- this._isStarted = false;
- if (!skipOnAnimationEnd) {
- this.onAnimationGroupEndObservable.notifyObservers(this);
- }
- this._animatables.length = 0;
- }
- }
- 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;
- }
- 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);
- }
- if (this.metadata) {
- serializationObject.metadata = this.metadata;
- }
- return serializationObject;
- }
- 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") {
- 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;
- }
- static MakeAnimationAdditive(sourceAnimationGroup, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) {
- let options;
- if (typeof referenceFrameOrOptions === "object") {
- options = referenceFrameOrOptions;
- } else {
- options = {
- referenceFrame: referenceFrameOrOptions,
- 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) {
- let from = Number.MAX_VALUE;
- let to = -Number.MAX_VALUE;
- const targetedAnimations2 = animationGroup.targetedAnimations;
- for (let index = 0;index < targetedAnimations2.length; index++) {
- const targetedAnimation = targetedAnimations2[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;
- }
- static ClipKeys(sourceAnimationGroup, fromKey, toKey, name18, dontCloneAnimations) {
- const animationGroup = sourceAnimationGroup.clone(name18 || sourceAnimationGroup.name);
- return AnimationGroup.ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations);
- }
- static ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations) {
- return AnimationGroup.ClipInPlace(animationGroup, fromKey, toKey, dontCloneAnimations, false);
- }
- static ClipFrames(sourceAnimationGroup, fromFrame, toFrame, name18, dontCloneAnimations) {
- const animationGroup = sourceAnimationGroup.clone(name18 || sourceAnimationGroup.name);
- return AnimationGroup.ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations);
- }
- static ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations) {
- return AnimationGroup.ClipInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations, true);
- }
- 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) {
- 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;
- }
- animationGroup._from = from;
- animationGroup._to = to;
- return animationGroup;
- }
- getClassName() {
- return "AnimationGroup";
- }
- 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;
- }
-}
-var init_animationGroup = __esm(() => {
- init_animation();
- init_observable();
- init_engineStore();
- init_tags();
- init_animatable();
-});
-
-// node_modules/@babylonjs/core/Maths/math.functions.js
-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);
- }
- }
-}
-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,
- maximum
- };
-}
-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,
- maximum
- };
-}
-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;
- for (let index = 0;index < indices.length; index += 3) {
- const a = indices[index];
- const b = indices[index + 1];
- const c = indices[index + 2];
- 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();
- 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) {
- indices[index] = c;
- indices[index + 2] = a;
- }
- }
-}
-var init_math_functions = __esm(() => {
- init_tslib_es6();
- init_math_vector();
- init_decorators();
- __decorate([
- nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices))
- ], MathHelpers, "extractMinAndMaxIndexed", null);
- __decorate([
- nativeOverride.filter((...[positions]) => !Array.isArray(positions))
- ], MathHelpers, "extractMinAndMax", null);
-});
-
-// node_modules/@babylonjs/core/Misc/bitArray.js
-function getByteIndex(bitIndex) {
- return Math.floor(bitIndex / 8);
-}
-function getBitMask(bitIndex) {
- return 1 << bitIndex % 8;
-}
-
-class BitArray {
- constructor(size) {
- this.size = size;
- this._byteArray = new Uint8Array(Math.ceil(this.size / 8));
- }
- 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;
- }
- 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;
- }
- }
-}
-
-// node_modules/@babylonjs/core/Meshes/mesh.vertexData.functions.js
-var exports_mesh_vertexData_functions = {};
-__export(exports_mesh_vertexData_functions, {
- OptimizeIndices: () => OptimizeIndices
-});
-function OptimizeIndices(indices) {
- const faces = [];
- const faceCount = indices.length / 3;
- for (let i = 0;i < faceCount; i++) {
- faces.push([indices[i * 3], indices[i * 3 + 1], indices[i * 3 + 2]]);
- }
- const vertexToFaceMap = new Map;
- faces.forEach((face, faceIndex) => {
- face.forEach((vertex) => {
- let face2 = vertexToFaceMap.get(vertex);
- if (!face2) {
- vertexToFaceMap.set(vertex, face2 = []);
- }
- face2.push(faceIndex);
- });
- });
- const visited = new BitArray(faceCount);
- const sortedFaces = [];
- 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]);
- faces[currentFaceIndex].forEach((vertex) => {
- const neighbors = vertexToFaceMap.get(vertex);
- if (!neighbors) {
- return;
- }
- neighbors.forEach((neighborFaceIndex) => {
- if (!visited.get(neighborFaceIndex)) {
- stack.push(neighborFaceIndex);
- }
- });
- });
- }
- };
- for (let i = 0;i < faceCount; i++) {
- if (!visited.get(i)) {
- deepFirstSearchStack(i);
- }
- }
- let index = 0;
- sortedFaces.forEach((face) => {
- indices[index++] = face[0];
- indices[index++] = face[1];
- indices[index++] = face[2];
- });
-}
-var init_mesh_vertexData_functions = () => {};
-
-// node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js
-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");
- }
-}
-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");
-}
-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);
- 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;
-}
-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);
- }
-}
-
-// node_modules/@babylonjs/core/Materials/materialHelper.functions.js
-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 / (Math.log(camera.maxZ + 1) / Math.LN2));
- }
-}
-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);
- if (linearSpace) {
- scene.fogColor.toLinearSpaceToRef(_TempFogColor, scene.getEngine().useExactSrgbConversions);
- effect.setColor3("vFogColor", _TempFogColor);
- } else {
- effect.setColor3("vFogColor", scene.fogColor);
- }
- }
-}
-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;
-}
-function PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) {
- _TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;
- _TmpMorphInfluencers.NORMAL = false;
- _TmpMorphInfluencers.TANGENT = false;
- _TmpMorphInfluencers.UV = false;
- _TmpMorphInfluencers.UV2 = false;
- _TmpMorphInfluencers.COLOR = false;
- PrepareAttributesForMorphTargets(attribs, mesh, _TmpMorphInfluencers, true);
-}
-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);
- }
- }
- }
-}
-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");
- }
-}
-function BindMorphTargetParameters(abstractMesh, effect) {
- const manager = abstractMesh.morphTargetManager;
- if (!abstractMesh || !manager) {
- return;
- }
- effect.setFloatArray("morphTargetInfluences", manager.influences);
-}
-function BindSceneUniformBuffer(effect, sceneUbo) {
- sceneUbo.bindToEffect(effect, "Scene");
-}
-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;
- }
-}
-function BindTextureMatrix(texture, uniformBuffer, key) {
- const matrix = texture.getTextureMatrix();
- uniformBuffer.updateMatrix(key + "Matrix", matrix);
-}
-function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {
- const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"];
- if (enabled) {
- attribs.push("bakedVertexAnimationSettingsInstanced");
- }
-}
-function _CopyBonesTransformationMatrices(source, target) {
- target.set(source);
- return target;
-}
-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 * (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]);
- }
- }
- }
- }
-}
-function BindLightProperties(light, effect, lightIndex) {
- light.transferToEffect(effect, lightIndex + "");
-}
-function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {
- light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);
-}
-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);
- }
-}
-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`);
- }
- }
-}
-function PrepareAttributesForInstances(attribs, defines) {
- if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) {
- PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]);
- }
- if (defines.INSTANCESCOLOR) {
- attribs.push(`instanceColor`);
- }
-}
-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++;
-}
-function GetFogState(mesh, scene) {
- return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0;
-}
-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;
- }
-}
-function PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) {
- if (!defines._areLightsDirty) {
- return defines._needNormals;
- }
- let lightIndex = 0;
- const state = {
- needNormals: defines._needNormals,
- 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;
- 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;
-}
-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);
- 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;
- }
- if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
- state.specularEnabled = true;
- }
- 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;
- }
-}
-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();
- }
-}
-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;
- }
- }
-}
-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;
- }
-}
-function PrepareDefinesForBakedVertexAnimation(mesh, defines) {
- const manager = mesh.bakedVertexAnimationManager;
- defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false;
-}
-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;
-}
-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();
- }
- }
-}
-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();
- }
-}
-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();
- }
-}
-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;
-}
-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);
- }
-}
-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");
- }
-}
-var _TempFogColor, _TmpMorphInfluencers;
-var init_materialHelper_functions = __esm(() => {
- init_logger();
- init_math_color();
- init_engineStore();
- init_lightConstants();
- _TempFogColor = Color3.Black();
- _TmpMorphInfluencers = {
- NUM_MORPH_INFLUENCERS: 0,
- NORMAL: false,
- TANGENT: false,
- UV: false,
- UV2: false,
- COLOR: false
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/abstractAudioNode.js
-class AbstractAudioNode {
- constructor(engine, nodeType) {
- this.onDisposeObservable = new Observable;
- this.engine = engine;
- if (nodeType & 1) {
- this._upstreamNodes = new Set;
- }
- if (nodeType & 2) {
- this._downstreamNodes = new Set;
- }
- }
- dispose() {
- if (this._downstreamNodes) {
- for (const node of Array.from(this._downstreamNodes)) {
- if (!this._disconnect(node)) {
- throw new Error("Disconnect failed");
- }
- }
- this._downstreamNodes.clear();
- }
- if (this._upstreamNodes) {
- for (const node of Array.from(this._upstreamNodes)) {
- if (!node._disconnect(this)) {
- throw new Error("Disconnect failed");
- }
- }
- this._upstreamNodes.clear();
- }
- this.onDisposeObservable.notifyObservers(this);
- this.onDisposeObservable.clear();
- }
- _connect(node) {
- if (!this._downstreamNodes) {
- return false;
- }
- if (this._downstreamNodes.has(node)) {
- return false;
- }
- if (!node._onConnect(this)) {
- return false;
- }
- this._downstreamNodes.add(node);
- return true;
- }
- _disconnect(node) {
- if (!this._downstreamNodes) {
- return false;
- }
- if (!this._downstreamNodes.delete(node)) {
- return false;
- }
- return node._onDisconnect(this);
- }
- _onConnect(node) {
- if (!this._upstreamNodes) {
- return false;
- }
- if (this._upstreamNodes.has(node)) {
- return false;
- }
- this._upstreamNodes.add(node);
- return true;
- }
- _onDisconnect(node) {
- return this._upstreamNodes?.delete(node) ?? false;
- }
-}
-var AudioNodeType, AbstractNamedAudioNode;
-var init_abstractAudioNode = __esm(() => {
- init_observable();
- (function(AudioNodeType2) {
- AudioNodeType2[AudioNodeType2["HAS_INPUTS"] = 1] = "HAS_INPUTS";
- AudioNodeType2[AudioNodeType2["HAS_OUTPUTS"] = 2] = "HAS_OUTPUTS";
- AudioNodeType2[AudioNodeType2["HAS_INPUTS_AND_OUTPUTS"] = 3] = "HAS_INPUTS_AND_OUTPUTS";
- })(AudioNodeType || (AudioNodeType = {}));
- AbstractNamedAudioNode = class AbstractNamedAudioNode extends AbstractAudioNode {
- constructor(name18, engine, nodeType) {
- super(engine, nodeType);
- this.onNameChangedObservable = new Observable;
- this._name = name18;
- }
- get name() {
- return this._name;
- }
- set name(newName) {
- if (this._name === newName) {
- return;
- }
- const oldName = this._name;
- this._name = newName;
- this.onNameChangedObservable.notifyObservers({ newName, oldName, node: this });
- }
- dispose() {
- super.dispose();
- this.onNameChangedObservable.clear();
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/abstractAudioSubNode.js
-var _AbstractAudioSubNode;
-var init_abstractAudioSubNode = __esm(() => {
- init_abstractAudioNode();
- _AbstractAudioSubNode = class _AbstractAudioSubNode extends AbstractNamedAudioNode {
- constructor(name18, engine) {
- super(name18, engine, 3);
- }
- connect(node) {
- if (!this._connect(node)) {
- throw new Error("Connect failed");
- }
- }
- disconnect(node) {
- if (!this._disconnect(node)) {
- throw new Error("Disconnect failed");
- }
- }
- disconnectAll() {
- if (!this._downstreamNodes) {
- throw new Error("Disconnect failed");
- }
- const it = this._downstreamNodes.values();
- for (let next = it.next();!next.done; next = it.next()) {
- if (!this._disconnect(next.value)) {
- throw new Error("Disconnect failed");
- }
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/volumeAudioSubNode.js
-function _GetVolumeAudioSubNode(subGraph) {
- return subGraph.getSubNode("Volume");
-}
-function _GetVolumeAudioProperty(subGraph, property) {
- return _GetVolumeAudioSubNode(subGraph)?.[property] ?? _VolumeAudioDefaults[property];
-}
-var _VolumeAudioDefaults, _VolumeAudioSubNode;
-var init_volumeAudioSubNode = __esm(() => {
- init_abstractAudioSubNode();
- _VolumeAudioDefaults = {
- volume: 1
- };
- _VolumeAudioSubNode = class _VolumeAudioSubNode extends _AbstractAudioSubNode {
- constructor(engine) {
- super("Volume", engine);
- }
- setOptions(options) {
- this.volume = options.volume ?? _VolumeAudioDefaults.volume;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/abstractAudioAnalyzer.js
-function _HasAudioAnalyzerOptions(options) {
- return options.analyzerEnabled || options.analyzerFFTSize !== undefined || options.analyzerMinDecibels !== undefined || options.analyzerMaxDecibels !== undefined || options.analyzerSmoothing !== undefined;
-}
-
-class AbstractAudioAnalyzer {
- get frequencyBinCount() {
- return this.fftSize / 2;
- }
-}
-var _AudioAnalyzerDefaults;
-var init_abstractAudioAnalyzer = __esm(() => {
- _AudioAnalyzerDefaults = {
- fftSize: 2048,
- minDecibels: -100,
- maxDecibels: -30,
- smoothing: 0.8
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/audioAnalyzerSubNode.js
-function _GetAudioAnalyzerSubNode(subGraph) {
- return subGraph.getSubNode("Analyzer");
-}
-function _GetAudioAnalyzerProperty(subGraph, property) {
- return _GetAudioAnalyzerSubNode(subGraph)?.[property] ?? _AudioAnalyzerDefaults[property];
-}
-function _SetAudioAnalyzerProperty(subGraph, property, value) {
- subGraph.callOnSubNode("Analyzer", (node) => {
- node[property] = value;
- });
-}
-var _AudioAnalyzerSubNode;
-var init_audioAnalyzerSubNode = __esm(() => {
- init_abstractAudioAnalyzer();
- init_abstractAudioSubNode();
- _AudioAnalyzerSubNode = class _AudioAnalyzerSubNode extends _AbstractAudioSubNode {
- constructor(engine) {
- super("Analyzer", engine);
- }
- setOptions(options) {
- this.fftSize = options.analyzerFFTSize ?? _AudioAnalyzerDefaults.fftSize;
- this.minDecibels = options.analyzerMinDecibels ?? _AudioAnalyzerDefaults.minDecibels;
- this.maxDecibels = options.analyzerMaxDecibels ?? _AudioAnalyzerDefaults.maxDecibels;
- this.smoothing = options.analyzerSmoothing ?? _AudioAnalyzerDefaults.smoothing;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/audioAnalyzer.js
-function _GetEmptyByteFrequencyData() {
- if (!_emptyByteFrequencyData) {
- _emptyByteFrequencyData = new Uint8Array;
- }
- return _emptyByteFrequencyData;
-}
-function _GetEmptyFloatFrequencyData() {
- if (!_emptyFloatFrequencyData) {
- _emptyFloatFrequencyData = new Float32Array;
- }
- return _emptyFloatFrequencyData;
-}
-var _emptyByteFrequencyData = null, _emptyFloatFrequencyData = null, _AudioAnalyzer;
-var init_audioAnalyzer = __esm(() => {
- init_logger();
- init_abstractAudioAnalyzer();
- init_audioAnalyzerSubNode();
- _AudioAnalyzer = class _AudioAnalyzer extends AbstractAudioAnalyzer {
- constructor(subGraph) {
- super();
- this._subGraph = subGraph;
- }
- get fftSize() {
- return _GetAudioAnalyzerProperty(this._subGraph, "fftSize");
- }
- set fftSize(value) {
- _SetAudioAnalyzerProperty(this._subGraph, "fftSize", value);
- }
- get isEnabled() {
- return _GetAudioAnalyzerSubNode(this._subGraph) !== null;
- }
- get minDecibels() {
- return _GetAudioAnalyzerProperty(this._subGraph, "minDecibels");
- }
- set minDecibels(value) {
- _SetAudioAnalyzerProperty(this._subGraph, "minDecibels", value);
- }
- get maxDecibels() {
- return _GetAudioAnalyzerProperty(this._subGraph, "maxDecibels");
- }
- set maxDecibels(value) {
- _SetAudioAnalyzerProperty(this._subGraph, "maxDecibels", value);
- }
- get smoothing() {
- return _GetAudioAnalyzerProperty(this._subGraph, "smoothing");
- }
- set smoothing(value) {
- _SetAudioAnalyzerProperty(this._subGraph, "smoothing", value);
- }
- dispose() {
- const subNode = _GetAudioAnalyzerSubNode(this._subGraph);
- if (subNode) {
- this._subGraph.removeSubNode(subNode);
- subNode.dispose();
- }
- }
- async enableAsync() {
- const subNode = _GetAudioAnalyzerSubNode(this._subGraph);
- if (!subNode) {
- await this._subGraph.createAndAddSubNode("Analyzer");
- }
- return Promise.resolve();
- }
- getByteFrequencyData() {
- const subNode = _GetAudioAnalyzerSubNode(this._subGraph);
- if (!subNode) {
- Logger.Warn("AudioAnalyzer not enabled");
- this.enableAsync();
- return _GetEmptyByteFrequencyData();
- }
- return subNode.getByteFrequencyData();
- }
- getFloatFrequencyData() {
- const subNode = _GetAudioAnalyzerSubNode(this._subGraph);
- if (!subNode) {
- Logger.Warn("AudioAnalyzer not enabled");
- this.enableAsync();
- return _GetEmptyFloatFrequencyData();
- }
- return subNode.getFloatFrequencyData();
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/abstractAudioBus.js
-var AbstractAudioBus;
-var init_abstractAudioBus = __esm(() => {
- init_abstractAudioNode();
- init_volumeAudioSubNode();
- init_audioAnalyzer();
- AbstractAudioBus = class AbstractAudioBus extends AbstractNamedAudioNode {
- constructor(name18, engine) {
- super(name18, engine, 3);
- this._analyzer = null;
- }
- get analyzer() {
- return this._analyzer ?? (this._analyzer = new _AudioAnalyzer(this._subGraph));
- }
- get volume() {
- return _GetVolumeAudioProperty(this._subGraph, "volume");
- }
- set volume(value) {
- const node = _GetVolumeAudioSubNode(this._subGraph);
- if (!node) {
- throw new Error("No volume subnode");
- }
- node.volume = value;
- }
- dispose() {
- super.dispose();
- this._analyzer?.dispose();
- this._analyzer = null;
- this._subGraph.dispose();
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/abstractSound.js
-var AbstractSound;
-var init_abstractSound = __esm(() => {
- init_observable();
- init_abstractAudioNode();
- init_volumeAudioSubNode();
- init_audioAnalyzer();
- AbstractSound = class AbstractSound extends AbstractNamedAudioNode {
- constructor(name18, engine) {
- super(name18, engine, 3);
- this._analyzer = null;
- this._newestInstance = null;
- this._outBus = null;
- this._privateInstances = new Set;
- this._state = 1;
- this._instances = this._privateInstances;
- this.onEndedObservable = new Observable;
- this._onInstanceEnded = (instance) => {
- if (this._newestInstance === instance) {
- this._newestInstance = null;
- }
- this._privateInstances.delete(instance);
- if (this._instances.size === 0) {
- this._state = 1;
- this.onEndedObservable.notifyObservers(this);
- }
- };
- this._onOutBusDisposed = () => {
- this.outBus = null;
- };
- }
- get analyzer() {
- return this._analyzer ?? (this._analyzer = new _AudioAnalyzer(this._subGraph));
- }
- get autoplay() {
- return this._options.autoplay;
- }
- get currentTime() {
- const instance = this._getNewestInstance();
- return instance ? instance.currentTime : 0;
- }
- set currentTime(value) {
- this.startOffset = value;
- const instance = this._getNewestInstance();
- if (instance) {
- instance.currentTime = value;
- }
- }
- get loop() {
- return this._options.loop;
- }
- set loop(value) {
- this._options.loop = value;
- }
- get maxInstances() {
- return this._options.maxInstances;
- }
- set maxInstances(value) {
- this._options.maxInstances = value;
- }
- get outBus() {
- return this._outBus;
- }
- set outBus(outBus) {
- if (this._outBus === outBus) {
- return;
- }
- if (this._outBus) {
- this._outBus.onDisposeObservable.removeCallback(this._onOutBusDisposed);
- if (!this._disconnect(this._outBus)) {
- throw new Error("Disconnect failed");
- }
- }
- this._outBus = outBus;
- if (this._outBus) {
- this._outBus.onDisposeObservable.add(this._onOutBusDisposed);
- if (!this._connect(this._outBus)) {
- throw new Error("Connect failed");
- }
- }
- }
- get startOffset() {
- return this._options.startOffset;
- }
- set startOffset(value) {
- this._options.startOffset = value;
- }
- get state() {
- return this._state;
- }
- get volume() {
- return _GetVolumeAudioProperty(this._subGraph, "volume");
- }
- set volume(value) {
- const node = _GetVolumeAudioSubNode(this._subGraph);
- if (!node) {
- throw new Error("No volume subnode");
- }
- node.volume = value;
- }
- dispose() {
- super.dispose();
- this.stop();
- this._analyzer?.dispose();
- this._analyzer = null;
- this._newestInstance = null;
- this._outBus = null;
- this._privateInstances.clear();
- this.onEndedObservable.clear();
- }
- pause() {
- const it = this._instances.values();
- for (let next = it.next();!next.done; next = it.next()) {
- next.value.pause();
- }
- this._state = 5;
- }
- resume() {
- if (this._state !== 5) {
- return;
- }
- const it = this._instances.values();
- for (let next = it.next();!next.done; next = it.next()) {
- next.value.resume();
- }
- this._state = 3;
- }
- _beforePlay(instance) {
- if (this.state === 5 && this._instances.size > 0) {
- this.resume();
- return;
- }
- instance.onEndedObservable.addOnce(this._onInstanceEnded);
- this._privateInstances.add(instance);
- this._newestInstance = instance;
- }
- _afterPlay(instance) {
- this._state = instance.state;
- }
- _getNewestInstance() {
- if (this._instances.size === 0) {
- return null;
- }
- if (!this._newestInstance) {
- const it = this._instances.values();
- for (let next = it.next();!next.done; next = it.next()) {
- this._newestInstance = next.value;
- }
- }
- return this._newestInstance;
- }
- _setState(state) {
- this._state = state;
- }
- _stopExcessInstances() {
- if (this.maxInstances < Infinity) {
- const numberOfInstancesToStop = Array.from(this._instances).filter((instance) => instance.state === 3).length - this.maxInstances;
- const it = this._instances.values();
- for (let i = 0;i < numberOfInstancesToStop; i++) {
- const instance = it.next().value;
- instance.stop();
- }
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/audioBus.js
-var AudioBus;
-var init_audioBus = __esm(() => {
- init_abstractAudioBus();
- AudioBus = class AudioBus extends AbstractAudioBus {
- constructor(name18, engine) {
- super(name18, engine);
- this._outBus = null;
- this._onOutBusDisposed = () => {
- this.outBus = this.engine.defaultMainBus;
- };
- }
- get outBus() {
- return this._outBus;
- }
- set outBus(outBus) {
- if (this._outBus === outBus) {
- return;
- }
- if (this._outBus) {
- this._outBus.onDisposeObservable.removeCallback(this._onOutBusDisposed);
- if (!this._disconnect(this._outBus)) {
- throw new Error("Disconnect failed");
- }
- }
- this._outBus = outBus;
- if (this._outBus) {
- this._outBus.onDisposeObservable.add(this._onOutBusDisposed);
- if (!this._connect(this._outBus)) {
- throw new Error("Connect failed");
- }
- }
- }
- dispose() {
- super.dispose();
- this._outBus = null;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/mainAudioBus.js
-var MainAudioBus;
-var init_mainAudioBus = __esm(() => {
- init_abstractAudioBus();
- MainAudioBus = class MainAudioBus extends AbstractAudioBus {
- constructor(name18, engine) {
- super(name18, engine);
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/staticSound.js
-var StaticSound;
-var init_staticSound = __esm(() => {
- init_abstractSound();
- StaticSound = class StaticSound extends AbstractSound {
- constructor(name18, engine) {
- super(name18, engine);
- }
- get duration() {
- return this._options.duration;
- }
- set duration(value) {
- this._options.duration = value;
- }
- get loopStart() {
- return this._options.loopStart;
- }
- set loopStart(value) {
- this._options.loopStart = value;
- }
- get loopEnd() {
- return this._options.loopEnd;
- }
- set loopEnd(value) {
- this._options.loopEnd = value;
- }
- get pitch() {
- return this._options.pitch;
- }
- set pitch(value) {
- this._options.pitch = value;
- const it = this._instances.values();
- for (let instance = it.next();!instance.done; instance = it.next()) {
- instance.value.pitch = value;
- }
- }
- get playbackRate() {
- return this._options.playbackRate;
- }
- set playbackRate(value) {
- this._options.playbackRate = value;
- const it = this._instances.values();
- for (let instance = it.next();!instance.done; instance = it.next()) {
- instance.value.playbackRate = value;
- }
- }
- play(options = {}) {
- if (this.state === 5) {
- this.resume();
- return;
- }
- options.duration ?? (options.duration = this.duration);
- options.loop ?? (options.loop = this.loop);
- options.loopStart ?? (options.loopStart = this.loopStart);
- options.loopEnd ?? (options.loopEnd = this.loopEnd);
- options.startOffset ?? (options.startOffset = this.startOffset);
- options.volume ?? (options.volume = 1);
- options.waitTime ?? (options.waitTime = 0);
- const instance = this._createInstance();
- this._beforePlay(instance);
- instance.play(options);
- this._afterPlay(instance);
- this._stopExcessInstances();
- }
- stop(options = {}) {
- if (options.waitTime && 0 < options.waitTime) {
- this._setState(0);
- } else {
- this._setState(1);
- }
- if (!this._instances) {
- return;
- }
- for (const instance of Array.from(this._instances)) {
- instance.stop(options);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/staticSoundBuffer.js
-class StaticSoundBuffer {
- constructor(engine) {
- this.engine = engine;
- }
-}
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/streamingSound.js
-var StreamingSound;
-var init_streamingSound = __esm(() => {
- init_abstractSound();
- StreamingSound = class StreamingSound extends AbstractSound {
- constructor(name18, engine) {
- super(name18, engine);
- this._preloadedInstances = new Array;
- }
- get preloadCount() {
- return this._options.preloadCount ?? 1;
- }
- get preloadCompletedCount() {
- return this._preloadedInstances.length;
- }
- preloadInstanceAsync() {
- const instance = this._createInstance();
- this._addPreloadedInstance(instance);
- return instance.preloadedPromise;
- }
- async preloadInstancesAsync(count) {
- for (let i = 0;i < count; i++) {
- this.preloadInstanceAsync();
- }
- await Promise.all(this._preloadedInstances.map((instance) => instance.preloadedPromise));
- }
- play(options = {}) {
- if (this.state === 5) {
- this.resume();
- return;
- }
- let instance;
- if (this.preloadCompletedCount > 0) {
- instance = this._preloadedInstances[0];
- instance.startOffset = this.startOffset;
- this._removePreloadedInstance(instance);
- } else {
- instance = this._createInstance();
- }
- const onInstanceStateChanged = () => {
- if (instance.state === 3) {
- this._stopExcessInstances();
- instance.onStateChangedObservable.removeCallback(onInstanceStateChanged);
- }
- };
- instance.onStateChangedObservable.add(onInstanceStateChanged);
- options.startOffset ?? (options.startOffset = this.startOffset);
- options.loop ?? (options.loop = this.loop);
- options.volume ?? (options.volume = 1);
- this._beforePlay(instance);
- instance.play(options);
- this._afterPlay(instance);
- }
- stop() {
- this._setState(1);
- if (!this._instances) {
- return;
- }
- for (const instance of Array.from(this._instances)) {
- instance.stop();
- }
- }
- _addPreloadedInstance(instance) {
- if (!this._preloadedInstances.includes(instance)) {
- this._preloadedInstances.push(instance);
- }
- }
- _removePreloadedInstance(instance) {
- const index = this._preloadedInstances.indexOf(instance);
- if (index !== -1) {
- this._preloadedInstances.splice(index, 1);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/abstractSpatialAudio.js
-function _HasSpatialAudioOptions(options) {
- return options.spatialEnabled || options.spatialAutoUpdate !== undefined || options.spatialConeInnerAngle !== undefined || options.spatialConeOuterAngle !== undefined || options.spatialConeOuterVolume !== undefined || options.spatialDistanceModel !== undefined || options.spatialMaxDistance !== undefined || options.spatialMinDistance !== undefined || options.spatialMinUpdateTime !== undefined || options.spatialPanningModel !== undefined || options.spatialPosition !== undefined || options.spatialRolloffFactor !== undefined || options.spatialRotation !== undefined || options.spatialRotationQuaternion !== undefined;
-}
-
-class AbstractSpatialAudio {
-}
-var _SpatialAudioDefaults;
-var init_abstractSpatialAudio = __esm(() => {
- init_math_vector();
- _SpatialAudioDefaults = {
- coneInnerAngle: 6.28318530718,
- coneOuterAngle: 6.28318530718,
- coneOuterVolume: 0,
- distanceModel: "linear",
- maxDistance: 1e4,
- minDistance: 1,
- panningModel: "equalpower",
- position: Vector3.Zero(),
- rolloffFactor: 1,
- rotation: Vector3.Zero(),
- rotationQuaternion: new Quaternion
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/abstractStereoAudio.js
-function _HasStereoAudioOptions(options) {
- return options.stereoEnabled || options.stereoPan !== undefined;
-}
-
-class AbstractStereoAudio {
-}
-var _StereoAudioDefaults;
-var init_abstractStereoAudio = __esm(() => {
- _StereoAudioDefaults = {
- pan: 0
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/stereoAudioSubNode.js
-function _GetStereoAudioSubNode(subGraph) {
- return subGraph.getSubNode("Stereo");
-}
-function _GetStereoAudioProperty(subGraph, property) {
- return _GetStereoAudioSubNode(subGraph)?.[property] ?? _StereoAudioDefaults[property];
-}
-function _SetStereoAudioProperty(subGraph, property, value) {
- subGraph.callOnSubNode("Stereo", (node) => {
- node[property] = value;
- });
-}
-var _StereoAudioSubNode;
-var init_stereoAudioSubNode = __esm(() => {
- init_abstractAudioSubNode();
- init_abstractStereoAudio();
- _StereoAudioSubNode = class _StereoAudioSubNode extends _AbstractAudioSubNode {
- constructor(engine) {
- super("Stereo", engine);
- }
- setOptions(options) {
- this.pan = options.stereoPan ?? _StereoAudioDefaults.pan;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/stereoAudio.js
-var _StereoAudio;
-var init_stereoAudio = __esm(() => {
- init_abstractStereoAudio();
- init_stereoAudioSubNode();
- _StereoAudio = class _StereoAudio extends AbstractStereoAudio {
- constructor(subGraph) {
- super();
- this._subGraph = subGraph;
- }
- get pan() {
- return _GetStereoAudioProperty(this._subGraph, "pan");
- }
- set pan(value) {
- _SetStereoAudioProperty(this._subGraph, "pan", value);
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/components/spatialAudioAttacherComponent.js
-class _SpatialAudioAttacherComponent {
- constructor(spatialAudioNode) {
- this._attachmentType = 3;
- this._position = new Vector3;
- this._rotationQuaternion = new Quaternion;
- this._sceneNode = null;
- this._useBoundingBox = false;
- this.dispose = () => {
- this.detach();
- };
- this._spatialAudioNode = spatialAudioNode;
- }
- get isAttached() {
- return this._sceneNode !== null;
- }
- attach(sceneNode, useBoundingBox, attachmentType) {
- if (this._sceneNode === sceneNode) {
- return;
- }
- this.detach();
- if (!sceneNode) {
- return;
- }
- this._attachmentType = attachmentType;
- this._sceneNode = sceneNode;
- this._sceneNode.onDisposeObservable.add(this.dispose);
- this._useBoundingBox = useBoundingBox;
- }
- detach() {
- this._sceneNode?.onDisposeObservable.removeCallback(this.dispose);
- this._sceneNode = null;
- }
- update() {
- if (this._attachmentType & 1) {
- if (this._useBoundingBox && this._sceneNode.getBoundingInfo) {
- this._position.copyFrom(this._sceneNode.getBoundingInfo().boundingBox.centerWorld);
- } else {
- this._sceneNode?.getWorldMatrix().getTranslationToRef(this._position);
- }
- this._spatialAudioNode.position.copyFrom(this._position);
- this._spatialAudioNode._updatePosition();
- }
- if (this._attachmentType & 2) {
- this._sceneNode?.getWorldMatrix().decompose(undefined, this._rotationQuaternion);
- this._spatialAudioNode.rotationQuaternion.copyFrom(this._rotationQuaternion);
- this._spatialAudioNode._updateRotation();
- }
- }
-}
-var init_spatialAudioAttacherComponent = __esm(() => {
- init_math_vector();
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/spatialAudioSubNode.js
-function _GetSpatialAudioSubNode(subGraph) {
- return subGraph.getSubNode("Spatial");
-}
-function _GetSpatialAudioProperty(subGraph, property) {
- return _GetSpatialAudioSubNode(subGraph)?.[property] ?? _SpatialAudioDefaults[property];
-}
-function _SetSpatialAudioProperty(subGraph, property, value) {
- subGraph.callOnSubNode("Spatial", (node) => {
- node[property] = value;
- });
-}
-var _SpatialAudioSubNode;
-var init_spatialAudioSubNode = __esm(() => {
- init_spatialAudioAttacherComponent();
- init_abstractSpatialAudio();
- init_abstractAudioSubNode();
- _SpatialAudioSubNode = class _SpatialAudioSubNode extends _AbstractAudioSubNode {
- constructor(engine) {
- super("Spatial", engine);
- this._attacherComponent = null;
- }
- get isAttached() {
- return this._attacherComponent !== null && this._attacherComponent.isAttached;
- }
- attach(sceneNode, useBoundingBox, attachmentType) {
- this.detach();
- if (!this._attacherComponent) {
- this._attacherComponent = new _SpatialAudioAttacherComponent(this);
- }
- this._attacherComponent.attach(sceneNode, useBoundingBox, attachmentType);
- }
- detach() {
- this._attacherComponent?.detach();
- }
- dispose() {
- super.dispose();
- this._attacherComponent?.dispose();
- this._attacherComponent = null;
- }
- setOptions(options) {
- this.coneInnerAngle = options.spatialConeInnerAngle ?? _SpatialAudioDefaults.coneInnerAngle;
- this.coneOuterAngle = options.spatialConeOuterAngle ?? _SpatialAudioDefaults.coneOuterAngle;
- this.coneOuterVolume = options.spatialConeOuterVolume ?? _SpatialAudioDefaults.coneOuterVolume;
- this.distanceModel = options.spatialDistanceModel ?? _SpatialAudioDefaults.distanceModel;
- this.maxDistance = options.spatialMaxDistance ?? _SpatialAudioDefaults.maxDistance;
- this.minDistance = options.spatialMinDistance ?? _SpatialAudioDefaults.minDistance;
- this.panningModel = options.spatialPanningModel ?? _SpatialAudioDefaults.panningModel;
- this.rolloffFactor = options.spatialRolloffFactor ?? _SpatialAudioDefaults.rolloffFactor;
- if (options.spatialPosition) {
- this.position = options.spatialPosition.clone();
- }
- if (options.spatialRotationQuaternion) {
- this.rotationQuaternion = options.spatialRotationQuaternion.clone();
- } else if (options.spatialRotation) {
- this.rotation = options.spatialRotation.clone();
- } else {
- this.rotationQuaternion = _SpatialAudioDefaults.rotationQuaternion.clone();
- }
- this.update();
- }
- update() {
- if (this.isAttached) {
- this._attacherComponent?.update();
- } else {
- this._updatePosition();
- this._updateRotation();
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/spatialWebAudioSubNode.js
-function d2r(degrees) {
- return degrees * Math.PI / 180;
-}
-function r2d(radians) {
- return radians * 180 / Math.PI;
-}
-async function _CreateSpatialAudioSubNodeAsync(engine) {
- return new _SpatialWebAudioSubNode(engine);
-}
-var TmpMatrix, TmpQuaternion, TmpVector, _SpatialWebAudioSubNode;
-var init_spatialWebAudioSubNode = __esm(() => {
- init_math_vector();
- init_spatialAudioSubNode();
- init_abstractSpatialAudio();
- TmpMatrix = Matrix.Zero();
- TmpQuaternion = new Quaternion;
- TmpVector = Vector3.Zero();
- _SpatialWebAudioSubNode = class _SpatialWebAudioSubNode extends _SpatialAudioSubNode {
- constructor(engine) {
- super(engine);
- this._lastPosition = Vector3.Zero();
- this._lastRotation = Vector3.Zero();
- this._lastRotationQuaternion = new Quaternion;
- this.position = _SpatialAudioDefaults.position.clone();
- this.rotation = _SpatialAudioDefaults.rotation.clone();
- this.rotationQuaternion = _SpatialAudioDefaults.rotationQuaternion.clone();
- this.node = new PannerNode(engine._audioContext);
- }
- get coneInnerAngle() {
- return d2r(this.node.coneInnerAngle);
- }
- set coneInnerAngle(value) {
- this.node.coneInnerAngle = r2d(value);
- }
- get coneOuterAngle() {
- return d2r(this.node.coneOuterAngle);
- }
- set coneOuterAngle(value) {
- this.node.coneOuterAngle = r2d(value);
- }
- get coneOuterVolume() {
- return this.node.coneOuterGain;
- }
- set coneOuterVolume(value) {
- this.node.coneOuterGain = value;
- }
- get distanceModel() {
- return this.node.distanceModel;
- }
- set distanceModel(value) {
- this.node.distanceModel = value;
- const maxDistance = this.node.maxDistance;
- this.node.maxDistance = maxDistance + 0.001;
- this.node.maxDistance = maxDistance;
- }
- get minDistance() {
- return this.node.refDistance;
- }
- set minDistance(value) {
- this.node.refDistance = value;
- }
- get maxDistance() {
- return this.node.maxDistance;
- }
- set maxDistance(value) {
- this.node.maxDistance = value;
- }
- get panningModel() {
- return this.node.panningModel;
- }
- set panningModel(value) {
- this.node.panningModel = value;
- }
- get rolloffFactor() {
- return this.node.rolloffFactor;
- }
- set rolloffFactor(value) {
- this.node.rolloffFactor = value;
- }
- get _inNode() {
- return this.node;
- }
- get _outNode() {
- return this.node;
- }
- _updatePosition() {
- if (this._lastPosition.equalsWithEpsilon(this.position)) {
- return;
- }
- this.engine._setAudioParam(this.node.positionX, this.position.x);
- this.engine._setAudioParam(this.node.positionY, this.position.y);
- this.engine._setAudioParam(this.node.positionZ, this.position.z);
- this._lastPosition.copyFrom(this.position);
- }
- _updateRotation() {
- if (!this._lastRotationQuaternion.equalsWithEpsilon(this.rotationQuaternion)) {
- TmpQuaternion.copyFrom(this.rotationQuaternion);
- this._lastRotationQuaternion.copyFrom(this.rotationQuaternion);
- } else if (!this._lastRotation.equalsWithEpsilon(this.rotation)) {
- Quaternion.FromEulerAnglesToRef(this.rotation.x, this.rotation.y, this.rotation.z, TmpQuaternion);
- this._lastRotation.copyFrom(this.rotation);
- } else {
- return;
- }
- Matrix.FromQuaternionToRef(TmpQuaternion, TmpMatrix);
- Vector3.TransformNormalToRef(Vector3.RightReadOnly, TmpMatrix, TmpVector);
- this.engine._setAudioParam(this.node.orientationX, TmpVector.x);
- this.engine._setAudioParam(this.node.orientationY, TmpVector.y);
- this.engine._setAudioParam(this.node.orientationZ, TmpVector.z);
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this.node.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this.node.disconnect(node._inNode);
- }
- return true;
- }
- getClassName() {
- return "_SpatialWebAudioSubNode";
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/stereoWebAudioSubNode.js
-async function _CreateStereoAudioSubNodeAsync(engine) {
- return new _StereoWebAudioSubNode(engine);
-}
-var _StereoWebAudioSubNode;
-var init_stereoWebAudioSubNode = __esm(() => {
- init_stereoAudioSubNode();
- _StereoWebAudioSubNode = class _StereoWebAudioSubNode extends _StereoAudioSubNode {
- constructor(engine) {
- super(engine);
- this._pan = 0;
- this.node = new StereoPannerNode(engine._audioContext);
- }
- get pan() {
- return this._pan;
- }
- set pan(value) {
- this._pan = value;
- this.engine._setAudioParam(this.node.pan, value);
- }
- get _inNode() {
- return this.node;
- }
- get _outNode() {
- return this.node;
- }
- getClassName() {
- return "_StereoWebAudioSubNode";
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this.node.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this.node.disconnect(node._inNode);
- }
- return true;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subNodes/abstractAudioSubGraph.js
-class _AbstractAudioSubGraph {
- constructor() {
- this._createSubNodePromises = {};
- this._isDisposed = false;
- this._subNodes = {};
- this._onSubNodeDisposed = (node) => {
- const subNode = node;
- delete this._subNodes[subNode.name];
- this._onSubNodesChanged();
- };
- }
- callOnSubNode(name18, callback) {
- const node = this.getSubNode(name18);
- if (node) {
- callback(node);
- return;
- }
- this._createSubNodePromisesResolved().then(() => {
- const node2 = this.getSubNode(name18);
- if (node2) {
- callback(node2);
- return;
- }
- this.createAndAddSubNode(name18).then((node3) => {
- callback(node3);
- });
- });
- }
- createAndAddSubNode(name18) {
- var _a;
- (_a = this._createSubNodePromises)[name18] || (_a[name18] = this._createSubNode(name18).then((node) => {
- this._addSubNode(node);
- return node;
- }));
- return this._createSubNodePromises[name18];
- }
- dispose() {
- this._isDisposed = true;
- const subNodes = Object.values(this._subNodes);
- for (const subNode of subNodes) {
- subNode.dispose();
- }
- this._subNodes = {};
- this._createSubNodePromises = {};
- }
- getSubNode(name18) {
- return this._subNodes[name18] ?? null;
- }
- async removeSubNode(subNode) {
- await this._createSubNodePromisesResolved();
- const name18 = subNode.name;
- if (this._subNodes[name18]) {
- delete this._subNodes[name18];
- }
- delete this._createSubNodePromises[name18];
- this._onSubNodesChanged();
- }
- _createSubNodePromisesResolved() {
- return Promise.all(Object.values(this._createSubNodePromises));
- }
- _addSubNode(node) {
- if (this._isDisposed) {
- node.dispose();
- return;
- }
- this._subNodes[node.name] = node;
- node.onDisposeObservable.addOnce(this._onSubNodeDisposed);
- this._onSubNodesChanged();
- }
-}
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/volumeWebAudioSubNode.js
-async function _CreateVolumeAudioSubNodeAsync(engine) {
- return new _VolumeWebAudioSubNode(engine);
-}
-var _VolumeWebAudioSubNode;
-var init_volumeWebAudioSubNode = __esm(() => {
- init_volumeAudioSubNode();
- _VolumeWebAudioSubNode = class _VolumeWebAudioSubNode extends _VolumeAudioSubNode {
- constructor(engine) {
- super(engine);
- this._volume = 1;
- this.node = new GainNode(engine._audioContext);
- }
- get volume() {
- return this._volume;
- }
- set volume(value) {
- this._volume = value;
- this.engine._setAudioParam(this.node.gain, value);
- }
- get _inNode() {
- return this.node;
- }
- get _outNode() {
- return this.node;
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this.node.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this.node.disconnect(node._inNode);
- }
- return true;
- }
- getClassName() {
- return "_VolumeWebAudioSubNode";
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/webAudioAnalyzerSubNode.js
-async function _CreateAudioAnalyzerSubNodeAsync(engine) {
- return new _WebAudioAnalyzerSubNode(engine);
-}
-var _WebAudioAnalyzerSubNode;
-var init_webAudioAnalyzerSubNode = __esm(() => {
- init_audioAnalyzerSubNode();
- init_audioAnalyzer();
- _WebAudioAnalyzerSubNode = class _WebAudioAnalyzerSubNode extends _AudioAnalyzerSubNode {
- constructor(engine) {
- super(engine);
- this._byteFrequencyData = null;
- this._floatFrequencyData = null;
- this._analyzerNode = new AnalyserNode(engine._audioContext);
- }
- get fftSize() {
- return this._analyzerNode.fftSize;
- }
- set fftSize(value) {
- if (value === this._analyzerNode.fftSize) {
- return;
- }
- this._analyzerNode.fftSize = value;
- this._clearArrays();
- }
- get _inNode() {
- return this._analyzerNode;
- }
- get minDecibels() {
- return this._analyzerNode.minDecibels;
- }
- set minDecibels(value) {
- this._analyzerNode.minDecibels = value;
- }
- get maxDecibels() {
- return this._analyzerNode.maxDecibels;
- }
- set maxDecibels(value) {
- this._analyzerNode.maxDecibels = value;
- }
- get smoothing() {
- return this._analyzerNode.smoothingTimeConstant;
- }
- set smoothing(value) {
- this._analyzerNode.smoothingTimeConstant = value;
- }
- dispose() {
- super.dispose();
- this._clearArrays();
- this._byteFrequencyData = null;
- this._floatFrequencyData = null;
- this._analyzerNode.disconnect();
- }
- getClassName() {
- return "_WebAudioAnalyzerSubNode";
- }
- getByteFrequencyData() {
- if (!this._byteFrequencyData || this._byteFrequencyData.length === 0) {
- this._byteFrequencyData = new Uint8Array(this._analyzerNode.frequencyBinCount);
- }
- this._analyzerNode.getByteFrequencyData(this._byteFrequencyData);
- return this._byteFrequencyData;
- }
- getFloatFrequencyData() {
- if (!this._floatFrequencyData || this._floatFrequencyData.length === 0) {
- this._floatFrequencyData = new Float32Array(this._analyzerNode.frequencyBinCount);
- }
- this._analyzerNode.getFloatFrequencyData(this._floatFrequencyData);
- return this._floatFrequencyData;
- }
- _clearArrays() {
- this._byteFrequencyData?.set(_GetEmptyByteFrequencyData());
- this._floatFrequencyData?.set(_GetEmptyFloatFrequencyData());
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/webAudioBaseSubGraph.js
-var _WebAudioBaseSubGraph;
-var init_webAudioBaseSubGraph = __esm(() => {
- init_audioAnalyzerSubNode();
- init_volumeAudioSubNode();
- init_abstractAudioAnalyzer();
- init_volumeWebAudioSubNode();
- init_webAudioAnalyzerSubNode();
- _WebAudioBaseSubGraph = class _WebAudioBaseSubGraph extends _AbstractAudioSubGraph {
- constructor(owner) {
- super();
- this._outputNode = null;
- this._owner = owner;
- }
- async init(options) {
- const hasAnalyzerOptions = _HasAudioAnalyzerOptions(options);
- if (hasAnalyzerOptions) {
- await this.createAndAddSubNode("Analyzer");
- }
- await this.createAndAddSubNode("Volume");
- await this._createSubNodePromisesResolved();
- if (hasAnalyzerOptions) {
- const analyzerNode = _GetAudioAnalyzerSubNode(this);
- if (!analyzerNode) {
- throw new Error("No analyzer subnode.");
- }
- analyzerNode.setOptions(options);
- }
- const volumeNode = _GetVolumeAudioSubNode(this);
- if (!volumeNode) {
- throw new Error("No volume subnode.");
- }
- volumeNode.setOptions(options);
- if (volumeNode.getClassName() !== "_VolumeWebAudioSubNode") {
- throw new Error("Not a WebAudio subnode.");
- }
- this._outputNode = volumeNode.node;
- if (this._outputNode && this._downstreamNodes) {
- const it = this._downstreamNodes.values();
- for (let next = it.next();!next.done; next = it.next()) {
- const inNode = next.value._inNode;
- if (inNode) {
- this._outputNode.connect(inNode);
- }
- }
- }
- }
- get _inNode() {
- return this._outputNode;
- }
- get _outNode() {
- return this._outputNode;
- }
- _createSubNode(name18) {
- switch (name18) {
- case "Analyzer":
- return _CreateAudioAnalyzerSubNodeAsync(this._owner.engine);
- case "Volume":
- return _CreateVolumeAudioSubNodeAsync(this._owner.engine);
- default:
- throw new Error(`Unknown subnode name: ${name18}`);
- }
- }
- _onSubNodesChanged() {
- const analyzerNode = _GetAudioAnalyzerSubNode(this);
- const volumeNode = _GetVolumeAudioSubNode(this);
- if (analyzerNode && volumeNode) {
- volumeNode.connect(analyzerNode);
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subNodes/webAudioBusAndSoundSubGraph.js
-var _WebAudioBusAndSoundSubGraph;
-var init_webAudioBusAndSoundSubGraph = __esm(() => {
- init_spatialAudioSubNode();
- init_stereoAudioSubNode();
- init_volumeAudioSubNode();
- init_abstractSpatialAudio();
- init_abstractStereoAudio();
- init_spatialWebAudioSubNode();
- init_stereoWebAudioSubNode();
- init_webAudioBaseSubGraph();
- _WebAudioBusAndSoundSubGraph = class _WebAudioBusAndSoundSubGraph extends _WebAudioBaseSubGraph {
- constructor() {
- super(...arguments);
- this._rootNode = null;
- this._inputNode = null;
- }
- async init(options) {
- await super.init(options);
- let hasSpatialOptions = false;
- let hasStereoOptions = false;
- if (hasSpatialOptions = _HasSpatialAudioOptions(options)) {
- await this.createAndAddSubNode("Spatial");
- }
- if (hasStereoOptions = _HasStereoAudioOptions(options)) {
- await this.createAndAddSubNode("Stereo");
- }
- await this._createSubNodePromisesResolved();
- if (hasSpatialOptions) {
- _GetSpatialAudioSubNode(this)?.setOptions(options);
- }
- if (hasStereoOptions) {
- _GetStereoAudioSubNode(this)?.setOptions(options);
- }
- }
- get _inNode() {
- return this._inputNode;
- }
- _createSubNode(name18) {
- try {
- const node = super._createSubNode(name18);
- return node;
- } catch (e) {}
- switch (name18) {
- case "Spatial":
- return _CreateSpatialAudioSubNodeAsync(this._owner.engine);
- case "Stereo":
- return _CreateStereoAudioSubNodeAsync(this._owner.engine);
- default:
- throw new Error(`Unknown subnode name: ${name18}`);
- }
- }
- _onSubNodesChanged() {
- super._onSubNodesChanged();
- const spatialNode = _GetSpatialAudioSubNode(this);
- const stereoNode = _GetStereoAudioSubNode(this);
- const volumeNode = _GetVolumeAudioSubNode(this);
- if (spatialNode && spatialNode.getClassName() !== "_SpatialWebAudioSubNode") {
- throw new Error("Not a WebAudio subnode.");
- }
- if (stereoNode && stereoNode.getClassName() !== "_StereoWebAudioSubNode") {
- throw new Error("Not a WebAudio subnode.");
- }
- if (volumeNode && volumeNode.getClassName() !== "_VolumeWebAudioSubNode") {
- throw new Error("Not a WebAudio subnode.");
- }
- if (spatialNode) {
- spatialNode.disconnectAll();
- if (volumeNode) {
- spatialNode.connect(volumeNode);
- }
- }
- if (stereoNode) {
- stereoNode.disconnectAll();
- if (volumeNode) {
- stereoNode.connect(volumeNode);
- }
- }
- if (spatialNode && stereoNode) {
- this._rootNode = new GainNode(this._owner.engine._audioContext);
- this._rootNode.connect(spatialNode._outNode);
- this._rootNode.connect(stereoNode._outNode);
- } else {
- this._rootNode?.disconnect();
- this._rootNode = null;
- }
- let inSubNode = null;
- let inNode = null;
- if (this._rootNode) {
- inNode = this._rootNode;
- } else {
- if (spatialNode) {
- inSubNode = spatialNode;
- } else if (stereoNode) {
- inSubNode = stereoNode;
- } else if (volumeNode) {
- inSubNode = volumeNode;
- }
- inNode = inSubNode?.node ?? null;
- }
- if (this._inputNode !== inNode) {
- if (this._inputNode && this._upstreamNodes) {
- const it = this._upstreamNodes.values();
- for (let next = it.next();!next.done; next = it.next()) {
- next.value._outNode?.disconnect(this._inputNode);
- }
- }
- this._inputNode = inNode;
- if (inNode && this._upstreamNodes) {
- const it = this._upstreamNodes.values();
- for (let next = it.next();!next.done; next = it.next()) {
- next.value._outNode?.connect(inNode);
- }
- }
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/spatialAudio.js
-var _SpatialAudio;
-var init_spatialAudio = __esm(() => {
- init_spatialAudioSubNode();
- init_abstractSpatialAudio();
- _SpatialAudio = class _SpatialAudio extends AbstractSpatialAudio {
- constructor(subGraph) {
- super();
- const subNode = _GetSpatialAudioSubNode(subGraph);
- if (subNode) {
- this._position = subNode.position.clone();
- this._rotation = subNode.rotation.clone();
- this._rotationQuaternion = subNode.rotationQuaternion.clone();
- } else {
- this._position = _SpatialAudioDefaults.position.clone();
- this._rotation = _SpatialAudioDefaults.rotation.clone();
- this._rotationQuaternion = _SpatialAudioDefaults.rotationQuaternion.clone();
- subGraph.createAndAddSubNode("Spatial");
- }
- this._subGraph = subGraph;
- }
- get coneInnerAngle() {
- return _GetSpatialAudioProperty(this._subGraph, "coneInnerAngle") ?? _SpatialAudioDefaults.coneInnerAngle;
- }
- set coneInnerAngle(value) {
- _SetSpatialAudioProperty(this._subGraph, "coneInnerAngle", value);
- }
- get coneOuterAngle() {
- return _GetSpatialAudioProperty(this._subGraph, "coneOuterAngle");
- }
- set coneOuterAngle(value) {
- _SetSpatialAudioProperty(this._subGraph, "coneOuterAngle", value);
- }
- get coneOuterVolume() {
- return _GetSpatialAudioProperty(this._subGraph, "coneOuterVolume");
- }
- set coneOuterVolume(value) {
- _SetSpatialAudioProperty(this._subGraph, "coneOuterVolume", value);
- }
- get distanceModel() {
- return _GetSpatialAudioProperty(this._subGraph, "distanceModel");
- }
- set distanceModel(value) {
- _SetSpatialAudioProperty(this._subGraph, "distanceModel", value);
- }
- get isAttached() {
- return this._subGraph.getSubNode("Spatial")?.isAttached ?? false;
- }
- get maxDistance() {
- return _GetSpatialAudioProperty(this._subGraph, "maxDistance") ?? _SpatialAudioDefaults.maxDistance;
- }
- set maxDistance(value) {
- if (value <= 0) {
- value = 0.000001;
- }
- _SetSpatialAudioProperty(this._subGraph, "maxDistance", value);
- }
- get minDistance() {
- return _GetSpatialAudioProperty(this._subGraph, "minDistance");
- }
- set minDistance(value) {
- _SetSpatialAudioProperty(this._subGraph, "minDistance", value);
- }
- get panningModel() {
- return _GetSpatialAudioProperty(this._subGraph, "panningModel");
- }
- set panningModel(value) {
- _SetSpatialAudioProperty(this._subGraph, "panningModel", value);
- }
- get position() {
- return this._position;
- }
- set position(value) {
- this._position = value;
- this._updatePosition();
- }
- get rolloffFactor() {
- return _GetSpatialAudioProperty(this._subGraph, "rolloffFactor");
- }
- set rolloffFactor(value) {
- _SetSpatialAudioProperty(this._subGraph, "rolloffFactor", value);
- }
- get rotation() {
- return this._rotation;
- }
- set rotation(value) {
- this._rotation = value;
- this._updateRotation();
- }
- get rotationQuaternion() {
- return this._rotationQuaternion;
- }
- set rotationQuaternion(value) {
- this._rotationQuaternion = value;
- this._updateRotation();
- }
- attach(sceneNode, useBoundingBox = false, attachmentType = 3) {
- _GetSpatialAudioSubNode(this._subGraph)?.attach(sceneNode, useBoundingBox, attachmentType);
- }
- detach() {
- _GetSpatialAudioSubNode(this._subGraph)?.detach();
- }
- update() {
- const subNode = _GetSpatialAudioSubNode(this._subGraph);
- if (!subNode) {
- return;
- }
- if (subNode.isAttached) {
- subNode.update();
- } else {
- this._updatePosition(subNode);
- this._updateRotation(subNode);
- }
- }
- _updatePosition(subNode = null) {
- if (!subNode) {
- subNode = _GetSpatialAudioSubNode(this._subGraph);
- if (!subNode) {
- return;
- }
- }
- const position = subNode.position;
- if (!position.equalsWithEpsilon(this._position)) {
- subNode.position.copyFrom(this._position);
- subNode._updatePosition();
- }
- }
- _updateRotation(subNode = null) {
- if (!subNode) {
- subNode = _GetSpatialAudioSubNode(this._subGraph);
- if (!subNode) {
- return;
- }
- }
- if (!subNode.rotationQuaternion.equalsWithEpsilon(this._rotationQuaternion)) {
- subNode.rotationQuaternion.copyFrom(this._rotationQuaternion);
- subNode._updateRotation();
- } else if (!subNode.rotation.equalsWithEpsilon(this._rotation)) {
- subNode.rotation.copyFrom(this._rotation);
- subNode._updateRotation();
- }
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/components/spatialWebAudioUpdaterComponent.js
-class _SpatialWebAudioUpdaterComponent {
- constructor(parent, autoUpdate, minUpdateTime) {
- this._autoUpdate = true;
- this._lastUpdateTime = 0;
- this.minUpdateTime = 0;
- if (!autoUpdate) {
- return;
- }
- this.minUpdateTime = minUpdateTime;
- const update = () => {
- if (!this._autoUpdate) {
- return;
- }
- let skipUpdate = false;
- if (0 < this.minUpdateTime) {
- const now = PrecisionDate.Now;
- if (this._lastUpdateTime && now - this._lastUpdateTime < this.minUpdateTime) {
- skipUpdate = true;
- }
- this._lastUpdateTime = now;
- }
- if (!skipUpdate) {
- parent.update();
- }
- requestAnimationFrame(update);
- };
- requestAnimationFrame(update);
- }
- dispose() {
- this._autoUpdate = false;
- }
-}
-var init_spatialWebAudioUpdaterComponent = __esm(() => {
- init_precisionDate();
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/subProperties/spatialWebAudio.js
-var _SpatialWebAudio;
-var init_spatialWebAudio = __esm(() => {
- init_spatialAudio();
- init_spatialWebAudioUpdaterComponent();
- _SpatialWebAudio = class _SpatialWebAudio extends _SpatialAudio {
- constructor(subGraph, autoUpdate, minUpdateTime) {
- super(subGraph);
- this._updaterComponent = new _SpatialWebAudioUpdaterComponent(this, autoUpdate, minUpdateTime);
- }
- get minUpdateTime() {
- return this._updaterComponent.minUpdateTime;
- }
- set minUpdateTime(value) {
- this._updaterComponent.minUpdateTime = value;
- }
- dispose() {
- this._updaterComponent.dispose();
- this._updaterComponent = null;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioBus.js
-var _WebAudioBus;
-var init_webAudioBus = __esm(() => {
- init_audioBus();
- init_abstractSpatialAudio();
- init_stereoAudio();
- init_webAudioBusAndSoundSubGraph();
- init_spatialWebAudio();
- _WebAudioBus = class _WebAudioBus extends AudioBus {
- constructor(name18, engine, options) {
- super(name18, engine);
- this._spatial = null;
- this._spatialAutoUpdate = true;
- this._spatialMinUpdateTime = 0;
- this._stereo = null;
- if (typeof options.spatialAutoUpdate === "boolean") {
- this._spatialAutoUpdate = options.spatialAutoUpdate;
- }
- if (typeof options.spatialMinUpdateTime === "number") {
- this._spatialMinUpdateTime = options.spatialMinUpdateTime;
- }
- this._subGraph = new _WebAudioBus._SubGraph(this);
- }
- async _init(options) {
- if (options.outBus) {
- this.outBus = options.outBus;
- } else {
- await this.engine.isReadyPromise;
- this.outBus = this.engine.defaultMainBus;
- }
- await this._subGraph.init(options);
- if (_HasSpatialAudioOptions(options)) {
- this._initSpatialProperty();
- }
- this.engine._addNode(this);
- }
- dispose() {
- super.dispose();
- this._spatial = null;
- this._stereo = null;
- this.engine._removeNode(this);
- }
- get _inNode() {
- return this._subGraph._inNode;
- }
- get _outNode() {
- return this._subGraph._outNode;
- }
- get spatial() {
- if (this._spatial) {
- return this._spatial;
- }
- return this._initSpatialProperty();
- }
- get stereo() {
- return this._stereo ?? (this._stereo = new _StereoAudio(this._subGraph));
- }
- getClassName() {
- return "_WebAudioBus";
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- _initSpatialProperty() {
- if (!this._spatial) {
- this._spatial = new _SpatialWebAudio(this._subGraph, this._spatialAutoUpdate, this._spatialMinUpdateTime);
- }
- return this._spatial;
- }
- };
- _WebAudioBus._SubGraph = class extends _WebAudioBusAndSoundSubGraph {
- get _downstreamNodes() {
- return this._owner._downstreamNodes ?? null;
- }
- get _upstreamNodes() {
- return this._owner._upstreamNodes ?? null;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioMainBus.js
-var _WebAudioMainBus;
-var init_webAudioMainBus = __esm(() => {
- init_mainAudioBus();
- init_webAudioBaseSubGraph();
- _WebAudioMainBus = class _WebAudioMainBus extends MainAudioBus {
- constructor(name18, engine) {
- super(name18, engine);
- this._subGraph = new _WebAudioMainBus._SubGraph(this);
- }
- async _init(options) {
- await this._subGraph.init(options);
- if (this.engine.mainOut) {
- if (!this._connect(this.engine.mainOut)) {
- throw new Error("Connect failed");
- }
- }
- this.engine._addMainBus(this);
- }
- dispose() {
- super.dispose();
- this.engine._removeMainBus(this);
- }
- get _inNode() {
- return this._subGraph._inNode;
- }
- get _outNode() {
- return this._subGraph._outNode;
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- getClassName() {
- return "_WebAudioMainBus";
- }
- };
- _WebAudioMainBus._SubGraph = class extends _WebAudioBaseSubGraph {
- get _downstreamNodes() {
- return this._owner._downstreamNodes ?? null;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/abstractSoundInstance.js
-var _AbstractSoundInstance;
-var init_abstractSoundInstance = __esm(() => {
- init_observable();
- init_abstractAudioNode();
- _AbstractSoundInstance = class _AbstractSoundInstance extends AbstractAudioNode {
- constructor(sound2) {
- super(sound2.engine, 2);
- this._state = 1;
- this.onEndedObservable = new Observable;
- this.onErrorObservable = new Observable;
- this.onStateChangedObservable = new Observable;
- this._sound = sound2;
- }
- get state() {
- return this._state;
- }
- dispose() {
- super.dispose();
- this.stop();
- this.onEndedObservable.clear();
- this.onStateChangedObservable.clear();
- }
- _setState(value) {
- if (this._state === value) {
- return;
- }
- this._state = value;
- this.onStateChangedObservable.notifyObservers(this);
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/staticSoundInstance.js
-var _StaticSoundInstance;
-var init_staticSoundInstance = __esm(() => {
- init_abstractSoundInstance();
- _StaticSoundInstance = class _StaticSoundInstance extends _AbstractSoundInstance {
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/audioUtils.js
-function _CleanUrl(url) {
- return url.replace(/#/gm, "%23");
-}
-var _FileExtensionRegex;
-var init_audioUtils = __esm(() => {
- _FileExtensionRegex = new RegExp("\\.(\\w{3,4})($|\\?)");
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioStaticSound.js
-var _WebAudioStaticSound, _WebAudioStaticSoundBuffer, _WebAudioStaticSoundInstance;
-var init_webAudioStaticSound = __esm(() => {
- init_staticSound();
- init_staticSoundInstance();
- init_abstractSpatialAudio();
- init_stereoAudio();
- init_audioUtils();
- init_webAudioBusAndSoundSubGraph();
- init_spatialWebAudio();
- _WebAudioStaticSound = class _WebAudioStaticSound extends StaticSound {
- constructor(name18, engine, options) {
- super(name18, engine);
- this._spatial = null;
- this._spatialAutoUpdate = true;
- this._spatialMinUpdateTime = 0;
- this._stereo = null;
- if (typeof options.spatialAutoUpdate === "boolean") {
- this._spatialAutoUpdate = options.spatialAutoUpdate;
- }
- if (typeof options.spatialMinUpdateTime === "number") {
- this._spatialMinUpdateTime = options.spatialMinUpdateTime;
- }
- this._options = {
- autoplay: options.autoplay ?? false,
- duration: options.duration ?? 0,
- loop: options.loop ?? false,
- loopEnd: options.loopEnd ?? 0,
- loopStart: options.loopStart ?? 0,
- maxInstances: options.maxInstances ?? Infinity,
- pitch: options.pitch ?? 0,
- playbackRate: options.playbackRate ?? 1,
- startOffset: options.startOffset ?? 0
- };
- this._subGraph = new _WebAudioStaticSound._SubGraph(this);
- }
- async _init(source, options) {
- this._audioContext = this.engine._audioContext;
- if (source instanceof _WebAudioStaticSoundBuffer) {
- this._buffer = source;
- } else if (typeof source === "string" || Array.isArray(source) || source instanceof ArrayBuffer || source instanceof AudioBuffer) {
- this._buffer = await this.engine.createSoundBufferAsync(source, options);
- }
- if (options.outBus) {
- this.outBus = options.outBus;
- } else {
- await this.engine.isReadyPromise;
- this.outBus = this.engine.defaultMainBus;
- }
- await this._subGraph.init(options);
- if (_HasSpatialAudioOptions(options)) {
- this._initSpatialProperty();
- }
- if (options.autoplay) {
- this.play();
- }
- this.engine._addNode(this);
- }
- get buffer() {
- return this._buffer;
- }
- get _inNode() {
- return this._subGraph._inNode;
- }
- get _outNode() {
- return this._subGraph._outNode;
- }
- get spatial() {
- if (this._spatial) {
- return this._spatial;
- }
- return this._initSpatialProperty();
- }
- get stereo() {
- return this._stereo ?? (this._stereo = new _StereoAudio(this._subGraph));
- }
- dispose() {
- super.dispose();
- this._spatial?.dispose();
- this._spatial = null;
- this._stereo = null;
- this._subGraph.dispose();
- this.engine._removeNode(this);
- }
- getClassName() {
- return "_WebAudioStaticSound";
- }
- _createInstance() {
- return new _WebAudioStaticSoundInstance(this, this._options);
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- _initSpatialProperty() {
- if (!this._spatial) {
- this._spatial = new _SpatialWebAudio(this._subGraph, this._spatialAutoUpdate, this._spatialMinUpdateTime);
- }
- return this._spatial;
- }
- };
- _WebAudioStaticSound._SubGraph = class extends _WebAudioBusAndSoundSubGraph {
- get _downstreamNodes() {
- return this._owner._downstreamNodes ?? null;
- }
- get _upstreamNodes() {
- return this._owner._upstreamNodes ?? null;
- }
- };
- _WebAudioStaticSoundBuffer = class _WebAudioStaticSoundBuffer extends StaticSoundBuffer {
- constructor(engine) {
- super(engine);
- }
- async _init(source, options) {
- if (source instanceof AudioBuffer) {
- this._audioBuffer = source;
- } else if (typeof source === "string") {
- await this._initFromUrl(source);
- } else if (Array.isArray(source)) {
- await this._initFromUrls(source, options.skipCodecCheck ?? false);
- } else if (source instanceof ArrayBuffer) {
- await this._initFromArrayBuffer(source);
- }
- }
- get channelCount() {
- return this._audioBuffer.numberOfChannels;
- }
- get duration() {
- return this._audioBuffer.duration;
- }
- get length() {
- return this._audioBuffer.length;
- }
- get sampleRate() {
- return this._audioBuffer.sampleRate;
- }
- async _initFromArrayBuffer(arrayBuffer) {
- this._audioBuffer = await this.engine._audioContext.decodeAudioData(arrayBuffer);
- }
- async _initFromUrl(url) {
- url = _CleanUrl(url);
- await this._initFromArrayBuffer(await (await fetch(url)).arrayBuffer());
- }
- async _initFromUrls(urls, skipCodecCheck) {
- for (const url of urls) {
- if (skipCodecCheck) {
- await this._initFromUrl(url);
- } else {
- const matches = url.match(_FileExtensionRegex);
- const format = matches?.at(1);
- if (format && this.engine.isFormatValid(format)) {
- try {
- await this._initFromUrl(url);
- } catch (e) {
- if (format && 0 < format.length) {
- this.engine.flagInvalidFormat(format);
- }
- }
- }
- }
- if (this._audioBuffer) {
- break;
- }
- }
- }
- };
- _WebAudioStaticSoundInstance = class _WebAudioStaticSoundInstance extends _StaticSoundInstance {
- constructor(sound2, options) {
- super(sound2);
- this._enginePlayTime = 0;
- this._enginePauseTime = 0;
- this._sourceNode = null;
- this._onEnded = () => {
- this._enginePlayTime = 0;
- this.onEndedObservable.notifyObservers(this);
- this._deinitSourceNode();
- };
- this._onEngineStateChanged = () => {
- if (this.engine.state !== "running") {
- return;
- }
- if (this._options.loop && this.state === 2) {
- this.play();
- }
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- };
- this._options = options;
- this._volumeNode = new GainNode(sound2._audioContext);
- this._initSourceNode();
- }
- get currentTime() {
- if (this._state === 1) {
- return 0;
- }
- const timeSinceLastStart = this._state === 5 ? 0 : this.engine.currentTime - this._enginePlayTime;
- return this._enginePauseTime + timeSinceLastStart + this._options.startOffset;
- }
- set currentTime(value) {
- const restart = this._state === 2 || this._state === 3;
- if (restart) {
- this.stop();
- this._deinitSourceNode();
- }
- this._options.startOffset = value;
- if (restart) {
- this.play();
- }
- }
- get _outNode() {
- return this._volumeNode;
- }
- set pitch(value) {
- if (this._sourceNode) {
- this.engine._setAudioParam(this._sourceNode.detune, value);
- }
- }
- set playbackRate(value) {
- if (this._sourceNode) {
- this.engine._setAudioParam(this._sourceNode.playbackRate, value);
- }
- }
- get startTime() {
- if (this._state === 1) {
- return 0;
- }
- return this._enginePlayTime;
- }
- dispose() {
- super.dispose();
- this._sourceNode = null;
- this.stop();
- this._deinitSourceNode();
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- }
- getClassName() {
- return "_WebAudioStaticSoundInstance";
- }
- play(options = {}) {
- if (this._state === 3) {
- return;
- }
- if (options.duration !== undefined) {
- this._options.duration = options.duration;
- }
- if (options.loop !== undefined) {
- this._options.loop = options.loop;
- }
- if (options.loopStart !== undefined) {
- this._options.loopStart = options.loopStart;
- }
- if (options.loopEnd !== undefined) {
- this._options.loopEnd = options.loopEnd;
- }
- if (options.startOffset !== undefined) {
- this._options.startOffset = options.startOffset;
- }
- let startOffset = this._options.startOffset;
- if (this._state === 5) {
- startOffset += this.currentTime;
- startOffset %= this._sound.buffer.duration;
- }
- this._enginePlayTime = this.engine.currentTime + (options.waitTime ?? 0);
- this._volumeNode.gain.value = options.volume ?? 1;
- this._initSourceNode();
- if (this.engine.state === "running") {
- this._setState(3);
- this._sourceNode?.start(this._enginePlayTime, startOffset, this._options.duration > 0 ? this._options.duration : undefined);
- } else if (this._options.loop) {
- this._setState(2);
- this.engine.stateChangedObservable.add(this._onEngineStateChanged);
- }
- }
- pause() {
- if (this._state === 5) {
- return;
- }
- this._setState(5);
- this._enginePauseTime += this.engine.currentTime - this._enginePlayTime;
- this._sourceNode?.stop();
- this._deinitSourceNode();
- }
- resume() {
- if (this._state === 5) {
- this.play();
- }
- }
- stop(options = {}) {
- if (this._state === 1) {
- return;
- }
- this._setState(1);
- const engineStopTime = this.engine.currentTime + (options.waitTime ?? 0);
- this._sourceNode?.stop(engineStopTime);
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node instanceof _WebAudioStaticSound && node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node instanceof _WebAudioStaticSound && node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- _deinitSourceNode() {
- if (!this._sourceNode) {
- return;
- }
- if (!this._disconnect(this._sound)) {
- throw new Error("Disconnect failed");
- }
- this._sourceNode.disconnect(this._volumeNode);
- this._sourceNode.removeEventListener("ended", this._onEnded);
- this._sourceNode = null;
- }
- _initSourceNode() {
- if (!this._sourceNode) {
- this._sourceNode = new AudioBufferSourceNode(this._sound._audioContext, { buffer: this._sound.buffer._audioBuffer });
- this._sourceNode.addEventListener("ended", this._onEnded, { once: true });
- this._sourceNode.connect(this._volumeNode);
- if (!this._connect(this._sound)) {
- throw new Error("Connect failed");
- }
- }
- const node = this._sourceNode;
- node.detune.value = this._sound.pitch;
- node.loop = this._options.loop;
- node.loopEnd = this._options.loopEnd;
- node.loopStart = this._options.loopStart;
- node.playbackRate.value = this._sound.playbackRate;
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/abstractAudio/streamingSoundInstance.js
-var _StreamingSoundInstance;
-var init_streamingSoundInstance = __esm(() => {
- init_observable();
- init_abstractSoundInstance();
- _StreamingSoundInstance = class _StreamingSoundInstance extends _AbstractSoundInstance {
- constructor(sound2) {
- super(sound2);
- this.onReadyObservable = new Observable;
- this.preloadedPromise = new Promise((resolve3, reject) => {
- this._rejectPreloadedProimse = reject;
- this._resolvePreloadedPromise = resolve3;
- });
- this.onErrorObservable.add(this._rejectPreloadedProimse);
- this.onReadyObservable.add(this._resolvePreloadedPromise);
- }
- set startOffset(value) {
- this._options.startOffset = value;
- }
- dispose() {
- super.dispose();
- this.onErrorObservable.clear();
- this.onReadyObservable.clear();
- this._resolvePreloadedPromise();
- }
- };
-});
-
-// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioStreamingSound.js
-var _WebAudioStreamingSound, _WebAudioStreamingSoundInstance;
-var init_webAudioStreamingSound = __esm(() => {
- init_logger();
- init_tools();
- init_streamingSound();
- init_streamingSoundInstance();
- init_abstractSpatialAudio();
- init_stereoAudio();
- init_audioUtils();
- init_webAudioBusAndSoundSubGraph();
- init_spatialWebAudio();
- _WebAudioStreamingSound = class _WebAudioStreamingSound extends StreamingSound {
- constructor(name18, engine, options) {
- super(name18, engine);
- this._spatial = null;
- this._spatialAutoUpdate = true;
- this._spatialMinUpdateTime = 0;
- this._stereo = null;
- if (typeof options.spatialAutoUpdate === "boolean") {
- this._spatialAutoUpdate = options.spatialAutoUpdate;
- }
- if (typeof options.spatialMinUpdateTime === "number") {
- this._spatialMinUpdateTime = options.spatialMinUpdateTime;
- }
- this._options = {
- autoplay: options.autoplay ?? false,
- loop: options.loop ?? false,
- maxInstances: options.maxInstances ?? Infinity,
- preloadCount: options.preloadCount ?? 1,
- startOffset: options.startOffset ?? 0
- };
- this._subGraph = new _WebAudioStreamingSound._SubGraph(this);
- }
- async _init(source, options) {
- const audioContext = this.engine._audioContext;
- if (!(audioContext instanceof AudioContext)) {
- throw new Error("Unsupported audio context type.");
- }
- this._audioContext = audioContext;
- this._source = source;
- if (options.outBus) {
- this.outBus = options.outBus;
- } else {
- await this.engine.isReadyPromise;
- this.outBus = this.engine.defaultMainBus;
- }
- await this._subGraph.init(options);
- if (_HasSpatialAudioOptions(options)) {
- this._initSpatialProperty();
- }
- if (this.preloadCount) {
- await this.preloadInstancesAsync(this.preloadCount);
- }
- if (options.autoplay) {
- this.play(options);
- }
- this.engine._addNode(this);
- }
- get _inNode() {
- return this._subGraph._inNode;
- }
- get _outNode() {
- return this._subGraph._outNode;
- }
- get spatial() {
- if (this._spatial) {
- return this._spatial;
- }
- return this._initSpatialProperty();
- }
- get stereo() {
- return this._stereo ?? (this._stereo = new _StereoAudio(this._subGraph));
- }
- dispose() {
- super.dispose();
- this._spatial = null;
- this._stereo = null;
- this._subGraph.dispose();
- this.engine._removeNode(this);
- }
- getClassName() {
- return "_WebAudioStreamingSound";
- }
- _createInstance() {
- return new _WebAudioStreamingSoundInstance(this, this._options);
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- _initSpatialProperty() {
- if (!this._spatial) {
- this._spatial = new _SpatialWebAudio(this._subGraph, this._spatialAutoUpdate, this._spatialMinUpdateTime);
- }
- return this._spatial;
- }
- };
- _WebAudioStreamingSound._SubGraph = class extends _WebAudioBusAndSoundSubGraph {
- get _downstreamNodes() {
- return this._owner._downstreamNodes ?? null;
- }
- get _upstreamNodes() {
- return this._owner._upstreamNodes ?? null;
- }
- };
- _WebAudioStreamingSoundInstance = class _WebAudioStreamingSoundInstance extends _StreamingSoundInstance {
- constructor(sound2, options) {
- super(sound2);
- this._currentTimeChangedWhilePaused = false;
- this._enginePlayTime = Infinity;
- this._enginePauseTime = 0;
- this._isReady = false;
- this._isReadyPromise = new Promise((resolve3, reject) => {
- this._resolveIsReadyPromise = resolve3;
- this._rejectIsReadyPromise = reject;
- });
- this._onCanPlayThrough = () => {
- this._isReady = true;
- this._resolveIsReadyPromise(this._mediaElement);
- this.onReadyObservable.notifyObservers(this);
- };
- this._onEnded = () => {
- this.onEndedObservable.notifyObservers(this);
- this.dispose();
- };
- this._onError = (reason) => {
- this._setState(4);
- this.onErrorObservable.notifyObservers(reason);
- this._rejectIsReadyPromise(reason);
- this.dispose();
- };
- this._onEngineStateChanged = () => {
- if (this.engine.state !== "running") {
- return;
- }
- if (this._options.loop && this.state === 2) {
- this.play();
- }
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- };
- this._onUserGesture = () => {
- this.play();
- };
- this._options = options;
- this._volumeNode = new GainNode(sound2._audioContext);
- if (typeof sound2._source === "string") {
- this._initFromUrl(sound2._source);
- } else if (Array.isArray(sound2._source)) {
- this._initFromUrls(sound2._source);
- } else if (sound2._source instanceof HTMLMediaElement) {
- this._initFromMediaElement(sound2._source);
- }
- }
- get currentTime() {
- if (this._state === 1) {
- return 0;
- }
- const timeSinceLastStart = this._state === 5 ? 0 : this.engine.currentTime - this._enginePlayTime;
- return this._enginePauseTime + timeSinceLastStart + this._options.startOffset;
- }
- set currentTime(value) {
- const restart = this._state === 2 || this._state === 3;
- if (restart) {
- this._mediaElement.pause();
- this._setState(1);
- }
- this._options.startOffset = value;
- if (restart) {
- this.play({ startOffset: value });
- } else if (this._state === 5) {
- this._currentTimeChangedWhilePaused = true;
- }
- }
- get _outNode() {
- return this._volumeNode;
- }
- get startTime() {
- if (this._state === 1) {
- return 0;
- }
- return this._enginePlayTime;
- }
- dispose() {
- super.dispose();
- this.stop();
- this._sourceNode?.disconnect(this._volumeNode);
- this._sourceNode = null;
- this._mediaElement.removeEventListener("error", this._onError);
- this._mediaElement.removeEventListener("ended", this._onEnded);
- this._mediaElement.removeEventListener("canplaythrough", this._onCanPlayThrough);
- for (const source of Array.from(this._mediaElement.children)) {
- this._mediaElement.removeChild(source);
- }
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- this.engine.userGestureObservable.removeCallback(this._onUserGesture);
- }
- play(options = {}) {
- if (this._state === 3) {
- return;
- }
- if (options.loop !== undefined) {
- this._options.loop = options.loop;
- }
- this._mediaElement.loop = this._options.loop;
- let startOffset = options.startOffset;
- if (this._currentTimeChangedWhilePaused) {
- startOffset = this._options.startOffset;
- this._currentTimeChangedWhilePaused = false;
- } else if (this._state === 5) {
- startOffset = this.currentTime + this._options.startOffset;
- }
- if (startOffset && startOffset > 0) {
- this._mediaElement.currentTime = startOffset;
- }
- this._volumeNode.gain.value = options.volume ?? 1;
- this._play();
- }
- pause() {
- if (this._state !== 2 && this._state !== 3) {
- return;
- }
- this._setState(5);
- this._enginePauseTime += this.engine.currentTime - this._enginePlayTime;
- this._mediaElement.pause();
- }
- resume() {
- if (this._state === 5) {
- this.play();
- } else if (this._currentTimeChangedWhilePaused) {
- this.play();
- }
- }
- stop() {
- if (this._state === 1) {
- return;
- }
- this._stop();
- }
- getClassName() {
- return "_WebAudioStreamingSoundInstance";
- }
- _connect(node) {
- const connected = super._connect(node);
- if (!connected) {
- return false;
- }
- if (node instanceof _WebAudioStreamingSound && node._inNode) {
- this._outNode?.connect(node._inNode);
- }
- return true;
- }
- _disconnect(node) {
- const disconnected = super._disconnect(node);
- if (!disconnected) {
- return false;
- }
- if (node instanceof _WebAudioStreamingSound && node._inNode) {
- this._outNode?.disconnect(node._inNode);
- }
- return true;
- }
- _initFromMediaElement(mediaElement) {
- Tools.SetCorsBehavior(mediaElement.currentSrc, mediaElement);
- mediaElement.controls = false;
- mediaElement.loop = this._options.loop;
- mediaElement.preload = "auto";
- mediaElement.addEventListener("canplaythrough", this._onCanPlayThrough, { once: true });
- mediaElement.addEventListener("ended", this._onEnded, { once: true });
- mediaElement.addEventListener("error", this._onError, { once: true });
- mediaElement.load();
- this._sourceNode = new MediaElementAudioSourceNode(this._sound._audioContext, { mediaElement });
- this._sourceNode.connect(this._volumeNode);
- if (!this._connect(this._sound)) {
- throw new Error("Connect failed");
- }
- this._mediaElement = mediaElement;
- }
- _initFromUrl(url) {
- const audio = new Audio(_CleanUrl(url));
- this._initFromMediaElement(audio);
- }
- _initFromUrls(urls) {
- const audio = new Audio;
- for (const url of urls) {
- const source = document.createElement("source");
- source.src = _CleanUrl(url);
- audio.appendChild(source);
- }
- this._initFromMediaElement(audio);
- }
- _play() {
- this._setState(2);
- if (!this._isReady) {
- this._playWhenReady();
- return;
- }
- if (this._state !== 2) {
- return;
- }
- if (this.engine.state === "running") {
- const result = this._mediaElement.play();
- this._enginePlayTime = this.engine.currentTime;
- this._setState(3);
- result.catch(() => {
- this._setState(4);
- if (this._options.loop) {
- this.engine.userGestureObservable.addOnce(this._onUserGesture);
- }
- });
- } else if (this._options.loop) {
- this.engine.stateChangedObservable.add(this._onEngineStateChanged);
- } else {
- this.stop();
- this._setState(4);
- }
- }
- _playWhenReady() {
- this._isReadyPromise.then(() => {
- this._play();
- }).catch(() => {
- Logger.Error("Streaming sound instance failed to play");
- this._setState(4);
- });
- }
- _stop() {
- this._mediaElement.pause();
- this._setState(1);
- this._onEnded();
- this.engine.stateChangedObservable.removeCallback(this._onEngineStateChanged);
- }
- };
-});
-
-// node_modules/@babylonjs/core/Buffers/storageBuffer.js
-class StorageBuffer {
- 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);
- }
- _rebuild() {
- this._create(this._bufferSize, this._creationFlags);
- }
- getBuffer() {
- return this._buffer;
- }
- update(data, byteOffset, byteLength) {
- if (!this._buffer) {
- return;
- }
- this._engine.updateStorageBuffer(this._buffer, data, byteOffset, byteLength);
- }
- read(offset, size, buffer, noDelay) {
- return this._engine.readFromStorageBuffer(this._buffer, offset, size, buffer, noDelay);
- }
- 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;
- }
-}
-
-// node_modules/@babylonjs/core/ShadersWGSL/anaglyph.fragment.js
-var exports_anaglyph_fragment = {};
-__export(exports_anaglyph_fragment, {
- anaglyphPixelShaderWGSL: () => anaglyphPixelShaderWGSL
-});
-var name18 = "anaglyphPixelShader", shader17 = `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);}`, anaglyphPixelShaderWGSL;
-var init_anaglyph_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name18]) {
- ShaderStore.ShadersStoreWGSL[name18] = shader17;
- }
- anaglyphPixelShaderWGSL = { name: name18, shader: shader17 };
-});
-
-// node_modules/@babylonjs/core/Shaders/anaglyph.fragment.js
-var exports_anaglyph_fragment2 = {};
-__export(exports_anaglyph_fragment2, {
- anaglyphPixelShader: () => anaglyphPixelShader
-});
-var name19 = "anaglyphPixelShader", shader18 = `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);}`, anaglyphPixelShader;
-var init_anaglyph_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name19]) {
- ShaderStore.ShadersStore[name19] = shader18;
- }
- anaglyphPixelShader = { name: name19, shader: shader18 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/vrDistortionCorrection.fragment.js
-var exports_vrDistortionCorrection_fragment = {};
-__export(exports_vrDistortionCorrection_fragment, {
- vrDistortionCorrectionPixelShaderWGSL: () => vrDistortionCorrectionPixelShaderWGSL
-});
-var name21 = "vrDistortionCorrectionPixelShader", shader20 = `#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);}}`, vrDistortionCorrectionPixelShaderWGSL;
-var init_vrDistortionCorrection_fragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStoreWGSL[name21]) {
- ShaderStore.ShadersStoreWGSL[name21] = shader20;
- }
- vrDistortionCorrectionPixelShaderWGSL = { name: name21, shader: shader20 };
-});
-
-// node_modules/@babylonjs/core/Shaders/vrDistortionCorrection.fragment.js
-var exports_vrDistortionCorrection_fragment2 = {};
-__export(exports_vrDistortionCorrection_fragment2, {
- vrDistortionCorrectionPixelShader: () => vrDistortionCorrectionPixelShader
-});
-var name22 = "vrDistortionCorrectionPixelShader", shader21 = `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);}}`, vrDistortionCorrectionPixelShader;
-var init_vrDistortionCorrection_fragment2 = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.ShadersStore[name22]) {
- ShaderStore.ShadersStore[name22] = shader21;
- }
- vrDistortionCorrectionPixelShader = { name: name22, shader: shader21 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js
-var name24 = "sceneUboDeclaration", shader23 = `struct Scene {viewProjection : mat4x4,
-#ifdef MULTIVIEW
-viewProjectionR : mat4x4,
-#endif
-view : mat4x4,
-projection : mat4x4,
-vEyePosition : vec4,};
-#define SCENE_UBO
-var scene : Scene;
-`;
-var init_sceneUboDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name24]) {
- ShaderStore.IncludesShadersStoreWGSL[name24] = shader23;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js
-var name25 = "meshUboDeclaration", shader24 = `struct Mesh {world : mat4x4,
-visibility : f32,};var mesh : Mesh;
-#define WORLD_UBO
-`;
-var init_meshUboDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name25]) {
- ShaderStore.IncludesShadersStoreWGSL[name25] = shader24;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/defaultUboDeclaration.js
-var name26 = "defaultUboDeclaration", shader25 = `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
-`;
-var init_defaultUboDeclaration = __esm(() => {
- init_shaderStore();
- init_sceneUboDeclaration();
- init_meshUboDeclaration();
- if (!ShaderStore.IncludesShadersStoreWGSL[name26]) {
- ShaderStore.IncludesShadersStoreWGSL[name26] = shader25;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvAttributeDeclaration.js
-var name27 = "uvAttributeDeclaration", shader26 = `#ifdef UV{X}
-attribute uv{X}: vec2f;
-#endif
-`;
-var init_uvAttributeDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name27]) {
- ShaderStore.IncludesShadersStoreWGSL[name27] = shader26;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js
-var exports_bonesDeclaration = {};
-__export(exports_bonesDeclaration, {
- bonesDeclarationWGSL: () => bonesDeclarationWGSL
-});
-var name28 = "bonesDeclaration", shader27 = `#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
-`, bonesDeclarationWGSL;
-var init_bonesDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name28]) {
- ShaderStore.IncludesShadersStoreWGSL[name28] = shader27;
- }
- bonesDeclarationWGSL = { name: name28, shader: shader27 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js
-var name29 = "bakedVertexAnimationDeclaration", shader28 = `#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
-`;
-var init_bakedVertexAnimationDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name29]) {
- ShaderStore.IncludesShadersStoreWGSL[name29] = shader28;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js
-var name30 = "instancesDeclaration", shader29 = `#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
-`;
-var init_instancesDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name30]) {
- ShaderStore.IncludesShadersStoreWGSL[name30] = shader29;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertexDeclaration.js
-var name31 = "prePassVertexDeclaration", shader30 = `#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
-`;
-var init_prePassVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name31]) {
- ShaderStore.IncludesShadersStoreWGSL[name31] = shader30;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/mainUVVaryingDeclaration.js
-var name32 = "mainUVVaryingDeclaration", shader31 = `#ifdef MAINUV{X}
-varying vMainUV{X}: vec2f;
-#endif
-`;
-var init_mainUVVaryingDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name32]) {
- ShaderStore.IncludesShadersStoreWGSL[name32] = shader31;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexDeclaration.js
-var name33 = "samplerVertexDeclaration", shader32 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
-varying v_VARYINGNAME_UV: vec2f;
-#endif
-`;
-var init_samplerVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name33]) {
- ShaderStore.IncludesShadersStoreWGSL[name33] = shader32;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertexDeclaration.js
-var name34 = "bumpVertexDeclaration", shader33 = `#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
-`;
-var init_bumpVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name34]) {
- ShaderStore.IncludesShadersStoreWGSL[name34] = shader33;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js
-var exports_clipPlaneVertexDeclaration = {};
-__export(exports_clipPlaneVertexDeclaration, {
- clipPlaneVertexDeclarationWGSL: () => clipPlaneVertexDeclarationWGSL
-});
-var name35 = "clipPlaneVertexDeclaration", shader34 = `#ifdef CLIPPLANE
-uniform vClipPlane: vec4;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
-`, clipPlaneVertexDeclarationWGSL;
-var init_clipPlaneVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name35]) {
- ShaderStore.IncludesShadersStoreWGSL[name35] = shader34;
- }
- clipPlaneVertexDeclarationWGSL = { name: name35, shader: shader34 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertexDeclaration.js
-var name36 = "fogVertexDeclaration", shader35 = `#ifdef FOG
-varying vFogDistance: vec3f;
-#endif
-`;
-var init_fogVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name36]) {
- ShaderStore.IncludesShadersStoreWGSL[name36] = shader35;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxFragmentDeclaration.js
-var name37 = "lightVxFragmentDeclaration", shader36 = `#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
-`;
-var init_lightVxFragmentDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name37]) {
- ShaderStore.IncludesShadersStoreWGSL[name37] = shader36;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxUboDeclaration.js
-var exports_lightVxUboDeclaration = {};
-__export(exports_lightVxUboDeclaration, {
- lightVxUboDeclarationWGSL: () => lightVxUboDeclarationWGSL
-});
-var name38 = "lightVxUboDeclaration", shader37 = `#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
-`, lightVxUboDeclarationWGSL;
-var init_lightVxUboDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name38]) {
- ShaderStore.IncludesShadersStoreWGSL[name38] = shader37;
- }
- lightVxUboDeclarationWGSL = { name: name38, shader: shader37 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js
-var exports_morphTargetsVertexGlobalDeclaration = {};
-__export(exports_morphTargetsVertexGlobalDeclaration, {
- morphTargetsVertexGlobalDeclarationWGSL: () => morphTargetsVertexGlobalDeclarationWGSL
-});
-var name39 = "morphTargetsVertexGlobalDeclaration", shader38 = `#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
-`, morphTargetsVertexGlobalDeclarationWGSL;
-var init_morphTargetsVertexGlobalDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name39]) {
- ShaderStore.IncludesShadersStoreWGSL[name39] = shader38;
- }
- morphTargetsVertexGlobalDeclarationWGSL = { name: name39, shader: shader38 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js
-var exports_morphTargetsVertexDeclaration = {};
-__export(exports_morphTargetsVertexDeclaration, {
- morphTargetsVertexDeclarationWGSL: () => morphTargetsVertexDeclarationWGSL
-});
-var name40 = "morphTargetsVertexDeclaration", shader39 = `#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
-`, morphTargetsVertexDeclarationWGSL;
-var init_morphTargetsVertexDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name40]) {
- ShaderStore.IncludesShadersStoreWGSL[name40] = shader39;
- }
- morphTargetsVertexDeclarationWGSL = { name: name40, shader: shader39 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthDeclaration.js
-var name41 = "logDepthDeclaration", shader40 = `#ifdef LOGARITHMICDEPTH
-uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32;
-#endif
-`;
-var init_logDepthDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name41]) {
- ShaderStore.IncludesShadersStoreWGSL[name41] = shader40;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js
-var exports_morphTargetsVertexGlobal = {};
-__export(exports_morphTargetsVertexGlobal, {
- morphTargetsVertexGlobalWGSL: () => morphTargetsVertexGlobalWGSL
-});
-var name42 = "morphTargetsVertexGlobal", shader41 = `#ifdef MORPHTARGETS
-#ifdef MORPHTARGETS_TEXTURE
-var vertexID : f32;
-#endif
-#endif
-`, morphTargetsVertexGlobalWGSL;
-var init_morphTargetsVertexGlobal = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name42]) {
- ShaderStore.IncludesShadersStoreWGSL[name42] = shader41;
- }
- morphTargetsVertexGlobalWGSL = { name: name42, shader: shader41 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js
-var exports_morphTargetsVertex = {};
-__export(exports_morphTargetsVertex, {
- morphTargetsVertexWGSL: () => morphTargetsVertexWGSL
-});
-var name43 = "morphTargetsVertex", shader42 = `#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
-`, morphTargetsVertexWGSL;
-var init_morphTargetsVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name43]) {
- ShaderStore.IncludesShadersStoreWGSL[name43] = shader42;
- }
- morphTargetsVertexWGSL = { name: name43, shader: shader42 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js
-var name44 = "instancesVertex", shader43 = `#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
-`;
-var init_instancesVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name44]) {
- ShaderStore.IncludesShadersStoreWGSL[name44] = shader43;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js
-var exports_bonesVertex = {};
-__export(exports_bonesVertex, {
- bonesVertexWGSL: () => bonesVertexWGSL
-});
-var name45 = "bonesVertex", shader44 = `#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
-`, bonesVertexWGSL;
-var init_bonesVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name45]) {
- ShaderStore.IncludesShadersStoreWGSL[name45] = shader44;
- }
- bonesVertexWGSL = { name: name45, shader: shader44 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js
-var name46 = "bakedVertexAnimation", shader45 = `#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
-`;
-var init_bakedVertexAnimation = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name46]) {
- ShaderStore.IncludesShadersStoreWGSL[name46] = shader45;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertex.js
-var name47 = "prePassVertex", shader46 = `#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
-`;
-var init_prePassVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name47]) {
- ShaderStore.IncludesShadersStoreWGSL[name47] = shader46;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvVariableDeclaration.js
-var name48 = "uvVariableDeclaration", shader47 = `#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
-`;
-var init_uvVariableDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name48]) {
- ShaderStore.IncludesShadersStoreWGSL[name48] = shader47;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexImplementation.js
-var name49 = "samplerVertexImplementation", shader48 = `#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
-`;
-var init_samplerVertexImplementation = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name49]) {
- ShaderStore.IncludesShadersStoreWGSL[name49] = shader48;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertex.js
-var name50 = "bumpVertex", shader49 = `#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
-`;
-var init_bumpVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name50]) {
- ShaderStore.IncludesShadersStoreWGSL[name50] = shader49;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js
-var exports_clipPlaneVertex = {};
-__export(exports_clipPlaneVertex, {
- clipPlaneVertexWGSL: () => clipPlaneVertexWGSL
-});
-var name51 = "clipPlaneVertex", shader50 = `#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
-`, clipPlaneVertexWGSL;
-var init_clipPlaneVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name51]) {
- ShaderStore.IncludesShadersStoreWGSL[name51] = shader50;
- }
- clipPlaneVertexWGSL = { name: name51, shader: shader50 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertex.js
-var name52 = "fogVertex", shader51 = `#ifdef FOG
-#ifdef SCENE_UBO
-vertexOutputs.vFogDistance=(scene.view*worldPos).xyz;
-#else
-vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz;
-#endif
-#endif
-`;
-var init_fogVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name52]) {
- ShaderStore.IncludesShadersStoreWGSL[name52] = shader51;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsVertex.js
-var exports_shadowsVertex = {};
-__export(exports_shadowsVertex, {
- shadowsVertexWGSL: () => shadowsVertexWGSL
-});
-var name53 = "shadowsVertex", shader52 = `#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
-`, shadowsVertexWGSL;
-var init_shadowsVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name53]) {
- ShaderStore.IncludesShadersStoreWGSL[name53] = shader52;
- }
- shadowsVertexWGSL = { name: name53, shader: shader52 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/vertexColorMixing.js
-var name54 = "vertexColorMixing", shader53 = `#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
-`;
-var init_vertexColorMixing = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name54]) {
- ShaderStore.IncludesShadersStoreWGSL[name54] = shader53;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthVertex.js
-var name55 = "logDepthVertex", shader54 = `#ifdef LOGARITHMICDEPTH
-vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant;
-#endif
-`;
-var init_logDepthVertex = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name55]) {
- ShaderStore.IncludesShadersStoreWGSL[name55] = shader54;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/default.vertex.js
-var exports_default_vertex = {};
-__export(exports_default_vertex, {
- defaultVertexShaderWGSL: () => defaultVertexShaderWGSL
-});
-var name56 = "defaultVertexShader", shader55 = `#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
-}
-`, defaultVertexShaderWGSL;
-var init_default_vertex = __esm(() => {
- init_shaderStore();
- init_defaultUboDeclaration();
- init_uvAttributeDeclaration();
- init_helperFunctions();
- init_bonesDeclaration();
- init_bakedVertexAnimationDeclaration();
- init_instancesDeclaration();
- init_prePassVertexDeclaration();
- init_mainUVVaryingDeclaration();
- init_samplerVertexDeclaration();
- init_bumpVertexDeclaration();
- init_clipPlaneVertexDeclaration();
- init_fogVertexDeclaration();
- init_lightVxFragmentDeclaration();
- init_lightVxUboDeclaration();
- init_morphTargetsVertexGlobalDeclaration();
- init_morphTargetsVertexDeclaration();
- init_logDepthDeclaration();
- init_morphTargetsVertexGlobal();
- init_morphTargetsVertex();
- init_instancesVertex();
- init_bonesVertex();
- init_bakedVertexAnimation();
- init_prePassVertex();
- init_uvVariableDeclaration();
- init_samplerVertexImplementation();
- init_bumpVertex();
- init_clipPlaneVertex();
- init_fogVertex();
- init_shadowsVertex();
- init_vertexColorMixing();
- init_logDepthVertex();
- if (!ShaderStore.ShadersStoreWGSL[name56]) {
- ShaderStore.ShadersStoreWGSL[name56] = shader55;
- }
- defaultVertexShaderWGSL = { name: name56, shader: shader55 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassDeclaration.js
-var name57 = "prePassDeclaration", shader56 = `#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
-`;
-var init_prePassDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name57]) {
- ShaderStore.IncludesShadersStoreWGSL[name57] = shader56;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitDeclaration.js
-var name58 = "oitDeclaration", shader57 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY
-#define MAX_DEPTH 99999.0
-var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d;
-#endif
-`;
-var init_oitDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name58]) {
- ShaderStore.IncludesShadersStoreWGSL[name58] = shader57;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightUboDeclaration.js
-var exports_lightUboDeclaration = {};
-__export(exports_lightUboDeclaration, {
- lightUboDeclarationWGSL: () => lightUboDeclarationWGSL
-});
-var name59 = "lightUboDeclaration", shader58 = `#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
-`, lightUboDeclarationWGSL;
-var init_lightUboDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name59]) {
- ShaderStore.IncludesShadersStoreWGSL[name59] = shader58;
- }
- lightUboDeclarationWGSL = { name: name59, shader: shader58 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/ltcHelperFunctions.js
-var name60 = "ltcHelperFunctions", shader59 = `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;}`;
-var init_ltcHelperFunctions = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name60]) {
- ShaderStore.IncludesShadersStoreWGSL[name60] = shader59;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightsFragmentFunctions.js
-var exports_lightsFragmentFunctions = {};
-__export(exports_lightsFragmentFunctions, {
- lightsFragmentFunctionsWGSL: () => lightsFragmentFunctionsWGSL
-});
-var name61 = "lightsFragmentFunctions", shader60 = `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
-`, lightsFragmentFunctionsWGSL;
-var init_lightsFragmentFunctions = __esm(() => {
- init_shaderStore();
- init_ltcHelperFunctions();
- if (!ShaderStore.IncludesShadersStoreWGSL[name61]) {
- ShaderStore.IncludesShadersStoreWGSL[name61] = shader60;
- }
- lightsFragmentFunctionsWGSL = { name: name61, shader: shader60 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsFragmentFunctions.js
-var exports_shadowsFragmentFunctions = {};
-__export(exports_shadowsFragmentFunctions, {
- shadowsFragmentFunctionsWGSL: () => shadowsFragmentFunctionsWGSL
-});
-var name62 = "shadowsFragmentFunctions", shader61 = `#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
-`, shadowsFragmentFunctionsWGSL;
-var init_shadowsFragmentFunctions = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name62]) {
- ShaderStore.IncludesShadersStoreWGSL[name62] = shader61;
- }
- shadowsFragmentFunctionsWGSL = { name: name62, shader: shader61 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerFragmentDeclaration.js
-var name63 = "samplerFragmentDeclaration", shader62 = `#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
-`;
-var init_samplerFragmentDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name63]) {
- ShaderStore.IncludesShadersStoreWGSL[name63] = shader62;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fresnelFunction.js
-var name64 = "fresnelFunction", shader63 = `#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
-`;
-var init_fresnelFunction = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name64]) {
- ShaderStore.IncludesShadersStoreWGSL[name64] = shader63;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/reflectionFunction.js
-var exports_reflectionFunction = {};
-__export(exports_reflectionFunction, {
- reflectionFunctionWGSL: () => reflectionFunctionWGSL
-});
-var name65 = "reflectionFunction", shader64 = `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
-`, reflectionFunctionWGSL;
-var init_reflectionFunction = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name65]) {
- ShaderStore.IncludesShadersStoreWGSL[name65] = shader64;
- }
- reflectionFunctionWGSL = { name: name65, shader: shader64 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingDeclaration.js
-var exports_imageProcessingDeclaration = {};
-__export(exports_imageProcessingDeclaration, {
- imageProcessingDeclarationWGSL: () => imageProcessingDeclarationWGSL
-});
-var name66 = "imageProcessingDeclaration", shader65 = `#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
-`, imageProcessingDeclarationWGSL;
-var init_imageProcessingDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name66]) {
- ShaderStore.IncludesShadersStoreWGSL[name66] = shader65;
- }
- imageProcessingDeclarationWGSL = { name: name66, shader: shader65 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingFunctions.js
-var exports_imageProcessingFunctions = {};
-__export(exports_imageProcessingFunctions, {
- imageProcessingFunctionsWGSL: () => imageProcessingFunctionsWGSL
-});
-var name67 = "imageProcessingFunctions", shader66 = `#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);}`, imageProcessingFunctionsWGSL;
-var init_imageProcessingFunctions = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name67]) {
- ShaderStore.IncludesShadersStoreWGSL[name67] = shader66;
- }
- imageProcessingFunctionsWGSL = { name: name67, shader: shader66 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentMainFunctions.js
-var exports_bumpFragmentMainFunctions = {};
-__export(exports_bumpFragmentMainFunctions, {
- bumpFragmentMainFunctionsWGSL: () => bumpFragmentMainFunctionsWGSL
-});
-var name68 = "bumpFragmentMainFunctions", shader67 = `#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
-`, bumpFragmentMainFunctionsWGSL;
-var init_bumpFragmentMainFunctions = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name68]) {
- ShaderStore.IncludesShadersStoreWGSL[name68] = shader67;
- }
- bumpFragmentMainFunctionsWGSL = { name: name68, shader: shader67 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentFunctions.js
-var exports_bumpFragmentFunctions = {};
-__export(exports_bumpFragmentFunctions, {
- bumpFragmentFunctionsWGSL: () => bumpFragmentFunctionsWGSL
-});
-var name69 = "bumpFragmentFunctions", shader68 = `#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
-`, bumpFragmentFunctionsWGSL;
-var init_bumpFragmentFunctions = __esm(() => {
- init_shaderStore();
- init_samplerFragmentDeclaration();
- if (!ShaderStore.IncludesShadersStoreWGSL[name69]) {
- ShaderStore.IncludesShadersStoreWGSL[name69] = shader68;
- }
- bumpFragmentFunctionsWGSL = { name: name69, shader: shader68 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js
-var exports_clipPlaneFragmentDeclaration = {};
-__export(exports_clipPlaneFragmentDeclaration, {
- clipPlaneFragmentDeclarationWGSL: () => clipPlaneFragmentDeclarationWGSL
-});
-var name70 = "clipPlaneFragmentDeclaration", shader69 = `#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
-`, clipPlaneFragmentDeclarationWGSL;
-var init_clipPlaneFragmentDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name70]) {
- ShaderStore.IncludesShadersStoreWGSL[name70] = shader69;
- }
- clipPlaneFragmentDeclarationWGSL = { name: name70, shader: shader69 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragmentDeclaration.js
-var exports_fogFragmentDeclaration = {};
-__export(exports_fogFragmentDeclaration, {
- fogFragmentDeclarationWGSL: () => fogFragmentDeclarationWGSL
-});
-var name71 = "fogFragmentDeclaration", shader70 = `#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
-`, fogFragmentDeclarationWGSL;
-var init_fogFragmentDeclaration = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name71]) {
- ShaderStore.IncludesShadersStoreWGSL[name71] = shader70;
- }
- fogFragmentDeclarationWGSL = { name: name71, shader: shader70 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js
-var exports_clipPlaneFragment = {};
-__export(exports_clipPlaneFragment, {
- clipPlaneFragmentWGSL: () => clipPlaneFragmentWGSL
-});
-var name72 = "clipPlaneFragment", shader71 = `#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
-`, clipPlaneFragmentWGSL;
-var init_clipPlaneFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name72]) {
- ShaderStore.IncludesShadersStoreWGSL[name72] = shader71;
- }
- clipPlaneFragmentWGSL = { name: name72, shader: shader71 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragment.js
-var exports_bumpFragment = {};
-__export(exports_bumpFragment, {
- bumpFragmentWGSL: () => bumpFragmentWGSL
-});
-var name73 = "bumpFragment", shader72 = `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
-`, bumpFragmentWGSL;
-var init_bumpFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name73]) {
- ShaderStore.IncludesShadersStoreWGSL[name73] = shader72;
- }
- bumpFragmentWGSL = { name: name73, shader: shader72 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/decalFragment.js
-var name74 = "decalFragment", shader73 = `#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
-`;
-var init_decalFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name74]) {
- ShaderStore.IncludesShadersStoreWGSL[name74] = shader73;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/depthPrePass.js
-var name75 = "depthPrePass", shader74 = `#ifdef DEPTHPREPASS
-fragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs;
-#endif
-`;
-var init_depthPrePass = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name75]) {
- ShaderStore.IncludesShadersStoreWGSL[name75] = shader74;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightFragment.js
-var exports_lightFragment = {};
-__export(exports_lightFragment, {
- lightFragmentWGSL: () => lightFragmentWGSL
-});
-var name76 = "lightFragment", shader75 = `#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
-`, lightFragmentWGSL;
-var init_lightFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name76]) {
- ShaderStore.IncludesShadersStoreWGSL[name76] = shader75;
- }
- lightFragmentWGSL = { name: name76, shader: shader75 };
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthFragment.js
-var name77 = "logDepthFragment", shader76 = `#ifdef LOGARITHMICDEPTH
-fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5;
-#endif
-`;
-var init_logDepthFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name77]) {
- ShaderStore.IncludesShadersStoreWGSL[name77] = shader76;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragment.js
-var name78 = "fogFragment", shader77 = `#ifdef FOG
-var fog: f32=CalcFogFactor();
-#ifdef PBR
-fog=toLinearSpace(fog);
-#endif
-color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a);
-#endif
-`;
-var init_fogFragment = __esm(() => {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name78]) {
- ShaderStore.IncludesShadersStoreWGSL[name78] = shader77;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitFragment.js
-var name79 = "oitFragment", shader78 = `#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 && fragDepth {
- init_shaderStore();
- if (!ShaderStore.IncludesShadersStoreWGSL[name79]) {
- ShaderStore.IncludesShadersStoreWGSL[name79] = shader78;
- }
-});
-
-// node_modules/@babylonjs/core/ShadersWGSL/default.fragment.js
-var exports_default_fragment = {};
-__export(exports_default_fragment, {
- defaultPixelShaderWGSL: () => defaultPixelShaderWGSL
-});
-var name80 = "defaultPixelShader", shader79 = `#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