// @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, Screen, 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);
  Screen = {
    getPrimaryDisplay: () => {
      const jsonStr = native.symbols.getPrimaryDisplay();
      if (!jsonStr) {
        return {
          id: 0,
          bounds: { x: 0, y: 0, width: 0, height: 0 },
          workArea: { x: 0, y: 0, width: 0, height: 0 },
          scaleFactor: 1,
          isPrimary: true
        };
      }
      try {
        return JSON.parse(jsonStr.toString());
      } catch {
        return {
          id: 0,
          bounds: { x: 0, y: 0, width: 0, height: 0 },
          workArea: { x: 0, y: 0, width: 0, height: 0 },
          scaleFactor: 1,
          isPrimary: true
        };
      }
    },
    getAllDisplays: () => {
      const jsonStr = native.symbols.getAllDisplays();
      if (!jsonStr) {
        return [];
      }
      try {
        return JSON.parse(jsonStr.toString());
      } catch {
        return [];
      }
    },
    getCursorScreenPoint: () => {
      const jsonStr = native.symbols.getCursorScreenPoint();
      if (!jsonStr) {
        return { x: 0, y: 0 };
      }
      try {
        return JSON.parse(jsonStr.toString());
      } catch {
        return { x: 0, y: 0 };
      }
    },
    getMouseButtons: () => {
      try {
        return native.symbols.getMouseButtons();
      } catch {
        return 0n;
      }
    }
  };
  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 = `<div style='color:${type.color}'>${formattedMessage}</div><br>`;
    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<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;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<f32>;
#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<f32>;
#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<f32>;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<f32>;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<f32>)->vec4<f32>
{
#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<f32>)->vec4<f32>
{
#if USE_EXACT_SRGB_CONVERSIONS
return vec4<f32>(toGammaSpaceExact(color.rgb),color.a);
#else
return vec4<f32>(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>)->f32 {return fract(sin(dot(seed.xy ,vec2<f32>(12.9898,78.233)))*43758.5453);}
fn dither(seed: vec2<f32>,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<f32> {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<f32>(saturateVec3(rgb),D);}
fn fromRGBD(rgbd: vec4<f32>)->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<f32>;
#include<helperFunctions>
#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<helperFunctions>
#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<helperFunctions>
#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<f32>;
#include<helperFunctions>
#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<f32>;var leftSamplerSampler: sampler;var leftSampler: texture_2d<f32>;
#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<f32>;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<f32>,
#ifdef MULTIVIEW
viewProjectionR : mat4x4<f32>,
#endif 
view : mat4x4<f32>,
projection : mat4x4<f32>,
vEyePosition : vec4<f32>,};
#define SCENE_UBO
var<uniform> 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<f32>,
visibility : f32,};var<uniform> 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<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
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<f32>;attribute matricesWeights : vec4<f32>;
#if NUM_BONE_INFLUENCERS>4
attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32;
#else
uniform mBones : array<mat4x4,BonesPerMesh>;
#ifdef BONES_VELOCITY_ENABLED
uniform mPreviousBones : array<mat4x4,BonesPerMesh>;
#endif
#endif
#ifdef BONETEXTURE
fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>
{let offset=i32(index) *4; 
let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(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<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>;
#ifdef INSTANCES
attribute bakedVertexAnimationSettingsInstanced : vec4<f32>;
#endif
fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>
{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(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<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;
#ifdef INSTANCESCOLOR
attribute instanceColor : vec4<f32>;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>;
#ifdef THIN_INSTANCES
uniform previousWorld : mat4x4<f32>;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform world : mat4x4<f32>;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
uniform previousWorld : mat4x4<f32>;
#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<f32>;varying fClipDistance: f32;
#endif
#ifdef CLIPPLANE2
uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32;
#endif
#ifdef CLIPPLANE3
uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32;
#endif
#ifdef CLIPPLANE4
uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32;
#endif
#ifdef CLIPPLANE5
uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32;
#endif
#ifdef CLIPPLANE6
uniform vClipPlane6: vec4<f32>;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<uniform> light{X} : Light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;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<f32,NUM_MORPH_INFLUENCERS>;
#ifdef MORPHTARGETS_TEXTURE 
uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>
{ 
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((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<f32>
{ 
let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((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<f32>;
#endif
#ifdef MORPHTARGETS_NORMAL
attribute normal{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_TANGENT
attribute tangent{X} : vec3<f32>;
#endif
#ifdef MORPHTARGETS_UV
attribute uv_{X} : vec2<f32>;
#endif
#ifdef MORPHTARGETS_UV2
attribute uv2_{X} : vec2<f32>;
#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<NUM_MORPH_INFLUENCERS; i=i+1) {if (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<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
var finalPreviousWorld=mat4x4<f32>(
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<f32>;
#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<f32>;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<defaultUboDeclaration>
#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<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_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<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#include<logDepthDeclaration>
#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<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#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<bonesVertex>
#include<bakedVertexAnimation>
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<prePassVertex>
#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<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<logDepthVertex>
#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<f32>;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d<f32>;
#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<uniform> light{X} : Light{X};
#ifdef IESLIGHTTEXTURE{X}
var iesLightTexture{X}Sampler: sampler;var iesLightTexture{X}: texture_2d<f32>;
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d<f32>;
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform lightMatrix{X}: array<mat4x4f,SHADOWCSMNUM_CASCADES{X}>;uniform viewFrustumZ{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;uniform frustumLengths{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;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<private> vPositionFromLight{X}: array<vec4f,4>;var<private> vDepthMetric{X} : array<f32,4>;
#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<f32>;uniform lightSizeUVCorrection{X}: array<vec2f,SHADOWCSMNUM_CASCADES{X}>;uniform depthCorrection{X}: array<f32,SHADOWCSMNUM_CASCADES{X}>;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<f32>;
#endif
#ifdef SHADOWCSMDEBUG{X}
const vCascadeColorsMultiplier{X}: array<vec3f,8>=array<vec3f,8>
(
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<f32>;
#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<f32>;
#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<f32>;
#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<f32>,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<f32>=mInv*transposeMat3( mat3x3<f32>( 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<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,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<f32>=mat3x3<f32>(
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<f32>=mat3x3<f32>(
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<f32>,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<f32>,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<f32>,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<ltcHelperFunctions>
var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d<f32>;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d<f32>;fn computeAreaLighting(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,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<f32>,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<f32>,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<vec3f,4>;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))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) {visibility-=0.25;};if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) {visibility-=0.25;};
#else
if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) {visibility-=0.25;};if (textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) {visibility-=0.25;};
#endif
return min(1.0,visibility+darkness);}
fn computeShadowWithESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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<vec2f,4>;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.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) {visibility-=0.25;}
#else
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
if (textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) {visibility-=0.25;}
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}
fn computeShadowWithESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d<f32>,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<f32>,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<vec3f,64>=array<vec3f,64> (
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<vec3f,64>=array<vec3f,64> (
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<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>,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<searchTapCount; i ++) {blockerDepth=textureSample(depthTexture,depthSampler, uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}
var avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);var filterRadius: vec4f= vec4f(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {var offset: vec4f= vec4f(poissonSamplers[i],0.);offset= vec4f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);let coords=uvDepthLayer+offset*filterRadius;shadow+=textureSampleCompare(shadowTexture,shadowSampler,coords.xy,i32(coords.z),coords.w);}
shadow/= f32(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);return select(computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff),1.0,numBlocker<1.0);}
fn computeShadowWithPCSS(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array<vec3f,64>)->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<searchTapCount; i ++) {if (exitCondition) {break;}
blockerDepth=textureSampleLevel(depthTexture,depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0).r;numBlocker+=select(0.,1.,blockerDepth<depthMetric);sumBlockerDepth+=select(0.,blockerDepth,blockerDepth<depthMetric);}
exitCondition=exitCondition || numBlocker<1.0;var avgBlockerDepth: f32=sumBlockerDepth/numBlocker;var AAOffset: f32=shadowMapSizeInverse*10.;var penumbraRatio: f32=((depthMetric-avgBlockerDepth)+AAOffset);var filterRadius: f32=penumbraRatio*lightSizeUV*shadowMapSizeInverse;var random: f32=getRand(vPositionFromLight.xy);var rotationAngle: f32=random*3.1415926;var rotationVector: vec2f= vec2f(cos(rotationAngle),sin(rotationAngle));var shadow: f32=0.;for (var i: i32=0; i<pcfTapCount; i++) {if (exitCondition) {break;}
var offset: vec3f=poissonSamplers[i];offset= vec3f(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);let coords=uvDepth+offset*filterRadius;shadow+=textureSampleCompareLevel(shadowTexture,shadowSampler,coords.xy,coords.z);}
shadow/= f32(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return select(computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff),1.0,exitCondition);}
fn computeShadowWithPCSS16(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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<f32>,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<f32>;
#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<f32>;
#else
var txColorTransformSampler: sampler;var txColorTransform: texture_2d<f32>;
#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 (peak<PBRNeutralStartCompression) {return result;}
var d: f32=1.-PBRNeutralStartCompression;var newPeak: f32=1.-d*d/(peak+d-PBRNeutralStartCompression);result*=newPeak/peak;var g: f32=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(result,newPeak* vec3f(1,1,1),g);}
#endif
#if TONEMAPPING==2
const ACESInputMat: mat3x3f= mat3x3f(
vec3f(0.59719,0.07600,0.02840),
vec3f(0.35458,0.90834,0.13383),
vec3f(0.04823,0.01566,0.83777)
);const ACESOutputMat: mat3x3f= mat3x3f(
vec3f( 1.60475,-0.10208,-0.00327),
vec3f(-0.53108, 1.10813,-0.07276),
vec3f(-0.07367,-0.00605, 1.07602)
);fn RRTAndODTFit(v: vec3f)->vec3f
{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<f32>(
(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<f32>(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<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_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; i<iMaxSamples; i++)
{currSampledHeight=textureSample(bumpSampler,bumpSamplerSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{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<f32>(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<f32>(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<SHADOWCSMNUM_CASCADES{X}; i++) 
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=uniforms.viewFrustumZ{X}[i]+fragmentInputs.vPositionFromCamera{X}.z;
#else
diff{X}=uniforms.viewFrustumZ{X}[i]-fragmentInputs.vPositionFromCamera{X}.z;
#endif
if (diff{X}>=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 || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif
return fragmentOutputs;}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif
fragmentOutputs.depth=vec2f(-fragDepth,fragDepth);return fragmentOutputs;}
#endif
`;
var init_oitFragment = __esm(() => {
  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<defaultUboDeclaration>
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#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<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
var refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube<f32>;
#else
var refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d<f32>;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif
#include<fresnelFunction>
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
var reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube<f32>;
#else
var reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d<f32>;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a;
#ifdef NORMAL
var normalW: vec3f=normalize(fragmentInputs.vNormalW);
#else
var normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)));
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=select(-normalW,normalW,fragmentInputs.frontFacing);
#endif
#ifdef DIFFUSE
baseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<uniforms.alphaCutOff) {discard;}
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor=vec4f(baseColor.rgb*uniforms.vDiffuseInfos.y,baseColor.a);
#endif
#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#include<depthPrePass>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
baseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a);
#endif
#ifdef DETAIL
baseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a);
#endif
#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
var baseAmbientColor: vec3f= vec3f(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
var glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb;
#ifdef SPECULARTERM
#ifdef SPECULAR
var specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#endif
var diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo;
#ifdef SPECULARTERM
var specularBase: vec3f= vec3f(0.,0.,0.);
#endif
var shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.;
#ifdef LIGHTMAP
var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);
#endif
lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);
#endif
#include<lightFragment>[0..maxSimultaneousLights]
aggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.);
#ifdef REFRACTION
var refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}
#else
var vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a);
#endif
refractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a);
#endif
var reflectionColor: vec4f= vec4f(0.,0.,0.,1.);
#ifdef REFLECTION
var vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0);
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
var bias: f32=uniforms.vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias);
#else
reflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW);
#endif
#else
var coords: vec2f=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a);
#endif
reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);
#ifdef REFLECTIONFRESNEL
var reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#else
reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#endif
#else
reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a);
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
var refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a);
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y;
#else
alpha*=opacityMap.a*uniforms.vOpacityInfos.y;
#endif
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=fragmentInputs.vColor.a;
#endif
#ifdef OPACITYFRESNEL
var opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<uniforms.alphaCutOff) {discard;}
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
var emissiveColor: vec3f=uniforms.vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb*uniforms.vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
var emissiveFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.emissiveRightColor.a,uniforms.emissiveLeftColor.a);emissiveColor*=uniforms.emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*uniforms.emissiveRightColor.rgb;
#endif
#ifdef DIFFUSEFRESNEL
var diffuseFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.diffuseRightColor.a,uniforms.diffuseLeftColor.a);diffuseBase*=uniforms.diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*uniforms.diffuseRightColor.rgb;
#endif
#ifdef EMISSIVEASILLUMINATION
var finalDiffuse: vec3f=clamp(diffuseBase*diffuseColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
var finalDiffuse: vec3f=clamp((diffuseBase+emissiveColor)*diffuseColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#else
var finalDiffuse: vec3f=clamp(diffuseBase*diffuseColor+emissiveColor+uniforms.vAmbientColor,vec3f(0.0),vec3f(1.0))*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
var finalSpecular: vec3f=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular, vec3f(0.3,0.59,0.11)),0.0,1.0);
#endif
#else
var finalSpecular: vec3f= vec3f(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb, vec3f(0.3,0.59,0.11)),0.0,1.0);
#endif
#ifdef EMISSIVEASILLUMINATION
var color: vec4f= vec4f(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
#else
var color: vec4f= vec4f(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color=vec4f(color.rgb*lightmapColor.rgb,color.a);
#else
color=vec4f(color.rgb+lightmapColor.rgb,color.a);
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color=vec4f(max(color.rgb,vec3f(0.)),color.a);
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
color=vec4f(toLinearSpaceVec3(color.rgb),color.a);
#else
#ifdef IMAGEPROCESSING
color=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color);
#endif
#endif
color=vec4f(color.rgb,color.a*mesh.visibility);
#ifdef PREMULTIPLYALPHA
color=vec4f(color.rgb*color.a, color.a);
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
var writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=color; 
#endif
#ifdef PREPASS_POSITION
fragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -
(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_DEPTH
fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);
#else
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
fragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULAR)
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; 
#else
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo;
#endif
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
#endif
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=color;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`, defaultPixelShaderWGSL;
var init_default_fragment = __esm(() => {
  init_shaderStore();
  init_defaultUboDeclaration();
  init_prePassDeclaration();
  init_oitDeclaration();
  init_mainUVVaryingDeclaration();
  init_helperFunctions();
  init_lightUboDeclaration();
  init_lightsFragmentFunctions();
  init_shadowsFragmentFunctions();
  init_samplerFragmentDeclaration();
  init_fresnelFunction();
  init_reflectionFunction();
  init_imageProcessingDeclaration();
  init_imageProcessingFunctions();
  init_bumpFragmentMainFunctions();
  init_bumpFragmentFunctions();
  init_clipPlaneFragmentDeclaration();
  init_logDepthDeclaration();
  init_fogFragmentDeclaration();
  init_clipPlaneFragment();
  init_bumpFragment();
  init_decalFragment();
  init_depthPrePass();
  init_lightFragment();
  init_logDepthFragment();
  init_fogFragment();
  init_oitFragment();
  if (!ShaderStore.ShadersStoreWGSL[name80]) {
    ShaderStore.ShadersStoreWGSL[name80] = shader79;
  }
  defaultPixelShaderWGSL = { name: name80, shader: shader79 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/decalVertexDeclaration.js
var name81 = "decalVertexDeclaration", shader80 = `#ifdef DECAL
uniform vec4 vDecalInfos;uniform mat4 decalMatrix;
#endif
`;
var init_decalVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name81]) {
    ShaderStore.IncludesShadersStore[name81] = shader80;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultVertexDeclaration.js
var name82 = "defaultVertexDeclaration", shader81 = `uniform mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif 
uniform mat4 view;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;uniform mat4 specularMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef REFLECTION
uniform mat4 reflectionMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;
var init_defaultVertexDeclaration = __esm(() => {
  init_shaderStore();
  init_decalVertexDeclaration();
  if (!ShaderStore.IncludesShadersStore[name82]) {
    ShaderStore.IncludesShadersStore[name82] = shader81;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js
var name83 = "sceneUboDeclaration", shader82 = `layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif 
mat4 view;mat4 projection;vec4 vEyePosition;};
`;
var init_sceneUboDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name83]) {
    ShaderStore.IncludesShadersStore[name83] = shader82;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js
var name84 = "meshUboDeclaration", shader83 = `#ifdef WEBGL2
uniform mat4 world;uniform float visibility;
#else
layout(std140,column_major) uniform;uniform Mesh
{mat4 world;float visibility;};
#endif
#define WORLD_UBO
`;
var init_meshUboDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name84]) {
    ShaderStore.IncludesShadersStore[name84] = shader83;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js
var name85 = "defaultUboDeclaration", shader84 = `layout(std140,column_major) uniform;uniform Material
{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
var init_defaultUboDeclaration2 = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  init_meshUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name85]) {
    ShaderStore.IncludesShadersStore[name85] = shader84;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/uvAttributeDeclaration.js
var name86 = "uvAttributeDeclaration", shader85 = `#ifdef UV{X}
attribute vec2 uv{X};
#endif
`;
var init_uvAttributeDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name86]) {
    ShaderStore.IncludesShadersStore[name86] = shader85;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js
var exports_bonesDeclaration2 = {};
__export(exports_bonesDeclaration2, {
  bonesDeclaration: () => bonesDeclaration
});
var name87 = "bonesDeclaration", shader86 = `#if NUM_BONE_INFLUENCERS>0
attribute vec4 matricesIndices;attribute vec4 matricesWeights;
#if NUM_BONE_INFLUENCERS>4
attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;
#endif
#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#ifdef BONETEXTURE
uniform highp sampler2D boneSampler;uniform float boneTextureWidth;
#else
uniform mat4 mBones[BonesPerMesh];
#endif
#ifdef BONES_VELOCITY_ENABLED
uniform mat4 mPreviousBones[BonesPerMesh];
#endif
#ifdef BONETEXTURE
#define inline
mat4 readMatrixFromRawSampler(sampler2D smp,float index)
{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);}
#endif
#endif
#endif
`, bonesDeclaration;
var init_bonesDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name87]) {
    ShaderStore.IncludesShadersStore[name87] = shader86;
  }
  bonesDeclaration = { name: name87, shader: shader86 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js
var name88 = "bakedVertexAnimationDeclaration", shader87 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;
#ifdef INSTANCES
attribute vec4 bakedVertexAnimationSettingsInstanced;
#endif
#define inline
mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)
{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);}
#endif
`;
var init_bakedVertexAnimationDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name88]) {
    ShaderStore.IncludesShadersStore[name88] = shader87;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js
var name89 = "instancesDeclaration", shader88 = `#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#ifdef INSTANCESCOLOR
attribute vec4 instanceColor;
#endif
#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;
#ifdef THIN_INSTANCES
uniform mat4 previousWorld;
#endif
#endif
#else
#if !defined(WORLD_UBO)
uniform mat4 world;
#endif
#if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
uniform mat4 previousWorld;
#endif
#endif
`;
var init_instancesDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name89]) {
    ShaderStore.IncludesShadersStore[name89] = shader88;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertexDeclaration.js
var name90 = "prePassVertexDeclaration", shader89 = `#ifdef PREPASS
#ifdef PREPASS_LOCAL_POSITION
varying vec3 vPosition;
#endif
#ifdef PREPASS_DEPTH
varying vec3 vViewPos;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#endif
`;
var init_prePassVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name90]) {
    ShaderStore.IncludesShadersStore[name90] = shader89;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/mainUVVaryingDeclaration.js
var name91 = "mainUVVaryingDeclaration", shader90 = `#ifdef MAINUV{X}
varying vec2 vMainUV{X};
#endif
`;
var init_mainUVVaryingDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name91]) {
    ShaderStore.IncludesShadersStore[name91] = shader90;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexDeclaration.js
var name92 = "samplerVertexDeclaration", shader91 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
varying vec2 v_VARYINGNAME_UV;
#endif
`;
var init_samplerVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name92]) {
    ShaderStore.IncludesShadersStore[name92] = shader91;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertexDeclaration.js
var name93 = "bumpVertexDeclaration", shader92 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL) 
varying mat3 vTBN;
#endif
#endif
`;
var init_bumpVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name93]) {
    ShaderStore.IncludesShadersStore[name93] = shader92;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js
var exports_clipPlaneVertexDeclaration2 = {};
__export(exports_clipPlaneVertexDeclaration2, {
  clipPlaneVertexDeclaration: () => clipPlaneVertexDeclaration
});
var name94 = "clipPlaneVertexDeclaration", shader93 = `#ifdef CLIPPLANE
uniform vec4 vClipPlane;varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;varying float fClipDistance6;
#endif
`, clipPlaneVertexDeclaration;
var init_clipPlaneVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name94]) {
    ShaderStore.IncludesShadersStore[name94] = shader93;
  }
  clipPlaneVertexDeclaration = { name: name94, shader: shader93 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertexDeclaration.js
var name95 = "fogVertexDeclaration", shader94 = `#ifdef FOG
varying vec3 vFogDistance;
#endif
`;
var init_fogVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name95]) {
    ShaderStore.IncludesShadersStore[name95] = shader94;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js
var exports_lightVxFragmentDeclaration = {};
__export(exports_lightVxFragmentDeclaration, {
  lightVxFragmentDeclaration: () => lightVxFragmentDeclaration
});
var name96 = "lightVxFragmentDeclaration", shader95 = `#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#if defined(AREALIGHT{X})
uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X};
#endif
#endif
`, lightVxFragmentDeclaration;
var init_lightVxFragmentDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name96]) {
    ShaderStore.IncludesShadersStore[name96] = shader95;
  }
  lightVxFragmentDeclaration = { name: name96, shader: shader95 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js
var exports_lightVxUboDeclaration2 = {};
__export(exports_lightVxUboDeclaration2, {
  lightVxUboDeclaration: () => lightVxUboDeclaration
});
var name97 = "lightVxUboDeclaration", shader96 = `#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
#if defined(AREALIGHT{X})
vec4 vLightWidth;vec4 vLightHeight;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#elif defined(SHADOWCUBE{X})
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`, lightVxUboDeclaration;
var init_lightVxUboDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name97]) {
    ShaderStore.IncludesShadersStore[name97] = shader96;
  }
  lightVxUboDeclaration = { name: name97, shader: shader96 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js
var exports_morphTargetsVertexGlobalDeclaration2 = {};
__export(exports_morphTargetsVertexGlobalDeclaration2, {
  morphTargetsVertexGlobalDeclaration: () => morphTargetsVertexGlobalDeclaration
});
var name98 = "morphTargetsVertexGlobalDeclaration", shader97 = `#ifdef MORPHTARGETS
uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];
#ifdef MORPHTARGETS_TEXTURE 
uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)
{ 
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;}
vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex)
{ 
float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);}
#endif
#endif
`, morphTargetsVertexGlobalDeclaration;
var init_morphTargetsVertexGlobalDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name98]) {
    ShaderStore.IncludesShadersStore[name98] = shader97;
  }
  morphTargetsVertexGlobalDeclaration = { name: name98, shader: shader97 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js
var exports_morphTargetsVertexDeclaration2 = {};
__export(exports_morphTargetsVertexDeclaration2, {
  morphTargetsVertexDeclaration: () => morphTargetsVertexDeclaration
});
var name99 = "morphTargetsVertexDeclaration", shader98 = `#ifdef MORPHTARGETS
#ifndef MORPHTARGETS_TEXTURE
#ifdef MORPHTARGETS_POSITION
attribute vec3 position{X};
#endif
#ifdef MORPHTARGETS_NORMAL
attribute vec3 normal{X};
#endif
#ifdef MORPHTARGETS_TANGENT
attribute vec3 tangent{X};
#endif
#ifdef MORPHTARGETS_UV
attribute vec2 uv_{X};
#endif
#ifdef MORPHTARGETS_UV2
attribute vec2 uv2_{X};
#endif
#elif {X}==0
uniform int morphTargetCount;
#endif
#endif
`, morphTargetsVertexDeclaration;
var init_morphTargetsVertexDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name99]) {
    ShaderStore.IncludesShadersStore[name99] = shader98;
  }
  morphTargetsVertexDeclaration = { name: name99, shader: shader98 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthDeclaration.js
var name100 = "logDepthDeclaration", shader99 = `#ifdef LOGARITHMICDEPTH
uniform float logarithmicDepthConstant;varying float vFragmentDepth;
#endif
`;
var init_logDepthDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name100]) {
    ShaderStore.IncludesShadersStore[name100] = shader99;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js
var exports_morphTargetsVertexGlobal2 = {};
__export(exports_morphTargetsVertexGlobal2, {
  morphTargetsVertexGlobal: () => morphTargetsVertexGlobal
});
var name101 = "morphTargetsVertexGlobal", shader100 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
float vertexID;
#endif
#endif
`, morphTargetsVertexGlobal;
var init_morphTargetsVertexGlobal2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name101]) {
    ShaderStore.IncludesShadersStore[name101] = shader100;
  }
  morphTargetsVertexGlobal = { name: name101, shader: shader100 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js
var exports_morphTargetsVertex2 = {};
__export(exports_morphTargetsVertex2, {
  morphTargetsVertex: () => morphTargetsVertex
});
var name102 = "morphTargetsVertex", shader101 = `#ifdef MORPHTARGETS
#ifdef MORPHTARGETS_TEXTURE
#if {X}==0
for (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (i>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;
#ifdef MORPHTARGETS_POSITION
positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASNORMALS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASUVS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASTANGENTS
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i];
#endif
#ifdef MORPHTARGETTEXTURE_HASUV2S
vertexID+=1.0;
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i];
#endif
}
#endif
#else
#ifdef MORPHTARGETS_POSITION
positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_NORMAL
normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_TANGENT
tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV
uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_UV2
uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}];
#endif
#ifdef MORPHTARGETS_COLOR
colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}];
#endif
#endif
#endif
`, morphTargetsVertex;
var init_morphTargetsVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name102]) {
    ShaderStore.IncludesShadersStore[name102] = shader101;
  }
  morphTargetsVertex = { name: name102, shader: shader101 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js
var name103 = "instancesVertex", shader102 = `#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,
previousWorld2,previousWorld3);
#endif
#ifdef THIN_INSTANCES
finalWorld=world*finalWorld;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
finalPreviousWorld=previousWorld*finalPreviousWorld;
#endif
#endif
#else
mat4 finalWorld=world;
#if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR)
mat4 finalPreviousWorld=previousWorld;
#endif
#endif
`;
var init_instancesVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name103]) {
    ShaderStore.IncludesShadersStore[name103] = shader102;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js
var exports_bonesVertex2 = {};
__export(exports_bonesVertex2, {
  bonesVertex: () => bonesVertex
});
var name104 = "bonesVertex", shader103 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE
#if NUM_BONE_INFLUENCERS>0
mat4 influence;
#ifdef BONETEXTURE
influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];
#endif
#else
influence=mBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence+=mBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
influence+=mBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
influence+=mBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
#endif
finalWorld=finalWorld*influence;
#endif
#endif
`, bonesVertex;
var init_bonesVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name104]) {
    ShaderStore.IncludesShadersStore[name104] = shader103;
  }
  bonesVertex = { name: name104, shader: shader103 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js
var name105 = "bakedVertexAnimation", shader104 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE
{
#ifdef INSTANCES
#define BVASNAME bakedVertexAnimationSettingsInstanced
#else
#define BVASNAME bakedVertexAnimationSettings
#endif
float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];
#endif
finalWorld=finalWorld*VATInfluence;}
#endif
`;
var init_bakedVertexAnimation2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name105]) {
    ShaderStore.IncludesShadersStore[name105] = shader104;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js
var name106 = "prePassVertex", shader105 = `#ifdef PREPASS_DEPTH
vViewPos=(view*worldPos).rgb;
#endif
#ifdef PREPASS_LOCAL_POSITION
vPosition=positionUpdated.xyz;
#endif
#if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*worldPos;
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif 
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif 
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif 
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif 
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif 
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
`;
var init_prePassVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name106]) {
    ShaderStore.IncludesShadersStore[name106] = shader105;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/uvVariableDeclaration.js
var name107 = "uvVariableDeclaration", shader106 = `#if !defined(UV{X}) && defined(MAINUV{X})
vec2 uv{X}=vec2(0.,0.);
#endif
#ifdef MAINUV{X}
vMainUV{X}=uv{X};
#endif
`;
var init_uvVariableDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name107]) {
    ShaderStore.IncludesShadersStore[name107] = shader106;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexImplementation.js
var name108 = "samplerVertexImplementation", shader107 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0
if (v_INFONAME_==0.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}
#ifdef UV2
else if (v_INFONAME_==1.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2Updated,1.0,0.0));}
#endif
#ifdef UV3
else if (v_INFONAME_==2.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}
#endif
#ifdef UV4
else if (v_INFONAME_==3.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}
#endif
#ifdef UV5
else if (v_INFONAME_==4.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}
#endif
#ifdef UV6
else if (v_INFONAME_==5.)
{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}
#endif
#endif
`;
var init_samplerVertexImplementation2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name108]) {
    ShaderStore.IncludesShadersStore[name108] = shader107;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertex.js
var name109 = "bumpVertex", shader108 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);
#endif
#endif
`;
var init_bumpVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name109]) {
    ShaderStore.IncludesShadersStore[name109] = shader108;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js
var exports_clipPlaneVertex2 = {};
__export(exports_clipPlaneVertex2, {
  clipPlaneVertex: () => clipPlaneVertex
});
var name110 = "clipPlaneVertex", shader109 = `#ifdef CLIPPLANE
fClipDistance=dot(worldPos,vClipPlane);
#endif
#ifdef CLIPPLANE2
fClipDistance2=dot(worldPos,vClipPlane2);
#endif
#ifdef CLIPPLANE3
fClipDistance3=dot(worldPos,vClipPlane3);
#endif
#ifdef CLIPPLANE4
fClipDistance4=dot(worldPos,vClipPlane4);
#endif
#ifdef CLIPPLANE5
fClipDistance5=dot(worldPos,vClipPlane5);
#endif
#ifdef CLIPPLANE6
fClipDistance6=dot(worldPos,vClipPlane6);
#endif
`, clipPlaneVertex;
var init_clipPlaneVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name110]) {
    ShaderStore.IncludesShadersStore[name110] = shader109;
  }
  clipPlaneVertex = { name: name110, shader: shader109 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertex.js
var name111 = "fogVertex", shader110 = `#ifdef FOG
vFogDistance=(view*worldPos).xyz;
#endif
`;
var init_fogVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name111]) {
    ShaderStore.IncludesShadersStore[name111] = shader110;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsVertex.js
var exports_shadowsVertex2 = {};
__export(exports_shadowsVertex2, {
  shadowsVertex: () => shadowsVertex
});
var name112 = "shadowsVertex", shader111 = `#ifdef SHADOWS
#if defined(SHADOWCSM{X})
vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
}
#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})
vPositionFromLight{X}=lightMatrix{X}*worldPos;
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#else
vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;
#endif
#endif
#endif
`, shadowsVertex;
var init_shadowsVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name112]) {
    ShaderStore.IncludesShadersStore[name112] = shader111;
  }
  shadowsVertex = { name: name112, shader: shader111 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/vertexColorMixing.js
var name113 = "vertexColorMixing", shader112 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
vColor=vec4(1.0);
#ifdef VERTEXCOLOR
#ifdef VERTEXALPHA
vColor*=colorUpdated;
#else
vColor.rgb*=colorUpdated.rgb;
#endif
#endif
#ifdef INSTANCESCOLOR
vColor*=instanceColor;
#endif
#endif
`;
var init_vertexColorMixing2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name113]) {
    ShaderStore.IncludesShadersStore[name113] = shader112;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js
var name114 = "pointCloudVertex", shader113 = `#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
`;
var init_pointCloudVertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name114]) {
    ShaderStore.IncludesShadersStore[name114] = shader113;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthVertex.js
var name115 = "logDepthVertex", shader114 = `#ifdef LOGARITHMICDEPTH
vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;
#endif
`;
var init_logDepthVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name115]) {
    ShaderStore.IncludesShadersStore[name115] = shader114;
  }
});

// node_modules/@babylonjs/core/Shaders/default.vertex.js
var exports_default_vertex2 = {};
__export(exports_default_vertex2, {
  defaultVertexShader: () => defaultVertexShader
});
var name116 = "defaultVertexShader", shader115 = `#define CUSTOM_VERTEX_EXTENSION
#include<__decl__defaultVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<mainUVVaryingDeclaration>[1..7]
#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#if defined(SPECULARTERM)
#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)
#endif
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
vPositionW=vec3(worldPos);
#ifdef PREPASS
#include<prePassVertex>
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2Updated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#ifdef MAINUV2
vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#if defined(SPECULARTERM)
#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)
#endif
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<pointCloudVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`, defaultVertexShader;
var init_default_vertex2 = __esm(() => {
  init_shaderStore();
  init_defaultVertexDeclaration();
  init_defaultUboDeclaration2();
  init_uvAttributeDeclaration2();
  init_helperFunctions2();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_instancesDeclaration2();
  init_prePassVertexDeclaration2();
  init_mainUVVaryingDeclaration2();
  init_samplerVertexDeclaration2();
  init_bumpVertexDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_lightVxFragmentDeclaration2();
  init_lightVxUboDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_logDepthDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_prePassVertex2();
  init_uvVariableDeclaration2();
  init_samplerVertexImplementation2();
  init_bumpVertex2();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_shadowsVertex2();
  init_vertexColorMixing2();
  init_pointCloudVertex();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name116]) {
    ShaderStore.ShadersStore[name116] = shader115;
  }
  defaultVertexShader = { name: name116, shader: shader115 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js
var name117 = "decalFragmentDeclaration", shader116 = `#ifdef DECAL
uniform vec4 vDecalInfos;
#endif
`;
var init_decalFragmentDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name117]) {
    ShaderStore.IncludesShadersStore[name117] = shader116;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js
var name118 = "defaultFragmentDeclaration", shader117 = `uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef AMBIENT
uniform vec2 vAmbientInfos;
#endif
#ifdef OPACITY 
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef ALPHATEST
uniform float alphaCutOff;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFRACTION
uniform vec4 vRefractionInfos;
#ifndef REFRACTIONMAP_3D
uniform mat4 refractionMatrix;
#endif
#ifdef REFRACTIONFRESNEL
uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;
#endif
#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; 
#endif
#endif
#if defined(SPECULAR) && defined(SPECULARTERM)
uniform vec2 vSpecularInfos;
#endif
#ifdef DIFFUSEFRESNEL
uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;
#endif
#ifdef OPACITYFRESNEL
uniform vec4 opacityParts;
#endif
#ifdef EMISSIVEFRESNEL
uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;
#endif
#if defined(REFLECTION) || (defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED))
uniform vec2 vReflectionInfos;
#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)
uniform mat4 reflectionMatrix;
#endif
#ifndef REFLECTIONMAP_SKYBOX
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; 
#endif
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#define ADDITIONAL_FRAGMENT_DECLARATION
`;
var init_defaultFragmentDeclaration = __esm(() => {
  init_shaderStore();
  init_decalFragmentDeclaration();
  if (!ShaderStore.IncludesShadersStore[name118]) {
    ShaderStore.IncludesShadersStore[name118] = shader117;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js
var name119 = "prePassDeclaration", shader118 = `#ifdef PREPASS
#extension GL_EXT_draw_buffers : require
layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;
#ifdef PREPASS_LOCAL_POSITION
varying highp vec3 vPosition;
#endif
#ifdef PREPASS_DEPTH
varying highp vec3 vViewPos;
#endif
#if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)
varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;
#endif
#endif
`;
var init_prePassDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name119]) {
    ShaderStore.IncludesShadersStore[name119] = shader118;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/oitDeclaration.js
var name120 = "oitDeclaration", shader119 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY
#extension GL_EXT_draw_buffers : require
layout(location=0) out vec2 depth; 
layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;
#define MAX_DEPTH 99999.0
highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;
#endif
`;
var init_oitDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name120]) {
    ShaderStore.IncludesShadersStore[name120] = shader119;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js
var exports_lightFragmentDeclaration = {};
__export(exports_lightFragmentDeclaration, {
  lightFragmentDeclaration: () => lightFragmentDeclaration
});
var name121 = "lightFragmentDeclaration", shader120 = `#ifdef LIGHT{X}
uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};
#ifdef SPECULARTERM
uniform vec4 vLightSpecular{X};
#else
vec4 vLightSpecular{X}=vec4(0.);
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowTexture{X};
#else
uniform highp sampler2DArray shadowTexture{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowTexture{X};
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowTexture{X};
#else
uniform sampler2D shadowTexture{X};
#endif
uniform mat4 lightMatrix{X};
#endif
uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};
#endif
#ifdef SPOTLIGHT{X}
uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};
#elif defined(POINTLIGHT{X})
uniform vec4 vLightFalloff{X};
#elif defined(HEMILIGHT{X})
uniform vec3 vLightGround{X};
#endif
#ifdef AREALIGHT{X}
uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X};
#endif
#ifdef IESLIGHTTEXTURE{X}
uniform sampler2D iesLightTexture{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};
#endif
#endif
`, lightFragmentDeclaration;
var init_lightFragmentDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name121]) {
    ShaderStore.IncludesShadersStore[name121] = shader120;
  }
  lightFragmentDeclaration = { name: name121, shader: shader120 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js
var exports_lightUboDeclaration2 = {};
__export(exports_lightUboDeclaration2, {
  lightUboDeclaration: () => lightUboDeclaration
});
var name122 = "lightUboDeclaration", shader121 = `#ifdef LIGHT{X}
uniform Light{X}
{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;
#ifdef SPOTLIGHT{X}
vec4 vLightDirection;vec4 vLightFalloff;
#elif defined(POINTLIGHT{X})
vec4 vLightFalloff;
#elif defined(HEMILIGHT{X})
vec3 vLightGround;
#endif
#if defined(AREALIGHT{X})
vec4 vLightWidth;vec4 vLightHeight;
#endif
vec4 shadowsInfo;vec2 depthValues;} light{X};
#ifdef IESLIGHTTEXTURE{X}
uniform sampler2D iesLightTexture{X};
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DArrayShadow shadowTexture{X};
#else
uniform highp sampler2DArray shadowTexture{X};
#endif
#ifdef SHADOWCSMDEBUG{X}
const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]
(
vec3 ( 1.5,0.0,0.0 ),
vec3 ( 0.0,1.5,0.0 ),
vec3 ( 0.0,0.0,5.5 ),
vec3 ( 1.5,0.0,5.5 ),
vec3 ( 1.5,1.5,0.0 ),
vec3 ( 1.0,1.0,1.0 ),
vec3 ( 0.0,1.0,5.5 ),
vec3 ( 0.5,3.5,0.75 )
);vec3 shadowDebug{X};
#endif
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
int index{X}=-1;
#else
int index{X}=SHADOWCSMNUM_CASCADES{X}-1;
#endif
float diff{X}=0.;
#elif defined(SHADOWCUBE{X})
uniform samplerCube shadowTexture{X}; 
#else
varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};
#if defined(SHADOWPCSS{X})
uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};
#elif defined(SHADOWPCF{X})
uniform highp sampler2DShadow shadowTexture{X};
#else
uniform sampler2D shadowTexture{X};
#endif
uniform mat4 lightMatrix{X};
#endif
#endif
#endif
`, lightUboDeclaration;
var init_lightUboDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name122]) {
    ShaderStore.IncludesShadersStore[name122] = shader121;
  }
  lightUboDeclaration = { name: name122, shader: shader121 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/ltcHelperFunctions.js
var name123 = "ltcHelperFunctions", shader122 = `vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;}
float LTCClippedSphereFormFactor( const in vec3 f ) {float l=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );}
vec3 LTCEdgeVectorFormFactor( const in vec3 v1,const in vec3 v2 ) {float x=dot( v1,v2 );float y=abs( x );float a=0.8543985+( 0.4965155+0.0145206*y )*y;float b=3.4175940+( 4.1616724+y )*y;float v=a/b;float thetaSintheta=0.0;if( x>0.0 )
{thetaSintheta=v;}
else
{thetaSintheta=0.5*inversesqrt( max( 1.0-x*x,1e-7 ) )-v;}
return cross( v1,v2 )*thetaSintheta;}
vec3 LTCEvaluate( const in vec3 N,const in vec3 V,const in vec3 P,const in mat3 mInv,const in vec3 rectCoords[ 4 ] ) {vec3 v1=rectCoords[ 1 ]-rectCoords[ 0 ];vec3 v2=rectCoords[ 3 ]-rectCoords[ 0 ];vec3 lightNormal=cross( v1,v2 );if( dot( lightNormal,P-rectCoords[ 0 ] )<0.0 ) return vec3( 0.0 );vec3 T1,T2;T1=normalize( V-N*dot( V,N ) );T2=- cross( N,T1 ); 
mat3 mat=mInv*transposeMat3( mat3( T1,T2,N ) );vec3 coords[ 4 ];coords[ 0 ]=mat*( rectCoords[ 0 ]-P );coords[ 1 ]=mat*( rectCoords[ 1 ]-P );coords[ 2 ]=mat*( rectCoords[ 2 ]-P );coords[ 3 ]=mat*( rectCoords[ 3 ]-P );coords[ 0 ]=normalize( coords[ 0 ] );coords[ 1 ]=normalize( coords[ 1 ] );coords[ 2 ]=normalize( coords[ 2 ] );coords[ 3 ]=normalize( coords[ 3 ] );vec3 vectorFormFactor=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 0 ],coords[ 1 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 1 ],coords[ 2 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 2 ],coords[ 3 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 3 ],coords[ 0 ] );float result=LTCClippedSphereFormFactor( vectorFormFactor );return vec3( result );}
struct areaLightData
{vec3 Diffuse;vec3 Specular;vec4 Fresnel;};
#define inline
areaLightData computeAreaLightSpecularDiffuseFresnel(const in sampler2D ltc1,const in sampler2D ltc2,const in vec3 viewDir,const in vec3 normal,const in vec3 position,const in vec3 lightPos,const in vec3 halfWidth,const in vec3 halfHeight,const in float roughness) 
{areaLightData result;vec3 rectCoords[ 4 ];rectCoords[ 0 ]=lightPos+halfWidth-halfHeight; 
rectCoords[ 1 ]=lightPos-halfWidth-halfHeight;rectCoords[ 2 ]=lightPos-halfWidth+halfHeight;rectCoords[ 3 ]=lightPos+halfWidth+halfHeight;
#ifdef SPECULARTERM
vec2 uv=LTCUv( normal,viewDir,roughness );vec4 t1=texture2D( ltc1,uv );vec4 t2=texture2D( ltc2,uv );mat3 mInv=mat3(
vec3( t1.x,0,t1.y ),
vec3( 0,1, 0 ),
vec3( t1.z,0,t1.w )
);result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords );result.Fresnel=t2;
#endif
result.Diffuse=LTCEvaluate( normal,viewDir,position,mat3( 1.0 ),rectCoords );return result;}`;
var init_ltcHelperFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name123]) {
    ShaderStore.IncludesShadersStore[name123] = shader122;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightsFragmentFunctions.js
var exports_lightsFragmentFunctions2 = {};
__export(exports_lightsFragmentFunctions2, {
  lightsFragmentFunctions: () => lightsFragmentFunctions
});
var name124 = "lightsFragmentFunctions", shader123 = `struct lightingInfo
{vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef NDOTL
float ndl;
#endif
};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)
{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}
else
{lightVectorW=normalize(-lightData.xyz);}
float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
float getAttenuation(float cosAngle,float exponent) {return max(0.,pow(cosAngle,exponent));}
float getIESAttenuation(float cosAngle,sampler2D iesLightSampler) {float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;}
lightingInfo basicSpotLighting(vec3 viewDirectionW,vec3 lightVectorW,vec3 vNormal,float attenuation,vec3 diffuseColor,vec3 specularColor,float glossiness) {lightingInfo result; 
float ndl=max(0.,dot(vNormal,lightVectorW));
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=ndl*diffuseColor*attenuation;
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;
#endif
return result;}
lightingInfo computeIESSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness,sampler2D iesLightSampler) { 
vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float dotProduct=dot(lightDirection.xyz,-lightVectorW);float cosAngle=max(0.,dotProduct);if (cosAngle>=lightDirection.w)
{ 
attenuation*=getIESAttenuation(dotProduct,iesLightSampler);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
lightingInfo result;result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)
{ 
attenuation*=getAttenuation(cosAngle,lightData.w);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);}
lightingInfo result;result.diffuse=vec3(0.);
#ifdef SPECULARTERM
result.specular=vec3(0.);
#endif
#ifdef NDOTL
result.ndl=0.;
#endif
return result;}
lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;
#ifdef NDOTL
result.ndl=ndl;
#endif
result.diffuse=mix(groundColor,diffuseColor,ndl);
#ifdef SPECULARTERM
vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;
#endif
return result;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler;
#define inline
lightingInfo computeAreaLighting(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec3 lightPosition,vec3 halfWidth,vec3 halfHeight,vec3 diffuseColor,vec3 specularColor,float roughness) 
{lightingInfo result;areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
vec3 fresnel=( specularColor*data.Fresnel.x+( vec3( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular;
#endif
result.diffuse+=diffuseColor*data.Diffuse;return result;}
#endif
`, lightsFragmentFunctions;
var init_lightsFragmentFunctions2 = __esm(() => {
  init_shaderStore();
  init_ltcHelperFunctions2();
  if (!ShaderStore.IncludesShadersStore[name124]) {
    ShaderStore.IncludesShadersStore[name124] = shader123;
  }
  lightsFragmentFunctions = { name: name124, shader: shader123 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js
var exports_shadowsFragmentFunctions2 = {};
__export(exports_shadowsFragmentFunctions2, {
  shadowsFragmentFunctions: () => shadowsFragmentFunctions
});
var name125 = "shadowsFragmentFunctions", shader124 = `#ifdef SHADOWS
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
#ifndef SHADOWFLOAT
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}
#endif
float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)
{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}
#define inline
float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadow=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadow=textureCube(shadowSampler,directionToLight).x;
#endif
return depth>shadow ? darkness : 1.0;}
#define inline
float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);
#ifndef SHADOWFLOAT
if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;
#else
if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;
#endif
return min(1.0,visibility+darkness);}
#define inline
float computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}
#define inline
float computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)
{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));
#else
float shadowMapSample=textureCube(shadowSampler,directionToLight).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define inline
float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(texture2D(shadowSampler,uvLayer));
#else
float shadow=texture2D(shadowSampler,uvLayer).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}
#endif
#define inline
float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}
#define inline
float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);
#ifndef SHADOWFLOAT
if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;
#else
if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;
#endif
return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0);
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)
{return 1.0;}
else
{float shadowPixelDepth=clamp(depthMetric,0.,1.0); 
#ifndef SHADOWFLOAT
float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));
#else
float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;
#endif
float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}
#ifdef IS_NDC_HALF_ZRANGE
#define ZINCLIP clipSpace.z
#else
#define ZINCLIP uvDepth.z
#endif
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define GREATEST_LESS_THAN_ONE 0.99999994
#define DISABLE_UNIFORMITY_ANALYSIS
#define inline
float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}
#define inline
float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; 
uv+=0.5; 
vec2 st=fract(uv); 
vec2 base_uv=floor(uv)-0.5; 
base_uv*=shadowMapSizeAndInverse.y; 
vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
const vec3 PoissonSamplers32[64]=vec3[64](
vec3(0.06407013,0.05409927,0.),
vec3(0.7366577,0.5789394,0.),
vec3(-0.6270542,-0.5320278,0.),
vec3(-0.4096107,0.8411095,0.),
vec3(0.6849564,-0.4990818,0.),
vec3(-0.874181,-0.04579735,0.),
vec3(0.9989998,0.0009880066,0.),
vec3(-0.004920578,-0.9151649,0.),
vec3(0.1805763,0.9747483,0.),
vec3(-0.2138451,0.2635818,0.),
vec3(0.109845,0.3884785,0.),
vec3(0.06876755,-0.3581074,0.),
vec3(0.374073,-0.7661266,0.),
vec3(0.3079132,-0.1216763,0.),
vec3(-0.3794335,-0.8271583,0.),
vec3(-0.203878,-0.07715034,0.),
vec3(0.5912697,0.1469799,0.),
vec3(-0.88069,0.3031784,0.),
vec3(0.5040108,0.8283722,0.),
vec3(-0.5844124,0.5494877,0.),
vec3(0.6017799,-0.1726654,0.),
vec3(-0.5554981,0.1559997,0.),
vec3(-0.3016369,-0.3900928,0.),
vec3(-0.5550632,-0.1723762,0.),
vec3(0.925029,0.2995041,0.),
vec3(-0.2473137,0.5538505,0.),
vec3(0.9183037,-0.2862392,0.),
vec3(0.2469421,0.6718712,0.),
vec3(0.3916397,-0.4328209,0.),
vec3(-0.03576927,-0.6220032,0.),
vec3(-0.04661255,0.7995201,0.),
vec3(0.4402924,0.3640312,0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.),
vec3(0.)
);const vec3 PoissonSamplers64[64]=vec3[64](
vec3(-0.613392,0.617481,0.),
vec3(0.170019,-0.040254,0.),
vec3(-0.299417,0.791925,0.),
vec3(0.645680,0.493210,0.),
vec3(-0.651784,0.717887,0.),
vec3(0.421003,0.027070,0.),
vec3(-0.817194,-0.271096,0.),
vec3(-0.705374,-0.668203,0.),
vec3(0.977050,-0.108615,0.),
vec3(0.063326,0.142369,0.),
vec3(0.203528,0.214331,0.),
vec3(-0.667531,0.326090,0.),
vec3(-0.098422,-0.295755,0.),
vec3(-0.885922,0.215369,0.),
vec3(0.566637,0.605213,0.),
vec3(0.039766,-0.396100,0.),
vec3(0.751946,0.453352,0.),
vec3(0.078707,-0.715323,0.),
vec3(-0.075838,-0.529344,0.),
vec3(0.724479,-0.580798,0.),
vec3(0.222999,-0.215125,0.),
vec3(-0.467574,-0.405438,0.),
vec3(-0.248268,-0.814753,0.),
vec3(0.354411,-0.887570,0.),
vec3(0.175817,0.382366,0.),
vec3(0.487472,-0.063082,0.),
vec3(-0.084078,0.898312,0.),
vec3(0.488876,-0.783441,0.),
vec3(0.470016,0.217933,0.),
vec3(-0.696890,-0.549791,0.),
vec3(-0.149693,0.605762,0.),
vec3(0.034211,0.979980,0.),
vec3(0.503098,-0.308878,0.),
vec3(-0.016205,-0.872921,0.),
vec3(0.385784,-0.393902,0.),
vec3(-0.146886,-0.859249,0.),
vec3(0.643361,0.164098,0.),
vec3(0.634388,-0.049471,0.),
vec3(-0.688894,0.007843,0.),
vec3(0.464034,-0.188818,0.),
vec3(-0.440840,0.137486,0.),
vec3(0.364483,0.511704,0.),
vec3(0.034028,0.325968,0.),
vec3(0.099094,-0.308023,0.),
vec3(0.693960,-0.366253,0.),
vec3(0.678884,-0.204688,0.),
vec3(0.001801,0.780328,0.),
vec3(0.145177,-0.898984,0.),
vec3(0.062655,-0.611866,0.),
vec3(0.315226,-0.604297,0.),
vec3(-0.780145,0.486251,0.),
vec3(-0.371868,0.882138,0.),
vec3(0.200476,0.494430,0.),
vec3(-0.494552,-0.711051,0.),
vec3(0.612476,0.705252,0.),
vec3(-0.578845,-0.768792,0.),
vec3(-0.772454,-0.090976,0.),
vec3(0.504440,0.372295,0.),
vec3(0.155736,0.065157,0.),
vec3(0.391522,0.849605,0.),
vec3(-0.620106,-0.328104,0.),
vec3(0.789239,-0.419965,0.),
vec3(-0.545396,0.538133,0.),
vec3(-0.178564,-0.596057,0.)
);
#define inline
float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}
else
{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}
#define inline
float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)
{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}
else
{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}
if (numBlocker<1.0) {return 1.0;}
else
{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}
shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}
#define inline
float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}
#define inline
float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)
{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}
#define inline
float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#define inline
float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)
{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}
#endif
#endif
`, shadowsFragmentFunctions;
var init_shadowsFragmentFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name125]) {
    ShaderStore.IncludesShadersStore[name125] = shader124;
  }
  shadowsFragmentFunctions = { name: name125, shader: shader124 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerFragmentDeclaration.js
var name126 = "samplerFragmentDeclaration", shader125 = `#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
uniform sampler2D _SAMPLERNAME_Sampler;
#endif
`;
var init_samplerFragmentDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name126]) {
    ShaderStore.IncludesShadersStore[name126] = shader125;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fresnelFunction.js
var name127 = "fresnelFunction", shader126 = `#ifdef FRESNEL
float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)
{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}
#endif
`;
var init_fresnelFunction2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name127]) {
    ShaderStore.IncludesShadersStore[name127] = shader126;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/reflectionFunction.js
var exports_reflectionFunction2 = {};
__export(exports_reflectionFunction2, {
  reflectionFunction: () => reflectionFunction
});
var name128 = "reflectionFunction", shader127 = `vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }
vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)
{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }
vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}
vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)
{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}
vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}
vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)
{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));
#ifdef INVERTCUBICMAP
coords.y*=-1.0;
#endif
return coords;}
vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*(view*worldPos));}
vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)
{return vec3(reflectionMatrix*vec4(positionW,1.));}
#ifdef REFLECTION
vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)
{
#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED
vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);
#endif
#ifdef REFLECTIONMAP_EQUIRECTANGULAR
return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SPHERICAL
return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_PLANAR
return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_CUBIC
#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC
return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);
#else
return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);
#endif
#endif
#ifdef REFLECTIONMAP_PROJECTION
return computeProjectionCoords(worldPos,view,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_SKYBOX
return computeSkyBoxCoords(vPositionUVW,reflectionMatrix);
#endif
#ifdef REFLECTIONMAP_EXPLICIT
return vec3(0,0,0);
#endif
}
#endif
`, reflectionFunction;
var init_reflectionFunction2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name128]) {
    ShaderStore.IncludesShadersStore[name128] = shader127;
  }
  reflectionFunction = { name: name128, shader: shader127 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingDeclaration.js
var exports_imageProcessingDeclaration2 = {};
__export(exports_imageProcessingDeclaration2, {
  imageProcessingDeclaration: () => imageProcessingDeclaration
});
var name129 = "imageProcessingDeclaration", shader128 = `#ifdef EXPOSURE
uniform float exposureLinear;
#endif
#ifdef CONTRAST
uniform float contrast;
#endif
#if defined(VIGNETTE) || defined(DITHER)
uniform vec2 vInverseScreenSize;
#endif
#ifdef VIGNETTE
uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;
#endif
#ifdef COLORCURVES
uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;
#endif
#ifdef COLORGRADING
#ifdef COLORGRADING3D
uniform highp sampler3D txColorTransform;
#else
uniform sampler2D txColorTransform;
#endif
uniform vec4 colorTransformSettings;
#endif
#ifdef DITHER
uniform float ditherIntensity;
#endif
`, imageProcessingDeclaration;
var init_imageProcessingDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name129]) {
    ShaderStore.IncludesShadersStore[name129] = shader128;
  }
  imageProcessingDeclaration = { name: name129, shader: shader128 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js
var exports_imageProcessingFunctions2 = {};
__export(exports_imageProcessingFunctions2, {
  imageProcessingFunctions: () => imageProcessingFunctions
});
var name130 = "imageProcessingFunctions", shader129 = `#if defined(COLORGRADING) && !defined(COLORGRADING3D)
/** 
* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.
* sampler3dSetting.x=textureOffset (0.5/textureSize).
* sampler3dSetting.y=textureSize.
*/
#define inline
vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)
{float sliceSize=2.0*sampler3dSetting.x; 
#ifdef SAMPLER3DGREENDEPTH
float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;
#else
float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;
#endif
float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;
#ifdef SAMPLER3DGREENDEPTH
vec2 sliceUV=color.rb;
#else
vec2 sliceUV=color.rg;
#endif
sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);
#ifdef SAMPLER3DBGRMAP
color.rgb=result.rgb;
#else
color.rgb=result.bgr;
#endif
return color;}
#endif
#if TONEMAPPING==3
const float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}
#endif
#if TONEMAPPING==2
const mat3 ACESInputMat=mat3(
vec3(0.59719,0.07600,0.02840),
vec3(0.35458,0.90834,0.13383),
vec3(0.04823,0.01566,0.83777)
);const mat3 ACESOutputMat=mat3(
vec3( 1.60475,-0.10208,-0.00327),
vec3(-0.53108, 1.10813,-0.07276),
vec3(-0.07367,-0.00605, 1.07602)
);vec3 RRTAndODTFit(vec3 v)
{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}
vec3 ACESFitted(vec3 color)
{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS
vec4 applyImageProcessing(vec4 result) {
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART
#ifdef EXPOSURE
result.rgb*=exposureLinear;
#endif
#ifdef VIGNETTE
vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;
#ifdef VIGNETTEBLENDMODEMULTIPLY
vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;
#endif
#ifdef VIGNETTEBLENDMODEOPAQUE
result.rgb=mix(vignetteColor,result.rgb,vignette);
#endif
#endif
#if TONEMAPPING==3
result.rgb=PBRNeutralToneMapping(result.rgb);
#elif TONEMAPPING==2
result.rgb=ACESFitted(result.rgb);
#elif TONEMAPPING==1
const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);
#endif
result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);
#ifdef CONTRAST
vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}
#endif
#ifdef COLORGRADING
vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;
#ifdef COLORGRADING3D
vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;
#else
vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;
#endif
result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);
#endif
#ifdef COLORCURVES
float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);
#endif
#ifdef DITHER
float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));
#endif
#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND
return result;}`, imageProcessingFunctions;
var init_imageProcessingFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name130]) {
    ShaderStore.IncludesShadersStore[name130] = shader129;
  }
  imageProcessingFunctions = { name: name130, shader: shader129 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentMainFunctions.js
var exports_bumpFragmentMainFunctions2 = {};
__export(exports_bumpFragmentMainFunctions2, {
  bumpFragmentMainFunctions: () => bumpFragmentMainFunctions
});
var name131 = "bumpFragmentMainFunctions", shader130 = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)
#if defined(TANGENT) && defined(NORMAL) 
varying mat3 vTBN;
#endif
#ifdef OBJECTSPACE_NORMALMAP
uniform mat4 normalMatrix;
#if defined(WEBGL2) || defined(WEBGPU)
mat4 toNormalMatrix(mat4 wMatrix)
{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}
#else
mat4 toNormalMatrix(mat4 m)
{float
a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],
a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],
a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],
a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],
b00=a00*a11-a01*a10,
b01=a00*a12-a02*a10,
b02=a00*a13-a03*a10,
b03=a01*a12-a02*a11,
b04=a01*a13-a03*a11,
b05=a02*a13-a03*a12,
b06=a20*a31-a21*a30,
b07=a20*a32-a22*a30,
b08=a20*a33-a23*a30,
b09=a21*a32-a22*a31,
b10=a21*a33-a23*a31,
b11=a22*a33-a23*a32,
det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(
a11*b11-a12*b10+a13*b09,
a02*b10-a01*b11-a03*b09,
a31*b05-a32*b04+a33*b03,
a22*b04-a21*b05-a23*b03,
a12*b08-a10*b11-a13*b07,
a00*b11-a02*b08+a03*b07,
a32*b02-a30*b05-a33*b01,
a20*b05-a22*b02+a23*b01,
a10*b10-a11*b08+a13*b06,
a01*b08-a00*b10-a03*b06,
a30*b04-a31*b02+a33*b00,
a21*b02-a20*b04-a23*b00,
a11*b07-a10*b09-a12*b06,
a00*b09-a01*b07+a02*b06,
a31*b01-a30*b03-a32*b00,
a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],
mi[0][1],mi[1][1],mi[2][1],mi[3][1],
mi[0][2],mi[1][2],mi[2][2],mi[3][2],
mi[0][3],mi[1][3],mi[2][3],mi[3][3]);}
#endif
#endif
vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)
{
#ifdef NORMALXYSCALE
normal=normalize(normal*vec3(scale,scale,1.0));
#endif
return normalize(cotangentFrame*normal);}
vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)
{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}
mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)
{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}
#endif
`, bumpFragmentMainFunctions;
var init_bumpFragmentMainFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name131]) {
    ShaderStore.IncludesShadersStore[name131] = shader130;
  }
  bumpFragmentMainFunctions = { name: name131, shader: shader130 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentFunctions.js
var exports_bumpFragmentFunctions2 = {};
__export(exports_bumpFragmentFunctions2, {
  bumpFragmentFunctions: () => bumpFragmentFunctions
});
var name132 = "bumpFragmentFunctions", shader131 = `#if defined(BUMP)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)
#endif
#if defined(DETAIL)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)
#endif
#if defined(BUMP) && defined(PARALLAX)
const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)
{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)
{}
else if (currSampledHeight>currRayHeight)
{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}
else
{currRayHeight-=stepSize;vLastOffset=vCurrOffset;
#ifdef PARALLAX_RHS
vCurrOffset-=stepSize*vMaxOffset;
#else
vCurrOffset+=stepSize*vMaxOffset;
#endif
lastSampledHeight=currSampledHeight;}}
return vCurrOffset;}
vec2 parallaxOffset(vec3 viewDir,float heightScale)
{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;
#ifdef PARALLAX_RHS
return texCoordOffset;
#else
return -texCoordOffset;
#endif
}
#endif
`, bumpFragmentFunctions;
var init_bumpFragmentFunctions2 = __esm(() => {
  init_shaderStore();
  init_samplerFragmentDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name132]) {
    ShaderStore.IncludesShadersStore[name132] = shader131;
  }
  bumpFragmentFunctions = { name: name132, shader: shader131 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js
var exports_clipPlaneFragmentDeclaration2 = {};
__export(exports_clipPlaneFragmentDeclaration2, {
  clipPlaneFragmentDeclaration: () => clipPlaneFragmentDeclaration
});
var name133 = "clipPlaneFragmentDeclaration", shader132 = `#ifdef CLIPPLANE
varying float fClipDistance;
#endif
#ifdef CLIPPLANE2
varying float fClipDistance2;
#endif
#ifdef CLIPPLANE3
varying float fClipDistance3;
#endif
#ifdef CLIPPLANE4
varying float fClipDistance4;
#endif
#ifdef CLIPPLANE5
varying float fClipDistance5;
#endif
#ifdef CLIPPLANE6
varying float fClipDistance6;
#endif
`, clipPlaneFragmentDeclaration;
var init_clipPlaneFragmentDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name133]) {
    ShaderStore.IncludesShadersStore[name133] = shader132;
  }
  clipPlaneFragmentDeclaration = { name: name133, shader: shader132 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js
var exports_fogFragmentDeclaration2 = {};
__export(exports_fogFragmentDeclaration2, {
  fogFragmentDeclaration: () => fogFragmentDeclaration
});
var name134 = "fogFragmentDeclaration", shader133 = `#ifdef FOG
#define FOGMODE_NONE 0.
#define FOGMODE_EXP 1.
#define FOGMODE_EXP2 2.
#define FOGMODE_LINEAR 3.
#define E 2.71828
uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()
{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x)
{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}
else if (FOGMODE_EXP==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}
else if (FOGMODE_EXP2==vFogInfos.x)
{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}
return clamp(fogCoeff,0.0,1.0);}
#endif
`, fogFragmentDeclaration;
var init_fogFragmentDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name134]) {
    ShaderStore.IncludesShadersStore[name134] = shader133;
  }
  fogFragmentDeclaration = { name: name134, shader: shader133 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js
var exports_clipPlaneFragment2 = {};
__export(exports_clipPlaneFragment2, {
  clipPlaneFragment: () => clipPlaneFragment
});
var name135 = "clipPlaneFragment", shader134 = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
if (false) {}
#endif
#ifdef CLIPPLANE
else if (fClipDistance>0.0)
{discard;}
#endif
#ifdef CLIPPLANE2
else if (fClipDistance2>0.0)
{discard;}
#endif
#ifdef CLIPPLANE3
else if (fClipDistance3>0.0)
{discard;}
#endif
#ifdef CLIPPLANE4
else if (fClipDistance4>0.0)
{discard;}
#endif
#ifdef CLIPPLANE5
else if (fClipDistance5>0.0)
{discard;}
#endif
#ifdef CLIPPLANE6
else if (fClipDistance6>0.0)
{discard;}
#endif
`, clipPlaneFragment;
var init_clipPlaneFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name135]) {
    ShaderStore.IncludesShadersStore[name135] = shader134;
  }
  clipPlaneFragment = { name: name135, shader: shader134 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragment.js
var exports_bumpFragment2 = {};
__export(exports_bumpFragment2, {
  bumpFragment: () => bumpFragment
});
var name136 = "bumpFragment", shader135 = `vec2 uvOffset=vec2(0.0,0.0);
#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)
#ifdef NORMALXYSCALE
float normalScale=1.0;
#elif defined(BUMP)
float normalScale=vBumpInfos.y;
#else
float normalScale=1.0;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#elif defined(BUMP)
vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);
#else
vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));
#endif
#elif defined(ANISOTROPIC)
#if defined(TANGENT) && defined(NORMAL)
mat3 TBN=vTBN;
#else
vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));
#endif
#endif
#ifdef PARALLAX
mat3 invTBN=transposeMat3(TBN);
#ifdef PARALLAXOCCLUSION
uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);
#else
uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);
#endif
#endif
#ifdef DETAIL
vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);
#endif
#ifdef BUMP
#ifdef OBJECTSPACE_NORMALMAP
#define CUSTOM_FRAGMENT_BUMP_FRAGMENT
normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);
#elif !defined(DETAIL)
normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);
#else
vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;
#if DETAIL_NORMALBLENDMETHOD==0 
detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));
#elif DETAIL_NORMALBLENDMETHOD==1 
detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;
#endif
normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);
#endif
#elif defined(DETAIL)
detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);
#endif
`, bumpFragment;
var init_bumpFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name136]) {
    ShaderStore.IncludesShadersStore[name136] = shader135;
  }
  bumpFragment = { name: name136, shader: shader135 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js
var name137 = "decalFragment", shader136 = `#ifdef DECAL
#ifdef GAMMADECAL
decalColor.rgb=toLinearSpace(decalColor.rgb);
#endif
#ifdef DECAL_SMOOTHALPHA
decalColor.a*=decalColor.a;
#endif
surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);
#endif
`;
var init_decalFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name137]) {
    ShaderStore.IncludesShadersStore[name137] = shader136;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js
var name138 = "depthPrePass", shader137 = `#ifdef DEPTHPREPASS
gl_FragColor=vec4(0.,0.,0.,1.0);return;
#endif
`;
var init_depthPrePass2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name138]) {
    ShaderStore.IncludesShadersStore[name138] = shader137;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js
var exports_lightFragment2 = {};
__export(exports_lightFragment2, {
  lightFragment: () => lightFragment
});
var name139 = "lightFragment", shader138 = `#ifdef LIGHT{X}
#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})
#else
vec4 diffuse{X}=light{X}.vLightDiffuse;
#define CUSTOM_LIGHT{X}_COLOR 
#ifdef PBR
#ifdef SPOTLIGHT{X}
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW);
#elif defined(POINTLIGHT{X})
preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,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,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData,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});
#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});
#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});
#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});
#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 defined(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});
#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 defined(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED)
info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.rgb,light{X}.vLightHeight.rgb,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,
#ifdef AREALIGHTNOROUGHTNESS
0.5
#else
vReflectionInfos.y
#endif
);
#endif
#endif
#ifdef PROJECTEDLIGHTTEXTURE{X}
info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW);
#endif
#endif
#ifdef SHADOW{X}
#ifdef SHADOWCSM{X}
for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) 
{
#ifdef SHADOWCSM_RIGHTHANDED{X}
diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;
#else
diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;
#endif
if (diff{X}>=0.) {index{X}=i;break;}}
#ifdef SHADOWCSMUSESHADOWMAXZ{X}
if (index{X}>=0)
#endif
{
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];
#endif
#ifndef SHADOWCSMNOBLEND{X}
float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)
{index{X}+=1;float nextShadow=0.;
#if defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#elif defined(SHADOWMEDIUMQUALITY{X})
nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#else
nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});
#endif
#else
nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
shadow=mix(nextShadow,shadow,diffRatio);
#ifdef SHADOWCSMDEBUG{X}
shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);
#endif
}
#endif
}
#elif defined(SHADOWCLOSEESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWESM{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);
#else
shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPOISSON{X})
#if defined(SHADOWCUBE{X})
shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCF{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#elif defined(SHADOWPCSS{X})
#if defined(SHADOWLOWQUALITY{X})
shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#elif defined(SHADOWMEDIUMQUALITY{X})
shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#else
shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#else
#if defined(SHADOWCUBE{X})
shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues);
#else
shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);
#endif
#endif
#ifdef SHADOWONLY
#ifndef SHADOWINUSE
#define SHADOWINUSE
#endif
globalShadow+=shadow;shadowLightCount+=1.0;
#endif
#else
shadow=1.;
#endif
aggShadow+=shadow;numLights+=1.0;
#ifndef SHADOWONLY
#ifdef CUSTOMUSERLIGHTING
diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);
#ifdef SPECULARTERM
specularBase+=computeCustomSpecularLighting(info,specularBase,shadow);
#endif
#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})
diffuseBase+=lightmapColor.rgb*shadow;
#ifdef SPECULARTERM
#ifndef LIGHTMAPNOSPECULAR{X}
specularBase+=info.specular*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef CLEARCOAT
#ifndef LIGHTMAPNOSPECULAR{X}
clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;
#endif
#endif
#ifdef SHEEN
#ifndef LIGHTMAPNOSPECULAR{X}
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#else
#ifdef SHADOWCSMDEBUG{X}
diffuseBase+=info.diffuse*shadowDebug{X};
#else 
diffuseBase+=info.diffuse*shadow;
#endif
#ifdef SPECULARTERM
specularBase+=info.specular*shadow;
#endif
#ifdef CLEARCOAT
clearCoatBase+=info.clearCoat.rgb*shadow;
#endif
#ifdef SHEEN
sheenBase+=info.sheen.rgb*shadow;
#endif
#endif
#endif
#endif
`, lightFragment;
var init_lightFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name139]) {
    ShaderStore.IncludesShadersStore[name139] = shader138;
  }
  lightFragment = { name: name139, shader: shader138 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthFragment.js
var name140 = "logDepthFragment", shader139 = `#ifdef LOGARITHMICDEPTH
gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;
#endif
`;
var init_logDepthFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name140]) {
    ShaderStore.IncludesShadersStore[name140] = shader139;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragment.js
var name141 = "fogFragment", shader140 = `#ifdef FOG
float fog=CalcFogFactor();
#ifdef PBR
fog=toLinearSpace(fog);
#endif
color.rgb=mix(vFogColor,color.rgb,fog);
#endif
`;
var init_fogFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name141]) {
    ShaderStore.IncludesShadersStore[name141] = shader140;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/oitFragment.js
var name142 = "oitFragment", shader141 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY
float fragDepth=gl_FragCoord.z; 
#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS
uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;
#endif
ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0);
#ifdef USE_REVERSE_DEPTHBUFFER
float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;
#else
float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;
#endif
float alphaMultiplier=1.0-lastFrontColor.a;
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth>nearestDepth || fragDepth<furthestDepth) {
#else
if (fragDepth<nearestDepth || fragDepth>furthestDepth) {
#endif
return;}
#ifdef USE_REVERSE_DEPTHBUFFER
if (fragDepth<nearestDepth && fragDepth>furthestDepth) {
#else
if (fragDepth>nearestDepth && fragDepth<furthestDepth) {
#endif
depth.rg=vec2(-fragDepth,fragDepth);return;}
#endif
`;
var init_oitFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name142]) {
    ShaderStore.IncludesShadersStore[name142] = shader141;
  }
});

// node_modules/@babylonjs/core/Shaders/default.fragment.js
var exports_default_fragment2 = {};
__export(exports_default_fragment2, {
  defaultPixelShader: () => defaultPixelShader
});
var name143 = "defaultPixelShader", shader142 = `#define CUSTOM_FRAGMENT_EXTENSION
#include<__decl__defaultFragment>
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#include<helperFunctions>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef REFRACTION
#ifdef REFRACTIONMAP_3D
uniform samplerCube refractionCubeSampler;
#else
uniform sampler2D refraction2DSampler;
#endif
#endif
#if defined(SPECULARTERM)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)
#endif
#include<fresnelFunction>
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
uniform samplerCube reflectionCubeSampler;
#else
uniform sampler2D reflection2DSampler;
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#include<imageProcessingDeclaration>
#include<imageProcessingFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));
#endif
#include<bumpFragment>
#ifdef TWOSIDEDLIGHTING
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
#ifdef DIFFUSE
baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);
#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)
if (baseColor.a<alphaCutOff)
discard;
#endif
#ifdef ALPHAFROMDIFFUSE
alpha*=baseColor.a;
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
baseColor.rgb*=vDiffuseInfos.y;
#endif
#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#include<depthPrePass>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
baseColor.rgb*=vColor.rgb;
#endif
#ifdef DETAIL
baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);
#endif
#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)
#endif
#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE
vec3 baseAmbientColor=vec3(1.,1.,1.);
#ifdef AMBIENT
baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;
#endif
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;
#ifdef SPECULARTERM
#ifdef SPECULAR
vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;
#ifdef GLOSSINESS
glossiness=glossiness*specularMapColor.a;
#endif
#endif
#endif
vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
float shadow=1.;float aggShadow=0.;float numLights=0.;
#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
#include<lightFragment>[0..maxSimultaneousLights]
aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);
#ifdef REFRACTION
vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));
#ifdef REFRACTIONMAP_3D
#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords);
#endif
#ifdef RGBDREFRACTION
refractionColor.rgb=fromRGBD(refractionColor);
#endif
#ifdef IS_REFRACTION_LINEAR
refractionColor.rgb=toGammaSpace(refractionColor.rgb);
#endif
refractionColor.rgb*=vRefractionInfos.x;
#endif
vec4 reflectionColor=vec4(0.,0.,0.,1.);
#ifdef REFLECTION
vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
vReflectionUVW.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
#ifdef ROUGHNESS
float bias=vReflectionInfos.y;
#ifdef SPECULARTERM
#ifdef SPECULAR
#ifdef GLOSSINESS
bias*=(1.0-specularMapColor.a);
#endif
#endif
#endif
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);
#else
reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);
#endif
#else
vec2 coords=vReflectionUVW.xy;
#ifdef REFLECTIONMAP_PROJECTION
coords/=vReflectionUVW.z;
#endif
coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef IS_REFLECTION_LINEAR
reflectionColor.rgb=toGammaSpace(reflectionColor.rgb);
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#ifdef REFLECTIONFRESNEL
float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);
#ifdef REFLECTIONFRESNELFROMSPECULAR
#ifdef SPECULARTERM
reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#else
reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;
#endif
#endif
#endif
#ifdef REFRACTIONFRESNEL
float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#ifdef OPACITYRGB
opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;
#else
alpha*=opacityMap.a*vOpacityInfos.y;
#endif
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#ifdef OPACITYFRESNEL
float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;
#endif
#ifdef ALPHATEST
#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS
if (alpha<alphaCutOff)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
vec3 emissiveColor=vEmissiveColor;
#ifdef EMISSIVE
emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;
#endif
#ifdef EMISSIVEFRESNEL
float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;
#endif
#ifdef DIFFUSEFRESNEL
float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;
#endif
#ifdef EMISSIVEASILLUMINATION
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
#ifdef LINKEMISSIVEWITHDIFFUSE
vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#else
vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;
#endif
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase*specularColor;
#ifdef SPECULAROVERALPHA
alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#else
vec3 finalSpecular=vec3(0.0);
#endif
#ifdef REFLECTIONOVERALPHA
alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);
#endif
#ifdef EMISSIVEASILLUMINATION
vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);
#else
vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);
#endif
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
color.rgb*=lightmapColor.rgb;
#else
color.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
#define CUSTOM_FRAGMENT_BEFORE_FOG
color.rgb=max(color.rgb,0.);
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
color.rgb=toLinearSpace(color.rgb);
#else
#ifdef IMAGEPROCESSING
color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);
#endif
#endif
color.a*=visibility;
#ifdef PREMULTIPLYALPHA
color.rgb*=color.a;
#endif
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=color; 
#endif
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);
#endif
#if defined(PREPASS_VELOCITY)
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_IRRADIANCE
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#if defined(SPECULAR)
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; 
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;
#endif
#endif
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=color;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`, defaultPixelShader;
var init_default_fragment2 = __esm(() => {
  init_shaderStore();
  init_defaultFragmentDeclaration();
  init_defaultUboDeclaration2();
  init_prePassDeclaration2();
  init_oitDeclaration2();
  init_mainUVVaryingDeclaration2();
  init_helperFunctions2();
  init_lightFragmentDeclaration();
  init_lightUboDeclaration2();
  init_lightsFragmentFunctions2();
  init_shadowsFragmentFunctions2();
  init_samplerFragmentDeclaration2();
  init_fresnelFunction2();
  init_reflectionFunction2();
  init_imageProcessingDeclaration2();
  init_imageProcessingFunctions2();
  init_bumpFragmentMainFunctions2();
  init_bumpFragmentFunctions2();
  init_clipPlaneFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_fogFragmentDeclaration2();
  init_clipPlaneFragment2();
  init_bumpFragment2();
  init_decalFragment2();
  init_depthPrePass2();
  init_lightFragment2();
  init_logDepthFragment2();
  init_fogFragment2();
  init_oitFragment2();
  if (!ShaderStore.ShadersStore[name143]) {
    ShaderStore.ShadersStore[name143] = shader142;
  }
  defaultPixelShader = { name: name143, shader: shader142 };
});

// node_modules/@babylonjs/core/ShadersWGSL/picking.fragment.js
var exports_picking_fragment = {};
__export(exports_picking_fragment, {
  pickingPixelShaderWGSL: () => pickingPixelShaderWGSL
});
var name144 = "pickingPixelShader", shader143 = `#if defined(INSTANCES)
varying vMeshID: vec4f;
#else
uniform meshID: vec4f;
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#if defined(INSTANCES)
fragmentOutputs.color=input.vMeshID;
#else
fragmentOutputs.color=uniforms.meshID;
#endif
}`, pickingPixelShaderWGSL;
var init_picking_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name144]) {
    ShaderStore.ShadersStoreWGSL[name144] = shader143;
  }
  pickingPixelShaderWGSL = { name: name144, shader: shader143 };
});

// node_modules/@babylonjs/core/ShadersWGSL/picking.vertex.js
var exports_picking_vertex = {};
__export(exports_picking_vertex, {
  pickingVertexShaderWGSL: () => pickingVertexShaderWGSL
});
var name145 = "pickingVertexShader", shader144 = `attribute position: vec3f;
#if defined(INSTANCES)
attribute instanceMeshID: vec4f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;
#if defined(INSTANCES)
varying vMeshID: vec4f;
#endif
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld*vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;
#if defined(INSTANCES)
vertexOutputs.vMeshID=input.instanceMeshID;
#endif
}`, pickingVertexShaderWGSL;
var init_picking_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_instancesDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  if (!ShaderStore.ShadersStoreWGSL[name145]) {
    ShaderStore.ShadersStoreWGSL[name145] = shader144;
  }
  pickingVertexShaderWGSL = { name: name145, shader: shader144 };
});

// node_modules/@babylonjs/core/Shaders/picking.fragment.js
var exports_picking_fragment2 = {};
__export(exports_picking_fragment2, {
  pickingPixelShader: () => pickingPixelShader
});
var name146 = "pickingPixelShader", shader145 = `#if defined(INSTANCES)
varying vec4 vMeshID;
#else
uniform vec4 meshID;
#endif
void main(void) {
#if defined(INSTANCES)
gl_FragColor=vMeshID;
#else
gl_FragColor=meshID;
#endif
}`, pickingPixelShader;
var init_picking_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name146]) {
    ShaderStore.ShadersStore[name146] = shader145;
  }
  pickingPixelShader = { name: name146, shader: shader145 };
});

// node_modules/@babylonjs/core/Shaders/picking.vertex.js
var exports_picking_vertex2 = {};
__export(exports_picking_vertex2, {
  pickingVertexShader: () => pickingVertexShader
});
var name147 = "pickingVertexShader", shader146 = `attribute vec3 position;
#if defined(INSTANCES)
attribute vec4 instanceMeshID;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
uniform mat4 viewProjection;
#if defined(INSTANCES)
varying vec4 vMeshID;
#endif
void main(void) {
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;
#if defined(INSTANCES)
vMeshID=instanceMeshID;
#endif
}`, pickingVertexShader;
var init_picking_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_instancesDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  if (!ShaderStore.ShadersStore[name147]) {
    ShaderStore.ShadersStore[name147] = shader146;
  }
  pickingVertexShader = { name: name147, shader: shader146 };
});

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuPerfCounter.js
class WebGPUPerfCounter {
  constructor() {
    this._gpuTimeInFrameId = -1;
    this.counter = new PerfCounter;
  }
  _addDuration(currentFrameId, duration) {
    if (currentFrameId < this._gpuTimeInFrameId) {
      return;
    }
    if (this._gpuTimeInFrameId !== currentFrameId) {
      this.counter._fetchResult();
      this.counter.fetchNewFrame();
      this.counter.addCount(duration, false);
      this._gpuTimeInFrameId = currentFrameId;
    } else {
      this.counter.addCount(duration, false);
    }
  }
}
var init_webgpuPerfCounter = __esm(() => {
  init_perfCounter();
});

// node_modules/@babylonjs/core/Compute/computeShader.js
class ComputeShader {
  get options() {
    return this._options;
  }
  get shaderPath() {
    return this._shaderPath;
  }
  constructor(name148, engine, shaderPath, options = {}) {
    this._bindings = {};
    this._samplers = {};
    this._contextIsDirty = false;
    this.fastMode = false;
    this.onCompiled = null;
    this.onError = null;
    this.name = name148;
    this._engine = engine;
    this.uniqueId = UniqueIdGenerator.UniqueId;
    if (engine.enableGPUTimingMeasurements) {
      this.gpuTimeInFrame = new WebGPUPerfCounter;
    }
    if (!this._engine.getCaps().supportComputeShaders) {
      Logger.Error("This engine does not support compute shaders!");
      return;
    }
    if (!options.bindingsMapping) {
      Logger.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");
      return;
    }
    this._context = engine.createComputeContext();
    this._shaderPath = shaderPath;
    this._options = {
      bindingsMapping: {},
      defines: [],
      ...options
    };
  }
  getClassName() {
    return "ComputeShader";
  }
  setTexture(name148, texture, bindSampler = true) {
    const current = this._bindings[name148];
    this._bindings[name148] = {
      type: bindSampler ? 0 : 4,
      object: texture,
      indexInGroupEntries: current?.indexInGroupEntries
    };
    this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture || current.type !== this._bindings[name148].type);
  }
  setStorageTexture(name148, texture) {
    const current = this._bindings[name148];
    this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture);
    this._bindings[name148] = {
      type: 1,
      object: texture,
      indexInGroupEntries: current?.indexInGroupEntries
    };
  }
  setExternalTexture(name148, texture) {
    const current = this._bindings[name148];
    this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture);
    this._bindings[name148] = {
      type: 6,
      object: texture,
      indexInGroupEntries: current?.indexInGroupEntries
    };
  }
  setVideoTexture(name148, texture) {
    if (texture.externalTexture) {
      this.setExternalTexture(name148, texture.externalTexture);
      return true;
    }
    return false;
  }
  setUniformBuffer(name148, buffer2) {
    const current = this._bindings[name148];
    this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer2);
    this._bindings[name148] = {
      type: ComputeShader._BufferIsDataBuffer(buffer2) ? 7 : 2,
      object: buffer2,
      indexInGroupEntries: current?.indexInGroupEntries
    };
  }
  setStorageBuffer(name148, buffer2) {
    const current = this._bindings[name148];
    this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer2);
    this._bindings[name148] = {
      type: ComputeShader._BufferIsDataBuffer(buffer2) ? 7 : 3,
      object: buffer2,
      indexInGroupEntries: current?.indexInGroupEntries
    };
  }
  setTextureSampler(name148, sampler) {
    const current = this._bindings[name148];
    this._contextIsDirty || (this._contextIsDirty = !current || !sampler.compareSampler(current.object));
    this._bindings[name148] = {
      type: 5,
      object: sampler,
      indexInGroupEntries: current?.indexInGroupEntries
    };
  }
  isReady() {
    let effect = this._effect;
    for (const key in this._bindings) {
      const binding = this._bindings[key], type = binding.type, object = binding.object;
      switch (type) {
        case 0:
        case 4:
        case 1: {
          const texture = object;
          if (!texture.isReady()) {
            return false;
          }
          break;
        }
        case 6: {
          const texture = object;
          if (!texture.isReady()) {
            return false;
          }
          break;
        }
      }
    }
    const defines = [];
    const shaderName = this._shaderPath;
    if (this._options.defines) {
      for (let index = 0;index < this._options.defines.length; index++) {
        defines.push(this._options.defines[index]);
      }
    }
    const join6 = defines.join(`
`);
    if (this._cachedDefines !== join6) {
      this._cachedDefines = join6;
      effect = this._engine.createComputeEffect(shaderName, {
        defines: join6,
        entryPoint: this._options.entryPoint,
        onCompiled: this.onCompiled,
        onError: this.onError
      });
      this._effect = effect;
    }
    if (!effect.isReady()) {
      return false;
    }
    return true;
  }
  dispatch(x, y, z) {
    if (!this.fastMode && !this._checkContext()) {
      return false;
    }
    this._engine.computeDispatch(this._effect, this._context, this._bindings, x, y, z, this._options.bindingsMapping, this.gpuTimeInFrame);
    return true;
  }
  dispatchIndirect(buffer2, offset = 0) {
    if (!this.fastMode && !this._checkContext()) {
      return false;
    }
    const dataBuffer2 = ComputeShader._BufferIsDataBuffer(buffer2) ? buffer2 : buffer2.getBuffer();
    this._engine.computeDispatchIndirect(this._effect, this._context, this._bindings, dataBuffer2, offset, this._options.bindingsMapping, this.gpuTimeInFrame);
    return true;
  }
  _checkContext() {
    if (!this.isReady()) {
      return false;
    }
    for (const key in this._bindings) {
      const binding = this._bindings[key];
      if (!this._options.bindingsMapping[key]) {
        throw new Error("ComputeShader ('" + this.name + "'): No binding mapping has been provided for the property '" + key + "'");
      }
      switch (binding.type) {
        case 0: {
          const sampler = this._samplers[key];
          const texture = binding.object;
          if (!sampler || !texture._texture || !sampler.compareSampler(texture._texture)) {
            this._samplers[key] = new TextureSampler().setParameters(texture.wrapU, texture.wrapV, texture.wrapR, texture.anisotropicFilteringLevel, texture._texture.samplingMode, texture._texture?._comparisonFunction);
            this._contextIsDirty = true;
          }
          break;
        }
        case 6: {
          this._contextIsDirty = true;
          break;
        }
        case 2: {
          const ubo = binding.object;
          if (ubo.getBuffer() !== binding.buffer) {
            binding.buffer = ubo.getBuffer();
            this._contextIsDirty = true;
          }
          break;
        }
      }
    }
    if (this._contextIsDirty) {
      this._contextIsDirty = false;
      this._context.clear();
    }
    return true;
  }
  dispatchWhenReady(x, y, z, delay = 10) {
    return new Promise((resolve3) => {
      _retryWithInterval(() => this.dispatch(x, y, z), resolve3, undefined, delay);
    });
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.options = this._options;
    serializationObject.shaderPath = this._shaderPath;
    serializationObject.bindings = {};
    serializationObject.textures = {};
    for (const key in this._bindings) {
      const binding = this._bindings[key];
      const object = binding.object;
      switch (binding.type) {
        case 0:
        case 4:
        case 1: {
          const serializedData = object.serialize();
          if (serializedData) {
            serializationObject.textures[key] = serializedData;
            serializationObject.bindings[key] = {
              type: binding.type
            };
          }
          break;
        }
        case 2: {
          break;
        }
      }
    }
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const compute = SerializationHelper.Parse(() => new ComputeShader(source.name, scene.getEngine(), source.shaderPath, source.options), source, scene, rootUrl);
    for (const key in source.textures) {
      const binding = source.bindings[key];
      const texture = Texture.Parse(source.textures[key], scene, rootUrl);
      if (binding.type === 0) {
        compute.setTexture(key, texture);
      } else if (binding.type === 4) {
        compute.setTexture(key, texture, false);
      } else {
        compute.setStorageTexture(key, texture);
      }
    }
    return compute;
  }
  static _BufferIsDataBuffer(buffer2) {
    return buffer2.underlyingResource !== undefined;
  }
}
var init_computeShader = __esm(() => {
  init_tslib_es6();
  init_decorators();
  init_decorators_serialization();
  init_typeStore();
  init_texture();
  init_uniqueIdGenerator();
  init_logger();
  init_webgpuPerfCounter();
  init_timingTools();
  __decorate([
    serialize()
  ], ComputeShader.prototype, "name", undefined);
  __decorate([
    serialize()
  ], ComputeShader.prototype, "fastMode", undefined);
  RegisterClass("BABYLON.ComputeShader", ComputeShader);
});

// node_modules/@babylonjs/core/Shaders/gpuTransform.vertex.js
var name148 = "gpuTransformVertexShader", shader147 = `attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
out vec3 outPosition;const mat4 identity=mat4(
vec4(1.0,0.0,0.0,0.0),
vec4(0.0,1.0,0.0,0.0),
vec4(0.0,0.0,1.0,0.0),
vec4(0.0,0.0,0.0,1.0)
);void main(void) {vec3 positionUpdated=position;
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
mat4 finalWorld=identity;
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);outPosition=worldPos.xyz;}`;
var init_gpuTransform_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  if (!ShaderStore.ShadersStore[name148]) {
    ShaderStore.ShadersStore[name148] = shader147;
  }
});

// node_modules/@babylonjs/core/Shaders/gpuTransform.fragment.js
var name149 = "gpuTransformPixelShader", shader148 = `#version 300 es
void main() {discard;}
`;
var init_gpuTransform_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name149]) {
    ShaderStore.ShadersStore[name149] = shader148;
  }
});

// node_modules/@babylonjs/core/Culling/Helper/transformFeedbackBoundingHelper.js
class TransformFeedbackBoundingHelper {
  constructor(engine) {
    this._buffers = {};
    this._effects = {};
    this._meshListCounter = 0;
    this._engine = engine;
  }
  processAsync(meshes) {
    if (!Array.isArray(meshes)) {
      meshes = [meshes];
    }
    this._meshListCounter = 0;
    this._processMeshList(meshes);
    return Promise.resolve();
  }
  _processMeshList(meshes) {
    const parallelShaderCompile = this._engine.getCaps().parallelShaderCompile;
    this._engine.getCaps().parallelShaderCompile = undefined;
    for (let i = 0;i < meshes.length; ++i) {
      const mesh = meshes[i];
      const vertexCount = mesh.getTotalVertices();
      if (vertexCount === 0 || !mesh.getVertexBuffer || !mesh.getVertexBuffer(VertexBuffer.PositionKind)) {
        continue;
      }
      let computeEffect2;
      const defines = [];
      const attribs = [VertexBuffer.PositionKind];
      if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
        attribs.push(VertexBuffer.MatricesIndicesKind);
        attribs.push(VertexBuffer.MatricesWeightsKind);
        if (mesh.numBoneInfluencers > 4) {
          attribs.push(VertexBuffer.MatricesIndicesExtraKind);
          attribs.push(VertexBuffer.MatricesWeightsExtraKind);
        }
        defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
        defines.push("#define BONETEXTURE " + mesh.skeleton.isUsingTextureForMatrices);
        defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
      } else {
        defines.push("#define NUM_BONE_INFLUENCERS 0");
      }
      const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, false, false, false, false, false) : 0;
      const bvaManager = mesh.bakedVertexAnimationManager;
      if (bvaManager && bvaManager.isEnabled) {
        defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
        PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
      }
      const join6 = defines.join(`
`);
      if (!this._effects[join6]) {
        const uniforms = [
          "boneTextureWidth",
          "mBones",
          "morphTargetInfluences",
          "morphTargetCount",
          "morphTargetTextureInfo",
          "morphTargetTextureIndices",
          "bakedVertexAnimationSettings",
          "bakedVertexAnimationTextureSizeInverted",
          "bakedVertexAnimationTime"
        ];
        const samplers = ["boneSampler", "morphTargets", "bakedVertexAnimationTexture"];
        const computeEffectOptions = {
          attributes: attribs,
          uniformsNames: uniforms,
          uniformBuffersNames: [],
          samplers,
          defines: join6,
          fallbacks: null,
          onCompiled: null,
          onError: null,
          indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
          maxSimultaneousLights: 0,
          transformFeedbackVaryings: ["outPosition"]
        };
        computeEffect2 = this._engine.createEffect("gpuTransform", computeEffectOptions, this._engine);
        this._effects[join6] = computeEffect2;
      } else {
        computeEffect2 = this._effects[join6];
      }
      this._compute(mesh, computeEffect2);
    }
    this._engine.getCaps().parallelShaderCompile = parallelShaderCompile;
  }
  _compute(mesh, effect) {
    const engine = this._engine;
    let targetBuffer;
    const vertexCount = mesh.getTotalVertices();
    if (!this._buffers[mesh.uniqueId]) {
      const targetData = new Float32Array(vertexCount * 3);
      targetBuffer = new Buffer2(mesh.getEngine(), targetData, true, 3);
      this._buffers[mesh.uniqueId] = targetBuffer;
    } else {
      targetBuffer = this._buffers[mesh.uniqueId];
    }
    effect.getEngine().enableEffect(effect);
    mesh._bindDirect(effect, null, true);
    BindBonesParameters(mesh, effect);
    BindMorphTargetParameters(mesh, effect);
    if (mesh.morphTargetManager && mesh.morphTargetManager.isUsingTextureForTargets) {
      mesh.morphTargetManager._bind(effect);
    }
    const bvaManager = mesh.bakedVertexAnimationManager;
    if (bvaManager && bvaManager.isEnabled) {
      mesh.bakedVertexAnimationManager?.bind(effect, false);
    }
    const arrayBuffer = targetBuffer.getData();
    engine.bindTransformFeedbackBuffer(targetBuffer.getBuffer());
    engine.setRasterizerState(false);
    engine.beginTransformFeedback(true);
    engine.drawArraysType(2, 0, vertexCount);
    engine.endTransformFeedback();
    engine.setRasterizerState(true);
    engine.readTransformFeedbackBuffer(arrayBuffer);
    engine.bindTransformFeedbackBuffer(null);
    if (this._meshListCounter === 0) {
      mesh._refreshBoundingInfo(arrayBuffer, null);
    } else {
      const bb = mesh.getBoundingInfo().boundingBox;
      const extend = extractMinAndMax(arrayBuffer, 0, vertexCount);
      TransformFeedbackBoundingHelper._Min.copyFrom(bb.minimum).minimizeInPlace(extend.minimum);
      TransformFeedbackBoundingHelper._Max.copyFrom(bb.maximum).maximizeInPlace(extend.maximum);
      mesh._refreshBoundingInfoDirect({ minimum: TransformFeedbackBoundingHelper._Min, maximum: TransformFeedbackBoundingHelper._Max });
    }
  }
  registerMeshListAsync(meshes) {
    if (!Array.isArray(meshes)) {
      meshes = [meshes];
    }
    this._meshList = meshes;
    this._meshListCounter = 0;
    return Promise.resolve();
  }
  processMeshList() {
    if (this._meshList.length === 0) {
      return;
    }
    this._processMeshList(this._meshList);
    this._meshListCounter++;
  }
  fetchResultsForMeshListAsync() {
    this._meshListCounter = 0;
    return Promise.resolve();
  }
  dispose() {
    for (const key in this._buffers) {
      this._buffers[key].dispose();
    }
    this._buffers = {};
    this._effects = {};
    this._engine = null;
  }
}
var init_transformFeedbackBoundingHelper = __esm(() => {
  init_buffer();
  init_materialHelper_functions();
  init_math_functions();
  init_math_vector();
  init_gpuTransform_vertex();
  init_gpuTransform_fragment();
  TransformFeedbackBoundingHelper._Min = new Vector3;
  TransformFeedbackBoundingHelper._Max = new Vector3;
});

// node_modules/@babylonjs/core/ShadersWGSL/boundingInfo.compute.js
var name150 = "boundingInfoComputeShader", shader149 = `struct Results {minX : atomic<i32>,
minY : atomic<i32>,
minZ : atomic<i32>,
maxX : atomic<i32>,
maxY : atomic<i32>,
maxZ : atomic<i32>,
dummy1 : i32,
dummy2 : i32,};fn floatToBits(value: f32)->i32 {return bitcast<i32>(value);}
fn bitsToFloat(value: i32)->f32 {return bitcast<f32>(value);}
fn atomicMinFloat(atomicVar: ptr<storage,atomic<i32>,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value>=oldValue) {break;}
if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}
fn atomicMaxFloat(atomicVar: ptr<storage,atomic<i32>,read_write>,value: f32) {let intValue=floatToBits(value);loop {let oldIntValue=atomicLoad(atomicVar);let oldValue=bitsToFloat(oldIntValue);if (value<=oldValue) {break;}
if (atomicCompareExchangeWeak(atomicVar,oldIntValue,intValue).old_value==oldIntValue) {break;}}}
fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>
{let offset=i32(index) *4; 
let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);}
const identity=mat4x4f(
vec4f(1.0,0.0,0.0,0.0),
vec4f(0.0,1.0,0.0,0.0),
vec4f(0.0,0.0,1.0,0.0),
vec4f(0.0,0.0,0.0,1.0)
);struct Settings {morphTargetTextureInfo: vec3f,
morphTargetCount: i32,
indexResult : u32,};@group(0) @binding(0) var<storage,read> positionBuffer : array<f32>;@group(0) @binding(1) var<storage,read_write> resultBuffer : array<Results>;@group(0) @binding(7) var<uniform> settings : Settings;
#if NUM_BONE_INFLUENCERS>0
@group(0) @binding(2) var boneSampler : texture_2d<f32>;@group(0) @binding(3) var<storage,read> indexBuffer : array<vec4f>;@group(0) @binding(4) var<storage,read> weightBuffer : array<vec4f>;
#if NUM_BONE_INFLUENCERS>4
@group(0) @binding(5) var<storage,read> indexExtraBuffer : array<vec4f>;@group(0) @binding(6) var<storage,read> weightExtraBuffer : array<vec4f>;
#endif
#endif
#ifdef MORPHTARGETS
@group(0) @binding(8) var morphTargets : texture_2d_array<f32>;@group(0) @binding(9) var<storage,read> morphTargetInfluences : array<f32>;@group(0) @binding(10) var<storage,read> morphTargetTextureIndices : array<f32>;
#endif
#ifdef MORPHTARGETS
fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec3f
{ 
let vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2<i32>(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0).xyz;}
fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : u32)->vec4f
{ 
let vertexID=f32(vertexIndex)*settings.morphTargetTextureInfo.x;let y=floor(vertexID/settings.morphTargetTextureInfo.y);let x=vertexID-y*settings.morphTargetTextureInfo.y;let textureUV=vec2<i32>(i32(x),i32(y));return textureLoad(morphTargets,textureUV,i32(morphTargetTextureIndices[targetIndex]),0);}
#endif
@compute @workgroup_size(256,1,1)
fn main(@builtin(global_invocation_id) global_id : vec3<u32>) {let index=global_id.x;if (index>=arrayLength(&positionBuffer)/3) {return;}
let position=vec3f(positionBuffer[index*3],positionBuffer[index*3+1],positionBuffer[index*3+2]);var finalWorld=identity;var positionUpdated=position;
#if NUM_BONE_INFLUENCERS>0
var influence : mat4x4<f32>;let matricesIndices=indexBuffer[index];let matricesWeights=weightBuffer[index];influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];
#endif 
#if NUM_BONE_INFLUENCERS>2
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];
#endif 
#if NUM_BONE_INFLUENCERS>3
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];
#endif 
#if NUM_BONE_INFLUENCERS>4
let matricesIndicesExtra=indexExtraBuffer[index];let matricesWeightsExtra=weightExtraBuffer[index];influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.x)*matricesWeightsExtra.x;
#if NUM_BONE_INFLUENCERS>5
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.y)*matricesWeightsExtra.y;
#endif 
#if NUM_BONE_INFLUENCERS>6
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.z)*matricesWeightsExtra.z;
#endif 
#if NUM_BONE_INFLUENCERS>7
influence=influence+readMatrixFromRawSampler(boneSampler,matricesIndicesExtra.w)*matricesWeightsExtra.w;
#endif 
#endif 
finalWorld=finalWorld*influence;
#endif
#ifdef MORPHTARGETS
for (var i=0; i<NUM_MORPH_INFLUENCERS; i=i+1) {if (i>=settings.morphTargetCount) {break;}
positionUpdated=positionUpdated+(readVector3FromRawSampler(i,index)-position)*morphTargetInfluences[i];}
#endif
var worldPos=finalWorld*vec4f(positionUpdated.x,positionUpdated.y,positionUpdated.z,1.0);atomicMinFloat(&resultBuffer[settings.indexResult].minX,worldPos.x);atomicMinFloat(&resultBuffer[settings.indexResult].minY,worldPos.y);atomicMinFloat(&resultBuffer[settings.indexResult].minZ,worldPos.z);atomicMaxFloat(&resultBuffer[settings.indexResult].maxX,worldPos.x);atomicMaxFloat(&resultBuffer[settings.indexResult].maxY,worldPos.y);atomicMaxFloat(&resultBuffer[settings.indexResult].maxZ,worldPos.z);}
`;
var init_boundingInfo_compute = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name150]) {
    ShaderStore.ShadersStoreWGSL[name150] = shader149;
  }
});

// node_modules/@babylonjs/core/Culling/Helper/computeShaderBoundingHelper.js
var init_computeShaderBoundingHelper = __esm(() => {
  init_computeShader();
  init_buffer();
  init_math_vector();
  init_uniformBuffer();
  init_boundingInfo_compute();
  init_timingTools();
});

// node_modules/@babylonjs/core/ShadersWGSL/color.vertex.js
var exports_color_vertex = {};
__export(exports_color_vertex, {
  colorVertexShaderWGSL: () => colorVertexShaderWGSL
});
var name151 = "colorVertexShader", shader150 = `attribute position: vec3f;
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#ifdef FOG
uniform view: mat4x4f;
#endif
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef VERTEXCOLOR
var colorUpdated: vec4f=vertexInputs.color;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;
#include<clipPlaneVertex>
#include<fogVertex>
#include<vertexColorMixing>
#define CUSTOM_VERTEX_MAIN_END
}`, colorVertexShaderWGSL;
var init_color_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_clipPlaneVertexDeclaration();
  init_fogVertexDeclaration();
  init_instancesDeclaration();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  init_fogVertex();
  init_vertexColorMixing();
  if (!ShaderStore.ShadersStoreWGSL[name151]) {
    ShaderStore.ShadersStoreWGSL[name151] = shader150;
  }
  colorVertexShaderWGSL = { name: name151, shader: shader150 };
});

// node_modules/@babylonjs/core/ShadersWGSL/color.fragment.js
var exports_color_fragment = {};
__export(exports_color_fragment, {
  colorPixelShaderWGSL: () => colorPixelShaderWGSL
});
var name152 = "colorPixelShader", shader151 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
#define VERTEXCOLOR
varying vColor: vec4f;
#else
uniform color: vec4f;
#endif
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
fragmentOutputs.color=input.vColor;
#else
fragmentOutputs.color=uniforms.color;
#endif
#include<fogFragment>(color,fragmentOutputs.color)
#define CUSTOM_FRAGMENT_MAIN_END
}`, colorPixelShaderWGSL;
var init_color_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_fogFragmentDeclaration();
  init_clipPlaneFragment();
  init_fogFragment();
  if (!ShaderStore.ShadersStoreWGSL[name152]) {
    ShaderStore.ShadersStoreWGSL[name152] = shader151;
  }
  colorPixelShaderWGSL = { name: name152, shader: shader151 };
});

// node_modules/@babylonjs/core/Shaders/color.vertex.js
var exports_color_vertex2 = {};
__export(exports_color_vertex2, {
  colorVertexShader: () => colorVertexShader
});
var name153 = "colorVertexShader", shader152 = `attribute vec3 position;
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#ifdef FOG
uniform mat4 view;
#endif
#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(position,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<vertexColorMixing>
#define CUSTOM_VERTEX_MAIN_END
}`, colorVertexShader;
var init_color_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_instancesDeclaration2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_vertexColorMixing2();
  if (!ShaderStore.ShadersStore[name153]) {
    ShaderStore.ShadersStore[name153] = shader152;
  }
  colorVertexShader = { name: name153, shader: shader152 };
});

// node_modules/@babylonjs/core/Shaders/color.fragment.js
var exports_color_fragment2 = {};
__export(exports_color_fragment2, {
  colorPixelShader: () => colorPixelShader
});
var name154 = "colorPixelShader", shader153 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
#define VERTEXCOLOR
varying vec4 vColor;
#else
uniform vec4 color;
#endif
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
gl_FragColor=vColor;
#else
gl_FragColor=color;
#endif
#include<fogFragment>(color,gl_FragColor)
#define CUSTOM_FRAGMENT_MAIN_END
}`, colorPixelShader;
var init_color_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_fogFragmentDeclaration2();
  init_clipPlaneFragment2();
  init_fogFragment2();
  if (!ShaderStore.ShadersStore[name154]) {
    ShaderStore.ShadersStore[name154] = shader153;
  }
  colorPixelShader = { name: name154, shader: shader153 };
});

// node_modules/@babylonjs/core/FlowGraph/CustomTypes/flowGraphInteger.js
class FlowGraphInteger {
  constructor(value) {
    this.value = this._toInt(value);
  }
  _toInt(n) {
    return n | 0;
  }
  add(other) {
    return new FlowGraphInteger(this.value + other.value);
  }
  subtract(other) {
    return new FlowGraphInteger(this.value - other.value);
  }
  multiply(other) {
    return new FlowGraphInteger(Math.imul(this.value, other.value));
  }
  divide(other) {
    return new FlowGraphInteger(this.value / other.value);
  }
  getClassName() {
    return FlowGraphInteger.ClassName;
  }
  equals(other) {
    return this.value === other.value;
  }
  static FromValue(value) {
    return new FlowGraphInteger(value);
  }
  toString() {
    return this.value.toString();
  }
}
var init_flowGraphInteger = __esm(() => {
  init_typeStore();
  FlowGraphInteger.ClassName = "FlowGraphInteger";
  RegisterClass("FlowGraphInteger", FlowGraphInteger);
});

// node_modules/@babylonjs/core/FlowGraph/CustomTypes/flowGraphMatrix.js
class FlowGraphMatrix2D {
  constructor(m = [1, 0, 0, 1]) {
    this._m = m;
  }
  get m() {
    return this._m;
  }
  transformVector(v) {
    return this.transformVectorToRef(v, new Vector2);
  }
  transformVectorToRef(v, result) {
    result.x = v.x * this._m[0] + v.y * this._m[1];
    result.y = v.x * this._m[2] + v.y * this._m[3];
    return result;
  }
  asArray() {
    return this.toArray();
  }
  toArray(emptyArray = []) {
    for (let i = 0;i < 4; i++) {
      emptyArray[i] = this._m[i];
    }
    return emptyArray;
  }
  fromArray(array) {
    for (let i = 0;i < 4; i++) {
      this._m[i] = array[i];
    }
    return this;
  }
  multiplyToRef(other, result) {
    const otherMatrix = other._m;
    const thisMatrix = this._m;
    const r = result._m;
    r[0] = otherMatrix[0] * thisMatrix[0] + otherMatrix[1] * thisMatrix[2];
    r[1] = otherMatrix[0] * thisMatrix[1] + otherMatrix[1] * thisMatrix[3];
    r[2] = otherMatrix[2] * thisMatrix[0] + otherMatrix[3] * thisMatrix[2];
    r[3] = otherMatrix[2] * thisMatrix[1] + otherMatrix[3] * thisMatrix[3];
    return result;
  }
  multiply(other) {
    return this.multiplyToRef(other, new FlowGraphMatrix2D);
  }
  divideToRef(other, result) {
    const m = this._m;
    const o = other._m;
    const r = result._m;
    r[0] = m[0] / o[0];
    r[1] = m[1] / o[1];
    r[2] = m[2] / o[2];
    r[3] = m[3] / o[3];
    return result;
  }
  divide(other) {
    return this.divideToRef(other, new FlowGraphMatrix2D);
  }
  addToRef(other, result) {
    const m = this._m;
    const o = other.m;
    const r = result.m;
    r[0] = m[0] + o[0];
    r[1] = m[1] + o[1];
    r[2] = m[2] + o[2];
    r[3] = m[3] + o[3];
    return result;
  }
  add(other) {
    return this.addToRef(other, new FlowGraphMatrix2D);
  }
  subtractToRef(other, result) {
    const m = this._m;
    const o = other.m;
    const r = result.m;
    r[0] = m[0] - o[0];
    r[1] = m[1] - o[1];
    r[2] = m[2] - o[2];
    r[3] = m[3] - o[3];
    return result;
  }
  subtract(other) {
    return this.subtractToRef(other, new FlowGraphMatrix2D);
  }
  transpose() {
    const m = this._m;
    return new FlowGraphMatrix2D([m[0], m[2], m[1], m[3]]);
  }
  determinant() {
    const m = this._m;
    return m[0] * m[3] - m[1] * m[2];
  }
  inverse() {
    const det = this.determinant();
    if (det === 0) {
      throw new Error("Matrix is not invertible");
    }
    const m = this._m;
    const invDet = 1 / det;
    return new FlowGraphMatrix2D([m[3] * invDet, -m[1] * invDet, -m[2] * invDet, m[0] * invDet]);
  }
  equals(other, epsilon = 0) {
    const m = this._m;
    const o = other.m;
    if (epsilon === 0) {
      return m[0] === o[0] && m[1] === o[1] && m[2] === o[2] && m[3] === o[3];
    }
    return Math.abs(m[0] - o[0]) < epsilon && Math.abs(m[1] - o[1]) < epsilon && Math.abs(m[2] - o[2]) < epsilon && Math.abs(m[3] - o[3]) < epsilon;
  }
  getClassName() {
    return "FlowGraphMatrix2D";
  }
  toString() {
    return `FlowGraphMatrix2D(${this._m.join(", ")})`;
  }
}

class FlowGraphMatrix3D {
  constructor(array = [1, 0, 0, 0, 1, 0, 0, 0, 1]) {
    this._m = array;
  }
  get m() {
    return this._m;
  }
  transformVector(v) {
    return this.transformVectorToRef(v, new Vector3);
  }
  transformVectorToRef(v, result) {
    const m = this._m;
    result.x = v.x * m[0] + v.y * m[1] + v.z * m[2];
    result.y = v.x * m[3] + v.y * m[4] + v.z * m[5];
    result.z = v.x * m[6] + v.y * m[7] + v.z * m[8];
    return result;
  }
  multiplyToRef(other, result) {
    const otherMatrix = other._m;
    const thisMatrix = this._m;
    const r = result.m;
    r[0] = otherMatrix[0] * thisMatrix[0] + otherMatrix[1] * thisMatrix[3] + otherMatrix[2] * thisMatrix[6];
    r[1] = otherMatrix[0] * thisMatrix[1] + otherMatrix[1] * thisMatrix[4] + otherMatrix[2] * thisMatrix[7];
    r[2] = otherMatrix[0] * thisMatrix[2] + otherMatrix[1] * thisMatrix[5] + otherMatrix[2] * thisMatrix[8];
    r[3] = otherMatrix[3] * thisMatrix[0] + otherMatrix[4] * thisMatrix[3] + otherMatrix[5] * thisMatrix[6];
    r[4] = otherMatrix[3] * thisMatrix[1] + otherMatrix[4] * thisMatrix[4] + otherMatrix[5] * thisMatrix[7];
    r[5] = otherMatrix[3] * thisMatrix[2] + otherMatrix[4] * thisMatrix[5] + otherMatrix[5] * thisMatrix[8];
    r[6] = otherMatrix[6] * thisMatrix[0] + otherMatrix[7] * thisMatrix[3] + otherMatrix[8] * thisMatrix[6];
    r[7] = otherMatrix[6] * thisMatrix[1] + otherMatrix[7] * thisMatrix[4] + otherMatrix[8] * thisMatrix[7];
    r[8] = otherMatrix[6] * thisMatrix[2] + otherMatrix[7] * thisMatrix[5] + otherMatrix[8] * thisMatrix[8];
    return result;
  }
  multiply(other) {
    return this.multiplyToRef(other, new FlowGraphMatrix3D);
  }
  divideToRef(other, result) {
    const m = this._m;
    const o = other.m;
    const r = result.m;
    r[0] = m[0] / o[0];
    r[1] = m[1] / o[1];
    r[2] = m[2] / o[2];
    r[3] = m[3] / o[3];
    r[4] = m[4] / o[4];
    r[5] = m[5] / o[5];
    r[6] = m[6] / o[6];
    r[7] = m[7] / o[7];
    r[8] = m[8] / o[8];
    return result;
  }
  divide(other) {
    return this.divideToRef(other, new FlowGraphMatrix3D);
  }
  addToRef(other, result) {
    const m = this._m;
    const o = other.m;
    const r = result.m;
    r[0] = m[0] + o[0];
    r[1] = m[1] + o[1];
    r[2] = m[2] + o[2];
    r[3] = m[3] + o[3];
    r[4] = m[4] + o[4];
    r[5] = m[5] + o[5];
    r[6] = m[6] + o[6];
    r[7] = m[7] + o[7];
    r[8] = m[8] + o[8];
    return result;
  }
  add(other) {
    return this.addToRef(other, new FlowGraphMatrix3D);
  }
  subtractToRef(other, result) {
    const m = this._m;
    const o = other.m;
    const r = result.m;
    r[0] = m[0] - o[0];
    r[1] = m[1] - o[1];
    r[2] = m[2] - o[2];
    r[3] = m[3] - o[3];
    r[4] = m[4] - o[4];
    r[5] = m[5] - o[5];
    r[6] = m[6] - o[6];
    r[7] = m[7] - o[7];
    r[8] = m[8] - o[8];
    return result;
  }
  subtract(other) {
    return this.subtractToRef(other, new FlowGraphMatrix3D);
  }
  toArray(emptyArray = []) {
    for (let i = 0;i < 9; i++) {
      emptyArray[i] = this._m[i];
    }
    return emptyArray;
  }
  asArray() {
    return this.toArray();
  }
  fromArray(array) {
    for (let i = 0;i < 9; i++) {
      this._m[i] = array[i];
    }
    return this;
  }
  transpose() {
    const m = this._m;
    return new FlowGraphMatrix3D([m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]]);
  }
  determinant() {
    const m = this._m;
    return m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
  }
  inverse() {
    const det = this.determinant();
    if (det === 0) {
      throw new Error("Matrix is not invertible");
    }
    const m = this._m;
    const invDet = 1 / det;
    return new FlowGraphMatrix3D([
      (m[4] * m[8] - m[5] * m[7]) * invDet,
      (m[2] * m[7] - m[1] * m[8]) * invDet,
      (m[1] * m[5] - m[2] * m[4]) * invDet,
      (m[5] * m[6] - m[3] * m[8]) * invDet,
      (m[0] * m[8] - m[2] * m[6]) * invDet,
      (m[2] * m[3] - m[0] * m[5]) * invDet,
      (m[3] * m[7] - m[4] * m[6]) * invDet,
      (m[1] * m[6] - m[0] * m[7]) * invDet,
      (m[0] * m[4] - m[1] * m[3]) * invDet
    ]);
  }
  equals(other, epsilon = 0) {
    const m = this._m;
    const o = other.m;
    if (epsilon === 0) {
      return m[0] === o[0] && m[1] === o[1] && m[2] === o[2] && m[3] === o[3] && m[4] === o[4] && m[5] === o[5] && m[6] === o[6] && m[7] === o[7] && m[8] === o[8];
    }
    return Math.abs(m[0] - o[0]) < epsilon && Math.abs(m[1] - o[1]) < epsilon && Math.abs(m[2] - o[2]) < epsilon && Math.abs(m[3] - o[3]) < epsilon && Math.abs(m[4] - o[4]) < epsilon && Math.abs(m[5] - o[5]) < epsilon && Math.abs(m[6] - o[6]) < epsilon && Math.abs(m[7] - o[7]) < epsilon && Math.abs(m[8] - o[8]) < epsilon;
  }
  getClassName() {
    return "FlowGraphMatrix3D";
  }
  toString() {
    return `FlowGraphMatrix3D(${this._m.join(", ")})`;
  }
}
var init_flowGraphMatrix = __esm(() => {
  init_math_vector();
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphRichTypes.js
class RichType {
  constructor(typeName, defaultValue, animationType = -1) {
    this.typeName = typeName;
    this.defaultValue = defaultValue;
    this.animationType = animationType;
  }
  serialize(serializationObject) {
    serializationObject.typeName = this.typeName;
    serializationObject.defaultValue = this.defaultValue;
  }
}
function getRichTypeFromValue(value) {
  const anyValue = value;
  switch (typeof value) {
    case "string":
      return RichTypeString;
    case "number":
      return RichTypeNumber;
    case "boolean":
      return RichTypeBoolean;
    case "object":
      if (anyValue.getClassName) {
        switch (anyValue.getClassName()) {
          case "Vector2":
            return RichTypeVector2;
          case "Vector3":
            return RichTypeVector3;
          case "Vector4":
            return RichTypeVector4;
          case "Matrix":
            return RichTypeMatrix;
          case "Color3":
            return RichTypeColor3;
          case "Color4":
            return RichTypeColor4;
          case "Quaternion":
            return RichTypeQuaternion;
          case "FlowGraphInteger":
            return RichTypeFlowGraphInteger;
          case "Matrix2D":
            return RichTypeMatrix2D;
          case "Matrix3D":
            return RichTypeMatrix3D;
        }
      }
      return RichTypeAny;
    default:
      return RichTypeAny;
  }
}
function getRichTypeByFlowGraphType(flowGraphType) {
  switch (flowGraphType) {
    case "string":
      return RichTypeString;
    case "number":
      return RichTypeNumber;
    case "boolean":
      return RichTypeBoolean;
    case "Vector2":
      return RichTypeVector2;
    case "Vector3":
      return RichTypeVector3;
    case "Vector4":
      return RichTypeVector4;
    case "Matrix":
      return RichTypeMatrix;
    case "Color3":
      return RichTypeColor3;
    case "Color4":
      return RichTypeColor4;
    case "Quaternion":
      return RichTypeQuaternion;
    case "FlowGraphInteger":
      return RichTypeFlowGraphInteger;
    case "Matrix2D":
      return RichTypeMatrix2D;
    case "Matrix3D":
      return RichTypeMatrix3D;
    default:
      return RichTypeAny;
  }
}
function getRichTypeByAnimationType(animationType) {
  switch (animationType) {
    case 0:
      return RichTypeNumber;
    case 5:
      return RichTypeVector2;
    case 1:
      return RichTypeVector3;
    case 3:
      return RichTypeMatrix;
    case 4:
      return RichTypeColor3;
    case 7:
      return RichTypeColor4;
    case 2:
      return RichTypeQuaternion;
    default:
      return RichTypeAny;
  }
}
var FlowGraphTypes, RichTypeAny, RichTypeString, RichTypeNumber, RichTypeBoolean, RichTypeVector2, RichTypeVector3, RichTypeVector4, RichTypeMatrix, RichTypeMatrix2D, RichTypeMatrix3D, RichTypeColor3, RichTypeColor4, RichTypeQuaternion, RichTypeFlowGraphInteger;
var init_flowGraphRichTypes = __esm(() => {
  init_math_vector();
  init_math_color();
  init_flowGraphInteger();
  init_flowGraphMatrix();
  (function(FlowGraphTypes2) {
    FlowGraphTypes2["Any"] = "any";
    FlowGraphTypes2["String"] = "string";
    FlowGraphTypes2["Number"] = "number";
    FlowGraphTypes2["Boolean"] = "boolean";
    FlowGraphTypes2["Object"] = "object";
    FlowGraphTypes2["Integer"] = "FlowGraphInteger";
    FlowGraphTypes2["Vector2"] = "Vector2";
    FlowGraphTypes2["Vector3"] = "Vector3";
    FlowGraphTypes2["Vector4"] = "Vector4";
    FlowGraphTypes2["Quaternion"] = "Quaternion";
    FlowGraphTypes2["Matrix"] = "Matrix";
    FlowGraphTypes2["Matrix2D"] = "Matrix2D";
    FlowGraphTypes2["Matrix3D"] = "Matrix3D";
    FlowGraphTypes2["Color3"] = "Color3";
    FlowGraphTypes2["Color4"] = "Color4";
  })(FlowGraphTypes || (FlowGraphTypes = {}));
  RichTypeAny = new RichType("any", undefined);
  RichTypeString = new RichType("string", "");
  RichTypeNumber = new RichType("number", 0, 0);
  RichTypeBoolean = new RichType("boolean", false);
  RichTypeVector2 = new RichType("Vector2", Vector2.Zero(), 5);
  RichTypeVector3 = new RichType("Vector3", Vector3.Zero(), 1);
  RichTypeVector4 = new RichType("Vector4", Vector4.Zero());
  RichTypeMatrix = new RichType("Matrix", Matrix.Identity(), 3);
  RichTypeMatrix2D = new RichType("Matrix2D", new FlowGraphMatrix2D);
  RichTypeMatrix3D = new RichType("Matrix3D", new FlowGraphMatrix3D);
  RichTypeColor3 = new RichType("Color3", Color3.Black(), 4);
  RichTypeColor4 = new RichType("Color4", new Color4(0, 0, 0, 0), 7);
  RichTypeQuaternion = new RichType("Quaternion", Quaternion.Identity(), 2);
  RichTypeQuaternion.typeTransformer = (value) => {
    if (value.getClassName && value.getClassName() === "Vector4") {
      return Quaternion.FromArray(value.asArray());
    } else if (value.getClassName && value.getClassName() === "Vector3") {
      return Quaternion.FromEulerVector(value);
    } else if (value.getClassName && value.getClassName() === "Matrix") {
      return Quaternion.FromRotationMatrix(value);
    }
    return value;
  };
  RichTypeFlowGraphInteger = new RichType("FlowGraphInteger", new FlowGraphInteger(0), 0);
});

// node_modules/@babylonjs/core/FlowGraph/serialization.js
function isVectorClassName(className) {
  return className === "Vector2" || className === "Vector3" || className === "Vector4" || className === "Quaternion" || className === "Color3" || className === "Color4";
}
function isMatrixClassName(className) {
  return className === "Matrix" || className === "Matrix2D" || className === "Matrix3D";
}
function defaultValueSerializationFunction(key, value, serializationObject) {
  const className = value?.getClassName?.() ?? "";
  if (isVectorClassName(className) || isMatrixClassName(className)) {
    serializationObject[key] = {
      value: value.asArray(),
      className
    };
  } else if (className === "FlowGraphInteger") {
    serializationObject[key] = {
      value: value.value,
      className
    };
  } else {
    if (className && (value.id || value.name)) {
      serializationObject[key] = {
        id: value.id,
        name: value.name,
        className
      };
    } else {
      if (typeof value !== "object") {
        serializationObject[key] = value;
      } else {
        throw new Error(`Could not serialize value ${value}`);
      }
    }
  }
}
var init_serialization = __esm(() => {
  init_math_color();
  init_math_vector();
  init_flowGraphInteger();
  init_flowGraphRichTypes();
  init_flowGraphMatrix();
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphAssetsContext.js
function GetFlowGraphAssetWithType(assetsContext, type, index, useIndexAsUniqueId) {
  switch (type) {
    case "Animation":
      return useIndexAsUniqueId ? assetsContext.animations.find((a) => a.uniqueId === index) ?? null : assetsContext.animations[index] ?? null;
    case "AnimationGroup":
      return useIndexAsUniqueId ? assetsContext.animationGroups.find((a) => a.uniqueId === index) ?? null : assetsContext.animationGroups[index] ?? null;
    case "Mesh":
      return useIndexAsUniqueId ? assetsContext.meshes.find((a) => a.uniqueId === index) ?? null : assetsContext.meshes[index] ?? null;
    case "Material":
      return useIndexAsUniqueId ? assetsContext.materials.find((a) => a.uniqueId === index) ?? null : assetsContext.materials[index] ?? null;
    case "Camera":
      return useIndexAsUniqueId ? assetsContext.cameras.find((a) => a.uniqueId === index) ?? null : assetsContext.cameras[index] ?? null;
    case "Light":
      return useIndexAsUniqueId ? assetsContext.lights.find((a) => a.uniqueId === index) ?? null : assetsContext.lights[index] ?? null;
    default:
      return null;
  }
}
var FlowGraphAssetType;
var init_flowGraphAssetsContext = __esm(() => {
  (function(FlowGraphAssetType2) {
    FlowGraphAssetType2["Animation"] = "Animation";
    FlowGraphAssetType2["AnimationGroup"] = "AnimationGroup";
    FlowGraphAssetType2["Mesh"] = "Mesh";
    FlowGraphAssetType2["Material"] = "Material";
    FlowGraphAssetType2["Camera"] = "Camera";
    FlowGraphAssetType2["Light"] = "Light";
  })(FlowGraphAssetType || (FlowGraphAssetType = {}));
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphLogger.js
class FlowGraphLogger {
  constructor() {
    this.logToConsole = false;
    this.log = [];
  }
  addLogItem(item) {
    if (!item.time) {
      item.time = Date.now();
    }
    this.log.push(item);
    if (this.logToConsole) {
      const value = item.payload?.value;
      if (typeof value === "object" && value.getClassName) {
        Logger.Log(`[FGLog] ${item.className}:${item.uniqueId.split("-")[0]} ${item.action} - ${JSON.stringify(value.getClassName())}: ${value.toString()}`);
      } else {
        Logger.Log(`[FGLog] ${item.className}:${item.uniqueId.split("-")[0]} ${item.action} - ${JSON.stringify(item.payload)}`);
      }
    }
  }
  getItemsOfType(action2) {
    return this.log.filter((i) => i.action === action2);
  }
}
var FlowGraphAction;
var init_flowGraphLogger = __esm(() => {
  init_logger();
  (function(FlowGraphAction2) {
    FlowGraphAction2["ExecuteBlock"] = "ExecuteBlock";
    FlowGraphAction2["ExecuteEvent"] = "ExecuteEvent";
    FlowGraphAction2["TriggerConnection"] = "TriggerConnection";
    FlowGraphAction2["ContextVariableSet"] = "ContextVariableSet";
    FlowGraphAction2["GlobalVariableSet"] = "GlobalVariableSet";
    FlowGraphAction2["GlobalVariableDelete"] = "GlobalVariableDelete";
    FlowGraphAction2["GlobalVariableGet"] = "GlobalVariableGet";
    FlowGraphAction2["AddConnection"] = "AddConnection";
    FlowGraphAction2["GetConnectionValue"] = "GetConnectionValue";
    FlowGraphAction2["SetConnectionValue"] = "SetConnectionValue";
    FlowGraphAction2["ActivateSignal"] = "ActivateSignal";
    FlowGraphAction2["ContextVariableGet"] = "ContextVariableGet";
  })(FlowGraphAction || (FlowGraphAction = {}));
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphContext.js
class FlowGraphContext {
  get enableLogging() {
    return this._enableLogging;
  }
  set enableLogging(value) {
    if (this._enableLogging === value) {
      return;
    }
    this._enableLogging = value;
    if (this._enableLogging) {
      this.logger = new FlowGraphLogger;
      this.logger.logToConsole = true;
    } else {
      this.logger = null;
    }
  }
  constructor(params) {
    this.uniqueId = RandomGUID();
    this._userVariables = {};
    this._executionVariables = {};
    this._globalContextVariables = {};
    this._connectionValues = {};
    this._pendingBlocks = [];
    this._executionId = 0;
    this.onNodeExecutedObservable = new Observable;
    this.treatDataAsRightHanded = false;
    this._enableLogging = false;
    this._configuration = params;
    this.assetsContext = params.assetsContext ?? params.scene;
  }
  hasVariable(name157) {
    return name157 in this._userVariables;
  }
  setVariable(name157, value) {
    this._userVariables[name157] = value;
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "ContextVariableSet",
      payload: {
        name: name157,
        value
      }
    });
  }
  getAsset(type, index) {
    return GetFlowGraphAssetWithType(this.assetsContext, type, index);
  }
  getVariable(name157) {
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "ContextVariableGet",
      payload: {
        name: name157,
        value: this._userVariables[name157]
      }
    });
    return this._userVariables[name157];
  }
  get userVariables() {
    return this._userVariables;
  }
  getScene() {
    return this._configuration.scene;
  }
  _getUniqueIdPrefixedName(obj, name157) {
    return `${obj.uniqueId}_${name157}`;
  }
  _getGlobalContextVariable(name157, defaultValue) {
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "GlobalVariableGet",
      payload: {
        name: name157,
        defaultValue,
        possibleValue: this._globalContextVariables[name157]
      }
    });
    if (this._hasGlobalContextVariable(name157)) {
      return this._globalContextVariables[name157];
    } else {
      return defaultValue;
    }
  }
  _setGlobalContextVariable(name157, value) {
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "GlobalVariableSet",
      payload: { name: name157, value }
    });
    this._globalContextVariables[name157] = value;
  }
  _deleteGlobalContextVariable(name157) {
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "GlobalVariableDelete",
      payload: { name: name157 }
    });
    delete this._globalContextVariables[name157];
  }
  _hasGlobalContextVariable(name157) {
    return name157 in this._globalContextVariables;
  }
  _setExecutionVariable(block, name157, value) {
    this._executionVariables[this._getUniqueIdPrefixedName(block, name157)] = value;
  }
  _getExecutionVariable(block, name157, defaultValue) {
    if (this._hasExecutionVariable(block, name157)) {
      return this._executionVariables[this._getUniqueIdPrefixedName(block, name157)];
    } else {
      return defaultValue;
    }
  }
  _deleteExecutionVariable(block, name157) {
    delete this._executionVariables[this._getUniqueIdPrefixedName(block, name157)];
  }
  _hasExecutionVariable(block, name157) {
    return this._getUniqueIdPrefixedName(block, name157) in this._executionVariables;
  }
  _hasConnectionValue(connectionPoint) {
    return connectionPoint.uniqueId in this._connectionValues;
  }
  _setConnectionValue(connectionPoint, value) {
    this._connectionValues[connectionPoint.uniqueId] = value;
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "SetConnectionValue",
      payload: {
        connectionPointId: connectionPoint.uniqueId,
        value
      }
    });
  }
  _setConnectionValueByKey(key, value) {
    this._connectionValues[key] = value;
  }
  _getConnectionValue(connectionPoint) {
    this.logger?.addLogItem({
      time: Date.now(),
      className: this.getClassName(),
      uniqueId: this.uniqueId,
      action: "GetConnectionValue",
      payload: {
        connectionPointId: connectionPoint.uniqueId,
        value: this._connectionValues[connectionPoint.uniqueId]
      }
    });
    return this._connectionValues[connectionPoint.uniqueId];
  }
  get configuration() {
    return this._configuration;
  }
  get hasPendingBlocks() {
    return this._pendingBlocks.length > 0;
  }
  _addPendingBlock(block) {
    if (this._pendingBlocks.includes(block)) {
      return;
    }
    this._pendingBlocks.push(block);
    this._pendingBlocks.sort((a, b) => a.priority - b.priority);
  }
  _removePendingBlock(block) {
    const index = this._pendingBlocks.indexOf(block);
    if (index !== -1) {
      this._pendingBlocks.splice(index, 1);
    }
  }
  _clearPendingBlocks() {
    for (const block of this._pendingBlocks) {
      block._cancelPendingTasks(this);
    }
    this._pendingBlocks.length = 0;
  }
  _notifyExecuteNode(node) {
    this.onNodeExecutedObservable.notifyObservers(node);
    this.logger?.addLogItem({
      time: Date.now(),
      className: node.getClassName(),
      uniqueId: node.uniqueId,
      action: "ExecuteBlock"
    });
  }
  _notifyOnTick(framePayload) {
    this._setGlobalContextVariable("timeSinceStart", framePayload.timeSinceStart);
    this._setGlobalContextVariable("deltaTime", framePayload.deltaTime);
    for (const block of this._pendingBlocks) {
      block._executeOnTick?.(this);
    }
  }
  _increaseExecutionId() {
    this._executionId++;
  }
  get executionId() {
    return this._executionId;
  }
  serialize(serializationObject = {}, valueSerializationFunction = defaultValueSerializationFunction) {
    serializationObject.uniqueId = this.uniqueId;
    serializationObject._userVariables = {};
    for (const key in this._userVariables) {
      valueSerializationFunction(key, this._userVariables[key], serializationObject._userVariables);
    }
    serializationObject._connectionValues = {};
    for (const key in this._connectionValues) {
      valueSerializationFunction(key, this._connectionValues[key], serializationObject._connectionValues);
    }
    if (this.assetsContext !== this.getScene()) {
      serializationObject._assetsContext = {
        meshes: this.assetsContext.meshes.map((m) => m.id),
        materials: this.assetsContext.materials.map((m) => m.id),
        textures: this.assetsContext.textures.map((m) => m.name),
        animations: this.assetsContext.animations.map((m) => m.name),
        lights: this.assetsContext.lights.map((m) => m.id),
        cameras: this.assetsContext.cameras.map((m) => m.id),
        sounds: this.assetsContext.sounds?.map((m) => m.name),
        skeletons: this.assetsContext.skeletons.map((m) => m.id),
        particleSystems: this.assetsContext.particleSystems.map((m) => m.name),
        geometries: this.assetsContext.geometries.map((m) => m.id),
        multiMaterials: this.assetsContext.multiMaterials.map((m) => m.id),
        transformNodes: this.assetsContext.transformNodes.map((m) => m.id)
      };
    }
  }
  getClassName() {
    return "FlowGraphContext";
  }
}
var init_flowGraphContext = __esm(() => {
  init_tslib_es6();
  init_decorators();
  init_guid();
  init_serialization();
  init_observable();
  init_flowGraphAssetsContext();
  init_flowGraphLogger();
  __decorate([
    serialize()
  ], FlowGraphContext.prototype, "uniqueId", undefined);
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphConnection.js
class FlowGraphConnection {
  constructor(name157, _connectionType, _ownerBlock) {
    this._ownerBlock = _ownerBlock;
    this._connectedPoint = [];
    this.uniqueId = RandomGUID();
    this.connectedPointIds = [];
    this.name = name157;
    this._connectionType = _connectionType;
  }
  get connectionType() {
    return this._connectionType;
  }
  _isSingularConnection() {
    return true;
  }
  isConnected() {
    return this._connectedPoint.length > 0;
  }
  connectTo(point) {
    if (this._connectionType === point._connectionType) {
      throw new Error(`Cannot connect two points of type ${this.connectionType}`);
    }
    if (this._isSingularConnection() && this._connectedPoint.length > 0 || point._isSingularConnection() && point._connectedPoint.length > 0) {
      throw new Error("Max number of connections for point reached");
    }
    this._connectedPoint.push(point);
    point._connectedPoint.push(this);
  }
  disconnectFrom(point, removeFromLocal = true) {
    const indexLocal = this._connectedPoint.indexOf(point);
    const indexConnected = point._connectedPoint.indexOf(this);
    if (indexLocal === -1 || indexConnected === -1) {
      return;
    }
    if (removeFromLocal) {
      this._connectedPoint.splice(indexLocal, 1);
    }
    point._connectedPoint.splice(indexConnected, 1);
  }
  disconnectFromAll() {
    for (const point of this._connectedPoint) {
      this.disconnectFrom(point, false);
    }
    this._connectedPoint.length = 0;
  }
  dispose() {
    for (const point of this._connectedPoint) {
      this.disconnectFrom(point);
    }
  }
  serialize(serializationObject = {}) {
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.name = this.name;
    serializationObject._connectionType = this._connectionType;
    serializationObject.connectedPointIds = [];
    serializationObject.className = this.getClassName();
    for (const point of this._connectedPoint) {
      serializationObject.connectedPointIds.push(point.uniqueId);
    }
  }
  getClassName() {
    return "FGConnection";
  }
  deserialize(serializationObject) {
    this.uniqueId = serializationObject.uniqueId;
    this.name = serializationObject.name;
    this._connectionType = serializationObject._connectionType;
    this.connectedPointIds = serializationObject.connectedPointIds;
  }
}
var FlowGraphConnectionType;
var init_flowGraphConnection = __esm(() => {
  init_guid();
  (function(FlowGraphConnectionType2) {
    FlowGraphConnectionType2[FlowGraphConnectionType2["Input"] = 0] = "Input";
    FlowGraphConnectionType2[FlowGraphConnectionType2["Output"] = 1] = "Output";
  })(FlowGraphConnectionType || (FlowGraphConnectionType = {}));
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphDataConnection.js
var FlowGraphDataConnection;
var init_flowGraphDataConnection = __esm(() => {
  init_typeStore();
  init_flowGraphConnection();
  init_observable();
  init_serialization();
  FlowGraphDataConnection = class FlowGraphDataConnection extends FlowGraphConnection {
    constructor(name157, connectionType, ownerBlock, richType, _defaultValue = richType.defaultValue, _optional = false) {
      super(name157, connectionType, ownerBlock);
      this.richType = richType;
      this._defaultValue = _defaultValue;
      this._optional = _optional;
      this._isDisabled = false;
      this._lastValue = null;
      this.dataTransformer = null;
      this.onValueChangedObservable = new Observable;
    }
    get optional() {
      return this._optional;
    }
    get isDisabled() {
      return this._isDisabled;
    }
    set isDisabled(value) {
      if (this._isDisabled === value) {
        return;
      }
      this._isDisabled = value;
      if (this._isDisabled) {
        this.disconnectFromAll();
      }
    }
    _isSingularConnection() {
      return this.connectionType === 0;
    }
    setValue(value, context) {
      if (context._getConnectionValue(this) === value) {
        return;
      }
      context._setConnectionValue(this, value);
      this.onValueChangedObservable.notifyObservers(value);
    }
    resetToDefaultValue(context) {
      context._setConnectionValue(this, this._defaultValue);
    }
    connectTo(point) {
      if (this._isDisabled) {
        return;
      }
      super.connectTo(point);
    }
    _getValueOrDefault(context) {
      const val = context._getConnectionValue(this) ?? this._defaultValue;
      return this.dataTransformer ? this.dataTransformer(val) : val;
    }
    getValue(context) {
      if (this.connectionType === 1) {
        context._notifyExecuteNode(this._ownerBlock);
        this._ownerBlock._updateOutputs(context);
        const value2 = this._getValueOrDefault(context);
        this._lastValue = value2;
        return this.richType.typeTransformer ? this.richType.typeTransformer(value2) : value2;
      }
      const value = !this.isConnected() ? this._getValueOrDefault(context) : this._connectedPoint[0].getValue(context);
      this._lastValue = value;
      return this.richType.typeTransformer ? this.richType.typeTransformer(value) : value;
    }
    _getLastValue() {
      return this._lastValue;
    }
    getClassName() {
      return "FlowGraphDataConnection";
    }
    serialize(serializationObject = {}) {
      super.serialize(serializationObject);
      serializationObject.richType = {};
      this.richType.serialize(serializationObject.richType);
      serializationObject.optional = this._optional;
      defaultValueSerializationFunction("defaultValue", this._defaultValue, serializationObject);
    }
  };
  RegisterClass("FlowGraphDataConnection", FlowGraphDataConnection);
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphBlock.js
class FlowGraphBlock {
  constructor(config) {
    this.config = config;
    this.uniqueId = RandomGUID();
    this.name = this.config?.name ?? this.getClassName();
    this.dataInputs = [];
    this.dataOutputs = [];
  }
  _updateOutputs(_context) {}
  registerDataInput(name157, richType, defaultValue) {
    const input = new FlowGraphDataConnection(name157, 0, this, richType, defaultValue);
    this.dataInputs.push(input);
    return input;
  }
  registerDataOutput(name157, richType, defaultValue) {
    const output = new FlowGraphDataConnection(name157, 1, this, richType, defaultValue);
    this.dataOutputs.push(output);
    return output;
  }
  getDataInput(name157) {
    return this.dataInputs.find((i) => i.name === name157);
  }
  getDataOutput(name157) {
    return this.dataOutputs.find((i) => i.name === name157);
  }
  serialize(serializationObject = {}, _valueSerializeFunction = defaultValueSerializationFunction) {
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.config = {};
    if (this.config) {
      const config = this.config;
      Object.keys(this.config).forEach((key) => {
        _valueSerializeFunction(key, config[key], serializationObject.config);
      });
    }
    serializationObject.dataInputs = [];
    serializationObject.dataOutputs = [];
    serializationObject.className = this.getClassName();
    for (const input of this.dataInputs) {
      const serializedInput = {};
      input.serialize(serializedInput);
      serializationObject.dataInputs.push(serializedInput);
    }
    for (const output of this.dataOutputs) {
      const serializedOutput = {};
      output.serialize(serializedOutput);
      serializationObject.dataOutputs.push(serializedOutput);
    }
  }
  deserialize(_serializationObject) {}
  _log(context, action2, payload) {
    context.logger?.addLogItem({
      action: action2,
      payload,
      className: this.getClassName(),
      uniqueId: this.uniqueId
    });
  }
  getClassName() {
    return "FlowGraphBlock";
  }
}
var init_flowGraphBlock = __esm(() => {
  init_guid();
  init_flowGraphDataConnection();
  init_serialization();
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphSignalConnection.js
var FlowGraphSignalConnection;
var init_flowGraphSignalConnection = __esm(() => {
  init_flowGraphConnection();
  init_typeStore();
  FlowGraphSignalConnection = class FlowGraphSignalConnection extends FlowGraphConnection {
    constructor() {
      super(...arguments);
      this.priority = 0;
    }
    _isSingularConnection() {
      return false;
    }
    connectTo(point) {
      super.connectTo(point);
      this._connectedPoint.sort((a, b) => b.priority - a.priority);
    }
    _activateSignal(context) {
      context.logger?.addLogItem({
        action: "ActivateSignal",
        className: this._ownerBlock.getClassName(),
        uniqueId: this._ownerBlock.uniqueId,
        payload: {
          connectionType: this.connectionType,
          name: this.name
        }
      });
      if (this.connectionType === 0) {
        context._notifyExecuteNode(this._ownerBlock);
        this._ownerBlock._execute(context, this);
        context._increaseExecutionId();
      } else {
        for (const connectedPoint of this._connectedPoint) {
          connectedPoint._activateSignal(context);
        }
      }
    }
  };
  RegisterClass("FlowGraphSignalConnection", FlowGraphSignalConnection);
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphExecutionBlock.js
var FlowGraphExecutionBlock;
var init_flowGraphExecutionBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphSignalConnection();
  FlowGraphExecutionBlock = class FlowGraphExecutionBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.priority = 0;
      this.signalInputs = [];
      this.signalOutputs = [];
      this.in = this._registerSignalInput("in");
      this.error = this._registerSignalOutput("error");
    }
    _registerSignalInput(name157) {
      const input = new FlowGraphSignalConnection(name157, 0, this);
      this.signalInputs.push(input);
      return input;
    }
    _registerSignalOutput(name157) {
      const output = new FlowGraphSignalConnection(name157, 1, this);
      this.signalOutputs.push(output);
      return output;
    }
    _unregisterSignalInput(name157) {
      const index = this.signalInputs.findIndex((input) => input.name === name157);
      if (index !== -1) {
        this.signalInputs[index].dispose();
        this.signalInputs.splice(index, 1);
      }
    }
    _unregisterSignalOutput(name157) {
      const index = this.signalOutputs.findIndex((output) => output.name === name157);
      if (index !== -1) {
        this.signalOutputs[index].dispose();
        this.signalOutputs.splice(index, 1);
      }
    }
    _reportError(context, error) {
      this.error.payload = typeof error === "string" ? new Error(error) : error;
      this.error._activateSignal(context);
    }
    getSignalInput(name157) {
      return this.signalInputs.find((input) => input.name === name157);
    }
    getSignalOutput(name157) {
      return this.signalOutputs.find((output) => output.name === name157);
    }
    serialize(serializationObject = {}) {
      super.serialize(serializationObject);
      serializationObject.signalInputs = [];
      serializationObject.signalOutputs = [];
      for (const input of this.signalInputs) {
        const serializedInput = {};
        input.serialize(serializedInput);
        serializationObject.signalInputs.push(serializedInput);
      }
      for (const output of this.signalOutputs) {
        const serializedOutput = {};
        output.serialize(serializedOutput);
        serializationObject.signalOutputs.push(serializedOutput);
      }
    }
    deserialize(serializationObject) {
      for (let i = 0;i < serializationObject.signalInputs.length; i++) {
        const signalInput = this.getSignalInput(serializationObject.signalInputs[i].name);
        if (signalInput) {
          signalInput.deserialize(serializationObject.signalInputs[i]);
        } else {
          throw new Error("Could not find signal input with name " + serializationObject.signalInputs[i].name + " in block " + serializationObject.className);
        }
      }
      for (let i = 0;i < serializationObject.signalOutputs.length; i++) {
        const signalOutput = this.getSignalOutput(serializationObject.signalOutputs[i].name);
        if (signalOutput) {
          signalOutput.deserialize(serializationObject.signalOutputs[i]);
        } else {
          throw new Error("Could not find signal output with name " + serializationObject.signalOutputs[i].name + " in block " + serializationObject.className);
        }
      }
    }
    getClassName() {
      return "FlowGraphExecutionBlock";
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphSceneEventCoordinator.js
class FlowGraphSceneEventCoordinator {
  constructor(scene) {
    this.onEventTriggeredObservable = new Observable;
    this.sceneReadyTriggered = false;
    this._pointerUnderMeshState = {};
    this._startingTime = 0;
    this._scene = scene;
    this._initialize();
  }
  _initialize() {
    this._sceneReadyObserver = this._scene.onReadyObservable.add(() => {
      if (!this.sceneReadyTriggered) {
        this.onEventTriggeredObservable.notifyObservers({ type: "SceneReady" });
        this.sceneReadyTriggered = true;
      }
    });
    this._sceneDisposeObserver = this._scene.onDisposeObservable.add(() => {
      this.onEventTriggeredObservable.notifyObservers({ type: "SceneDispose" });
    });
    this._sceneOnBeforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => {
      const deltaTime = this._scene.getEngine().getDeltaTime() / 1000;
      this.onEventTriggeredObservable.notifyObservers({
        type: "SceneBeforeRender",
        payload: {
          timeSinceStart: this._startingTime,
          deltaTime
        }
      });
      this._startingTime += deltaTime;
    });
    this._meshPickedObserver = this._scene.onPointerObservable.add((pointerInfo) => {
      this.onEventTriggeredObservable.notifyObservers({ type: "MeshPick", payload: pointerInfo });
    }, PointerEventTypes.POINTERPICK);
    this._meshUnderPointerObserver = this._scene.onMeshUnderPointerUpdatedObservable.add((data) => {
      const pointerId = data.pointerId;
      const mesh = data.mesh;
      const previousState = this._pointerUnderMeshState[pointerId];
      if (!previousState && mesh) {
        this.onEventTriggeredObservable.notifyObservers({ type: "PointerOver", payload: { pointerId, mesh } });
      } else if (previousState && !mesh) {
        this.onEventTriggeredObservable.notifyObservers({ type: "PointerOut", payload: { pointerId, mesh: previousState } });
      } else if (previousState && mesh && previousState !== mesh) {
        this.onEventTriggeredObservable.notifyObservers({ type: "PointerOut", payload: { pointerId, mesh: previousState, over: mesh } });
        this.onEventTriggeredObservable.notifyObservers({ type: "PointerOver", payload: { pointerId, mesh, out: previousState } });
      }
      this._pointerUnderMeshState[pointerId] = mesh;
    }, PointerEventTypes.POINTERMOVE);
  }
  dispose() {
    this._sceneDisposeObserver?.remove();
    this._sceneReadyObserver?.remove();
    this._sceneOnBeforeRenderObserver?.remove();
    this._meshPickedObserver?.remove();
    this._meshUnderPointerObserver?.remove();
    this.onEventTriggeredObservable.clear();
  }
}
var init_flowGraphSceneEventCoordinator = __esm(() => {
  init_pointerEvents();
  init_observable();
});

// node_modules/@babylonjs/core/FlowGraph/utils.js
function _isADescendantOf(mesh1, mesh2) {
  return !!(mesh1.parent && (mesh1.parent === mesh2 || _isADescendantOf(mesh1.parent, mesh2)));
}
function _getClassNameOf(v) {
  if (v.getClassName) {
    return v.getClassName();
  }
  return;
}
function _areSameVectorClass(className, className2) {
  return className === className2 && (className === "Vector2" || className === "Vector3" || className === "Vector4");
}
function _areSameMatrixClass(className, className2) {
  return className === className2 && (className === "Matrix" || className === "Matrix2D" || className === "Matrix3D");
}
function _areSameIntegerClass(className, className2) {
  return className === "FlowGraphInteger" && className2 === "FlowGraphInteger";
}
function isNumeric(a, validIfNaN) {
  const isNumeric2 = typeof a === "number" || typeof a?.value === "number";
  if (isNumeric2 && !validIfNaN) {
    return !isNaN(getNumericValue(a));
  }
  return isNumeric2;
}
function getNumericValue(a) {
  return typeof a === "number" ? a : a.value;
}

// node_modules/@babylonjs/core/FlowGraph/flowGraph.js
class FlowGraph {
  get state() {
    return this._state;
  }
  set state(value) {
    this._state = value;
    this.onStateChangedObservable.notifyObservers(value);
  }
  constructor(params) {
    this.onStateChangedObservable = new Observable;
    this._eventBlocks = {
      ["SceneReady"]: [],
      ["SceneDispose"]: [],
      ["SceneBeforeRender"]: [],
      ["MeshPick"]: [],
      ["PointerDown"]: [],
      ["PointerUp"]: [],
      ["PointerMove"]: [],
      ["PointerOver"]: [],
      ["PointerOut"]: [],
      ["SceneAfterRender"]: [],
      ["NoTrigger"]: []
    };
    this._executionContexts = [];
    this._state = 0;
    this._scene = params.scene;
    this._sceneEventCoordinator = new FlowGraphSceneEventCoordinator(this._scene);
    this._coordinator = params.coordinator;
    this._eventObserver = this._sceneEventCoordinator.onEventTriggeredObservable.add((event) => {
      for (const context of this._executionContexts) {
        const order = this._getContextualOrder(event.type, context);
        for (const block of order) {
          if (!block._executeEvent(context, event.payload)) {
            break;
          }
        }
      }
      switch (event.type) {
        case "SceneReady":
          this._sceneEventCoordinator.sceneReadyTriggered = true;
          break;
        case "SceneBeforeRender":
          for (const context of this._executionContexts) {
            context._notifyOnTick(event.payload);
          }
          break;
        case "SceneDispose":
          this.dispose();
          break;
      }
    });
  }
  createContext() {
    const context = new FlowGraphContext({ scene: this._scene, coordinator: this._coordinator });
    this._executionContexts.push(context);
    return context;
  }
  getContext(index) {
    return this._executionContexts[index];
  }
  addEventBlock(block) {
    if (block.type === "PointerOver" || block.type === "PointerOut") {
      this._scene.constantlyUpdateMeshUnderPointer = true;
    }
    if (block.type !== "NoTrigger") {
      this._eventBlocks[block.type].push(block);
    }
    if (this.state === 1) {
      for (const context of this._executionContexts) {
        block._startPendingTasks(context);
      }
    } else {
      this.onStateChangedObservable.addOnce((state) => {
        if (state === 1) {
          for (const context of this._executionContexts) {
            block._startPendingTasks(context);
          }
        }
      });
    }
  }
  start() {
    if (this.state === 1) {
      return;
    }
    if (this._executionContexts.length === 0) {
      this.createContext();
    }
    this.onStateChangedObservable.add((state) => {
      if (state === 1) {
        this._startPendingEvents();
        if (this._scene.isReady(true)) {
          this._sceneEventCoordinator.onEventTriggeredObservable.notifyObservers({ type: "SceneReady" });
        }
      }
    });
    this.state = 1;
  }
  _startPendingEvents() {
    for (const context of this._executionContexts) {
      for (const type in this._eventBlocks) {
        const order = this._getContextualOrder(type, context);
        for (const block of order) {
          block._startPendingTasks(context);
        }
      }
    }
  }
  _getContextualOrder(type, context) {
    const order = this._eventBlocks[type].sort((a, b) => b.initPriority - a.initPriority);
    if (type === "MeshPick") {
      const meshPickOrder = [];
      for (const block1 of order) {
        const mesh1 = block1.asset.getValue(context);
        let i = 0;
        for (;i < order.length; i++) {
          const block2 = order[i];
          const mesh2 = block2.asset.getValue(context);
          if (mesh1 && mesh2 && _isADescendantOf(mesh1, mesh2)) {
            break;
          }
        }
        meshPickOrder.splice(i, 0, block1);
      }
      return meshPickOrder;
    }
    return order;
  }
  dispose() {
    if (this.state === 0) {
      return;
    }
    this.state = 0;
    for (const context of this._executionContexts) {
      context._clearPendingBlocks();
    }
    this._executionContexts.length = 0;
    for (const type in this._eventBlocks) {
      this._eventBlocks[type].length = 0;
    }
    this._eventObserver?.remove();
    this._sceneEventCoordinator.dispose();
  }
  visitAllBlocks(visitor) {
    const visitList = [];
    const idsAddedToVisitList = new Set;
    for (const type in this._eventBlocks) {
      for (const block of this._eventBlocks[type]) {
        visitList.push(block);
        idsAddedToVisitList.add(block.uniqueId);
      }
    }
    while (visitList.length > 0) {
      const block = visitList.pop();
      visitor(block);
      for (const dataIn of block.dataInputs) {
        for (const connection of dataIn._connectedPoint) {
          if (!idsAddedToVisitList.has(connection._ownerBlock.uniqueId)) {
            visitList.push(connection._ownerBlock);
            idsAddedToVisitList.add(connection._ownerBlock.uniqueId);
          }
        }
      }
      if (block instanceof FlowGraphExecutionBlock) {
        for (const signalOut of block.signalOutputs) {
          for (const connection of signalOut._connectedPoint) {
            if (!idsAddedToVisitList.has(connection._ownerBlock.uniqueId)) {
              visitList.push(connection._ownerBlock);
              idsAddedToVisitList.add(connection._ownerBlock.uniqueId);
            }
          }
        }
      }
    }
  }
  serialize(serializationObject = {}, valueSerializeFunction) {
    serializationObject.allBlocks = [];
    this.visitAllBlocks((block) => {
      const serializedBlock = {};
      block.serialize(serializedBlock);
      serializationObject.allBlocks.push(serializedBlock);
    });
    serializationObject.executionContexts = [];
    for (const context of this._executionContexts) {
      const serializedContext = {};
      context.serialize(serializedContext, valueSerializeFunction);
      serializationObject.executionContexts.push(serializedContext);
    }
  }
}
var FlowGraphState;
var init_flowGraph = __esm(() => {
  init_observable();
  init_flowGraphContext();
  init_flowGraphExecutionBlock();
  init_flowGraphSceneEventCoordinator();
  (function(FlowGraphState2) {
    FlowGraphState2[FlowGraphState2["Stopped"] = 0] = "Stopped";
    FlowGraphState2[FlowGraphState2["Started"] = 1] = "Started";
  })(FlowGraphState || (FlowGraphState = {}));
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphExecutionBlockWithOutSignal.js
var FlowGraphExecutionBlockWithOutSignal;
var init_flowGraphExecutionBlockWithOutSignal = __esm(() => {
  init_flowGraphExecutionBlock();
  FlowGraphExecutionBlockWithOutSignal = class FlowGraphExecutionBlockWithOutSignal extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.out = this._registerSignalOutput("out");
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphAsyncExecutionBlock.js
var FlowGraphAsyncExecutionBlock;
var init_flowGraphAsyncExecutionBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  FlowGraphAsyncExecutionBlock = class FlowGraphAsyncExecutionBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config, events) {
      super(config);
      this._eventsSignalOutputs = {};
      this.done = this._registerSignalOutput("done");
      events?.forEach((eventName) => {
        this._eventsSignalOutputs[eventName] = this._registerSignalOutput(eventName + "Event");
      });
    }
    _executeOnTick(_context) {}
    _startPendingTasks(context) {
      if (context._getExecutionVariable(this, "_initialized", false)) {
        this._cancelPendingTasks(context);
        this._resetAfterCanceled(context);
      }
      this._preparePendingTasks(context);
      context._addPendingBlock(this);
      this.out._activateSignal(context);
      context._setExecutionVariable(this, "_initialized", true);
    }
    _resetAfterCanceled(context) {
      context._deleteExecutionVariable(this, "_initialized");
      context._removePendingBlock(this);
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphEventBlock.js
var FlowGraphEventBlock;
var init_flowGraphEventBlock = __esm(() => {
  init_flowGraphAsyncExecutionBlock();
  FlowGraphEventBlock = class FlowGraphEventBlock extends FlowGraphAsyncExecutionBlock {
    constructor() {
      super(...arguments);
      this.initPriority = 0;
      this.type = "NoTrigger";
    }
    _execute(context) {
      context._notifyExecuteNode(this);
      this.done._activateSignal(context);
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphCoordinator.js
class FlowGraphCoordinator {
  constructor(config) {
    this.config = config;
    this.dispatchEventsSynchronously = true;
    this._flowGraphs = [];
    this._customEventsMap = new Map;
    this._eventExecutionCounter = new Map;
    this._executeOnNextFrame = [];
    this._disposeObserver = this.config.scene.onDisposeObservable.add(() => {
      this.dispose();
    });
    this._onBeforeRenderObserver = this.config.scene.onBeforeRenderObservable.add(() => {
      this._eventExecutionCounter.clear();
      if (this._executeOnNextFrame.length) {
        this._executeOnNextFrame.forEach((event) => {
          this.notifyCustomEvent(event.id, event.data, false);
        });
        this._executeOnNextFrame.length = 0;
      }
    });
    const coordinators = FlowGraphCoordinator.SceneCoordinators.get(this.config.scene) ?? [];
    coordinators.push(this);
  }
  createGraph() {
    const graph = new FlowGraph({ scene: this.config.scene, coordinator: this });
    this._flowGraphs.push(graph);
    return graph;
  }
  removeGraph(graph) {
    const index = this._flowGraphs.indexOf(graph);
    if (index !== -1) {
      graph.dispose();
      this._flowGraphs.splice(index, 1);
    }
  }
  start() {
    this._flowGraphs.forEach((graph) => graph.start());
  }
  dispose() {
    this._flowGraphs.forEach((graph) => graph.dispose());
    this._flowGraphs.length = 0;
    this._disposeObserver?.remove();
    this._onBeforeRenderObserver?.remove();
    const coordinators = FlowGraphCoordinator.SceneCoordinators.get(this.config.scene) ?? [];
    const index = coordinators.indexOf(this);
    if (index !== -1) {
      coordinators.splice(index, 1);
    }
  }
  serialize(serializationObject, valueSerializeFunction) {
    serializationObject._flowGraphs = [];
    this._flowGraphs.forEach((graph) => {
      const serializedGraph = {};
      graph.serialize(serializedGraph, valueSerializeFunction);
      serializationObject._flowGraphs.push(serializedGraph);
    });
    serializationObject.dispatchEventsSynchronously = this.dispatchEventsSynchronously;
  }
  get flowGraphs() {
    return this._flowGraphs;
  }
  getCustomEventObservable(id) {
    let observable = this._customEventsMap.get(id);
    if (!observable) {
      observable = new Observable;
      this._customEventsMap.set(id, observable);
    }
    return observable;
  }
  notifyCustomEvent(id, data, async = !this.dispatchEventsSynchronously) {
    if (async) {
      this._executeOnNextFrame.push({ id, data });
      return;
    }
    if (this._eventExecutionCounter.has(id)) {
      const count = this._eventExecutionCounter.get(id);
      this._eventExecutionCounter.set(id, count + 1);
      if (count >= FlowGraphCoordinator.MaxEventTypeExecutionPerFrame) {
        count === FlowGraphCoordinator.MaxEventTypeExecutionPerFrame && Logger.Warn(`FlowGraphCoordinator: Too many executions of event "${id}".`);
        return;
      }
    } else {
      this._eventExecutionCounter.set(id, 1);
    }
    const observable = this._customEventsMap.get(id);
    if (observable) {
      observable.notifyObservers(data);
    }
  }
}
var init_flowGraphCoordinator = __esm(() => {
  init_observable();
  init_flowGraph();
  init_logger();
  FlowGraphCoordinator.MaxEventsPerType = 30;
  FlowGraphCoordinator.MaxEventTypeExecutionPerFrame = 30;
  FlowGraphCoordinator.SceneCoordinators = new Map;
});

// node_modules/@babylonjs/core/FlowGraph/flowGraphPathConverterComponent.js
class FlowGraphPathConverterComponent {
  constructor(path, ownerBlock) {
    this.path = path;
    this.ownerBlock = ownerBlock;
    this.templatedInputs = [];
    let match = pathHasTemplatesRegex.exec(path);
    const templateSet = new Set;
    while (match) {
      const [, matchGroup] = match;
      if (templateSet.has(matchGroup)) {
        throw new Error("Duplicate template variable detected.");
      }
      templateSet.add(matchGroup);
      this.templatedInputs.push(ownerBlock.registerDataInput(matchGroup, RichTypeFlowGraphInteger, new FlowGraphInteger(0)));
      match = pathHasTemplatesRegex.exec(path);
    }
  }
  getAccessor(pathConverter, context) {
    let finalPath = this.path;
    for (const templatedInput of this.templatedInputs) {
      const valueToReplace = templatedInput.getValue(context).value;
      if (typeof valueToReplace !== "number" || valueToReplace < 0) {
        throw new Error("Invalid value for templated input.");
      }
      finalPath = finalPath.replace(`{${templatedInput.name}}`, valueToReplace.toString());
    }
    return pathConverter.convert(finalPath);
  }
}
var pathHasTemplatesRegex;
var init_flowGraphPathConverterComponent = __esm(() => {
  init_flowGraphInteger();
  init_flowGraphRichTypes();
  pathHasTemplatesRegex = new RegExp(/\/\{(\w+)\}\//g);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/flowGraphConsoleLogBlock.js
var FlowGraphConsoleLogBlock;
var init_flowGraphConsoleLogBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  init_typeStore();
  init_logger();
  FlowGraphConsoleLogBlock = class FlowGraphConsoleLogBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.message = this.registerDataInput("message", RichTypeAny);
      this.logType = this.registerDataInput("logType", RichTypeAny, "log");
      if (config?.messageTemplate) {
        const matches = this._getTemplateMatches(config.messageTemplate);
        for (const match of matches) {
          this.registerDataInput(match, RichTypeAny);
        }
      }
    }
    _execute(context) {
      const typeValue = this.logType.getValue(context);
      const messageValue = this._getMessageValue(context);
      if (typeValue === "warn") {
        Logger.Warn(messageValue);
      } else if (typeValue === "error") {
        Logger.Error(messageValue);
      } else {
        Logger.Log(messageValue);
      }
      this.out._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphConsoleLogBlock";
    }
    _getMessageValue(context) {
      if (this.config?.messageTemplate) {
        let template = this.config.messageTemplate;
        const matches = this._getTemplateMatches(template);
        for (const match of matches) {
          const value = this.getDataInput(match)?.getValue(context);
          if (value !== undefined) {
            template = template.replace(new RegExp(`\\{${match}\\}`, "g"), value.toString());
          }
        }
        return template;
      } else {
        return this.message.getValue(context);
      }
    }
    _getTemplateMatches(template) {
      const regex = /\{([^}]+)\}/g;
      const matches = [];
      let match;
      while ((match = regex.exec(template)) !== null) {
        matches.push(match[1]);
      }
      return matches;
    }
  };
  RegisterClass("FlowGraphConsoleLogBlock", FlowGraphConsoleLogBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphBranchBlock.js
var FlowGraphBranchBlock;
var init_flowGraphBranchBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_flowGraphExecutionBlock();
  init_typeStore();
  FlowGraphBranchBlock = class FlowGraphBranchBlock extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.condition = this.registerDataInput("condition", RichTypeBoolean);
      this.onTrue = this._registerSignalOutput("onTrue");
      this.onFalse = this._registerSignalOutput("onFalse");
    }
    _execute(context) {
      if (this.condition.getValue(context)) {
        this.onTrue._activateSignal(context);
      } else {
        this.onFalse._activateSignal(context);
      }
    }
    getClassName() {
      return "FlowGraphBranchBlock";
    }
  };
  RegisterClass("FlowGraphBranchBlock", FlowGraphBranchBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphDoNBlock.js
var FlowGraphDoNBlock;
var init_flowGraphDoNBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphDoNBlock = class FlowGraphDoNBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config = {}) {
      super(config);
      this.config = config;
      this.config.startIndex = config.startIndex ?? new FlowGraphInteger(0);
      this.reset = this._registerSignalInput("reset");
      this.maxExecutions = this.registerDataInput("maxExecutions", RichTypeFlowGraphInteger);
      this.executionCount = this.registerDataOutput("executionCount", RichTypeFlowGraphInteger, new FlowGraphInteger(0));
    }
    _execute(context, callingSignal) {
      if (callingSignal === this.reset) {
        this.executionCount.setValue(this.config.startIndex, context);
      } else {
        const currentCountValue = this.executionCount.getValue(context);
        if (currentCountValue.value < this.maxExecutions.getValue(context).value) {
          this.executionCount.setValue(new FlowGraphInteger(currentCountValue.value + 1), context);
          this.out._activateSignal(context);
        }
      }
    }
    getClassName() {
      return "FlowGraphDoNBlock";
    }
  };
  RegisterClass("FlowGraphDoNBlock", FlowGraphDoNBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphForLoopBlock.js
var FlowGraphForLoopBlock;
var init_flowGraphForLoopBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphForLoopBlock = class FlowGraphForLoopBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.startIndex = this.registerDataInput("startIndex", RichTypeAny, 0);
      this.endIndex = this.registerDataInput("endIndex", RichTypeAny);
      this.step = this.registerDataInput("step", RichTypeNumber, 1);
      this.index = this.registerDataOutput("index", RichTypeFlowGraphInteger, new FlowGraphInteger(getNumericValue(config?.initialIndex ?? 0)));
      this.executionFlow = this._registerSignalOutput("executionFlow");
      this.completed = this._registerSignalOutput("completed");
      this._unregisterSignalOutput("out");
    }
    _execute(context) {
      const index = getNumericValue(this.startIndex.getValue(context));
      const step = this.step.getValue(context);
      let endIndex = getNumericValue(this.endIndex.getValue(context));
      for (let i = index;i < endIndex; i += step) {
        this.index.setValue(new FlowGraphInteger(i), context);
        this.executionFlow._activateSignal(context);
        endIndex = getNumericValue(this.endIndex.getValue(context));
        if (i > FlowGraphForLoopBlock.MaxLoopIterations) {
          break;
        }
      }
      this.completed._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphForLoopBlock";
    }
  };
  FlowGraphForLoopBlock.MaxLoopIterations = 1000;
  RegisterClass("FlowGraphForLoopBlock", FlowGraphForLoopBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphThrottleBlock.js
var FlowGraphThrottleBlock;
var init_flowGraphThrottleBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  FlowGraphThrottleBlock = class FlowGraphThrottleBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.reset = this._registerSignalInput("reset");
      this.duration = this.registerDataInput("duration", RichTypeNumber);
      this.lastRemainingTime = this.registerDataOutput("lastRemainingTime", RichTypeNumber, NaN);
    }
    _execute(context, callingSignal) {
      if (callingSignal === this.reset) {
        this.lastRemainingTime.setValue(NaN, context);
        context._setExecutionVariable(this, "lastRemainingTime", NaN);
        context._setExecutionVariable(this, "timestamp", 0);
        return;
      }
      const durationValue = this.duration.getValue(context);
      if (durationValue <= 0 || isNaN(durationValue) || !isFinite(durationValue)) {
        return this._reportError(context, "Invalid duration in Throttle block");
      }
      const lastRemainingTime = context._getExecutionVariable(this, "lastRemainingTime", NaN);
      const currentTime = Date.now();
      if (isNaN(lastRemainingTime)) {
        this.lastRemainingTime.setValue(0, context);
        context._setExecutionVariable(this, "lastRemainingTime", 0);
        context._setExecutionVariable(this, "timestamp", currentTime);
        return this.out._activateSignal(context);
      } else {
        const elapsedTime = currentTime - context._getExecutionVariable(this, "timestamp", 0);
        const durationInMs = durationValue * 1000;
        if (durationInMs <= elapsedTime) {
          this.lastRemainingTime.setValue(0, context);
          context._setExecutionVariable(this, "lastRemainingTime", 0);
          context._setExecutionVariable(this, "timestamp", currentTime);
          return this.out._activateSignal(context);
        } else {
          const remainingTime = durationInMs - elapsedTime;
          this.lastRemainingTime.setValue(remainingTime / 1000, context);
          context._setExecutionVariable(this, "lastRemainingTime", remainingTime);
        }
      }
    }
    getClassName() {
      return "FlowGraphThrottleBlock";
    }
  };
  RegisterClass("FlowGraphThrottleBlock", FlowGraphThrottleBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphMultiGateBlock.js
var FlowGraphMultiGateBlock;
var init_flowGraphMultiGateBlock = __esm(() => {
  init_typeStore();
  init_flowGraphExecutionBlock();
  init_flowGraphRichTypes();
  init_flowGraphInteger();
  FlowGraphMultiGateBlock = class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.outputSignals = [];
      this.reset = this._registerSignalInput("reset");
      this.lastIndex = this.registerDataOutput("lastIndex", RichTypeFlowGraphInteger, new FlowGraphInteger(-1));
      this.setNumberOfOutputSignals(config?.outputSignalCount);
    }
    _getNextIndex(indexesUsed) {
      if (!indexesUsed.includes(false)) {
        if (this.config.isLoop) {
          indexesUsed.fill(false);
        }
      }
      if (!this.config.isRandom) {
        return indexesUsed.indexOf(false);
      } else {
        const unusedIndexes = indexesUsed.map((used, index) => used ? -1 : index).filter((index) => index !== -1);
        return unusedIndexes.length ? unusedIndexes[Math.floor(Math.random() * unusedIndexes.length)] : -1;
      }
    }
    setNumberOfOutputSignals(numberOutputSignals = 1) {
      while (this.outputSignals.length > numberOutputSignals) {
        const flow = this.outputSignals.pop();
        if (flow) {
          flow.disconnectFromAll();
          this._unregisterSignalOutput(flow.name);
        }
      }
      while (this.outputSignals.length < numberOutputSignals) {
        this.outputSignals.push(this._registerSignalOutput(`out_${this.outputSignals.length}`));
      }
    }
    _execute(context, callingSignal) {
      if (!context._hasExecutionVariable(this, "indexesUsed")) {
        context._setExecutionVariable(this, "indexesUsed", this.outputSignals.map(() => false));
      }
      if (callingSignal === this.reset) {
        context._deleteExecutionVariable(this, "indexesUsed");
        this.lastIndex.setValue(new FlowGraphInteger(-1), context);
        return;
      }
      const indexesUsed = context._getExecutionVariable(this, "indexesUsed", []);
      const nextIndex = this._getNextIndex(indexesUsed);
      if (nextIndex > -1) {
        this.lastIndex.setValue(new FlowGraphInteger(nextIndex), context);
        indexesUsed[nextIndex] = true;
        context._setExecutionVariable(this, "indexesUsed", indexesUsed);
        this.outputSignals[nextIndex]._activateSignal(context);
      }
    }
    getClassName() {
      return "FlowGraphMultiGateBlock";
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
      serializationObject.config.outputSignalCount = this.config.outputSignalCount;
      serializationObject.config.isRandom = this.config.isRandom;
      serializationObject.config.loop = this.config.isLoop;
      serializationObject.config.startIndex = this.config.startIndex;
    }
  };
  RegisterClass("FlowGraphMultiGateBlock", FlowGraphMultiGateBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphSwitchBlock.js
var FlowGraphSwitchBlock;
var init_flowGraphSwitchBlock = __esm(() => {
  init_flowGraphExecutionBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphSwitchBlock = class FlowGraphSwitchBlock extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.default = this._registerSignalOutput("default");
      this._caseToOutputFlow = new Map;
      this.case = this.registerDataInput("case", RichTypeAny);
      (this.config.cases || []).forEach((caseValue) => {
        this._caseToOutputFlow.set(caseValue, this._registerSignalOutput(`out_${caseValue}`));
      });
    }
    _execute(context, _callingSignal) {
      const selectionValue = this.case.getValue(context);
      let outputFlow;
      if (isNumeric(selectionValue)) {
        outputFlow = this._getOutputFlowForCase(getNumericValue(selectionValue));
      } else {
        outputFlow = this._getOutputFlowForCase(selectionValue);
      }
      if (outputFlow) {
        outputFlow._activateSignal(context);
      } else {
        this.default._activateSignal(context);
      }
    }
    addCase(newCase) {
      if (this.config.cases.includes(newCase)) {
        return;
      }
      this.config.cases.push(newCase);
      this._caseToOutputFlow.set(newCase, this._registerSignalOutput(`out_${newCase}`));
    }
    removeCase(caseToRemove) {
      if (!this.config.cases.includes(caseToRemove)) {
        return;
      }
      const index = this.config.cases.indexOf(caseToRemove);
      this.config.cases.splice(index, 1);
      this._caseToOutputFlow.delete(caseToRemove);
    }
    _getOutputFlowForCase(caseValue) {
      return this._caseToOutputFlow.get(caseValue);
    }
    getClassName() {
      return "FlowGraphSwitchBlock";
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
      serializationObject.cases = this.config.cases;
    }
  };
  RegisterClass("FlowGraphSwitchBlock", FlowGraphSwitchBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphWaitAllBlock.js
var FlowGraphWaitAllBlock;
var init_flowGraphWaitAllBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  init_flowGraphRichTypes();
  FlowGraphWaitAllBlock = class FlowGraphWaitAllBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.config = config;
      this.inFlows = [];
      this._cachedActivationState = [];
      this.reset = this._registerSignalInput("reset");
      this.completed = this._registerSignalOutput("completed");
      this.remainingInputs = this.registerDataOutput("remainingInputs", RichTypeNumber, this.config.inputSignalCount || 0);
      for (let i = 0;i < this.config.inputSignalCount; i++) {
        this.inFlows.push(this._registerSignalInput(`in_${i}`));
      }
      this._unregisterSignalInput("in");
    }
    _getCurrentActivationState(context) {
      const activationState = this._cachedActivationState;
      activationState.length = 0;
      if (!context._hasExecutionVariable(this, "activationState")) {
        for (let i = 0;i < this.config.inputSignalCount; i++) {
          activationState.push(false);
        }
      } else {
        const contextActivationState = context._getExecutionVariable(this, "activationState", []);
        for (let i = 0;i < contextActivationState.length; i++) {
          activationState.push(contextActivationState[i]);
        }
      }
      return activationState;
    }
    _execute(context, callingSignal) {
      const activationState = this._getCurrentActivationState(context);
      if (callingSignal === this.reset) {
        for (let i = 0;i < this.config.inputSignalCount; i++) {
          activationState[i] = false;
        }
      } else {
        const index = this.inFlows.indexOf(callingSignal);
        if (index >= 0) {
          activationState[index] = true;
        }
      }
      this.remainingInputs.setValue(activationState.filter((v) => !v).length, context);
      context._setExecutionVariable(this, "activationState", activationState.slice());
      if (!activationState.includes(false)) {
        this.completed._activateSignal(context);
        for (let i = 0;i < this.config.inputSignalCount; i++) {
          activationState[i] = false;
        }
      } else {
        callingSignal !== this.reset && this.out._activateSignal(context);
      }
    }
    getClassName() {
      return "FlowGraphWaitAllBlock";
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
      serializationObject.config.inputFlows = this.config.inputSignalCount;
    }
  };
  RegisterClass("FlowGraphWaitAllBlock", FlowGraphWaitAllBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphCounterBlock.js
var FlowGraphCallCounterBlock;
var init_flowGraphCounterBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  FlowGraphCallCounterBlock = class FlowGraphCallCounterBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.count = this.registerDataOutput("count", RichTypeNumber);
      this.reset = this._registerSignalInput("reset");
    }
    _execute(context, callingSignal) {
      if (callingSignal === this.reset) {
        context._setExecutionVariable(this, "count", 0);
        this.count.setValue(0, context);
        return;
      }
      const countValue = context._getExecutionVariable(this, "count", 0) + 1;
      context._setExecutionVariable(this, "count", countValue);
      this.count.setValue(countValue, context);
      this.out._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphCallCounterBlock";
    }
  };
  RegisterClass("FlowGraphCallCounterBlock", FlowGraphCallCounterBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphWhileLoopBlock.js
var FlowGraphWhileLoopBlock;
var init_flowGraphWhileLoopBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphExecutionBlockWithOutSignal();
  init_logger();
  FlowGraphWhileLoopBlock = class FlowGraphWhileLoopBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.config = config;
      this.condition = this.registerDataInput("condition", RichTypeBoolean);
      this.executionFlow = this._registerSignalOutput("executionFlow");
      this.completed = this._registerSignalOutput("completed");
      this._unregisterSignalOutput("out");
    }
    _execute(context, _callingSignal) {
      let conditionValue = this.condition.getValue(context);
      if (this.config?.doWhile && !conditionValue) {
        this.executionFlow._activateSignal(context);
      }
      let i = 0;
      while (conditionValue) {
        this.executionFlow._activateSignal(context);
        ++i;
        if (i >= FlowGraphWhileLoopBlock.MaxLoopCount) {
          Logger.Warn("FlowGraphWhileLoopBlock: Max loop count reached. Breaking.");
          break;
        }
        conditionValue = this.condition.getValue(context);
      }
      this.completed._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphWhileLoopBlock";
    }
  };
  FlowGraphWhileLoopBlock.MaxLoopCount = 1000;
  RegisterClass("FlowGraphWhileLoopBlock", FlowGraphWhileLoopBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphDebounceBlock.js
var FlowGraphDebounceBlock;
var init_flowGraphDebounceBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  FlowGraphDebounceBlock = class FlowGraphDebounceBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.count = this.registerDataInput("count", RichTypeNumber);
      this.reset = this._registerSignalInput("reset");
      this.currentCount = this.registerDataOutput("currentCount", RichTypeNumber);
    }
    _execute(context, callingSignal) {
      if (callingSignal === this.reset) {
        context._setExecutionVariable(this, "debounceCount", 0);
        return;
      }
      const count = this.count.getValue(context);
      const currentCount = context._getExecutionVariable(this, "debounceCount", 0);
      const newCount = currentCount + 1;
      this.currentCount.setValue(newCount, context);
      context._setExecutionVariable(this, "debounceCount", newCount);
      if (newCount >= count) {
        this.out._activateSignal(context);
        context._setExecutionVariable(this, "debounceCount", 0);
      }
    }
    getClassName() {
      return "FlowGraphDebounceBlock";
    }
  };
  RegisterClass("FlowGraphDebounceBlock", FlowGraphDebounceBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphFlipFlopBlock.js
var FlowGraphFlipFlopBlock;
var init_flowGraphFlipFlopBlock = __esm(() => {
  init_flowGraphExecutionBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphFlipFlopBlock = class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.onOn = this._registerSignalOutput("onOn");
      this.onOff = this._registerSignalOutput("onOff");
      this.value = this.registerDataOutput("value", RichTypeBoolean);
    }
    _execute(context, _callingSignal) {
      let value = context._getExecutionVariable(this, "value", typeof this.config?.startValue === "boolean" ? !this.config.startValue : false);
      value = !value;
      context._setExecutionVariable(this, "value", value);
      this.value.setValue(value, context);
      if (value) {
        this.onOn._activateSignal(context);
      } else {
        this.onOff._activateSignal(context);
      }
    }
    getClassName() {
      return "FlowGraphFlipFlopBlock";
    }
  };
  RegisterClass("FlowGraphFlipFlopBlock", FlowGraphFlipFlopBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphSequenceBlock.js
var FlowGraphSequenceBlock;
var init_flowGraphSequenceBlock = __esm(() => {
  init_typeStore();
  init_flowGraphExecutionBlock();
  FlowGraphSequenceBlock = class FlowGraphSequenceBlock extends FlowGraphExecutionBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.executionSignals = [];
      this.setNumberOfOutputSignals(this.config.outputSignalCount);
    }
    _execute(context) {
      for (let i = 0;i < this.executionSignals.length; i++) {
        this.executionSignals[i]._activateSignal(context);
      }
    }
    setNumberOfOutputSignals(outputSignalCount = 1) {
      while (this.executionSignals.length > outputSignalCount) {
        const flow = this.executionSignals.pop();
        if (flow) {
          flow.disconnectFromAll();
          this._unregisterSignalOutput(flow.name);
        }
      }
      while (this.executionSignals.length < outputSignalCount) {
        this.executionSignals.push(this._registerSignalOutput(`out_${this.executionSignals.length}`));
      }
    }
    getClassName() {
      return "FlowGraphSequenceBlock";
    }
  };
  RegisterClass("FlowGraphSequenceBlock", FlowGraphSequenceBlock);
});

// node_modules/@babylonjs/core/Misc/timer.js
function setAndStartTimer(options) {
  let timer = 0;
  const startTime = Date.now();
  options.observableParameters = options.observableParameters ?? {};
  const observer2 = options.contextObservable.add((payload) => {
    const now = Date.now();
    timer = now - startTime;
    const data = {
      startTime,
      currentTime: now,
      deltaTime: timer,
      completeRate: timer / options.timeout,
      payload
    };
    options.onTick && options.onTick(data);
    if (options.breakCondition && options.breakCondition()) {
      options.contextObservable.remove(observer2);
      options.onAborted && options.onAborted(data);
    }
    if (timer >= options.timeout) {
      options.contextObservable.remove(observer2);
      options.onEnded && options.onEnded(data);
    }
  }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope);
  return observer2;
}

class AdvancedTimer {
  constructor(options) {
    this.onEachCountObservable = new Observable;
    this.onTimerAbortedObservable = new Observable;
    this.onTimerEndedObservable = new Observable;
    this.onStateChangedObservable = new Observable;
    this._observer = null;
    this._breakOnNextTick = false;
    this._tick = (payload) => {
      const now = Date.now();
      this._timer = now - this._startTime;
      const data = {
        startTime: this._startTime,
        currentTime: now,
        deltaTime: this._timer,
        completeRate: this._timer / this._timeToEnd,
        payload
      };
      const shouldBreak = this._breakOnNextTick || this._breakCondition(data);
      if (shouldBreak || this._timer >= this._timeToEnd) {
        this._stop(data, shouldBreak);
      } else {
        this.onEachCountObservable.notifyObservers(data);
      }
    };
    this._setState(0);
    this._contextObservable = options.contextObservable;
    this._observableParameters = options.observableParameters ?? {};
    this._breakCondition = options.breakCondition ?? (() => false);
    this._timeToEnd = options.timeout;
    if (options.onEnded) {
      this.onTimerEndedObservable.add(options.onEnded);
    }
    if (options.onTick) {
      this.onEachCountObservable.add(options.onTick);
    }
    if (options.onAborted) {
      this.onTimerAbortedObservable.add(options.onAborted);
    }
  }
  set breakCondition(predicate) {
    this._breakCondition = predicate;
  }
  clearObservables() {
    this.onEachCountObservable.clear();
    this.onTimerAbortedObservable.clear();
    this.onTimerEndedObservable.clear();
    this.onStateChangedObservable.clear();
  }
  start(timeToEnd = this._timeToEnd) {
    if (this._state === 1) {
      throw new Error("Timer already started. Please stop it before starting again");
    }
    this._timeToEnd = timeToEnd;
    this._startTime = Date.now();
    this._timer = 0;
    this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope);
    this._setState(1);
  }
  stop() {
    if (this._state !== 1) {
      return;
    }
    this._breakOnNextTick = true;
  }
  dispose() {
    if (this._observer) {
      this._contextObservable.remove(this._observer);
    }
    this.clearObservables();
  }
  _setState(newState) {
    this._state = newState;
    this.onStateChangedObservable.notifyObservers(this._state);
  }
  _stop(data, aborted = false) {
    this._contextObservable.remove(this._observer);
    this._setState(2);
    if (aborted) {
      this.onTimerAbortedObservable.notifyObservers(data);
    } else {
      this.onTimerEndedObservable.notifyObservers(data);
    }
  }
}
var TimerState;
var init_timer = __esm(() => {
  init_observable();
  (function(TimerState2) {
    TimerState2[TimerState2["INIT"] = 0] = "INIT";
    TimerState2[TimerState2["STARTED"] = 1] = "STARTED";
    TimerState2[TimerState2["ENDED"] = 2] = "ENDED";
  })(TimerState || (TimerState = {}));
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphSetDelayBlock.js
var FlowGraphSetDelayBlock;
var init_flowGraphSetDelayBlock = __esm(() => {
  init_flowGraphAsyncExecutionBlock();
  init_flowGraphRichTypes();
  init_timer();
  init_logger();
  init_typeStore();
  FlowGraphSetDelayBlock = class FlowGraphSetDelayBlock extends FlowGraphAsyncExecutionBlock {
    constructor(config) {
      super(config);
      this.cancel = this._registerSignalInput("cancel");
      this.duration = this.registerDataInput("duration", RichTypeNumber);
      this.lastDelayIndex = this.registerDataOutput("lastDelayIndex", RichTypeNumber, -1);
    }
    _preparePendingTasks(context) {
      const duration = this.duration.getValue(context);
      if (duration < 0 || isNaN(duration) || !isFinite(duration)) {
        return this._reportError(context, "Invalid duration in SetDelay block");
      }
      const activeDelays = context._getGlobalContextVariable("activeDelays", 0);
      if (activeDelays >= FlowGraphSetDelayBlock.MaxParallelDelayCount) {
        return this._reportError(context, "Max parallel delays reached");
      }
      const lastDelayIndex = context._getGlobalContextVariable("lastDelayIndex", -1);
      const timers = context._getExecutionVariable(this, "pendingDelays", []);
      const scene = context.configuration.scene;
      const timer = new AdvancedTimer({
        timeout: duration * 1000,
        contextObservable: scene.onBeforeRenderObservable,
        onEnded: () => this._onEnded(timer, context)
      });
      timer.start();
      const newIndex = lastDelayIndex + 1;
      this.lastDelayIndex.setValue(newIndex, context);
      context._setGlobalContextVariable("lastDelayIndex", newIndex);
      timers[newIndex] = timer;
      context._setExecutionVariable(this, "pendingDelays", timers);
    }
    _cancelPendingTasks(context) {
      const timers = context._getExecutionVariable(this, "pendingDelays", []);
      for (const timer of timers) {
        timer?.dispose();
      }
      context._deleteExecutionVariable(this, "pendingDelays");
      this.lastDelayIndex.setValue(-1, context);
    }
    _execute(context, callingSignal) {
      if (callingSignal === this.cancel) {
        this._cancelPendingTasks(context);
        return;
      } else {
        this._preparePendingTasks(context);
        this.out._activateSignal(context);
      }
    }
    getClassName() {
      return "FlowGraphSetDelayBlock";
    }
    _onEnded(timer, context) {
      const timers = context._getExecutionVariable(this, "pendingDelays", []);
      const index = timers.indexOf(timer);
      if (index !== -1) {
        timers.splice(index, 1);
      } else {
        Logger.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list");
      }
      context._removePendingBlock(this);
      this.done._activateSignal(context);
    }
  };
  FlowGraphSetDelayBlock.MaxParallelDelayCount = 100;
  RegisterClass("FlowGraphSetDelayBlock", FlowGraphSetDelayBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/flowGraphCancelDelayBlock.js
var FlowGraphCancelDelayBlock;
var init_flowGraphCancelDelayBlock = __esm(() => {
  init_typeStore();
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  FlowGraphCancelDelayBlock = class FlowGraphCancelDelayBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.delayIndex = this.registerDataInput("delayIndex", RichTypeNumber);
    }
    _execute(context, _callingSignal) {
      const delayIndex = this.delayIndex.getValue(context);
      if (delayIndex <= 0 || isNaN(delayIndex) || !isFinite(delayIndex)) {
        return this._reportError(context, "Invalid delay index");
      }
      const timers = context._getExecutionVariable(this, "pendingDelays", []);
      const timer = timers[delayIndex];
      if (timer) {
        timer.dispose();
      }
      this.out._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphCancelDelayBlock";
    }
  };
  RegisterClass("FlowGraphCancelDelayBlock", FlowGraphCancelDelayBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphPlayAnimationBlock.js
var FlowGraphPlayAnimationBlock;
var init_flowGraphPlayAnimationBlock = __esm(() => {
  init_flowGraphAsyncExecutionBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_animationGroup();
  FlowGraphPlayAnimationBlock = class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock {
    constructor(config) {
      super(config, ["animationLoop", "animationEnd", "animationGroupLoop"]);
      this.config = config;
      this.speed = this.registerDataInput("speed", RichTypeNumber);
      this.loop = this.registerDataInput("loop", RichTypeBoolean);
      this.from = this.registerDataInput("from", RichTypeNumber, 0);
      this.to = this.registerDataInput("to", RichTypeNumber);
      this.currentFrame = this.registerDataOutput("currentFrame", RichTypeNumber);
      this.currentTime = this.registerDataOutput("currentTime", RichTypeNumber);
      this.currentAnimationGroup = this.registerDataOutput("currentAnimationGroup", RichTypeAny);
      this.animationGroup = this.registerDataInput("animationGroup", RichTypeAny, config?.animationGroup);
      this.animation = this.registerDataInput("animation", RichTypeAny);
      this.object = this.registerDataInput("object", RichTypeAny);
    }
    _preparePendingTasks(context) {
      const ag = this.animationGroup.getValue(context);
      const animation2 = this.animation.getValue(context);
      if (!ag && !animation2) {
        return this._reportError(context, "No animation or animation group provided");
      } else {
        const currentAnimationGroup = this.currentAnimationGroup.getValue(context);
        if (currentAnimationGroup && currentAnimationGroup !== ag) {
          currentAnimationGroup.dispose();
        }
        let animationGroupToUse = ag;
        if (animation2 && !animationGroupToUse) {
          const target = this.object.getValue(context);
          if (!target) {
            return this._reportError(context, "No target object provided");
          }
          const animationsArray = Array.isArray(animation2) ? animation2 : [animation2];
          const name157 = animationsArray[0].name;
          animationGroupToUse = new AnimationGroup("flowGraphAnimationGroup-" + name157 + "-" + target.name, context.configuration.scene);
          let isInterpolation = false;
          const interpolationAnimations = context._getGlobalContextVariable("interpolationAnimations", []);
          for (const anim of animationsArray) {
            animationGroupToUse.addTargetedAnimation(anim, target);
            if (interpolationAnimations.indexOf(anim.uniqueId) !== -1) {
              isInterpolation = true;
            }
          }
          if (isInterpolation) {
            this._checkInterpolationDuplications(context, animationsArray, target);
          }
        }
        const speed = this.speed.getValue(context) || 1;
        const from = this.from.getValue(context) ?? 0;
        const to = this.to.getValue(context) || animationGroupToUse.to;
        const loop = !isFinite(to) || this.loop.getValue(context);
        this.currentAnimationGroup.setValue(animationGroupToUse, context);
        const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []);
        if (currentlyRunningAnimationGroups.indexOf(animationGroupToUse.uniqueId) !== -1) {
          animationGroupToUse.stop();
        }
        try {
          animationGroupToUse.start(loop, speed, from, to);
          animationGroupToUse.onAnimationGroupEndObservable.add(() => this._onAnimationGroupEnd(context));
          animationGroupToUse.onAnimationEndObservable.add(() => this._eventsSignalOutputs["animationEnd"]._activateSignal(context));
          animationGroupToUse.onAnimationLoopObservable.add(() => this._eventsSignalOutputs["animationLoop"]._activateSignal(context));
          animationGroupToUse.onAnimationGroupLoopObservable.add(() => this._eventsSignalOutputs["animationGroupLoop"]._activateSignal(context));
          currentlyRunningAnimationGroups.push(animationGroupToUse.uniqueId);
          context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups);
        } catch (e) {
          this._reportError(context, e);
        }
      }
    }
    _reportError(context, error) {
      super._reportError(context, error);
      this.currentFrame.setValue(-1, context);
      this.currentTime.setValue(-1, context);
    }
    _executeOnTick(_context) {
      const ag = this.currentAnimationGroup.getValue(_context);
      if (ag) {
        this.currentFrame.setValue(ag.getCurrentFrame(), _context);
        this.currentTime.setValue(ag.animatables[0]?.elapsedTime ?? 0, _context);
      }
    }
    _execute(context) {
      this._startPendingTasks(context);
    }
    _onAnimationGroupEnd(context) {
      this._removeFromCurrentlyRunning(context, this.currentAnimationGroup.getValue(context));
      this._resetAfterCanceled(context);
      this.done._activateSignal(context);
    }
    _checkInterpolationDuplications(context, animation2, target) {
      const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []);
      for (const uniqueId of currentlyRunningAnimationGroups) {
        const ag = context.assetsContext.animationGroups.find((ag2) => ag2.uniqueId === uniqueId);
        if (ag) {
          for (const anim of ag.targetedAnimations) {
            for (const animToCheck of animation2) {
              if (anim.animation.targetProperty === animToCheck.targetProperty && anim.target === target) {
                this._stopAnimationGroup(context, ag);
              }
            }
          }
        }
      }
    }
    _stopAnimationGroup(context, animationGroup2) {
      animationGroup2.stop(true);
      animationGroup2.dispose();
      this._removeFromCurrentlyRunning(context, animationGroup2);
    }
    _removeFromCurrentlyRunning(context, animationGroup2) {
      const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []);
      const idx = currentlyRunningAnimationGroups.indexOf(animationGroup2.uniqueId);
      if (idx !== -1) {
        currentlyRunningAnimationGroups.splice(idx, 1);
        context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups);
      }
    }
    _cancelPendingTasks(context) {
      const ag = this.currentAnimationGroup.getValue(context);
      if (ag) {
        this._stopAnimationGroup(context, ag);
      }
    }
    getClassName() {
      return "FlowGraphPlayAnimationBlock";
    }
  };
  RegisterClass("FlowGraphPlayAnimationBlock", FlowGraphPlayAnimationBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphStopAnimationBlock.js
var FlowGraphStopAnimationBlock;
var init_flowGraphStopAnimationBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_typeStore();
  init_logger();
  init_flowGraphAsyncExecutionBlock();
  FlowGraphStopAnimationBlock = class FlowGraphStopAnimationBlock extends FlowGraphAsyncExecutionBlock {
    constructor(config) {
      super(config);
      this.animationGroup = this.registerDataInput("animationGroup", RichTypeAny);
      this.stopAtFrame = this.registerDataInput("stopAtFrame", RichTypeNumber, -1);
    }
    _preparePendingTasks(context) {
      const animationToStopValue = this.animationGroup.getValue(context);
      const stopAtFrame = this.stopAtFrame.getValue(context) ?? -1;
      const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []);
      pendingStopAnimations.push({ uniqueId: animationToStopValue.uniqueId, stopAtFrame });
      context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations);
    }
    _cancelPendingTasks(context) {
      const animationToStopValue = this.animationGroup.getValue(context);
      const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []);
      for (let i = 0;i < pendingStopAnimations.length; i++) {
        if (pendingStopAnimations[i].uniqueId === animationToStopValue.uniqueId) {
          pendingStopAnimations.splice(i, 1);
          context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations);
          break;
        }
      }
    }
    _execute(context) {
      const animationToStopValue = this.animationGroup.getValue(context);
      const stopTime = this.stopAtFrame.getValue(context) ?? -1;
      if (!animationToStopValue) {
        Logger.Warn("No animation group provided to stop.");
        return this._reportError(context, "No animation group provided to stop.");
      }
      if (isNaN(stopTime)) {
        return this._reportError(context, "Invalid stop time.");
      }
      if (stopTime > 0) {
        this._startPendingTasks(context);
      } else {
        this._stopAnimation(animationToStopValue, context);
      }
      this.out._activateSignal(context);
    }
    _executeOnTick(context) {
      const animationToStopValue = this.animationGroup.getValue(context);
      const pendingStopAnimations = context._getGlobalContextVariable("pendingStopAnimations", []);
      for (let i = 0;i < pendingStopAnimations.length; i++) {
        if (pendingStopAnimations[i].uniqueId === animationToStopValue.uniqueId) {
          if (animationToStopValue.getCurrentFrame() >= pendingStopAnimations[i].stopAtFrame) {
            this._stopAnimation(animationToStopValue, context);
            pendingStopAnimations.splice(i, 1);
            context._setGlobalContextVariable("pendingStopAnimations", pendingStopAnimations);
            this.done._activateSignal(context);
            context._removePendingBlock(this);
            break;
          }
        }
      }
    }
    getClassName() {
      return "FlowGraphStopAnimationBlock";
    }
    _stopAnimation(animationGroup2, context) {
      const currentlyRunning = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []);
      const index = currentlyRunning.indexOf(animationGroup2.uniqueId);
      if (index !== -1) {
        animationGroup2.stop();
        currentlyRunning.splice(index, 1);
        context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunning);
      } else {}
    }
  };
  RegisterClass("FlowGraphStopAnimationBlock", FlowGraphStopAnimationBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphPauseAnimationBlock.js
var FlowGraphPauseAnimationBlock;
var init_flowGraphPauseAnimationBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphPauseAnimationBlock = class FlowGraphPauseAnimationBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.animationToPause = this.registerDataInput("animationToPause", RichTypeAny);
    }
    _execute(context) {
      const animationToPauseValue = this.animationToPause.getValue(context);
      animationToPauseValue.pause();
      this.out._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphPauseAnimationBlock";
    }
  };
  RegisterClass("FlowGraphPauseAnimationBlock", FlowGraphPauseAnimationBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphInterpolationBlock.js
var FlowGraphInterpolationBlock;
var init_flowGraphInterpolationBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_animation();
  init_typeStore();
  FlowGraphInterpolationBlock = class FlowGraphInterpolationBlock extends FlowGraphBlock {
    constructor(config = {}) {
      super(config);
      this.keyFrames = [];
      const type = typeof config?.animationType === "string" ? getRichTypeByFlowGraphType(config.animationType) : getRichTypeByAnimationType(config?.animationType ?? 0);
      const numberOfKeyFrames = config?.keyFramesCount ?? 1;
      const duration = this.registerDataInput(`duration_0`, RichTypeNumber, 0);
      const value = this.registerDataInput(`value_0`, type);
      this.keyFrames.push({ duration, value });
      for (let i = 1;i < numberOfKeyFrames + 1; i++) {
        const duration2 = this.registerDataInput(`duration_${i}`, RichTypeNumber, i === numberOfKeyFrames ? config.duration : undefined);
        const value2 = this.registerDataInput(`value_${i}`, type);
        this.keyFrames.push({ duration: duration2, value: value2 });
      }
      this.initialValue = this.keyFrames[0].value;
      this.endValue = this.keyFrames[numberOfKeyFrames].value;
      this.easingFunction = this.registerDataInput("easingFunction", RichTypeAny);
      this.animation = this.registerDataOutput("animation", RichTypeAny);
      this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config?.propertyName);
      this.customBuildAnimation = this.registerDataInput("customBuildAnimation", RichTypeAny);
    }
    _updateOutputs(context) {
      const interpolationAnimations = context._getGlobalContextVariable("interpolationAnimations", []);
      const propertyName = this.propertyName.getValue(context);
      const easingFunction = this.easingFunction.getValue(context);
      const animation2 = this._createAnimation(context, propertyName, easingFunction);
      this.animation.setValue(animation2, context);
      if (Array.isArray(animation2)) {
        for (const anim of animation2) {
          interpolationAnimations.push(anim.uniqueId);
        }
      } else {
        interpolationAnimations.push(animation2.uniqueId);
      }
      context._setGlobalContextVariable("interpolationAnimations", interpolationAnimations);
    }
    _createAnimation(context, propertyName, easingFunction) {
      const type = this.initialValue.richType;
      const keys = [];
      const currentValue = this.initialValue.getValue(context) || type.defaultValue;
      keys.push({ frame: 0, value: currentValue });
      const numberOfKeyFrames = this.config?.numberOfKeyFrames ?? 1;
      for (let i = 1;i < numberOfKeyFrames + 1; i++) {
        const duration = this.keyFrames[i].duration?.getValue(context);
        let value = this.keyFrames[i].value?.getValue(context);
        if (i === numberOfKeyFrames - 1) {
          value = value || type.defaultValue;
        }
        if (duration !== undefined && value) {
          keys.push({ frame: duration * 60, value });
        }
      }
      const customBuildAnimation = this.customBuildAnimation.getValue(context);
      if (customBuildAnimation) {
        return customBuildAnimation()(keys, 60, type.animationType, easingFunction);
      }
      if (typeof propertyName === "string") {
        const animation2 = Animation.CreateAnimation(propertyName, type.animationType, 60, easingFunction);
        animation2.setKeys(keys);
        return [animation2];
      } else {
        const animations = propertyName.map((name157) => {
          const animation2 = Animation.CreateAnimation(name157, type.animationType, 60, easingFunction);
          animation2.setKeys(keys);
          return animation2;
        });
        return animations;
      }
    }
    getClassName() {
      return "FlowGraphInterpolationBlock";
    }
  };
  RegisterClass("FlowGraphInterpolationBlock", FlowGraphInterpolationBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphEasingBlock.js
function CreateEasingFunction(type, ...parameters) {
  switch (type) {
    case 11:
      return new BezierCurveEase(...parameters);
    case 0:
      return new CircleEase;
    case 1:
      return new BackEase(...parameters);
    case 2:
      return new BounceEase(...parameters);
    case 3:
      return new CubicEase;
    case 4:
      return new ElasticEase(...parameters);
    case 5:
      return new ExponentialEase(...parameters);
    default:
      throw new Error("Easing type not yet implemented");
  }
}
var EasingFunctionType, FlowGraphEasingBlock;
var init_flowGraphEasingBlock = __esm(() => {
  init_easing();
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  (function(EasingFunctionType2) {
    EasingFunctionType2[EasingFunctionType2["CircleEase"] = 0] = "CircleEase";
    EasingFunctionType2[EasingFunctionType2["BackEase"] = 1] = "BackEase";
    EasingFunctionType2[EasingFunctionType2["BounceEase"] = 2] = "BounceEase";
    EasingFunctionType2[EasingFunctionType2["CubicEase"] = 3] = "CubicEase";
    EasingFunctionType2[EasingFunctionType2["ElasticEase"] = 4] = "ElasticEase";
    EasingFunctionType2[EasingFunctionType2["ExponentialEase"] = 5] = "ExponentialEase";
    EasingFunctionType2[EasingFunctionType2["PowerEase"] = 6] = "PowerEase";
    EasingFunctionType2[EasingFunctionType2["QuadraticEase"] = 7] = "QuadraticEase";
    EasingFunctionType2[EasingFunctionType2["QuarticEase"] = 8] = "QuarticEase";
    EasingFunctionType2[EasingFunctionType2["QuinticEase"] = 9] = "QuinticEase";
    EasingFunctionType2[EasingFunctionType2["SineEase"] = 10] = "SineEase";
    EasingFunctionType2[EasingFunctionType2["BezierCurveEase"] = 11] = "BezierCurveEase";
  })(EasingFunctionType || (EasingFunctionType = {}));
  FlowGraphEasingBlock = class FlowGraphEasingBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this._easingFunctions = {};
      this.type = this.registerDataInput("type", RichTypeAny, 11);
      this.mode = this.registerDataInput("mode", RichTypeNumber, 0);
      this.parameters = this.registerDataInput("parameters", RichTypeAny, [1, 0, 0, 1]);
      this.easingFunction = this.registerDataOutput("easingFunction", RichTypeAny);
    }
    _updateOutputs(context) {
      const type = this.type.getValue(context);
      const mode = this.mode.getValue(context);
      const parameters = this.parameters.getValue(context);
      if (type === undefined || mode === undefined) {
        return;
      }
      const key = `${type}-${mode}-${parameters.join("-")}`;
      if (!this._easingFunctions[key]) {
        const easing2 = CreateEasingFunction(type, ...parameters);
        easing2.setEasingMode(mode);
        this._easingFunctions[key] = easing2;
      }
      this.easingFunction.setValue(this._easingFunctions[key], context);
    }
    getClassName() {
      return "FlowGraphEasingBlock";
    }
  };
  RegisterClass("FlowGraphEasingBlock", FlowGraphEasingBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/flowGraphBezierCurveEasingBlock.js
var FlowGraphBezierCurveEasingBlock;
var init_flowGraphBezierCurveEasingBlock = __esm(() => {
  init_easing();
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphBezierCurveEasingBlock = class FlowGraphBezierCurveEasingBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this._easingFunctions = {};
      this.mode = this.registerDataInput("mode", RichTypeNumber, 0);
      this.controlPoint1 = this.registerDataInput("controlPoint1", RichTypeVector2);
      this.controlPoint2 = this.registerDataInput("controlPoint2", RichTypeVector2);
      this.easingFunction = this.registerDataOutput("easingFunction", RichTypeAny);
    }
    _updateOutputs(context) {
      const mode = this.mode.getValue(context);
      const controlPoint1 = this.controlPoint1.getValue(context);
      const controlPoint2 = this.controlPoint2.getValue(context);
      if (mode === undefined) {
        return;
      }
      const key = `${mode}-${controlPoint1.x}-${controlPoint1.y}-${controlPoint2.x}-${controlPoint2.y}`;
      if (!this._easingFunctions[key]) {
        const easing2 = new BezierCurveEase(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y);
        easing2.setEasingMode(mode);
        this._easingFunctions[key] = easing2;
      }
      this.easingFunction.setValue(this._easingFunctions[key], context);
    }
    getClassName() {
      return "FlowGraphBezierCurveEasing";
    }
  };
  RegisterClass("FlowGraphBezierCurveEasing", FlowGraphBezierCurveEasingBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphConditionalDataBlock.js
var FlowGraphConditionalDataBlock;
var init_flowGraphConditionalDataBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphConditionalDataBlock = class FlowGraphConditionalDataBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.condition = this.registerDataInput("condition", RichTypeBoolean);
      this.onTrue = this.registerDataInput("onTrue", RichTypeAny);
      this.onFalse = this.registerDataInput("onFalse", RichTypeAny);
      this.output = this.registerDataOutput("output", RichTypeAny);
    }
    _updateOutputs(context) {
      const condition2 = this.condition.getValue(context);
      this.output.setValue(condition2 ? this.onTrue.getValue(context) : this.onFalse.getValue(context), context);
    }
    getClassName() {
      return "FlowGraphConditionalBlock";
    }
  };
  RegisterClass("FlowGraphConditionalBlock", FlowGraphConditionalDataBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphGetVariableBlock.js
var FlowGraphGetVariableBlock;
var init_flowGraphGetVariableBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphGetVariableBlock = class FlowGraphGetVariableBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.value = this.registerDataOutput("value", RichTypeAny, config.initialValue);
    }
    _updateOutputs(context) {
      const variableNameValue = this.config.variable;
      if (context.hasVariable(variableNameValue)) {
        this.value.setValue(context.getVariable(variableNameValue), context);
      }
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
      serializationObject.config.variable = this.config.variable;
    }
    getClassName() {
      return "FlowGraphGetVariableBlock";
    }
  };
  RegisterClass("FlowGraphGetVariableBlock", FlowGraphGetVariableBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/flowGraphSetVariableBlock.js
var FlowGraphSetVariableBlock;
var init_flowGraphSetVariableBlock = __esm(() => {
  init_typeStore();
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  FlowGraphSetVariableBlock = class FlowGraphSetVariableBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      if (!config.variable && !config.variables) {
        throw new Error("FlowGraphSetVariableBlock: variable/variables is not defined");
      }
      if (config.variables && config.variable) {
        throw new Error("FlowGraphSetVariableBlock: variable and variables are both defined");
      }
      if (config.variables) {
        for (const variable of config.variables) {
          this.registerDataInput(variable, RichTypeAny);
        }
      } else {
        this.registerDataInput("value", RichTypeAny);
      }
    }
    _execute(context, _callingSignal) {
      if (this.config?.variables) {
        for (const variable of this.config.variables) {
          this._saveVariable(context, variable);
        }
      } else {
        this._saveVariable(context, this.config?.variable, "value");
      }
      this.out._activateSignal(context);
    }
    _saveVariable(context, variableName, inputName) {
      const currentlyRunningAnimationGroups = context._getGlobalContextVariable("currentlyRunningAnimationGroups", []);
      for (const animationUniqueId of currentlyRunningAnimationGroups) {
        const animation2 = context.assetsContext.animationGroups[animationUniqueId];
        for (const targetAnimation of animation2.targetedAnimations) {
          if (targetAnimation.target === context) {
            if (targetAnimation.target === context) {
              if (targetAnimation.animation.targetProperty === variableName) {
                animation2.stop();
                const index = currentlyRunningAnimationGroups.indexOf(animationUniqueId);
                if (index > -1) {
                  currentlyRunningAnimationGroups.splice(index, 1);
                }
                context._setGlobalContextVariable("currentlyRunningAnimationGroups", currentlyRunningAnimationGroups);
                break;
              }
            }
          }
        }
      }
      const value = this.getDataInput(inputName || variableName)?.getValue(context);
      context.setVariable(variableName, value);
    }
    getClassName() {
      return "FlowGraphSetVariableBlock";
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
      serializationObject.config.variable = this.config?.variable;
    }
  };
  RegisterClass("FlowGraphSetVariableBlock", FlowGraphSetVariableBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphTransformCoordinatesSystemBlock.js
var FlowGraphTransformCoordinatesSystemBlock;
var init_flowGraphTransformCoordinatesSystemBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_math_vector();
  init_typeStore();
  FlowGraphTransformCoordinatesSystemBlock = class FlowGraphTransformCoordinatesSystemBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.sourceSystem = this.registerDataInput("sourceSystem", RichTypeAny);
      this.destinationSystem = this.registerDataInput("destinationSystem", RichTypeAny);
      this.inputCoordinates = this.registerDataInput("inputCoordinates", RichTypeVector3);
      this.outputCoordinates = this.registerDataOutput("outputCoordinates", RichTypeVector3);
    }
    _updateOutputs(_context) {
      const sourceSystemValue = this.sourceSystem.getValue(_context);
      const destinationSystemValue = this.destinationSystem.getValue(_context);
      const inputCoordinatesValue = this.inputCoordinates.getValue(_context);
      const sourceWorld = sourceSystemValue.getWorldMatrix();
      const destinationWorld = destinationSystemValue.getWorldMatrix();
      const destinationWorldInverse = TmpVectors.Matrix[0].copyFrom(destinationWorld);
      destinationWorldInverse.invert();
      const sourceToDestination = TmpVectors.Matrix[1];
      destinationWorldInverse.multiplyToRef(sourceWorld, sourceToDestination);
      const outputCoordinatesValue = this.outputCoordinates.getValue(_context);
      Vector3.TransformCoordinatesToRef(inputCoordinatesValue, sourceToDestination, outputCoordinatesValue);
    }
    getClassName() {
      return "FlowGraphTransformCoordinatesSystemBlock";
    }
  };
  RegisterClass("FlowGraphTransformCoordinatesSystemBlock", FlowGraphTransformCoordinatesSystemBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphCachedOperationBlock.js
var cacheName = "cachedOperationValue", cacheExecIdName = "cachedExecutionId", FlowGraphCachedOperationBlock;
var init_flowGraphCachedOperationBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  FlowGraphCachedOperationBlock = class FlowGraphCachedOperationBlock extends FlowGraphBlock {
    constructor(outputRichType, config) {
      super(config);
      this.value = this.registerDataOutput("value", outputRichType);
      this.isValid = this.registerDataOutput("isValid", RichTypeBoolean);
    }
    _updateOutputs(context) {
      const cachedExecutionId = context._getExecutionVariable(this, cacheExecIdName, -1);
      const cachedValue = context._getExecutionVariable(this, cacheName, null);
      if (cachedValue !== undefined && cachedValue !== null && cachedExecutionId === context.executionId) {
        this.isValid.setValue(true, context);
        this.value.setValue(cachedValue, context);
      } else {
        try {
          const calculatedValue = this._doOperation(context);
          if (calculatedValue === undefined || calculatedValue === null) {
            this.isValid.setValue(false, context);
            return;
          }
          context._setExecutionVariable(this, cacheName, calculatedValue);
          context._setExecutionVariable(this, cacheExecIdName, context.executionId);
          this.value.setValue(calculatedValue, context);
          this.isValid.setValue(true, context);
        } catch (e) {
          this.isValid.setValue(false, context);
        }
      }
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphGetPropertyBlock.js
var FlowGraphGetPropertyBlock;
var init_flowGraphGetPropertyBlock = __esm(() => {
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphCachedOperationBlock();
  FlowGraphGetPropertyBlock = class FlowGraphGetPropertyBlock extends FlowGraphCachedOperationBlock {
    constructor(config) {
      super(RichTypeAny, config);
      this.config = config;
      this.object = this.registerDataInput("object", RichTypeAny, config.object);
      this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config.propertyName);
      this.customGetFunction = this.registerDataInput("customGetFunction", RichTypeAny);
    }
    _doOperation(context) {
      const getter = this.customGetFunction.getValue(context);
      let value;
      if (getter) {
        value = getter(this.object.getValue(context), this.propertyName.getValue(context), context);
      } else {
        const target = this.object.getValue(context);
        const propertyName = this.propertyName.getValue(context);
        value = target && propertyName ? this._getPropertyValue(target, propertyName) : undefined;
      }
      return value;
    }
    _getPropertyValue(target, propertyName) {
      const path = propertyName.split(".");
      let value = target;
      for (const prop of path) {
        value = value[prop];
        if (value === undefined) {
          return;
        }
      }
      return value;
    }
    getClassName() {
      return "FlowGraphGetPropertyBlock";
    }
  };
  RegisterClass("FlowGraphGetPropertyBlock", FlowGraphGetPropertyBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/flowGraphSetPropertyBlock.js
var FlowGraphSetPropertyBlock;
var init_flowGraphSetPropertyBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphSetPropertyBlock = class FlowGraphSetPropertyBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.config = config;
      this.object = this.registerDataInput("object", RichTypeAny, config.target);
      this.value = this.registerDataInput("value", RichTypeAny);
      this.propertyName = this.registerDataInput("propertyName", RichTypeAny, config.propertyName);
      this.customSetFunction = this.registerDataInput("customSetFunction", RichTypeAny);
    }
    _execute(context, _callingSignal) {
      try {
        const target = this.object.getValue(context);
        const value = this.value.getValue(context);
        const setFunction = this.customSetFunction.getValue(context);
        if (setFunction) {
          setFunction(target, this.propertyName.getValue(context), value, context);
        } else {
          this._setPropertyValue(target, this.propertyName.getValue(context), value);
        }
      } catch (e) {
        this._reportError(context, e);
      }
      this.out._activateSignal(context);
    }
    _setPropertyValue(target, propertyName, value) {
      const path = propertyName.split(".");
      let obj = target;
      for (let i = 0;i < path.length - 1; i++) {
        const prop = path[i];
        if (obj[prop] === undefined) {
          obj[prop] = {};
        }
        obj = obj[prop];
      }
      obj[path[path.length - 1]] = value;
    }
    getClassName() {
      return "FlowGraphSetPropertyBlock";
    }
  };
  RegisterClass("FlowGraphSetPropertyBlock", FlowGraphSetPropertyBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphConstantBlock.js
var FlowGraphConstantBlock;
var init_flowGraphConstantBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_serialization();
  FlowGraphConstantBlock = class FlowGraphConstantBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.output = this.registerDataOutput("output", getRichTypeFromValue(config.value));
    }
    _updateOutputs(context) {
      this.output.setValue(this.config.value, context);
    }
    getClassName() {
      return "FlowGraphConstantBlock";
    }
    serialize(serializationObject = {}, valueSerializeFunction = defaultValueSerializationFunction) {
      super.serialize(serializationObject);
      valueSerializeFunction("value", this.config.value, serializationObject.config);
    }
  };
  RegisterClass("FlowGraphConstantBlock", FlowGraphConstantBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphGetAssetBlock.js
var FlowGraphGetAssetBlock;
var init_flowGraphGetAssetBlock = __esm(() => {
  init_flowGraphAssetsContext();
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphGetAssetBlock = class FlowGraphGetAssetBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.type = this.registerDataInput("type", RichTypeAny, config.type);
      this.value = this.registerDataOutput("value", RichTypeAny);
      this.index = this.registerDataInput("index", RichTypeAny, new FlowGraphInteger(getNumericValue(config.index ?? -1)));
    }
    _updateOutputs(context) {
      const type = this.type.getValue(context);
      const index = this.index.getValue(context);
      const asset = GetFlowGraphAssetWithType(context.assetsContext, type, getNumericValue(index), this.config.useIndexAsUniqueId);
      this.value.setValue(asset, context);
    }
    getClassName() {
      return "FlowGraphGetAssetBlock";
    }
  };
  RegisterClass("FlowGraphGetAssetBlock", FlowGraphGetAssetBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphDataSwitchBlock.js
var FlowGraphDataSwitchBlock;
var init_flowGraphDataSwitchBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphDataSwitchBlock = class FlowGraphDataSwitchBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this._inputCases = new Map;
      this.case = this.registerDataInput("case", RichTypeAny, NaN);
      this.default = this.registerDataInput("default", RichTypeAny);
      this.value = this.registerDataOutput("value", RichTypeAny);
      (this.config.cases || []).forEach((caseValue) => {
        caseValue = getNumericValue(caseValue);
        if (this.config.treatCasesAsIntegers) {
          caseValue = caseValue | 0;
          if (this._inputCases.has(caseValue)) {
            return;
          }
        }
        this._inputCases.set(caseValue, this.registerDataInput(`in_${caseValue}`, RichTypeAny));
      });
    }
    _updateOutputs(context) {
      const selectionValue = this.case.getValue(context);
      let outputValue;
      if (isNumeric(selectionValue)) {
        outputValue = this._getOutputValueForCase(getNumericValue(selectionValue), context);
      } else {
        outputValue = this.default.getValue(context);
      }
      this.value.setValue(outputValue, context);
    }
    _getOutputValueForCase(caseValue, context) {
      return this._inputCases.get(caseValue)?.getValue(context);
    }
    getClassName() {
      return "FlowGraphDataSwitchBlock";
    }
  };
  RegisterClass("FlowGraphDataSwitchBlock", FlowGraphDataSwitchBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphBinaryOperationBlock.js
var FlowGraphBinaryOperationBlock;
var init_flowGraphBinaryOperationBlock = __esm(() => {
  init_flowGraphCachedOperationBlock();
  FlowGraphBinaryOperationBlock = class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock {
    constructor(leftRichType, rightRichType, resultRichType, _operation, _className, config) {
      super(resultRichType, config);
      this._operation = _operation;
      this._className = _className;
      this.a = this.registerDataInput("a", leftRichType);
      this.b = this.registerDataInput("b", rightRichType);
    }
    _doOperation(context) {
      const a = this.a.getValue(context);
      const b = this.b.getValue(context);
      return this._operation(a, b);
    }
    getClassName() {
      return this._className;
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphConstantOperationBlock.js
var FlowGraphConstantOperationBlock;
var init_flowGraphConstantOperationBlock = __esm(() => {
  init_flowGraphCachedOperationBlock();
  FlowGraphConstantOperationBlock = class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock {
    constructor(richType, _operation, _className, config) {
      super(richType, config);
      this._operation = _operation;
      this._className = _className;
    }
    _doOperation(context) {
      return this._operation(context);
    }
    getClassName() {
      return this._className;
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphUnaryOperationBlock.js
var FlowGraphUnaryOperationBlock;
var init_flowGraphUnaryOperationBlock = __esm(() => {
  init_flowGraphCachedOperationBlock();
  FlowGraphUnaryOperationBlock = class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock {
    constructor(inputRichType, resultRichType, _operation, _className, config) {
      super(resultRichType, config);
      this._operation = _operation;
      this._className = _className;
      this.a = this.registerDataInput("a", inputRichType);
    }
    _doOperation(context) {
      return this._operation(this.a.getValue(context));
    }
    getClassName() {
      return this._className;
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphTernaryOperationBlock.js
var FlowGraphTernaryOperationBlock;
var init_flowGraphTernaryOperationBlock = __esm(() => {
  init_flowGraphCachedOperationBlock();
  FlowGraphTernaryOperationBlock = class FlowGraphTernaryOperationBlock extends FlowGraphCachedOperationBlock {
    constructor(t1Type, t2Type, t3Type, resultRichType, _operation, _className, config) {
      super(resultRichType, config);
      this._operation = _operation;
      this._className = _className;
      this.a = this.registerDataInput("a", t1Type);
      this.b = this.registerDataInput("b", t2Type);
      this.c = this.registerDataInput("c", t3Type);
    }
    _doOperation(context) {
      return this._operation(this.a.getValue(context), this.b.getValue(context), this.c.getValue(context));
    }
    getClassName() {
      return this._className;
    }
  };
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Math/flowGraphMathBlocks.js
function _componentWiseUnaryOperation(a, op) {
  const aClassName = _getClassNameOf(a);
  switch (aClassName) {
    case "FlowGraphInteger":
      a = a;
      return new FlowGraphInteger(op(a.value));
    case "Vector2":
      a = a;
      return new Vector2(op(a.x), op(a.y));
    case "Vector3":
      a = a;
      return new Vector3(op(a.x), op(a.y), op(a.z));
    case "Vector4":
      a = a;
      return new Vector4(op(a.x), op(a.y), op(a.z), op(a.w));
    case "Quaternion":
      a = a;
      return new Quaternion(op(a.x), op(a.y), op(a.z), op(a.w));
    case "Matrix":
      a = a;
      return Matrix.FromArray(a.m.map(op));
    case "Matrix2D":
      a = a;
      return new FlowGraphMatrix2D(a.m.map(op));
    case "Matrix3D":
      a = a;
      return new FlowGraphMatrix3D(a.m.map(op));
    default:
      a = a;
      return op(a);
  }
}
function _componentWiseBinaryOperation(a, b, op) {
  const aClassName = _getClassNameOf(a);
  switch (aClassName) {
    case "FlowGraphInteger":
      a = a;
      b = b;
      return new FlowGraphInteger(op(a.value, b.value));
    case "Vector2":
      a = a;
      b = b;
      return new Vector2(op(a.x, b.x), op(a.y, b.y));
    case "Vector3":
      a = a;
      b = b;
      return new Vector3(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z));
    case "Vector4":
      a = a;
      b = b;
      return new Vector4(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z), op(a.w, b.w));
    case "Quaternion":
      a = a;
      b = b;
      return new Quaternion(op(a.x, b.x), op(a.y, b.y), op(a.z, b.z), op(a.w, b.w));
    case "Matrix":
      a = a;
      return Matrix.FromArray(a.m.map((v, i) => op(v, b.m[i])));
    case "Matrix2D":
      a = a;
      return new FlowGraphMatrix2D(a.m.map((v, i) => op(v, b.m[i])));
    case "Matrix3D":
      a = a;
      return new FlowGraphMatrix3D(a.m.map((v, i) => op(v, b.m[i])));
    default:
      return op(a, b);
  }
}
function _clamp(a, b, c) {
  return Math.min(Math.max(a, Math.min(b, c)), Math.max(b, c));
}
function _componentWiseTernaryOperation(a, b, c, op) {
  const aClassName = _getClassNameOf(a);
  switch (aClassName) {
    case "FlowGraphInteger":
      a = a;
      b = b;
      c = c;
      return new FlowGraphInteger(op(a.value, b.value, c.value));
    case "Vector2":
      a = a;
      b = b;
      c = c;
      return new Vector2(op(a.x, b.x, c.x), op(a.y, b.y, c.y));
    case "Vector3":
      a = a;
      b = b;
      c = c;
      return new Vector3(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z));
    case "Vector4":
      a = a;
      b = b;
      c = c;
      return new Vector4(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z), op(a.w, b.w, c.w));
    case "Quaternion":
      a = a;
      b = b;
      c = c;
      return new Quaternion(op(a.x, b.x, c.x), op(a.y, b.y, c.y), op(a.z, b.z, c.z), op(a.w, b.w, c.w));
    case "Matrix":
      return Matrix.FromArray(a.m.map((v, i) => op(v, b.m[i], c.m[i])));
    case "Matrix2D":
      return new FlowGraphMatrix2D(a.m.map((v, i) => op(v, b.m[i], c.m[i])));
    case "Matrix3D":
      return new FlowGraphMatrix3D(a.m.map((v, i) => op(v, b.m[i], c.m[i])));
    default:
      return op(a, b, c);
  }
}
function _saturate(a) {
  return Math.min(Math.max(a, 0), 1);
}
function _interpolate(a, b, c) {
  return (1 - c) * a + c * b;
}
function _comparisonOperators(a, b, op) {
  if (isNumeric(a) && isNumeric(b)) {
    return op(getNumericValue(a), getNumericValue(b));
  } else {
    throw new Error(`Cannot compare ${a} and ${b}`);
  }
}
function _countOnes(n) {
  let result = 0;
  while (n) {
    result += n & 1;
    n >>= 1;
  }
  return result;
}
var FlowGraphAddBlock, FlowGraphSubtractBlock, FlowGraphMultiplyBlock, FlowGraphDivideBlock, FlowGraphRandomBlock, FlowGraphEBlock, FlowGraphPiBlock, FlowGraphInfBlock, FlowGraphNaNBlock, FlowGraphAbsBlock, FlowGraphSignBlock, FlowGraphTruncBlock, FlowGraphFloorBlock, FlowGraphCeilBlock, FlowGraphRoundBlock, FlowGraphFractionBlock, FlowGraphNegationBlock, FlowGraphModuloBlock, FlowGraphMinBlock, FlowGraphMaxBlock, FlowGraphClampBlock, FlowGraphSaturateBlock, FlowGraphMathInterpolationBlock, FlowGraphEqualityBlock, FlowGraphLessThanBlock, FlowGraphLessThanOrEqualBlock, FlowGraphGreaterThanBlock, FlowGraphGreaterThanOrEqualBlock, FlowGraphIsNanBlock, FlowGraphIsInfinityBlock, FlowGraphDegToRadBlock, FlowGraphRadToDegBlock, FlowGraphAsinBlock, FlowGraphAcosBlock, FlowGraphAtanBlock, FlowGraphAtan2Block, FlowGraphSinhBlock, FlowGraphCoshBlock, FlowGraphTanhBlock, FlowGraphAsinhBlock, FlowGraphAcoshBlock, FlowGraphAtanhBlock, FlowGraphExpBlock, FlowGraphLogBlock, FlowGraphLog2Block, FlowGraphLog10Block, FlowGraphSquareRootBlock, FlowGraphCubeRootBlock, FlowGraphPowerBlock, FlowGraphBitwiseNotBlock, FlowGraphBitwiseAndBlock, FlowGraphBitwiseOrBlock, FlowGraphBitwiseXorBlock, FlowGraphBitwiseLeftShiftBlock, FlowGraphBitwiseRightShiftBlock, FlowGraphLeadingZerosBlock, FlowGraphTrailingZerosBlock, FlowGraphOneBitsCounterBlock;
var init_flowGraphMathBlocks = __esm(() => {
  init_typeStore();
  init_flowGraphRichTypes();
  init_flowGraphBinaryOperationBlock();
  init_flowGraphConstantOperationBlock();
  init_math_vector();
  init_flowGraphUnaryOperationBlock();
  init_flowGraphTernaryOperationBlock();
  init_flowGraphInteger();
  init_flowGraphMatrix();
  FlowGraphAddBlock = class FlowGraphAddBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicAdd(a, b), "FlowGraphAddBlock", config);
    }
    _polymorphicAdd(a, b) {
      const aClassName = _getClassNameOf(a);
      const bClassName = _getClassNameOf(b);
      if (_areSameVectorClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) {
        return a.add(b);
      } else if (aClassName === "Quaternion" || bClassName === "Quaternion") {
        return a.add(b);
      } else {
        return a + b;
      }
    }
  };
  RegisterClass("FlowGraphAddBlock", FlowGraphAddBlock);
  FlowGraphSubtractBlock = class FlowGraphSubtractBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicSubtract(a, b), "FlowGraphSubtractBlock", config);
    }
    _polymorphicSubtract(a, b) {
      const aClassName = _getClassNameOf(a);
      const bClassName = _getClassNameOf(b);
      if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName)) {
        return a.subtract(b);
      } else if (aClassName === "Quaternion" || bClassName === "Quaternion") {
        return a.subtract(b);
      } else {
        return a - b;
      }
    }
  };
  RegisterClass("FlowGraphSubtractBlock", FlowGraphSubtractBlock);
  FlowGraphMultiplyBlock = class FlowGraphMultiplyBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicMultiply(a, b), "FlowGraphMultiplyBlock", config);
    }
    _polymorphicMultiply(a, b) {
      const aClassName = _getClassNameOf(a);
      const bClassName = _getClassNameOf(b);
      if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) {
        return a.multiply(b);
      } else if (aClassName === "Quaternion" || bClassName === "Quaternion") {
        const aClone = a.clone();
        aClone.x *= b.x;
        aClone.y *= b.y;
        aClone.z *= b.z;
        aClone.w *= b.w;
        return aClone;
      } else if (_areSameMatrixClass(aClassName, bClassName)) {
        if (this.config?.useMatrixPerComponent) {
          const aM = a.m;
          for (let i = 0;i < aM.length; i++) {
            aM[i] *= b.m[i];
          }
          if (aClassName === "Matrix2D") {
            return new FlowGraphMatrix2D(aM);
          } else if (aClassName === "Matrix3D") {
            return new FlowGraphMatrix3D(aM);
          } else {
            return Matrix.FromArray(aM);
          }
        } else {
          a = a;
          b = b;
          return b.multiply(a);
        }
      } else {
        return a * b;
      }
    }
  };
  RegisterClass("FlowGraphMultiplyBlock", FlowGraphMultiplyBlock);
  FlowGraphDivideBlock = class FlowGraphDivideBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), getRichTypeByFlowGraphType(config?.type), (a, b) => this._polymorphicDivide(a, b), "FlowGraphDivideBlock", config);
    }
    _polymorphicDivide(a, b) {
      const aClassName = _getClassNameOf(a);
      const bClassName = _getClassNameOf(b);
      if (_areSameVectorClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) {
        return a.divide(b);
      } else if (aClassName === "Quaternion" || bClassName === "Quaternion") {
        const aClone = a.clone();
        aClone.x /= b.x;
        aClone.y /= b.y;
        aClone.z /= b.z;
        aClone.w /= b.w;
        return aClone;
      } else if (_areSameMatrixClass(aClassName, bClassName)) {
        if (this.config?.useMatrixPerComponent) {
          const aM = a.m;
          for (let i = 0;i < aM.length; i++) {
            aM[i] /= b.m[i];
          }
          if (aClassName === "Matrix2D") {
            return new FlowGraphMatrix2D(aM);
          } else if (aClassName === "Matrix3D") {
            return new FlowGraphMatrix3D(aM);
          } else {
            return Matrix.FromArray(aM);
          }
        } else {
          a = a;
          b = b;
          return a.divide(b);
        }
      } else {
        return a / b;
      }
    }
  };
  RegisterClass("FlowGraphDivideBlock", FlowGraphDivideBlock);
  FlowGraphRandomBlock = class FlowGraphRandomBlock extends FlowGraphConstantOperationBlock {
    constructor(config) {
      super(RichTypeNumber, (context) => this._random(context), "FlowGraphRandomBlock", config);
      this.min = this.registerDataInput("min", RichTypeNumber, config?.min ?? 0);
      this.max = this.registerDataInput("max", RichTypeNumber, config?.max ?? 1);
      if (config?.seed) {
        this._seed = config.seed;
      }
    }
    _isSeed(seed = this._seed) {
      return seed !== undefined;
    }
    _getRandomValue() {
      if (this._isSeed(this._seed)) {
        const x = Math.sin(this._seed++) * 1e4;
        return x - Math.floor(x);
      }
      return Math.random();
    }
    _random(context) {
      const min = this.min.getValue(context);
      const max = this.max.getValue(context);
      return this._getRandomValue() * (max - min) + min;
    }
  };
  RegisterClass("FlowGraphRandomBlock", FlowGraphRandomBlock);
  FlowGraphEBlock = class FlowGraphEBlock extends FlowGraphConstantOperationBlock {
    constructor(config) {
      super(RichTypeNumber, () => Math.E, "FlowGraphEBlock", config);
    }
  };
  RegisterClass("FlowGraphEBlock", FlowGraphEBlock);
  FlowGraphPiBlock = class FlowGraphPiBlock extends FlowGraphConstantOperationBlock {
    constructor(config) {
      super(RichTypeNumber, () => Math.PI, "FlowGraphPIBlock", config);
    }
  };
  RegisterClass("FlowGraphPIBlock", FlowGraphPiBlock);
  FlowGraphInfBlock = class FlowGraphInfBlock extends FlowGraphConstantOperationBlock {
    constructor(config) {
      super(RichTypeNumber, () => Number.POSITIVE_INFINITY, "FlowGraphInfBlock", config);
    }
  };
  RegisterClass("FlowGraphInfBlock", FlowGraphInfBlock);
  FlowGraphNaNBlock = class FlowGraphNaNBlock extends FlowGraphConstantOperationBlock {
    constructor(config) {
      super(RichTypeNumber, () => Number.NaN, "FlowGraphNaNBlock", config);
    }
  };
  RegisterClass("FlowGraphNaNBlock", FlowGraphNaNBlock);
  FlowGraphAbsBlock = class FlowGraphAbsBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAbs(a), "FlowGraphAbsBlock", config);
    }
    _polymorphicAbs(a) {
      return _componentWiseUnaryOperation(a, Math.abs);
    }
  };
  RegisterClass("FlowGraphAbsBlock", FlowGraphAbsBlock);
  FlowGraphSignBlock = class FlowGraphSignBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicSign(a), "FlowGraphSignBlock", config);
    }
    _polymorphicSign(a) {
      return _componentWiseUnaryOperation(a, Math.sign);
    }
  };
  RegisterClass("FlowGraphSignBlock", FlowGraphSignBlock);
  FlowGraphTruncBlock = class FlowGraphTruncBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicTrunc(a), "FlowGraphTruncBlock", config);
    }
    _polymorphicTrunc(a) {
      return _componentWiseUnaryOperation(a, Math.trunc);
    }
  };
  RegisterClass("FlowGraphTruncBlock", FlowGraphTruncBlock);
  FlowGraphFloorBlock = class FlowGraphFloorBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicFloor(a), "FlowGraphFloorBlock", config);
    }
    _polymorphicFloor(a) {
      return _componentWiseUnaryOperation(a, Math.floor);
    }
  };
  RegisterClass("FlowGraphFloorBlock", FlowGraphFloorBlock);
  FlowGraphCeilBlock = class FlowGraphCeilBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicCeiling(a), "FlowGraphCeilBlock", config);
    }
    _polymorphicCeiling(a) {
      return _componentWiseUnaryOperation(a, Math.ceil);
    }
  };
  RegisterClass("FlowGraphCeilBlock", FlowGraphCeilBlock);
  FlowGraphRoundBlock = class FlowGraphRoundBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicRound(a), "FlowGraphRoundBlock", config);
    }
    _polymorphicRound(a) {
      return _componentWiseUnaryOperation(a, (a2) => a2 < 0 && this.config?.roundHalfAwayFromZero ? -Math.round(-a2) : Math.round(a2));
    }
  };
  RegisterClass("FlowGraphRoundBlock", FlowGraphRoundBlock);
  FlowGraphFractionBlock = class FlowGraphFractionBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicFraction(a), "FlowGraphFractBlock", config);
    }
    _polymorphicFraction(a) {
      return _componentWiseUnaryOperation(a, (a2) => a2 - Math.floor(a2));
    }
  };
  RegisterClass("FlowGraphFractBlock", FlowGraphFractionBlock);
  FlowGraphNegationBlock = class FlowGraphNegationBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicNeg(a), "FlowGraphNegationBlock", config);
    }
    _polymorphicNeg(a) {
      return _componentWiseUnaryOperation(a, (a2) => -a2);
    }
  };
  RegisterClass("FlowGraphNegationBlock", FlowGraphNegationBlock);
  FlowGraphModuloBlock = class FlowGraphModuloBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicRemainder(a, b), "FlowGraphModuloBlock", config);
    }
    _polymorphicRemainder(a, b) {
      return _componentWiseBinaryOperation(a, b, (a2, b2) => a2 % b2);
    }
  };
  RegisterClass("FlowGraphModuloBlock", FlowGraphModuloBlock);
  FlowGraphMinBlock = class FlowGraphMinBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicMin(a, b), "FlowGraphMinBlock", config);
    }
    _polymorphicMin(a, b) {
      return _componentWiseBinaryOperation(a, b, Math.min);
    }
  };
  RegisterClass("FlowGraphMinBlock", FlowGraphMinBlock);
  FlowGraphMaxBlock = class FlowGraphMaxBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicMax(a, b), "FlowGraphMaxBlock", config);
    }
    _polymorphicMax(a, b) {
      return _componentWiseBinaryOperation(a, b, Math.max);
    }
  };
  RegisterClass("FlowGraphMaxBlock", FlowGraphMaxBlock);
  FlowGraphClampBlock = class FlowGraphClampBlock extends FlowGraphTernaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, RichTypeAny, (a, b, c) => this._polymorphicClamp(a, b, c), "FlowGraphClampBlock", config);
    }
    _polymorphicClamp(a, b, c) {
      return _componentWiseTernaryOperation(a, b, c, _clamp);
    }
  };
  RegisterClass("FlowGraphClampBlock", FlowGraphClampBlock);
  FlowGraphSaturateBlock = class FlowGraphSaturateBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicSaturate(a), "FlowGraphSaturateBlock", config);
    }
    _polymorphicSaturate(a) {
      return _componentWiseUnaryOperation(a, _saturate);
    }
  };
  RegisterClass("FlowGraphSaturateBlock", FlowGraphSaturateBlock);
  FlowGraphMathInterpolationBlock = class FlowGraphMathInterpolationBlock extends FlowGraphTernaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, RichTypeAny, (a, b, c) => this._polymorphicInterpolate(a, b, c), "FlowGraphMathInterpolationBlock", config);
    }
    _polymorphicInterpolate(a, b, c) {
      return _componentWiseTernaryOperation(a, b, c, _interpolate);
    }
  };
  RegisterClass("FlowGraphMathInterpolationBlock", FlowGraphMathInterpolationBlock);
  FlowGraphEqualityBlock = class FlowGraphEqualityBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicEq(a, b), "FlowGraphEqualityBlock", config);
    }
    _polymorphicEq(a, b) {
      const aClassName = _getClassNameOf(a);
      const bClassName = _getClassNameOf(b);
      if (_areSameVectorClass(aClassName, bClassName) || _areSameMatrixClass(aClassName, bClassName) || _areSameIntegerClass(aClassName, bClassName)) {
        return a.equals(b);
      } else {
        return a === b;
      }
    }
  };
  RegisterClass("FlowGraphEqualityBlock", FlowGraphEqualityBlock);
  FlowGraphLessThanBlock = class FlowGraphLessThanBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicLessThan(a, b), "FlowGraphLessThanBlock", config);
    }
    _polymorphicLessThan(a, b) {
      return _comparisonOperators(a, b, (a2, b2) => a2 < b2);
    }
  };
  RegisterClass("FlowGraphLessThanBlock", FlowGraphLessThanBlock);
  FlowGraphLessThanOrEqualBlock = class FlowGraphLessThanOrEqualBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicLessThanOrEqual(a, b), "FlowGraphLessThanOrEqualBlock", config);
    }
    _polymorphicLessThanOrEqual(a, b) {
      return _comparisonOperators(a, b, (a2, b2) => a2 <= b2);
    }
  };
  RegisterClass("FlowGraphLessThanOrEqualBlock", FlowGraphLessThanOrEqualBlock);
  FlowGraphGreaterThanBlock = class FlowGraphGreaterThanBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicGreaterThan(a, b), "FlowGraphGreaterThanBlock", config);
    }
    _polymorphicGreaterThan(a, b) {
      return _comparisonOperators(a, b, (a2, b2) => a2 > b2);
    }
  };
  RegisterClass("FlowGraphGreaterThanBlock", FlowGraphGreaterThanBlock);
  FlowGraphGreaterThanOrEqualBlock = class FlowGraphGreaterThanOrEqualBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeBoolean, (a, b) => this._polymorphicGreaterThanOrEqual(a, b), "FlowGraphGreaterThanOrEqualBlock", config);
    }
    _polymorphicGreaterThanOrEqual(a, b) {
      return _comparisonOperators(a, b, (a2, b2) => a2 >= b2);
    }
  };
  RegisterClass("FlowGraphGreaterThanOrEqualBlock", FlowGraphGreaterThanOrEqualBlock);
  FlowGraphIsNanBlock = class FlowGraphIsNanBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeBoolean, (a) => this._polymorphicIsNan(a), "FlowGraphIsNaNBlock", config);
    }
    _polymorphicIsNan(a) {
      if (isNumeric(a)) {
        return isNaN(getNumericValue(a));
      } else {
        throw new Error(`Cannot get NaN of ${a}`);
      }
    }
  };
  RegisterClass("FlowGraphIsNaNBlock", FlowGraphIsNanBlock);
  FlowGraphIsInfinityBlock = class FlowGraphIsInfinityBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeBoolean, (a) => this._polymorphicIsInf(a), "FlowGraphIsInfBlock", config);
    }
    _polymorphicIsInf(a) {
      if (isNumeric(a)) {
        return !isFinite(getNumericValue(a));
      } else {
        throw new Error(`Cannot get isInf of ${a}`);
      }
    }
  };
  RegisterClass("FlowGraphIsInfBlock", FlowGraphIsInfinityBlock);
  FlowGraphDegToRadBlock = class FlowGraphDegToRadBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicDegToRad(a), "FlowGraphDegToRadBlock", config);
    }
    _degToRad(a) {
      return a * Math.PI / 180;
    }
    _polymorphicDegToRad(a) {
      return _componentWiseUnaryOperation(a, this._degToRad);
    }
  };
  RegisterClass("FlowGraphDegToRadBlock", FlowGraphDegToRadBlock);
  FlowGraphRadToDegBlock = class FlowGraphRadToDegBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicRadToDeg(a), "FlowGraphRadToDegBlock", config);
    }
    _radToDeg(a) {
      return a * 180 / Math.PI;
    }
    _polymorphicRadToDeg(a) {
      return _componentWiseUnaryOperation(a, this._radToDeg);
    }
  };
  RegisterClass("FlowGraphRadToDegBlock", FlowGraphRadToDegBlock);
  FlowGraphAsinBlock = class FlowGraphAsinBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAsin(a), "FlowGraphASinBlock", config);
    }
    _polymorphicAsin(a) {
      return _componentWiseUnaryOperation(a, Math.asin);
    }
  };
  RegisterClass("FlowGraphASinBlock", FlowGraphAsinBlock);
  FlowGraphAcosBlock = class FlowGraphAcosBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAcos(a), "FlowGraphACosBlock", config);
    }
    _polymorphicAcos(a) {
      return _componentWiseUnaryOperation(a, Math.acos);
    }
  };
  RegisterClass("FlowGraphACosBlock", FlowGraphAcosBlock);
  FlowGraphAtanBlock = class FlowGraphAtanBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeNumber, (a) => this._polymorphicAtan(a), "FlowGraphATanBlock", config);
    }
    _polymorphicAtan(a) {
      return _componentWiseUnaryOperation(a, Math.atan);
    }
  };
  RegisterClass("FlowGraphATanBlock", FlowGraphAtanBlock);
  FlowGraphAtan2Block = class FlowGraphAtan2Block extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeAny, (a, b) => this._polymorphicAtan2(a, b), "FlowGraphATan2Block", config);
    }
    _polymorphicAtan2(a, b) {
      return _componentWiseBinaryOperation(a, b, Math.atan2);
    }
  };
  RegisterClass("FlowGraphATan2Block", FlowGraphAtan2Block);
  FlowGraphSinhBlock = class FlowGraphSinhBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicSinh(a), "FlowGraphSinhBlock", config);
    }
    _polymorphicSinh(a) {
      return _componentWiseUnaryOperation(a, Math.sinh);
    }
  };
  RegisterClass("FlowGraphSinhBlock", FlowGraphSinhBlock);
  FlowGraphCoshBlock = class FlowGraphCoshBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicCosh(a), "FlowGraphCoshBlock", config);
    }
    _polymorphicCosh(a) {
      return _componentWiseUnaryOperation(a, Math.cosh);
    }
  };
  RegisterClass("FlowGraphCoshBlock", FlowGraphCoshBlock);
  FlowGraphTanhBlock = class FlowGraphTanhBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicTanh(a), "FlowGraphTanhBlock", config);
    }
    _polymorphicTanh(a) {
      return _componentWiseUnaryOperation(a, Math.tanh);
    }
  };
  RegisterClass("FlowGraphTanhBlock", FlowGraphTanhBlock);
  FlowGraphAsinhBlock = class FlowGraphAsinhBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAsinh(a), "FlowGraphASinhBlock", config);
    }
    _polymorphicAsinh(a) {
      return _componentWiseUnaryOperation(a, Math.asinh);
    }
  };
  RegisterClass("FlowGraphASinhBlock", FlowGraphAsinhBlock);
  FlowGraphAcoshBlock = class FlowGraphAcoshBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAcosh(a), "FlowGraphACoshBlock", config);
    }
    _polymorphicAcosh(a) {
      return _componentWiseUnaryOperation(a, Math.acosh);
    }
  };
  RegisterClass("FlowGraphACoshBlock", FlowGraphAcoshBlock);
  FlowGraphAtanhBlock = class FlowGraphAtanhBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicAtanh(a), "FlowGraphATanhBlock", config);
    }
    _polymorphicAtanh(a) {
      return _componentWiseUnaryOperation(a, Math.atanh);
    }
  };
  RegisterClass("FlowGraphATanhBlock", FlowGraphAtanhBlock);
  FlowGraphExpBlock = class FlowGraphExpBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicExp(a), "FlowGraphExponentialBlock", config);
    }
    _polymorphicExp(a) {
      return _componentWiseUnaryOperation(a, Math.exp);
    }
  };
  RegisterClass("FlowGraphExponentialBlock", FlowGraphExpBlock);
  FlowGraphLogBlock = class FlowGraphLogBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog(a), "FlowGraphLogBlock", config);
    }
    _polymorphicLog(a) {
      return _componentWiseUnaryOperation(a, Math.log);
    }
  };
  RegisterClass("FlowGraphLogBlock", FlowGraphLogBlock);
  FlowGraphLog2Block = class FlowGraphLog2Block extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog2(a), "FlowGraphLog2Block", config);
    }
    _polymorphicLog2(a) {
      return _componentWiseUnaryOperation(a, Math.log2);
    }
  };
  RegisterClass("FlowGraphLog2Block", FlowGraphLog2Block);
  FlowGraphLog10Block = class FlowGraphLog10Block extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLog10(a), "FlowGraphLog10Block", config);
    }
    _polymorphicLog10(a) {
      return _componentWiseUnaryOperation(a, Math.log10);
    }
  };
  RegisterClass("FlowGraphLog10Block", FlowGraphLog10Block);
  FlowGraphSquareRootBlock = class FlowGraphSquareRootBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicSqrt(a), "FlowGraphSquareRootBlock", config);
    }
    _polymorphicSqrt(a) {
      return _componentWiseUnaryOperation(a, Math.sqrt);
    }
  };
  RegisterClass("FlowGraphSquareRootBlock", FlowGraphSquareRootBlock);
  FlowGraphCubeRootBlock = class FlowGraphCubeRootBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicCubeRoot(a), "FlowGraphCubeRootBlock", config);
    }
    _polymorphicCubeRoot(a) {
      return _componentWiseUnaryOperation(a, Math.cbrt);
    }
  };
  RegisterClass("FlowGraphCubeRootBlock", FlowGraphCubeRootBlock);
  FlowGraphPowerBlock = class FlowGraphPowerBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, RichTypeNumber, (a, b) => this._polymorphicPow(a, b), "FlowGraphPowerBlock", config);
    }
    _polymorphicPow(a, b) {
      return _componentWiseBinaryOperation(a, b, Math.pow);
    }
  };
  RegisterClass("FlowGraphPowerBlock", FlowGraphPowerBlock);
  FlowGraphBitwiseNotBlock = class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), (a) => {
        if (typeof a === "boolean") {
          return !a;
        } else if (typeof a === "number") {
          return ~a;
        }
        return new FlowGraphInteger(~a.value);
      }, "FlowGraphBitwiseNotBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseNotBlock", FlowGraphBitwiseNotBlock);
  FlowGraphBitwiseAndBlock = class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), (a, b) => {
        if (typeof a === "boolean" && typeof b === "boolean") {
          return a && b;
        } else if (typeof a === "number" && typeof b === "number") {
          return a & b;
        } else if (typeof a === "object" && typeof b === "object") {
          return new FlowGraphInteger(a.value & b.value);
        } else {
          throw new Error(`Cannot perform bitwise AND on ${a} and ${b}`);
        }
      }, "FlowGraphBitwiseAndBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseAndBlock", FlowGraphBitwiseAndBlock);
  FlowGraphBitwiseOrBlock = class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), (a, b) => {
        if (typeof a === "boolean" && typeof b === "boolean") {
          return a || b;
        } else if (typeof a === "number" && typeof b === "number") {
          return a | b;
        } else if (typeof a === "object" && typeof b === "object") {
          return new FlowGraphInteger(a.value | b.value);
        } else {
          throw new Error(`Cannot perform bitwise OR on ${a} and ${b}`);
        }
      }, "FlowGraphBitwiseOrBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseOrBlock", FlowGraphBitwiseOrBlock);
  FlowGraphBitwiseXorBlock = class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), getRichTypeByFlowGraphType(config?.valueType || "FlowGraphInteger"), (a, b) => {
        if (typeof a === "boolean" && typeof b === "boolean") {
          return a !== b;
        } else if (typeof a === "number" && typeof b === "number") {
          return a ^ b;
        } else if (typeof a === "object" && typeof b === "object") {
          return new FlowGraphInteger(a.value ^ b.value);
        } else {
          throw new Error(`Cannot perform bitwise XOR on ${a} and ${b}`);
        }
      }, "FlowGraphBitwiseXorBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseXorBlock", FlowGraphBitwiseXorBlock);
  FlowGraphBitwiseLeftShiftBlock = class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a, b) => new FlowGraphInteger(a.value << b.value), "FlowGraphBitwiseLeftShiftBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseLeftShiftBlock", FlowGraphBitwiseLeftShiftBlock);
  FlowGraphBitwiseRightShiftBlock = class FlowGraphBitwiseRightShiftBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a, b) => new FlowGraphInteger(a.value >> b.value), "FlowGraphBitwiseRightShiftBlock", config);
    }
  };
  RegisterClass("FlowGraphBitwiseRightShiftBlock", FlowGraphBitwiseRightShiftBlock);
  FlowGraphLeadingZerosBlock = class FlowGraphLeadingZerosBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(Math.clz32(a.value)), "FlowGraphLeadingZerosBlock", config);
    }
  };
  RegisterClass("FlowGraphLeadingZerosBlock", FlowGraphLeadingZerosBlock);
  FlowGraphTrailingZerosBlock = class FlowGraphTrailingZerosBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(a.value ? 31 - Math.clz32(a.value & -a.value) : 32), "FlowGraphTrailingZerosBlock", config);
    }
  };
  RegisterClass("FlowGraphTrailingZerosBlock", FlowGraphTrailingZerosBlock);
  FlowGraphOneBitsCounterBlock = class FlowGraphOneBitsCounterBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeFlowGraphInteger, (a) => new FlowGraphInteger(_countOnes(a.value)), "FlowGraphOneBitsCounterBlock", config);
    }
  };
  RegisterClass("FlowGraphOneBitsCounterBlock", FlowGraphOneBitsCounterBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Math/flowGraphMathCombineExtractBlocks.js
var FlowGraphMathCombineBlock, FlowGraphMathExtractBlock, FlowGraphCombineVector2Block, FlowGraphCombineVector3Block, FlowGraphCombineVector4Block, FlowGraphCombineMatrixBlock, FlowGraphCombineMatrix2DBlock, FlowGraphCombineMatrix3DBlock, FlowGraphExtractVector2Block, FlowGraphExtractVector3Block, FlowGraphExtractVector4Block, FlowGraphExtractMatrixBlock, FlowGraphExtractMatrix2DBlock, FlowGraphExtractMatrix3DBlock;
var init_flowGraphMathCombineExtractBlocks = __esm(() => {
  init_flowGraphCachedOperationBlock();
  init_flowGraphRichTypes();
  init_flowGraphBlock();
  init_math_vector();
  init_typeStore();
  init_flowGraphMatrix();
  FlowGraphMathCombineBlock = class FlowGraphMathCombineBlock extends FlowGraphCachedOperationBlock {
    constructor(numberOfInputs, type, config) {
      super(type, config);
      for (let i = 0;i < numberOfInputs; i++) {
        this.registerDataInput(`input_${i}`, RichTypeNumber, 0);
      }
    }
  };
  FlowGraphMathExtractBlock = class FlowGraphMathExtractBlock extends FlowGraphBlock {
    constructor(numberOfOutputs, type, config) {
      super(config);
      this.registerDataInput("input", type);
      for (let i = 0;i < numberOfOutputs; i++) {
        this.registerDataOutput(`output_${i}`, RichTypeNumber, 0);
      }
    }
  };
  FlowGraphCombineVector2Block = class FlowGraphCombineVector2Block extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(2, RichTypeVector2, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedVector")) {
        context._setExecutionVariable(this, "cachedVector", new Vector2);
      }
      const vector = context._getExecutionVariable(this, "cachedVector", null);
      vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context));
      return vector;
    }
    getClassName() {
      return "FlowGraphCombineVector2Block";
    }
  };
  RegisterClass("FlowGraphCombineVector2Block", FlowGraphCombineVector2Block);
  FlowGraphCombineVector3Block = class FlowGraphCombineVector3Block extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(3, RichTypeVector3, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedVector")) {
        context._setExecutionVariable(this, "cachedVector", new Vector3);
      }
      const vector = context._getExecutionVariable(this, "cachedVector", null);
      vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context));
      return vector;
    }
    getClassName() {
      return "FlowGraphCombineVector3Block";
    }
  };
  RegisterClass("FlowGraphCombineVector3Block", FlowGraphCombineVector3Block);
  FlowGraphCombineVector4Block = class FlowGraphCombineVector4Block extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(4, RichTypeVector4, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedVector")) {
        context._setExecutionVariable(this, "cachedVector", new Vector4);
      }
      const vector = context._getExecutionVariable(this, "cachedVector", null);
      vector.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_3").getValue(context));
      return vector;
    }
    getClassName() {
      return "FlowGraphCombineVector4Block";
    }
  };
  RegisterClass("FlowGraphCombineVector4Block", FlowGraphCombineVector4Block);
  FlowGraphCombineMatrixBlock = class FlowGraphCombineMatrixBlock extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(16, RichTypeMatrix, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedMatrix")) {
        context._setExecutionVariable(this, "cachedMatrix", new Matrix);
      }
      const matrix = context._getExecutionVariable(this, "cachedMatrix", null);
      if (this.config?.inputIsColumnMajor) {
        matrix.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_4").getValue(context), this.getDataInput("input_8").getValue(context), this.getDataInput("input_12").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_5").getValue(context), this.getDataInput("input_9").getValue(context), this.getDataInput("input_13").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_6").getValue(context), this.getDataInput("input_10").getValue(context), this.getDataInput("input_14").getValue(context), this.getDataInput("input_3").getValue(context), this.getDataInput("input_7").getValue(context), this.getDataInput("input_11").getValue(context), this.getDataInput("input_15").getValue(context));
      } else {
        matrix.set(this.getDataInput("input_0").getValue(context), this.getDataInput("input_1").getValue(context), this.getDataInput("input_2").getValue(context), this.getDataInput("input_3").getValue(context), this.getDataInput("input_4").getValue(context), this.getDataInput("input_5").getValue(context), this.getDataInput("input_6").getValue(context), this.getDataInput("input_7").getValue(context), this.getDataInput("input_8").getValue(context), this.getDataInput("input_9").getValue(context), this.getDataInput("input_10").getValue(context), this.getDataInput("input_11").getValue(context), this.getDataInput("input_12").getValue(context), this.getDataInput("input_13").getValue(context), this.getDataInput("input_14").getValue(context), this.getDataInput("input_15").getValue(context));
      }
      return matrix;
    }
    getClassName() {
      return "FlowGraphCombineMatrixBlock";
    }
  };
  RegisterClass("FlowGraphCombineMatrixBlock", FlowGraphCombineMatrixBlock);
  FlowGraphCombineMatrix2DBlock = class FlowGraphCombineMatrix2DBlock extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(4, RichTypeMatrix2D, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedMatrix")) {
        context._setExecutionVariable(this, "cachedMatrix", new FlowGraphMatrix2D);
      }
      const matrix = context._getExecutionVariable(this, "cachedMatrix", null);
      const array = this.config?.inputIsColumnMajor ? [
        this.getDataInput("input_0").getValue(context),
        this.getDataInput("input_2").getValue(context),
        this.getDataInput("input_1").getValue(context),
        this.getDataInput("input_3").getValue(context)
      ] : [
        this.getDataInput("input_0").getValue(context),
        this.getDataInput("input_1").getValue(context),
        this.getDataInput("input_2").getValue(context),
        this.getDataInput("input_3").getValue(context)
      ];
      matrix.fromArray(array);
      return matrix;
    }
    getClassName() {
      return "FlowGraphCombineMatrix2DBlock";
    }
  };
  RegisterClass("FlowGraphCombineMatrix2DBlock", FlowGraphCombineMatrix2DBlock);
  FlowGraphCombineMatrix3DBlock = class FlowGraphCombineMatrix3DBlock extends FlowGraphMathCombineBlock {
    constructor(config) {
      super(9, RichTypeMatrix3D, config);
    }
    _doOperation(context) {
      if (!context._hasExecutionVariable(this, "cachedMatrix")) {
        context._setExecutionVariable(this, "cachedMatrix", new FlowGraphMatrix3D);
      }
      const matrix = context._getExecutionVariable(this, "cachedMatrix", null);
      const array = this.config?.inputIsColumnMajor ? [
        this.getDataInput("input_0").getValue(context),
        this.getDataInput("input_3").getValue(context),
        this.getDataInput("input_6").getValue(context),
        this.getDataInput("input_1").getValue(context),
        this.getDataInput("input_4").getValue(context),
        this.getDataInput("input_7").getValue(context),
        this.getDataInput("input_2").getValue(context),
        this.getDataInput("input_5").getValue(context),
        this.getDataInput("input_8").getValue(context)
      ] : [
        this.getDataInput("input_0").getValue(context),
        this.getDataInput("input_1").getValue(context),
        this.getDataInput("input_2").getValue(context),
        this.getDataInput("input_3").getValue(context),
        this.getDataInput("input_4").getValue(context),
        this.getDataInput("input_5").getValue(context),
        this.getDataInput("input_6").getValue(context),
        this.getDataInput("input_7").getValue(context),
        this.getDataInput("input_8").getValue(context)
      ];
      matrix.fromArray(array);
      return matrix;
    }
    getClassName() {
      return "FlowGraphCombineMatrix3DBlock";
    }
  };
  RegisterClass("FlowGraphCombineMatrix3DBlock", FlowGraphCombineMatrix3DBlock);
  FlowGraphExtractVector2Block = class FlowGraphExtractVector2Block extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(2, RichTypeVector2, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = Vector2.Zero();
        this.getDataInput("input").setValue(input, context);
      }
      this.getDataOutput("output_0").setValue(input.x, context);
      this.getDataOutput("output_1").setValue(input.y, context);
    }
    getClassName() {
      return "FlowGraphExtractVector2Block";
    }
  };
  RegisterClass("FlowGraphExtractVector2Block", FlowGraphExtractVector2Block);
  FlowGraphExtractVector3Block = class FlowGraphExtractVector3Block extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(3, RichTypeVector3, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = Vector3.Zero();
        this.getDataInput("input").setValue(input, context);
      }
      this.getDataOutput("output_0").setValue(input.x, context);
      this.getDataOutput("output_1").setValue(input.y, context);
      this.getDataOutput("output_2").setValue(input.z, context);
    }
    getClassName() {
      return "FlowGraphExtractVector3Block";
    }
  };
  RegisterClass("FlowGraphExtractVector3Block", FlowGraphExtractVector3Block);
  FlowGraphExtractVector4Block = class FlowGraphExtractVector4Block extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(4, RichTypeVector4, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = Vector4.Zero();
        this.getDataInput("input").setValue(input, context);
      }
      this.getDataOutput("output_0").setValue(input.x, context);
      this.getDataOutput("output_1").setValue(input.y, context);
      this.getDataOutput("output_2").setValue(input.z, context);
      this.getDataOutput("output_3").setValue(input.w, context);
    }
    getClassName() {
      return "FlowGraphExtractVector4Block";
    }
  };
  RegisterClass("FlowGraphExtractVector4Block", FlowGraphExtractVector4Block);
  FlowGraphExtractMatrixBlock = class FlowGraphExtractMatrixBlock extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(16, RichTypeMatrix, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = Matrix.Identity();
        this.getDataInput("input").setValue(input, context);
      }
      for (let i = 0;i < 16; i++) {
        this.getDataOutput(`output_${i}`).setValue(input.m[i], context);
      }
    }
    getClassName() {
      return "FlowGraphExtractMatrixBlock";
    }
  };
  RegisterClass("FlowGraphExtractMatrixBlock", FlowGraphExtractMatrixBlock);
  FlowGraphExtractMatrix2DBlock = class FlowGraphExtractMatrix2DBlock extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(4, RichTypeMatrix2D, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = new FlowGraphMatrix2D;
        this.getDataInput("input").setValue(input, context);
      }
      for (let i = 0;i < 4; i++) {
        this.getDataOutput(`output_${i}`).setValue(input.m[i], context);
      }
    }
    getClassName() {
      return "FlowGraphExtractMatrix2DBlock";
    }
  };
  RegisterClass("FlowGraphExtractMatrix2DBlock", FlowGraphExtractMatrix2DBlock);
  FlowGraphExtractMatrix3DBlock = class FlowGraphExtractMatrix3DBlock extends FlowGraphMathExtractBlock {
    constructor(config) {
      super(9, RichTypeMatrix3D, config);
    }
    _updateOutputs(context) {
      let input = this.getDataInput("input")?.getValue(context);
      if (!input) {
        input = new FlowGraphMatrix3D;
        this.getDataInput("input").setValue(input, context);
      }
      for (let i = 0;i < 9; i++) {
        this.getDataOutput(`output_${i}`).setValue(input.m[i], context);
      }
    }
    getClassName() {
      return "FlowGraphExtractMatrix3DBlock";
    }
  };
  RegisterClass("FlowGraphExtractMatrix3DBlock", FlowGraphExtractMatrix3DBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Math/flowGraphMatrixMathBlocks.js
var FlowGraphTransposeBlock, FlowGraphDeterminantBlock, FlowGraphInvertMatrixBlock, FlowGraphMatrixMultiplicationBlock, FlowGraphMatrixDecomposeBlock, FlowGraphMatrixComposeBlock;
var init_flowGraphMatrixMathBlocks = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_math_vector();
  init_typeStore();
  init_flowGraphUnaryOperationBlock();
  init_flowGraphBinaryOperationBlock();
  FlowGraphTransposeBlock = class FlowGraphTransposeBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), (a) => a.transpose ? a.transpose() : Matrix.Transpose(a), "FlowGraphTransposeBlock", config);
    }
  };
  RegisterClass("FlowGraphTransposeBlock", FlowGraphTransposeBlock);
  FlowGraphDeterminantBlock = class FlowGraphDeterminantBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), RichTypeNumber, (a) => a.determinant(), "FlowGraphDeterminantBlock", config);
    }
  };
  RegisterClass("FlowGraphDeterminantBlock", FlowGraphDeterminantBlock);
  FlowGraphInvertMatrixBlock = class FlowGraphInvertMatrixBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), (a) => a.inverse ? a.inverse() : Matrix.Invert(a), "FlowGraphInvertMatrixBlock", config);
    }
  };
  RegisterClass("FlowGraphInvertMatrixBlock", FlowGraphInvertMatrixBlock);
  FlowGraphMatrixMultiplicationBlock = class FlowGraphMatrixMultiplicationBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), getRichTypeByFlowGraphType(config?.matrixType || "Matrix"), (a, b) => b.multiply(a), "FlowGraphMatrixMultiplicationBlock", config);
    }
  };
  RegisterClass("FlowGraphMatrixMultiplicationBlock", FlowGraphMatrixMultiplicationBlock);
  FlowGraphMatrixDecomposeBlock = class FlowGraphMatrixDecomposeBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.input = this.registerDataInput("input", RichTypeMatrix);
      this.position = this.registerDataOutput("position", RichTypeVector3);
      this.rotationQuaternion = this.registerDataOutput("rotationQuaternion", RichTypeQuaternion);
      this.scaling = this.registerDataOutput("scaling", RichTypeVector3);
      this.isValid = this.registerDataOutput("isValid", RichTypeBoolean, false);
    }
    _updateOutputs(context) {
      const cachedExecutionId = context._getExecutionVariable(this, "executionId", -1);
      const cachedPosition = context._getExecutionVariable(this, "cachedPosition", null);
      const cachedRotation = context._getExecutionVariable(this, "cachedRotation", null);
      const cachedScaling = context._getExecutionVariable(this, "cachedScaling", null);
      if (cachedExecutionId === context.executionId && cachedPosition && cachedRotation && cachedScaling) {
        this.position.setValue(cachedPosition, context);
        this.rotationQuaternion.setValue(cachedRotation, context);
        this.scaling.setValue(cachedScaling, context);
      } else {
        const matrix = this.input.getValue(context);
        const position = cachedPosition || new Vector3;
        const rotation = cachedRotation || new Quaternion;
        const scaling = cachedScaling || new Vector3;
        const m3 = Math.round(matrix.m[3] * 1e4) / 1e4;
        const m7 = Math.round(matrix.m[7] * 1e4) / 1e4;
        const m11 = Math.round(matrix.m[11] * 1e4) / 1e4;
        const m15 = Math.round(matrix.m[15] * 1e4) / 1e4;
        if (m3 !== 0 || m7 !== 0 || m11 !== 0 || m15 !== 1) {
          this.isValid.setValue(false, context);
          this.position.setValue(Vector3.Zero(), context);
          this.rotationQuaternion.setValue(Quaternion.Identity(), context);
          this.scaling.setValue(Vector3.One(), context);
          return;
        }
        const valid = matrix.decompose(scaling, rotation, position);
        this.isValid.setValue(valid, context);
        this.position.setValue(position, context);
        this.rotationQuaternion.setValue(rotation, context);
        this.scaling.setValue(scaling, context);
        context._setExecutionVariable(this, "cachedPosition", position);
        context._setExecutionVariable(this, "cachedRotation", rotation);
        context._setExecutionVariable(this, "cachedScaling", scaling);
        context._setExecutionVariable(this, "executionId", context.executionId);
      }
    }
    getClassName() {
      return "FlowGraphMatrixDecompose";
    }
  };
  RegisterClass("FlowGraphMatrixDecompose", FlowGraphMatrixDecomposeBlock);
  FlowGraphMatrixComposeBlock = class FlowGraphMatrixComposeBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.position = this.registerDataInput("position", RichTypeVector3);
      this.rotationQuaternion = this.registerDataInput("rotationQuaternion", RichTypeQuaternion);
      this.scaling = this.registerDataInput("scaling", RichTypeVector3);
      this.value = this.registerDataOutput("value", RichTypeMatrix);
    }
    _updateOutputs(context) {
      const cachedExecutionId = context._getExecutionVariable(this, "executionId", -1);
      const cachedMatrix = context._getExecutionVariable(this, "cachedMatrix", null);
      if (cachedExecutionId === context.executionId && cachedMatrix) {
        this.value.setValue(cachedMatrix, context);
      } else {
        const matrix = Matrix.Compose(this.scaling.getValue(context), this.rotationQuaternion.getValue(context), this.position.getValue(context));
        this.value.setValue(matrix, context);
        context._setExecutionVariable(this, "cachedMatrix", matrix);
        context._setExecutionVariable(this, "executionId", context.executionId);
      }
    }
    getClassName() {
      return "FlowGraphMatrixCompose";
    }
  };
  RegisterClass("FlowGraphMatrixCompose", FlowGraphMatrixComposeBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Math/flowGraphVectorMathBlocks.js
function _transformVector(a, b) {
  const className = _getClassNameOf(a);
  switch (className) {
    case "Vector2":
      return b.transformVector(a);
    case "Vector3":
      return b.transformVector(a);
    case "Vector4":
      a = a;
      return new Vector4(a.x * b.m[0] + a.y * b.m[1] + a.z * b.m[2] + a.w * b.m[3], a.x * b.m[4] + a.y * b.m[5] + a.z * b.m[6] + a.w * b.m[7], a.x * b.m[8] + a.y * b.m[9] + a.z * b.m[10] + a.w * b.m[11], a.x * b.m[12] + a.y * b.m[13] + a.z * b.m[14] + a.w * b.m[15]);
    default:
      throw new Error(`Cannot transform value ${a}`);
  }
}
var FlowGraphLengthBlock, FlowGraphNormalizeBlock, FlowGraphDotBlock, FlowGraphCrossBlock, FlowGraphRotate2DBlock, FlowGraphRotate3DBlock, FlowGraphTransformBlock, FlowGraphTransformCoordinatesBlock;
var init_flowGraphVectorMathBlocks = __esm(() => {
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphBinaryOperationBlock();
  init_flowGraphUnaryOperationBlock();
  init_math_vector();
  init_flowGraphTernaryOperationBlock();
  FlowGraphLengthBlock = class FlowGraphLengthBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeNumber, (a) => this._polymorphicLength(a), "FlowGraphLengthBlock", config);
    }
    _polymorphicLength(a) {
      const aClassName = _getClassNameOf(a);
      switch (aClassName) {
        case "Vector2":
        case "Vector3":
        case "Vector4":
        case "Quaternion":
          return a.length();
        default:
          throw new Error(`Cannot compute length of value ${a}`);
      }
    }
  };
  RegisterClass("FlowGraphLengthBlock", FlowGraphLengthBlock);
  FlowGraphNormalizeBlock = class FlowGraphNormalizeBlock extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, (a) => this._polymorphicNormalize(a), "FlowGraphNormalizeBlock", config);
    }
    _polymorphicNormalize(a) {
      const aClassName = _getClassNameOf(a);
      let normalized;
      switch (aClassName) {
        case "Vector2":
        case "Vector3":
        case "Vector4":
        case "Quaternion":
          normalized = a.normalizeToNew();
          if (this.config?.nanOnZeroLength) {
            const length = a.length();
            if (length === 0) {
              normalized.setAll(NaN);
            }
          }
          return normalized;
        default:
          throw new Error(`Cannot normalize value ${a}`);
      }
    }
  };
  RegisterClass("FlowGraphNormalizeBlock", FlowGraphNormalizeBlock);
  FlowGraphDotBlock = class FlowGraphDotBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeAny, RichTypeAny, RichTypeNumber, (a, b) => this._polymorphicDot(a, b), "FlowGraphDotBlock", config);
    }
    _polymorphicDot(a, b) {
      const className = _getClassNameOf(a);
      switch (className) {
        case "Vector2":
        case "Vector3":
        case "Vector4":
        case "Quaternion":
          return a.dot(b);
        default:
          throw new Error(`Cannot get dot product of ${a} and ${b}`);
      }
    }
  };
  RegisterClass("FlowGraphDotBlock", FlowGraphDotBlock);
  FlowGraphCrossBlock = class FlowGraphCrossBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeVector3, RichTypeVector3, RichTypeVector3, (a, b) => Vector3.Cross(a, b), "FlowGraphCrossBlock", config);
    }
  };
  RegisterClass("FlowGraphCrossBlock", FlowGraphCrossBlock);
  FlowGraphRotate2DBlock = class FlowGraphRotate2DBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeVector2, RichTypeNumber, RichTypeVector2, (a, b) => Vector2.Transform(a, Matrix.RotationZ(b)), "FlowGraphRotate2DBlock", config);
    }
  };
  RegisterClass("FlowGraphRotate2DBlock", FlowGraphRotate2DBlock);
  FlowGraphRotate3DBlock = class FlowGraphRotate3DBlock extends FlowGraphTernaryOperationBlock {
    constructor(config) {
      super(RichTypeVector3, RichTypeVector3, RichTypeNumber, RichTypeVector3, (a, b, c) => Vector3.TransformCoordinates(a, Matrix.RotationAxis(b, c)), "FlowGraphRotate3DBlock", config);
    }
  };
  RegisterClass("FlowGraphRotate3DBlock", FlowGraphRotate3DBlock);
  FlowGraphTransformBlock = class FlowGraphTransformBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      const vectorType = config?.vectorType || "Vector3";
      const matrixType = vectorType === "Vector2" ? "Matrix2D" : vectorType === "Vector3" ? "Matrix3D" : "Matrix";
      super(getRichTypeByFlowGraphType(vectorType), getRichTypeByFlowGraphType(matrixType), getRichTypeByFlowGraphType(vectorType), _transformVector, "FlowGraphTransformVectorBlock", config);
    }
  };
  RegisterClass("FlowGraphTransformVectorBlock", FlowGraphTransformBlock);
  FlowGraphTransformCoordinatesBlock = class FlowGraphTransformCoordinatesBlock extends FlowGraphBinaryOperationBlock {
    constructor(config) {
      super(RichTypeVector3, RichTypeMatrix, RichTypeVector3, (a, b) => Vector3.TransformCoordinates(a, b), "FlowGraphTransformCoordinatesBlock", config);
    }
  };
  RegisterClass("FlowGraphTransformCoordinatesBlock", FlowGraphTransformCoordinatesBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Transformers/flowGraphJsonPointerParserBlock.js
function ToColor(value, expectedValue) {
  if (value.getClassName().startsWith("Color")) {
    return value;
  }
  if (expectedValue === "Color3") {
    return new Color3(value.x, value.y, value.z);
  } else if (expectedValue === "Color4") {
    return new Color4(value.x, value.y, value.z, value.w);
  }
  return value;
}
var FlowGraphJsonPointerParserBlock;
var init_flowGraphJsonPointerParserBlock = __esm(() => {
  init_flowGraphPathConverterComponent();
  init_flowGraphRichTypes();
  init_typeStore();
  init_math_color();
  init_flowGraphCachedOperationBlock();
  FlowGraphJsonPointerParserBlock = class FlowGraphJsonPointerParserBlock extends FlowGraphCachedOperationBlock {
    constructor(config) {
      super(RichTypeAny, config);
      this.config = config;
      this.object = this.registerDataOutput("object", RichTypeAny);
      this.propertyName = this.registerDataOutput("propertyName", RichTypeAny);
      this.setterFunction = this.registerDataOutput("setFunction", RichTypeAny, this._setPropertyValue.bind(this));
      this.getterFunction = this.registerDataOutput("getFunction", RichTypeAny, this._getPropertyValue.bind(this));
      this.generateAnimationsFunction = this.registerDataOutput("generateAnimationsFunction", RichTypeAny, this._getInterpolationAnimationPropertyInfo.bind(this));
      this.templateComponent = new FlowGraphPathConverterComponent(config.jsonPointer, this);
    }
    _doOperation(context) {
      const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context);
      const value = accessorContainer.info.get(accessorContainer.object);
      const object = accessorContainer.info.getTarget?.(accessorContainer.object);
      const propertyName = accessorContainer.info.getPropertyName?.[0](accessorContainer.object);
      if (!object) {
        throw new Error("Object is undefined");
      } else {
        this.object.setValue(object, context);
        if (propertyName) {
          this.propertyName.setValue(propertyName, context);
        }
      }
      return value;
    }
    _setPropertyValue(_target, _propertyName, value, context) {
      const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context);
      const type = accessorContainer.info.type;
      if (type.startsWith("Color")) {
        value = ToColor(value, type);
      }
      accessorContainer.info.set?.(value, accessorContainer.object);
    }
    _getPropertyValue(_target, _propertyName, context) {
      const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context);
      return accessorContainer.info.get(accessorContainer.object);
    }
    _getInterpolationAnimationPropertyInfo(_target, _propertyName, context) {
      const accessorContainer = this.templateComponent.getAccessor(this.config.pathConverter, context);
      return (keys, fps, animationType, easingFunction) => {
        const animations = [];
        const type = accessorContainer.info.type;
        if (type.startsWith("Color")) {
          keys = keys.map((key) => {
            return {
              frame: key.frame,
              value: ToColor(key.value, type)
            };
          });
        }
        accessorContainer.info.interpolation?.forEach((info, index) => {
          const name157 = accessorContainer.info.getPropertyName?.[index](accessorContainer.object) || "Animation-interpolation-" + index;
          let newKeys = keys;
          if (animationType !== info.type) {
            newKeys = keys.map((key) => {
              return {
                frame: key.frame,
                value: info.getValue(undefined, key.value.asArray ? key.value.asArray() : [key.value], 0, 1)
              };
            });
          }
          const animationData = info.buildAnimations(accessorContainer.object, name157, 60, newKeys);
          animationData.forEach((animation2) => {
            if (easingFunction) {
              animation2.babylonAnimation.setEasingFunction(easingFunction);
            }
            animations.push(animation2.babylonAnimation);
          });
        });
        return animations;
      };
    }
    getClassName() {
      return "FlowGraphJsonPointerParserBlock";
    }
  };
  RegisterClass("FlowGraphJsonPointerParserBlock", FlowGraphJsonPointerParserBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Transformers/flowGraphTypeToTypeBlocks.js
var FlowGraphBooleanToFloat, FlowGraphBooleanToInt, FlowGraphFloatToBoolean, FlowGraphIntToBoolean, FlowGraphIntToFloat, FlowGraphFloatToInt;
var init_flowGraphTypeToTypeBlocks = __esm(() => {
  init_flowGraphUnaryOperationBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphBooleanToFloat = class FlowGraphBooleanToFloat extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeBoolean, RichTypeNumber, (a) => +a, "FlowGraphBooleanToFloat", config);
    }
  };
  RegisterClass("FlowGraphBooleanToFloat", FlowGraphBooleanToFloat);
  FlowGraphBooleanToInt = class FlowGraphBooleanToInt extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeBoolean, RichTypeFlowGraphInteger, (a) => FlowGraphInteger.FromValue(+a), "FlowGraphBooleanToInt", config);
    }
  };
  RegisterClass("FlowGraphBooleanToInt", FlowGraphBooleanToInt);
  FlowGraphFloatToBoolean = class FlowGraphFloatToBoolean extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeBoolean, (a) => !!a, "FlowGraphFloatToBoolean", config);
    }
  };
  RegisterClass("FlowGraphFloatToBoolean", FlowGraphFloatToBoolean);
  FlowGraphIntToBoolean = class FlowGraphIntToBoolean extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeBoolean, (a) => !!a.value, "FlowGraphIntToBoolean", config);
    }
  };
  RegisterClass("FlowGraphIntToBoolean", FlowGraphIntToBoolean);
  FlowGraphIntToFloat = class FlowGraphIntToFloat extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeFlowGraphInteger, RichTypeNumber, (a) => a.value, "FlowGraphIntToFloat", config);
    }
  };
  RegisterClass("FlowGraphIntToFloat", FlowGraphIntToFloat);
  FlowGraphFloatToInt = class FlowGraphFloatToInt extends FlowGraphUnaryOperationBlock {
    constructor(config) {
      super(RichTypeNumber, RichTypeFlowGraphInteger, (a) => {
        const roundingMode = config?.roundingMode;
        switch (roundingMode) {
          case "floor":
            return FlowGraphInteger.FromValue(Math.floor(a));
          case "ceil":
            return FlowGraphInteger.FromValue(Math.ceil(a));
          case "round":
            return FlowGraphInteger.FromValue(Math.round(a));
          default:
            return FlowGraphInteger.FromValue(a);
        }
      }, "FlowGraphFloatToInt", config);
    }
  };
  RegisterClass("FlowGraphFloatToInt", FlowGraphFloatToInt);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/flowGraphContextBlock.js
var FlowGraphContextBlock;
var init_flowGraphContextBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphContextBlock = class FlowGraphContextBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.userVariables = this.registerDataOutput("userVariables", RichTypeAny);
      this.executionId = this.registerDataOutput("executionId", RichTypeNumber);
    }
    _updateOutputs(context) {
      this.userVariables.setValue(context.userVariables, context);
      this.executionId.setValue(context.executionId, context);
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
    }
    getClassName() {
      return "FlowGraphContextBlock";
    }
  };
  RegisterClass("FlowGraphContextBlock", FlowGraphContextBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/flowGraphArrayIndexBlock.js
var FlowGraphArrayIndexBlock;
var init_flowGraphArrayIndexBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphArrayIndexBlock = class FlowGraphArrayIndexBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.array = this.registerDataInput("array", RichTypeAny);
      this.index = this.registerDataInput("index", RichTypeAny, new FlowGraphInteger(-1));
      this.value = this.registerDataOutput("value", RichTypeAny);
    }
    _updateOutputs(context) {
      const array = this.array.getValue(context);
      const index = getNumericValue(this.index.getValue(context));
      if (array && index >= 0 && index < array.length) {
        this.value.setValue(array[index], context);
      } else {
        this.value.setValue(null, context);
      }
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
    }
    getClassName() {
      return "FlowGraphArrayIndexBlock";
    }
  };
  RegisterClass("FlowGraphArrayIndexBlock", FlowGraphArrayIndexBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/flowGraphCodeExecutionBlock.js
var init_flowGraphCodeExecutionBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/flowGraphIndexOfBlock.js
var FlowGraphIndexOfBlock;
var init_flowGraphIndexOfBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  init_flowGraphInteger();
  FlowGraphIndexOfBlock = class FlowGraphIndexOfBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.object = this.registerDataInput("object", RichTypeAny);
      this.array = this.registerDataInput("array", RichTypeAny);
      this.index = this.registerDataOutput("index", RichTypeFlowGraphInteger, new FlowGraphInteger(-1));
    }
    _updateOutputs(context) {
      const object = this.object.getValue(context);
      const array = this.array.getValue(context);
      if (array) {
        this.index.setValue(new FlowGraphInteger(array.indexOf(object)), context);
      }
    }
    serialize(serializationObject) {
      super.serialize(serializationObject);
    }
    getClassName() {
      return "FlowGraphIndexOfBlock";
    }
  };
  RegisterClass("FlowGraphIndexOfBlock", FlowGraphIndexOfBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/flowGraphFunctionReferenceBlock.js
var FlowGraphFunctionReferenceBlock;
var init_flowGraphFunctionReferenceBlock = __esm(() => {
  init_flowGraphBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphFunctionReferenceBlock = class FlowGraphFunctionReferenceBlock extends FlowGraphBlock {
    constructor(config) {
      super(config);
      this.functionName = this.registerDataInput("functionName", RichTypeString);
      this.object = this.registerDataInput("object", RichTypeAny);
      this.context = this.registerDataInput("context", RichTypeAny, null);
      this.output = this.registerDataOutput("output", RichTypeAny);
    }
    _updateOutputs(context) {
      const functionName = this.functionName.getValue(context);
      const object = this.object.getValue(context);
      const contextValue = this.context.getValue(context);
      if (object && functionName) {
        const func = object[functionName];
        if (func && typeof func === "function") {
          this.output.setValue(func.bind(contextValue), context);
        }
      }
    }
    getClassName() {
      return "FlowGraphFunctionReference";
    }
  };
  RegisterClass("FlowGraphFunctionReference", FlowGraphFunctionReferenceBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphMeshPickEventBlock.js
var FlowGraphMeshPickEventBlock;
var init_flowGraphMeshPickEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_pointerEvents();
  init_typeStore();
  init_flowGraphRichTypes();
  FlowGraphMeshPickEventBlock = class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.type = "MeshPick";
      this.asset = this.registerDataInput("asset", RichTypeAny, config?.targetMesh);
      this.pickedPoint = this.registerDataOutput("pickedPoint", RichTypeVector3);
      this.pickOrigin = this.registerDataOutput("pickOrigin", RichTypeVector3);
      this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber);
      this.pickedMesh = this.registerDataOutput("pickedMesh", RichTypeAny);
      this.pointerType = this.registerDataInput("pointerType", RichTypeAny, PointerEventTypes.POINTERPICK);
    }
    _getReferencedMesh(context) {
      return this.asset.getValue(context);
    }
    _executeEvent(context, pickedInfo) {
      const pointerType = this.pointerType.getValue(context);
      if (pointerType !== pickedInfo.type) {
        return true;
      }
      const mesh = this._getReferencedMesh(context);
      if (mesh && pickedInfo.pickInfo?.pickedMesh && (pickedInfo.pickInfo?.pickedMesh === mesh || _isADescendantOf(pickedInfo.pickInfo?.pickedMesh, mesh))) {
        this.pointerId.setValue(pickedInfo.event.pointerId, context);
        this.pickOrigin.setValue(pickedInfo.pickInfo.ray?.origin, context);
        this.pickedPoint.setValue(pickedInfo.pickInfo.pickedPoint, context);
        this.pickedMesh.setValue(pickedInfo.pickInfo.pickedMesh, context);
        this._execute(context);
        return !this.config?.stopPropagation;
      } else {
        this.pointerId.resetToDefaultValue(context);
        this.pickOrigin.resetToDefaultValue(context);
        this.pickedPoint.resetToDefaultValue(context);
        this.pickedMesh.resetToDefaultValue(context);
      }
      return true;
    }
    _preparePendingTasks(_context) {}
    _cancelPendingTasks(_context) {}
    getClassName() {
      return "FlowGraphMeshPickEventBlock";
    }
  };
  RegisterClass("FlowGraphMeshPickEventBlock", FlowGraphMeshPickEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphSceneReadyEventBlock.js
var FlowGraphSceneReadyEventBlock;
var init_flowGraphSceneReadyEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_typeStore();
  FlowGraphSceneReadyEventBlock = class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock {
    constructor() {
      super(...arguments);
      this.initPriority = -1;
      this.type = "SceneReady";
    }
    _executeEvent(context, _payload) {
      this._execute(context);
      return true;
    }
    _preparePendingTasks(context) {}
    _cancelPendingTasks(context) {}
    getClassName() {
      return "FlowGraphSceneReadyEventBlock";
    }
  };
  RegisterClass("FlowGraphSceneReadyEventBlock", FlowGraphSceneReadyEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphReceiveCustomEventBlock.js
var FlowGraphReceiveCustomEventBlock;
var init_flowGraphReceiveCustomEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_tools();
  init_typeStore();
  init_flowGraphCoordinator();
  FlowGraphReceiveCustomEventBlock = class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock {
    constructor(config) {
      super(config);
      this.config = config;
      this.initPriority = 1;
      for (const key in this.config.eventData) {
        this.registerDataOutput(key, this.config.eventData[key].type);
      }
    }
    _preparePendingTasks(context) {
      const observable = context.configuration.coordinator.getCustomEventObservable(this.config.eventId);
      if (observable && observable.hasObservers() && observable.observers.length > FlowGraphCoordinator.MaxEventsPerType) {
        this._reportError(context, `FlowGraphReceiveCustomEventBlock: Too many observers for event ${this.config.eventId}. Max is ${FlowGraphCoordinator.MaxEventsPerType}.`);
        return;
      }
      const eventObserver = observable.add((eventData) => {
        Object.keys(eventData).forEach((key) => {
          this.getDataOutput(key)?.setValue(eventData[key], context);
        });
        this._execute(context);
      });
      context._setExecutionVariable(this, "_eventObserver", eventObserver);
    }
    _cancelPendingTasks(context) {
      const observable = context.configuration.coordinator.getCustomEventObservable(this.config.eventId);
      if (observable) {
        const eventObserver = context._getExecutionVariable(this, "_eventObserver", null);
        observable.remove(eventObserver);
      } else {
        Tools.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`);
      }
    }
    _executeEvent(_context, _payload) {
      return true;
    }
    getClassName() {
      return "FlowGraphReceiveCustomEventBlock";
    }
  };
  RegisterClass("FlowGraphReceiveCustomEventBlock", FlowGraphReceiveCustomEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphSendCustomEventBlock.js
var FlowGraphSendCustomEventBlock;
var init_flowGraphSendCustomEventBlock = __esm(() => {
  init_flowGraphExecutionBlockWithOutSignal();
  init_typeStore();
  FlowGraphSendCustomEventBlock = class FlowGraphSendCustomEventBlock extends FlowGraphExecutionBlockWithOutSignal {
    constructor(config) {
      super(config);
      this.config = config;
      for (const key in this.config.eventData) {
        this.registerDataInput(key, this.config.eventData[key].type, this.config.eventData[key].value);
      }
    }
    _execute(context) {
      const eventId = this.config.eventId;
      const eventData = {};
      this.dataInputs.forEach((port) => {
        eventData[port.name] = port.getValue(context);
      });
      context.configuration.coordinator.notifyCustomEvent(eventId, eventData);
      this.out._activateSignal(context);
    }
    getClassName() {
      return "FlowGraphReceiveCustomEventBlock";
    }
  };
  RegisterClass("FlowGraphReceiveCustomEventBlock", FlowGraphSendCustomEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphSceneTickEventBlock.js
var FlowGraphSceneTickEventBlock;
var init_flowGraphSceneTickEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_typeStore();
  init_flowGraphRichTypes();
  FlowGraphSceneTickEventBlock = class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock {
    constructor() {
      super();
      this.type = "SceneBeforeRender";
      this.timeSinceStart = this.registerDataOutput("timeSinceStart", RichTypeNumber);
      this.deltaTime = this.registerDataOutput("deltaTime", RichTypeNumber);
    }
    _preparePendingTasks(_context) {}
    _executeEvent(context, payload) {
      this.timeSinceStart.setValue(payload.timeSinceStart, context);
      this.deltaTime.setValue(payload.deltaTime, context);
      this._execute(context);
      return true;
    }
    _cancelPendingTasks(_context) {}
    getClassName() {
      return "FlowGraphSceneTickEventBlock";
    }
  };
  RegisterClass("FlowGraphSceneTickEventBlock", FlowGraphSceneTickEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphPointerOutEventBlock.js
var FlowGraphPointerOutEventBlock;
var init_flowGraphPointerOutEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphPointerOutEventBlock = class FlowGraphPointerOutEventBlock extends FlowGraphEventBlock {
    constructor(config) {
      super(config);
      this.type = "PointerOut";
      this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber);
      this.targetMesh = this.registerDataInput("targetMesh", RichTypeAny, config?.targetMesh);
      this.meshOutOfPointer = this.registerDataOutput("meshOutOfPointer", RichTypeAny);
    }
    _executeEvent(context, payload) {
      const mesh = this.targetMesh.getValue(context);
      this.meshOutOfPointer.setValue(payload.mesh, context);
      this.pointerId.setValue(payload.pointerId, context);
      const skipEvent = payload.over && _isADescendantOf(payload.mesh, mesh);
      if (!skipEvent && (payload.mesh === mesh || _isADescendantOf(payload.mesh, mesh))) {
        this._execute(context);
        return !this.config?.stopPropagation;
      }
      return true;
    }
    _preparePendingTasks(_context) {}
    _cancelPendingTasks(_context) {}
    getClassName() {
      return "FlowGraphPointerOutEventBlock";
    }
  };
  RegisterClass("FlowGraphPointerOutEventBlock", FlowGraphPointerOutEventBlock);
});

// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphPointerOverEventBlock.js
var FlowGraphPointerOverEventBlock;
var init_flowGraphPointerOverEventBlock = __esm(() => {
  init_flowGraphEventBlock();
  init_flowGraphRichTypes();
  init_typeStore();
  FlowGraphPointerOverEventBlock = class FlowGraphPointerOverEventBlock extends FlowGraphEventBlock {
    constructor(config) {
      super(config);
      this.type = "PointerOver";
      this.pointerId = this.registerDataOutput("pointerId", RichTypeNumber);
      this.targetMesh = this.registerDataInput("targetMesh", RichTypeAny, config?.targetMesh);
      this.meshUnderPointer = this.registerDataOutput("meshUnderPointer", RichTypeAny);
    }
    _executeEvent(context, payload) {
      const mesh = this.targetMesh.getValue(context);
      this.meshUnderPointer.setValue(payload.mesh, context);
      const skipEvent = payload.out && _isADescendantOf(payload.out, mesh);
      this.pointerId.setValue(payload.pointerId, context);
      if (!skipEvent && (payload.mesh === mesh || _isADescendantOf(payload.mesh, mesh))) {
        this._execute(context);
        return !this.config?.stopPropagation;
      }
      return true;
    }
    _preparePendingTasks(_context) {}
    _cancelPendingTasks(_context) {}
    getClassName() {
      return "FlowGraphPointerOverEventBlock";
    }
  };
  RegisterClass("FlowGraphPointerOverEventBlock", FlowGraphPointerOverEventBlock);
});

// node_modules/@babylonjs/core/ShadersWGSL/copyTextureToTexture.fragment.js
var exports_copyTextureToTexture_fragment = {};
__export(exports_copyTextureToTexture_fragment, {
  copyTextureToTexturePixelShaderWGSL: () => copyTextureToTexturePixelShaderWGSL
});
var name157 = "copyTextureToTexturePixelShader", shader156 = `uniform conversion: f32;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;varying vUV: vec2f;
#include<helperFunctions>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);
#ifdef DEPTH_TEXTURE
fragmentOutputs.fragDepth=color.r;
#else
if (uniforms.conversion==1.) {color=toLinearSpaceVec4(color);} else if (uniforms.conversion==2.) {color=toGammaSpace(color);}
fragmentOutputs.color=color;
#endif
}
`, copyTextureToTexturePixelShaderWGSL;
var init_copyTextureToTexture_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name157]) {
    ShaderStore.ShadersStoreWGSL[name157] = shader156;
  }
  copyTextureToTexturePixelShaderWGSL = { name: name157, shader: shader156 };
});

// node_modules/@babylonjs/core/Shaders/copyTextureToTexture.fragment.js
var exports_copyTextureToTexture_fragment2 = {};
__export(exports_copyTextureToTexture_fragment2, {
  copyTextureToTexturePixelShader: () => copyTextureToTexturePixelShader
});
var name158 = "copyTextureToTexturePixelShader", shader157 = `uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;
#include<helperFunctions>
void main(void) 
{vec4 color=texture2D(textureSampler,vUV);
#ifdef DEPTH_TEXTURE
gl_FragDepth=color.r;
#else
if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}
gl_FragColor=color;
#endif
}
`, copyTextureToTexturePixelShader;
var init_copyTextureToTexture_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name158]) {
    ShaderStore.ShadersStore[name158] = shader157;
  }
  copyTextureToTexturePixelShader = { name: name158, shader: shader157 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVaryingDeclaration.js
var name159 = "kernelBlurVaryingDeclaration", shader158 = `varying sampleCoord{X}: vec2f;`;
var init_kernelBlurVaryingDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name159]) {
    ShaderStore.IncludesShadersStoreWGSL[name159] = shader158;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/packingFunctions.js
var exports_packingFunctions = {};
__export(exports_packingFunctions, {
  packingFunctionsWGSL: () => packingFunctionsWGSL
});
var name160 = "packingFunctions", shader159 = `fn pack(depth: f32)->vec4f
{const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
fn unpack(color: vec4f)->f32
{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`, packingFunctionsWGSL;
var init_packingFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name160]) {
    ShaderStore.IncludesShadersStoreWGSL[name160] = shader159;
  }
  packingFunctionsWGSL = { name: name160, shader: shader159 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment.js
var name161 = "kernelBlurFragment", shader160 = `#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCoord{X}); 
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight;
#endif
`;
var init_kernelBlurFragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name161]) {
    ShaderStore.IncludesShadersStoreWGSL[name161] = shader160;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment2.js
var name162 = "kernelBlurFragment2", shader161 = `#ifdef DOF
factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;
var init_kernelBlurFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name162]) {
    ShaderStore.IncludesShadersStoreWGSL[name162] = shader161;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.fragment.js
var exports_kernelBlur_fragment = {};
__export(exports_kernelBlur_fragment, {
  kernelBlurPixelShaderWGSL: () => kernelBlurPixelShaderWGSL
});
var name163 = "kernelBlurPixelShader", shader162 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform delta: vec2f;varying sampleCenter: vec2f;
#ifdef DOF
var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d<f32>;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; }
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0;
#ifdef PACKEDFLOAT
var blend: f32=0.;
#else
var blend: vec4f= vec4f(0.);
#endif
#ifdef DOF
var sumOfWeights: f32=CENTER_WEIGHT; 
var factor: f32=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT;
#else
blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
fragmentOutputs.color=pack(blend);
#else
fragmentOutputs.color=blend;
#endif
#ifdef DOF
fragmentOutputs.color/=sumOfWeights;
#endif
}`, kernelBlurPixelShaderWGSL;
var init_kernelBlur_fragment = __esm(() => {
  init_shaderStore();
  init_kernelBlurVaryingDeclaration();
  init_packingFunctions();
  init_kernelBlurFragment();
  init_kernelBlurFragment2();
  if (!ShaderStore.ShadersStoreWGSL[name163]) {
    ShaderStore.ShadersStoreWGSL[name163] = shader162;
  }
  kernelBlurPixelShaderWGSL = { name: name163, shader: shader162 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVertex.js
var name164 = "kernelBlurVertex", shader163 = `vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};`;
var init_kernelBlurVertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name164]) {
    ShaderStore.IncludesShadersStoreWGSL[name164] = shader163;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.vertex.js
var exports_kernelBlur_vertex = {};
__export(exports_kernelBlur_vertex, {
  kernelBlurVertexShaderWGSL: () => kernelBlurVertexShaderWGSL
});
var name165 = "kernelBlurVertexShader", shader164 = `attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.sampleCenter=(input.position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, kernelBlurVertexShaderWGSL;
var init_kernelBlur_vertex = __esm(() => {
  init_shaderStore();
  init_kernelBlurVaryingDeclaration();
  init_kernelBlurVertex();
  if (!ShaderStore.ShadersStoreWGSL[name165]) {
    ShaderStore.ShadersStoreWGSL[name165] = shader164;
  }
  kernelBlurVertexShaderWGSL = { name: name165, shader: shader164 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js
var name166 = "kernelBlurVaryingDeclaration", shader165 = `varying vec2 sampleCoord{X};`;
var init_kernelBlurVaryingDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name166]) {
    ShaderStore.IncludesShadersStore[name166] = shader165;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js
var exports_packingFunctions2 = {};
__export(exports_packingFunctions2, {
  packingFunctions: () => packingFunctions
});
var name167 = "packingFunctions", shader166 = `vec4 pack(float depth)
{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}
float unpack(vec4 color)
{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`, packingFunctions;
var init_packingFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name167]) {
    ShaderStore.IncludesShadersStore[name167] = shader166;
  }
  packingFunctions = { name: name167, shader: shader166 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js
var name168 = "kernelBlurFragment", shader167 = `#ifdef DOF
factor=sampleCoC(sampleCoord{X}); 
computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;
#endif
`;
var init_kernelBlurFragment3 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name168]) {
    ShaderStore.IncludesShadersStore[name168] = shader167;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js
var name169 = "kernelBlurFragment2", shader168 = `#ifdef DOF
factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;
#else
computedWeight=KERNEL_DEP_WEIGHT{X};
#endif
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;
#else
blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;
#endif
`;
var init_kernelBlurFragment22 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name169]) {
    ShaderStore.IncludesShadersStore[name169] = shader168;
  }
});

// node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js
var exports_kernelBlur_fragment2 = {};
__export(exports_kernelBlur_fragment2, {
  kernelBlurPixelShader: () => kernelBlurPixelShader
});
var name170 = "kernelBlurPixelShader", shader169 = `uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;
#ifdef DOF
uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }
#endif
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
#ifdef PACKEDFLOAT
#include<packingFunctions>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float computedWeight=0.0;
#ifdef PACKEDFLOAT
float blend=0.;
#else
vec4 blend=vec4(0.);
#endif
#ifdef DOF
float sumOfWeights=CENTER_WEIGHT; 
float factor=0.0;
#ifdef PACKEDFLOAT
blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;
#else
blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;
#endif
#endif
#include<kernelBlurFragment>[0..varyingCount]
#include<kernelBlurFragment2>[0..depCount]
#ifdef PACKEDFLOAT
gl_FragColor=pack(blend);
#else
gl_FragColor=blend;
#endif
#ifdef DOF
gl_FragColor/=sumOfWeights;
#endif
}`, kernelBlurPixelShader;
var init_kernelBlur_fragment2 = __esm(() => {
  init_shaderStore();
  init_kernelBlurVaryingDeclaration2();
  init_packingFunctions2();
  init_kernelBlurFragment3();
  init_kernelBlurFragment22();
  if (!ShaderStore.ShadersStore[name170]) {
    ShaderStore.ShadersStore[name170] = shader169;
  }
  kernelBlurPixelShader = { name: name170, shader: shader169 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js
var name171 = "kernelBlurVertex", shader170 = `sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};`;
var init_kernelBlurVertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name171]) {
    ShaderStore.IncludesShadersStore[name171] = shader170;
  }
});

// node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js
var exports_kernelBlur_vertex2 = {};
__export(exports_kernelBlur_vertex2, {
  kernelBlurVertexShader: () => kernelBlurVertexShader
});
var name172 = "kernelBlurVertexShader", shader171 = `attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;
#include<kernelBlurVaryingDeclaration>[0..varyingCount]
const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
sampleCenter=(position*madd+madd);
#include<kernelBlurVertex>[0..varyingCount]
gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, kernelBlurVertexShader;
var init_kernelBlur_vertex2 = __esm(() => {
  init_shaderStore();
  init_kernelBlurVaryingDeclaration2();
  init_kernelBlurVertex2();
  if (!ShaderStore.ShadersStore[name172]) {
    ShaderStore.ShadersStore[name172] = shader171;
  }
  kernelBlurVertexShader = { name: name172, shader: shader171 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bayerDitherFunctions.js
var name173 = "bayerDitherFunctions", shader172 = `fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));}
fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); 
var P2: vec2f=floor(0.5*((_P)%(4.0))); 
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); 
var P2: vec2f=floor(0.5 *((_P)%(4.0))); 
var P4: vec2f=floor(0.25*((_P)%(8.0))); 
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;
var init_bayerDitherFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name173]) {
    ShaderStore.IncludesShadersStoreWGSL[name173] = shader172;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentExtraDeclaration.js
var name174 = "shadowMapFragmentExtraDeclaration", shader173 = `#if SM_FLOAT==0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include<bayerDitherFunctions>
uniform softTransparentShadowSM: vec2f;
#endif
varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
uniform lightDataSM: vec3f;varying vPositionWSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;
var init_shadowMapFragmentExtraDeclaration = __esm(() => {
  init_shaderStore();
  init_packingFunctions();
  init_bayerDitherFunctions();
  if (!ShaderStore.IncludesShadersStoreWGSL[name174]) {
    ShaderStore.IncludesShadersStoreWGSL[name174] = shader173;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragment.js
var exports_shadowMapFragment = {};
__export(exports_shadowMapFragment, {
  shadowMapFragmentWGSL: () => shadowMapFragmentWGSL
});
var name175 = "shadowMapFragment", shader174 = `var depthSM: f32=fragmentInputs.vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); 
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0);
#else
fragmentOutputs.color=pack(depthSM);
#endif
`, shadowMapFragmentWGSL;
var init_shadowMapFragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name175]) {
    ShaderStore.IncludesShadersStoreWGSL[name175] = shader174;
  }
  shadowMapFragmentWGSL = { name: name175, shader: shader174 };
});

// node_modules/@babylonjs/core/ShadersWGSL/shadowMap.fragment.js
var exports_shadowMap_fragment = {};
__export(exports_shadowMap_fragment, {
  shadowMapPixelShaderWGSL: () => shadowMapPixelShaderWGSL
});
var name176 = "shadowMapPixelShader", shader175 = `#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEXTURE
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEXTURE
var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture<ALPHATESTVALUE) {discard;}
#endif
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#ifdef ALPHATEXTURE
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;}
#else
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} 
#endif
#endif
#include<shadowMapFragment>
}`, shadowMapPixelShaderWGSL;
var init_shadowMap_fragment = __esm(() => {
  init_shaderStore();
  init_shadowMapFragmentExtraDeclaration();
  init_clipPlaneFragmentDeclaration();
  init_clipPlaneFragment();
  init_shadowMapFragment();
  if (!ShaderStore.ShadersStoreWGSL[name176]) {
    ShaderStore.ShadersStoreWGSL[name176] = shader175;
  }
  shadowMapPixelShaderWGSL = { name: name176, shader: shader175 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexExtraDeclaration.js
var name177 = "shadowMapVertexExtraDeclaration", shader176 = `#if SM_NORMALBIAS==1
uniform lightDataSM: vec3f;
#endif
uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32;
#if SM_USEDISTANCE==1
varying vPositionWSM: vec3f;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying zSM: f32;
#endif
`;
var init_shadowMapVertexExtraDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name177]) {
    ShaderStore.IncludesShadersStoreWGSL[name177] = shader176;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexNormalBias.js
var name178 = "shadowMapVertexNormalBias", shader177 = `#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz);
#else
var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM);
#endif
var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w);
#endif
`;
var init_shadowMapVertexNormalBias = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name178]) {
    ShaderStore.IncludesShadersStoreWGSL[name178] = shader177;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexMetric.js
var exports_shadowMapVertexMetric = {};
__export(exports_shadowMapVertexMetric, {
  shadowMapVertexMetricWGSL: () => shadowMapVertexMetricWGSL
});
var name179 = "shadowMapVertexMetric", shader178 = `#if SM_USEDISTANCE==1
vertexOutputs.vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#else
vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#else
vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x;
#endif
#endif
`, shadowMapVertexMetricWGSL;
var init_shadowMapVertexMetric = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name179]) {
    ShaderStore.IncludesShadersStoreWGSL[name179] = shader178;
  }
  shadowMapVertexMetricWGSL = { name: name179, shader: shader178 };
});

// node_modules/@babylonjs/core/ShadersWGSL/shadowMap.vertex.js
var exports_shadowMap_vertex = {};
__export(exports_shadowMap_vertex, {
  shadowMapVertexShaderWGSL: () => shadowMapVertexShaderWGSL
});
var name180 = "shadowMapVertexShader", shader179 = `attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f;
#endif
#include<helperFunctions>
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
#ifdef ALPHATEXTURE
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#ifdef NORMAL
var normalUpdated: vec3f=input.normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#ifdef NORMAL
var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
var vNormalW: vec3f=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>
vertexOutputs.position=scene.viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEXTURE
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#include<clipPlaneVertex>
}`, shadowMapVertexShaderWGSL;
var init_shadowMap_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_helperFunctions();
  init_sceneUboDeclaration();
  init_meshUboDeclaration();
  init_shadowMapVertexExtraDeclaration();
  init_clipPlaneVertexDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_shadowMapVertexNormalBias();
  init_shadowMapVertexMetric();
  init_clipPlaneVertex();
  if (!ShaderStore.ShadersStoreWGSL[name180]) {
    ShaderStore.ShadersStoreWGSL[name180] = shader179;
  }
  shadowMapVertexShaderWGSL = { name: name180, shader: shader179 };
});

// node_modules/@babylonjs/core/ShadersWGSL/depthBoxBlur.fragment.js
var exports_depthBoxBlur_fragment = {};
__export(exports_depthBoxBlur_fragment, {
  depthBoxBlurPixelShaderWGSL: () => depthBoxBlurPixelShaderWGSL
});
var name181 = "depthBoxBlurPixelShader", shader180 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}}
fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`, depthBoxBlurPixelShaderWGSL;
var init_depthBoxBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name181]) {
    ShaderStore.ShadersStoreWGSL[name181] = shader180;
  }
  depthBoxBlurPixelShaderWGSL = { name: name181, shader: shader180 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js
var exports_shadowMapFragmentSoftTransparentShadow = {};
__export(exports_shadowMapFragmentSoftTransparentShadow, {
  shadowMapFragmentSoftTransparentShadowWGSL: () => shadowMapFragmentSoftTransparentShadowWGSL
});
var name182 = "shadowMapFragmentSoftTransparentShadow", shader181 = `#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;}
#endif
`, shadowMapFragmentSoftTransparentShadowWGSL;
var init_shadowMapFragmentSoftTransparentShadow = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name182]) {
    ShaderStore.IncludesShadersStoreWGSL[name182] = shader181;
  }
  shadowMapFragmentSoftTransparentShadowWGSL = { name: name182, shader: shader181 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js
var name183 = "bayerDitherFunctions", shader182 = `float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}
float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); 
vec2 P2=floor(0.5*mod(_P,4.0)); 
return 4.0*bayerDither2(P1)+bayerDither2(P2);}
float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); 
vec2 P2=floor(0.5 *mod(_P,4.0)); 
vec2 P4=floor(0.25*mod(_P,8.0)); 
return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}
`;
var init_bayerDitherFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name183]) {
    ShaderStore.IncludesShadersStore[name183] = shader182;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js
var name184 = "shadowMapFragmentExtraDeclaration", shader183 = `#if SM_FLOAT==0
#include<packingFunctions>
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#include<bayerDitherFunctions>
uniform vec2 softTransparentShadowSM;
#endif
varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
uniform vec3 lightDataSM;varying vec3 vPositionWSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;
var init_shadowMapFragmentExtraDeclaration2 = __esm(() => {
  init_shaderStore();
  init_packingFunctions2();
  init_bayerDitherFunctions2();
  if (!ShaderStore.IncludesShadersStore[name184]) {
    ShaderStore.IncludesShadersStore[name184] = shader183;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js
var exports_shadowMapFragment2 = {};
__export(exports_shadowMapFragment2, {
  shadowMapFragment: () => shadowMapFragment
});
var name185 = "shadowMapFragment", shader184 = `float depthSM=vDepthMetricSM;
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
#if SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
depthSM=clamp(depthSM,0.0,1.0);
#ifdef USE_REVERSE_DEPTHBUFFER
gl_FragDepth=clamp(1.0-depthSM,0.0,1.0);
#else
gl_FragDepth=clamp(depthSM,0.0,1.0); 
#endif
#elif SM_USEDISTANCE==1
depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#if SM_ESM==1
depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);
#endif
#if SM_FLOAT==1
gl_FragColor=vec4(depthSM,1.0,1.0,1.0);
#else
gl_FragColor=pack(depthSM);
#endif
return;`, shadowMapFragment;
var init_shadowMapFragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name185]) {
    ShaderStore.IncludesShadersStore[name185] = shader184;
  }
  shadowMapFragment = { name: name185, shader: shader184 };
});

// node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js
var exports_shadowMap_fragment2 = {};
__export(exports_shadowMap_fragment2, {
  shadowMapPixelShader: () => shadowMapPixelShader
});
var name186 = "shadowMapPixelShader", shader185 = `#include<shadowMapFragmentExtraDeclaration>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEXTURE
vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a;
#if SM_SOFTTRANSPARENTSHADOW==1
if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;}
#endif
#ifdef ALPHATESTVALUE
if (alphaFromAlphaTexture<ALPHATESTVALUE)
discard;
#endif
#endif
#if SM_SOFTTRANSPARENTSHADOW==1
#ifdef ALPHATEXTURE
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alphaFromAlphaTexture) discard;
#else
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard;
#endif
#endif
#include<shadowMapFragment>
}`, shadowMapPixelShader;
var init_shadowMap_fragment2 = __esm(() => {
  init_shaderStore();
  init_shadowMapFragmentExtraDeclaration2();
  init_clipPlaneFragmentDeclaration2();
  init_clipPlaneFragment2();
  init_shadowMapFragment2();
  if (!ShaderStore.ShadersStore[name186]) {
    ShaderStore.ShadersStore[name186] = shader185;
  }
  shadowMapPixelShader = { name: name186, shader: shader185 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js
var name187 = "sceneVertexDeclaration", shader186 = `uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;
`;
var init_sceneVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name187]) {
    ShaderStore.IncludesShadersStore[name187] = shader186;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js
var name188 = "meshVertexDeclaration", shader187 = `uniform mat4 world;uniform float visibility;
`;
var init_meshVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name188]) {
    ShaderStore.IncludesShadersStore[name188] = shader187;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js
var name189 = "shadowMapVertexDeclaration", shader188 = `#include<sceneVertexDeclaration>
#include<meshVertexDeclaration>
`;
var init_shadowMapVertexDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneVertexDeclaration();
  init_meshVertexDeclaration();
  if (!ShaderStore.IncludesShadersStore[name189]) {
    ShaderStore.IncludesShadersStore[name189] = shader188;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js
var name190 = "shadowMapUboDeclaration", shader189 = `layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
var init_shadowMapUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  init_meshUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name190]) {
    ShaderStore.IncludesShadersStore[name190] = shader189;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js
var name191 = "shadowMapVertexExtraDeclaration", shader190 = `#if SM_NORMALBIAS==1
uniform vec3 lightDataSM;
#endif
uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;
#if SM_USEDISTANCE==1
varying vec3 vPositionWSM;
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
varying float zSM;
#endif
`;
var init_shadowMapVertexExtraDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name191]) {
    ShaderStore.IncludesShadersStore[name191] = shader190;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js
var name192 = "shadowMapVertexNormalBias", shader191 = `#if SM_NORMALBIAS==1
#if SM_DIRECTIONINLIGHTDATA==1
vec3 worldLightDirSM=normalize(-lightDataSM.xyz);
#else
vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);
#endif
float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;
#endif
`;
var init_shadowMapVertexNormalBias2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name192]) {
    ShaderStore.IncludesShadersStore[name192] = shader191;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js
var exports_shadowMapVertexMetric2 = {};
__export(exports_shadowMapVertexMetric2, {
  shadowMapVertexMetric: () => shadowMapVertexMetric
});
var name193 = "shadowMapVertexMetric", shader192 = `#if SM_USEDISTANCE==1
vPositionWSM=worldPos.xyz;
#endif
#if SM_DEPTHTEXTURE==1
#ifdef IS_NDC_HALF_ZRANGE
#define BIASFACTOR 0.5
#else
#define BIASFACTOR 1.0
#endif
#ifdef USE_REVERSE_DEPTHBUFFER
gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#else
gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;
#endif
#endif
#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1
zSM=gl_Position.z;gl_Position.z=0.0;
#elif SM_USEDISTANCE==0
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#else
vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;
#endif
#endif
`, shadowMapVertexMetric;
var init_shadowMapVertexMetric2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name193]) {
    ShaderStore.IncludesShadersStore[name193] = shader192;
  }
  shadowMapVertexMetric = { name: name193, shader: shader192 };
});

// node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js
var exports_shadowMap_vertex2 = {};
__export(exports_shadowMap_vertex2, {
  shadowMapVertexShader: () => shadowMapVertexShader
});
var name194 = "shadowMapVertexShader", shader193 = `attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#include<helperFunctions>
#include<__decl__shadowMapVertex>
#ifdef ALPHATEXTURE
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<shadowMapVertexExtraDeclaration>
#include<clipPlaneVertexDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef NORMAL
mat3 normWorldSM=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vec3 vNormalW=normalize(normWorldSM*normalUpdated);
#endif
#endif
#include<shadowMapVertexNormalBias>
gl_Position=viewProjection*worldPos;
#include<shadowMapVertexMetric>
#ifdef ALPHATEXTURE
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
}`, shadowMapVertexShader;
var init_shadowMap_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_helperFunctions2();
  init_shadowMapVertexDeclaration();
  init_shadowMapUboDeclaration();
  init_shadowMapVertexExtraDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_shadowMapVertexNormalBias2();
  init_shadowMapVertexMetric2();
  init_clipPlaneVertex2();
  if (!ShaderStore.ShadersStore[name194]) {
    ShaderStore.ShadersStore[name194] = shader193;
  }
  shadowMapVertexShader = { name: name194, shader: shader193 };
});

// node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js
var exports_depthBoxBlur_fragment2 = {};
__export(exports_depthBoxBlur_fragment2, {
  depthBoxBlurPixelShader: () => depthBoxBlurPixelShader
});
var name195 = "depthBoxBlurPixelShader", shader194 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)
for (int y=-OFFSET; y<=OFFSET; y++)
colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`, depthBoxBlurPixelShader;
var init_depthBoxBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name195]) {
    ShaderStore.ShadersStore[name195] = shader194;
  }
  depthBoxBlurPixelShader = { name: name195, shader: shader194 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js
var exports_shadowMapFragmentSoftTransparentShadow2 = {};
__export(exports_shadowMapFragmentSoftTransparentShadow2, {
  shadowMapFragmentSoftTransparentShadow: () => shadowMapFragmentSoftTransparentShadow
});
var name196 = "shadowMapFragmentSoftTransparentShadow", shader195 = `#if SM_SOFTTRANSPARENTSHADOW==1
if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard;
#endif
`, shadowMapFragmentSoftTransparentShadow;
var init_shadowMapFragmentSoftTransparentShadow2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name196]) {
    ShaderStore.IncludesShadersStore[name196] = shader195;
  }
  shadowMapFragmentSoftTransparentShadow = { name: name196, shader: shader195 };
});

// node_modules/@babylonjs/core/Shaders/depth.fragment.js
var exports_depth_fragment = {};
__export(exports_depth_fragment, {
  depthPixelShader: () => depthPixelShader
});
var name197 = "depthPixelShader", shader196 = `#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
varying float vDepthMetric;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vec4 vViewPos;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
gl_FragColor=pack(vViewPos.z);
#else
gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
gl_FragColor=pack(gl_FragCoord.z);
#else
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
gl_FragColor=pack(vDepthMetric);
#else
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`, depthPixelShader;
var init_depth_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_packingFunctions2();
  init_clipPlaneFragment2();
  if (!ShaderStore.ShadersStore[name197]) {
    ShaderStore.ShadersStore[name197] = shader196;
  }
  depthPixelShader = { name: name197, shader: shader196 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertexDeclaration.js
var name198 = "pointCloudVertexDeclaration", shader197 = `#ifdef POINTSIZE
uniform float pointSize;
#endif
`;
var init_pointCloudVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name198]) {
    ShaderStore.IncludesShadersStore[name198] = shader197;
  }
});

// node_modules/@babylonjs/core/Shaders/depth.vertex.js
var exports_depth_vertex = {};
__export(exports_depth_vertex, {
  depthVertexShader: () => depthVertexShader
});
var name199 = "depthVertexShader", shader198 = `attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform mat4 view;varying vec4 vViewPos;
#endif
#include<pointCloudVertexDeclaration>
varying float vDepthMetric;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
gl_Position=viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vViewPos=view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
#else
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<pointCloudVertex>
}
`, depthVertexShader;
var init_depth_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_instancesDeclaration2();
  init_pointCloudVertexDeclaration();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  init_pointCloudVertex();
  if (!ShaderStore.ShadersStore[name199]) {
    ShaderStore.ShadersStore[name199] = shader198;
  }
  depthVertexShader = { name: name199, shader: shader198 };
});

// node_modules/@babylonjs/core/ShadersWGSL/depth.vertex.js
var exports_depth_vertex2 = {};
__export(exports_depth_vertex2, {
  depthVertexShaderWGSL: () => depthVertexShaderWGSL
});
var name200 = "depthVertexShader", shader199 = `attribute position: vec3f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;uniform depthValues: vec2f;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform view: mat4x4f;varying vViewPos: vec4f;
#endif
varying vDepthMetric: f32;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#include<clipPlaneVertex>
vertexOutputs.position=uniforms.viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vertexOutputs.vViewPos=uniforms.view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#else
vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
}
`, depthVertexShaderWGSL;
var init_depth_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_clipPlaneVertexDeclaration();
  init_instancesDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  if (!ShaderStore.ShadersStoreWGSL[name200]) {
    ShaderStore.ShadersStoreWGSL[name200] = shader199;
  }
  depthVertexShaderWGSL = { name: name200, shader: shader199 };
});

// node_modules/@babylonjs/core/ShadersWGSL/depth.fragment.js
var exports_depth_fragment2 = {};
__export(exports_depth_fragment2, {
  depthPixelShaderWGSL: () => depthPixelShaderWGSL
});
var name201 = "depthPixelShader", shader200 = `#ifdef ALPHATEST
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
varying vDepthMetric: f32;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vViewPos: vec4f;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
fragmentOutputs.color=pack(input.vViewPos.z);
#else
fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
fragmentOutputs.color=pack(input.position.z);
#else
fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
fragmentOutputs.color=pack(input.vDepthMetric);
#else
fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`, depthPixelShaderWGSL;
var init_depth_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_packingFunctions();
  init_clipPlaneFragment();
  if (!ShaderStore.ShadersStoreWGSL[name201]) {
    ShaderStore.ShadersStoreWGSL[name201] = shader200;
  }
  depthPixelShaderWGSL = { name: name201, shader: shader200 };
});

// node_modules/@babylonjs/core/ShadersWGSL/glowBlurPostProcess.fragment.js
var exports_glowBlurPostProcess_fragment = {};
__export(exports_glowBlurPostProcess_fragment, {
  glowBlurPostProcessPixelShaderWGSL: () => glowBlurPostProcessPixelShaderWGSL
});
var name203 = "glowBlurPostProcessPixelShader", shader202 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32
{return dot(color, vec3f(0.2126,0.7152,0.0722));}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var weights: array<f32 ,7>;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++)
{var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;}
fragmentOutputs.color=baseColor;}`, glowBlurPostProcessPixelShaderWGSL;
var init_glowBlurPostProcess_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name203]) {
    ShaderStore.ShadersStoreWGSL[name203] = shader202;
  }
  glowBlurPostProcessPixelShaderWGSL = { name: name203, shader: shader202 };
});

// node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js
var exports_glowBlurPostProcess_fragment2 = {};
__export(exports_glowBlurPostProcess_fragment2, {
  glowBlurPostProcessPixelShader: () => glowBlurPostProcessPixelShader
});
var name204 = "glowBlurPostProcessPixelShader", shader203 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)
{return dot(color,vec3(0.2126,0.7152,0.0722));}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)
{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}
gl_FragColor=baseColor;}`, glowBlurPostProcessPixelShader;
var init_glowBlurPostProcess_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name204]) {
    ShaderStore.ShadersStore[name204] = shader203;
  }
  glowBlurPostProcessPixelShader = { name: name204, shader: shader203 };
});

// node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.vertex.js
var exports_glowMapGeneration_vertex = {};
__export(exports_glowMapGeneration_vertex, {
  glowMapGenerationVertexShaderWGSL: () => glowMapGenerationVertexShaderWGSL
});
var name205 = "glowMapGenerationVertexShader", shader204 = `attribute position: vec3f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;varying vPosition: vec4f;
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#ifdef DIFFUSE
varying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f;
#endif
#ifdef OPACITY
varying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f;
#endif
#ifdef EMISSIVE
varying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f;
#endif
#ifdef VERTEXALPHA
attribute color: vec4f;varying vColor: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);
#ifdef CUBEMAP
vertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0);
#else
vertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef DIFFUSEUV2
vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef OPACITYUV2
vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef EMISSIVEUV2
vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#ifdef VERTEXALPHA
vertexOutputs.vColor=vertexInputs.color;
#endif
#include<clipPlaneVertex>
}`, glowMapGenerationVertexShaderWGSL;
var init_glowMapGeneration_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_clipPlaneVertexDeclaration();
  init_instancesDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  if (!ShaderStore.ShadersStoreWGSL[name205]) {
    ShaderStore.ShadersStoreWGSL[name205] = shader204;
  }
  glowMapGenerationVertexShaderWGSL = { name: name205, shader: shader204 };
});

// node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.fragment.js
var exports_glowMapGeneration_fragment = {};
__export(exports_glowMapGeneration_fragment, {
  glowMapGenerationPixelShaderWGSL: () => glowMapGenerationPixelShaderWGSL
});
var name206 = "glowMapGenerationPixelShader", shader205 = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#ifdef OPACITY
varying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d<f32>;uniform opacityIntensity: f32;
#endif
#ifdef EMISSIVE
varying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d<f32>;
#endif
#ifdef VERTEXALPHA
varying vColor: vec4f;
#endif
uniform glowColor: vec4f;uniform glowIntensity: f32;
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
var finalColor: vec4f=uniforms.glowColor;
#ifdef DIFFUSE
var albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW
finalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a);
#endif
#ifdef HIGHLIGHT
finalColor=vec4f(finalColor.rgb,albedoTexture.a);
#endif
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity);
#ifdef OPACITYRGB
finalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb));
#else
finalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a);
#endif
finalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity);
#endif
#ifdef VERTEXALPHA
finalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a);
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE) {discard;}
#endif
#ifdef EMISSIVE
var emissive: vec4f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
fragmentOutputs.color=emissive*finalColor*uniforms.glowIntensity;
#else
fragmentOutputs.color=finalColor*uniforms.glowIntensity;
#endif
#ifdef HIGHLIGHT
fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb,uniforms.glowColor.a);
#endif
}
`, glowMapGenerationPixelShaderWGSL;
var init_glowMapGeneration_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  init_clipPlaneFragmentDeclaration();
  init_clipPlaneFragment();
  if (!ShaderStore.ShadersStoreWGSL[name206]) {
    ShaderStore.ShadersStoreWGSL[name206] = shader205;
  }
  glowMapGenerationPixelShaderWGSL = { name: name206, shader: shader205 };
});

// node_modules/@babylonjs/core/Shaders/glowMapGeneration.vertex.js
var exports_glowMapGeneration_vertex2 = {};
__export(exports_glowMapGeneration_vertex2, {
  glowMapGenerationVertexShader: () => glowMapGenerationVertexShader
});
var name207 = "glowMapGenerationVertexShader", shader206 = `attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;varying vec4 vPosition;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform mat4 opacityMatrix;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform mat4 emissiveMatrix;
#endif
#ifdef VERTEXALPHA
attribute vec4 color;varying vec4 vColor;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#ifdef CUBEMAP
vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#else
vPosition=viewProjection*worldPos;gl_Position=vPosition;
#endif
#ifdef DIFFUSE
#ifdef DIFFUSEUV1
vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef DIFFUSEUV2
vUVDiffuse=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef OPACITY
#ifdef OPACITYUV1
vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef OPACITYUV2
vUVOpacity=vec2(opacityMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef EMISSIVE
#ifdef EMISSIVEUV1
vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef EMISSIVEUV2
vUVEmissive=vec2(emissiveMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#ifdef VERTEXALPHA
vColor=color;
#endif
#include<clipPlaneVertex>
}`, glowMapGenerationVertexShader;
var init_glowMapGeneration_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_instancesDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  if (!ShaderStore.ShadersStore[name207]) {
    ShaderStore.ShadersStore[name207] = shader206;
  }
  glowMapGenerationVertexShader = { name: name207, shader: shader206 };
});

// node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js
var exports_glowMapGeneration_fragment2 = {};
__export(exports_glowMapGeneration_fragment2, {
  glowMapGenerationPixelShader: () => glowMapGenerationPixelShader
});
var name208 = "glowMapGenerationPixelShader", shader207 = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)
#include<helperFunctions>
#endif
#ifdef DIFFUSE
varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;
#endif
#ifdef OPACITY
varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;
#endif
#ifdef EMISSIVE
varying vec2 vUVEmissive;uniform sampler2D emissiveSampler;
#endif
#ifdef VERTEXALPHA
varying vec4 vColor;
#endif
uniform vec4 glowColor;uniform float glowIntensity;
#include<clipPlaneFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
vec4 finalColor=glowColor;
#ifdef DIFFUSE
vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);
#ifdef DIFFUSE_ISLINEAR
albedoTexture=toGammaSpace(albedoTexture);
#endif
#ifdef GLOW
finalColor.a*=albedoTexture.a;
#endif
#ifdef HIGHLIGHT
finalColor.a=albedoTexture.a;
#endif
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vUVOpacity);
#ifdef OPACITYRGB
finalColor.a*=getLuminance(opacityMap.rgb);
#else
finalColor.a*=opacityMap.a;
#endif
finalColor.a*=opacityIntensity;
#endif
#ifdef VERTEXALPHA
finalColor.a*=vColor.a;
#endif
#ifdef ALPHATEST
if (finalColor.a<ALPHATESTVALUE)
discard;
#endif
#ifdef EMISSIVE
vec4 emissive=texture2D(emissiveSampler,vUVEmissive);
#ifdef EMISSIVE_ISLINEAR
emissive=toGammaSpace(emissive);
#endif
gl_FragColor=emissive*finalColor*glowIntensity;
#else
gl_FragColor=finalColor*glowIntensity;
#endif
#ifdef HIGHLIGHT
gl_FragColor.a=glowColor.a;
#endif
}`, glowMapGenerationPixelShader;
var init_glowMapGeneration_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  init_clipPlaneFragmentDeclaration2();
  init_clipPlaneFragment2();
  if (!ShaderStore.ShadersStore[name208]) {
    ShaderStore.ShadersStore[name208] = shader207;
  }
  glowMapGenerationPixelShader = { name: name208, shader: shader207 };
});

// node_modules/@babylonjs/core/ShadersWGSL/glowMapMerge.fragment.js
var exports_glowMapMerge_fragment = {};
__export(exports_glowMapMerge_fragment, {
  glowMapMergePixelShaderWGSL: () => glowMapMergePixelShaderWGSL
});
var name209 = "glowMapMergePixelShader", shader208 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#ifdef EMISSIVE
var textureSampler2Sampler: sampler;var textureSampler2: texture_2d<f32>;
#endif
uniform offset: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);
#ifdef EMISSIVE
baseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset;
#else
baseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a));
#ifdef STROKE
var alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha);
#endif
#endif
#if LDR
baseColor=clamp(baseColor,vec4f(0.),vec4f(1.0));
#endif
fragmentOutputs.color=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}
`, glowMapMergePixelShaderWGSL;
var init_glowMapMerge_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name209]) {
    ShaderStore.ShadersStoreWGSL[name209] = shader208;
  }
  glowMapMergePixelShaderWGSL = { name: name209, shader: shader208 };
});

// node_modules/@babylonjs/core/ShadersWGSL/glowMapMerge.vertex.js
var exports_glowMapMerge_vertex = {};
__export(exports_glowMapMerge_vertex, {
  glowMapMergeVertexShaderWGSL: () => glowMapMergeVertexShaderWGSL
});
var name210 = "glowMapMergeVertexShader", shader209 = `attribute position: vec2f;varying vUV: vec2f;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, glowMapMergeVertexShaderWGSL;
var init_glowMapMerge_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name210]) {
    ShaderStore.ShadersStoreWGSL[name210] = shader209;
  }
  glowMapMergeVertexShaderWGSL = { name: name210, shader: shader209 };
});

// node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js
var exports_glowMapMerge_fragment2 = {};
__export(exports_glowMapMerge_fragment2, {
  glowMapMergePixelShader: () => glowMapMergePixelShader
});
var name211 = "glowMapMergePixelShader", shader210 = `varying vec2 vUV;uniform sampler2D textureSampler;
#ifdef EMISSIVE
uniform sampler2D textureSampler2;
#endif
uniform float offset;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);
#ifdef EMISSIVE
baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;
#else
baseColor.a=abs(offset-baseColor.a);
#ifdef STROKE
float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;
#endif
#endif
#if LDR
baseColor=clamp(baseColor,0.,1.0);
#endif
gl_FragColor=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`, glowMapMergePixelShader;
var init_glowMapMerge_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name211]) {
    ShaderStore.ShadersStore[name211] = shader210;
  }
  glowMapMergePixelShader = { name: name211, shader: shader210 };
});

// node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js
var exports_glowMapMerge_vertex2 = {};
__export(exports_glowMapMerge_vertex2, {
  glowMapMergeVertexShader: () => glowMapMergeVertexShader
});
var name212 = "glowMapMergeVertexShader", shader211 = `attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, glowMapMergeVertexShader;
var init_glowMapMerge_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name212]) {
    ShaderStore.ShadersStore[name212] = shader211;
  }
  glowMapMergeVertexShader = { name: name212, shader: shader211 };
});

// node_modules/@babylonjs/core/ShadersWGSL/blackAndWhite.fragment.js
var exports_blackAndWhite_fragment = {};
__export(exports_blackAndWhite_fragment, {
  blackAndWhitePixelShaderWGSL: () => blackAndWhitePixelShaderWGSL
});
var name213 = "blackAndWhitePixelShader", shader212 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform degree: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var luminance: f32=dot(color, vec3f(0.3,0.59,0.11)); 
var blackAndWhite: vec3f= vec3f(luminance,luminance,luminance);fragmentOutputs.color= vec4f(color-((color-blackAndWhite)*uniforms.degree),1.0);}`, blackAndWhitePixelShaderWGSL;
var init_blackAndWhite_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name213]) {
    ShaderStore.ShadersStoreWGSL[name213] = shader212;
  }
  blackAndWhitePixelShaderWGSL = { name: name213, shader: shader212 };
});

// node_modules/@babylonjs/core/Shaders/blackAndWhite.fragment.js
var exports_blackAndWhite_fragment2 = {};
__export(exports_blackAndWhite_fragment2, {
  blackAndWhitePixelShader: () => blackAndWhitePixelShader
});
var name214 = "blackAndWhitePixelShader", shader213 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); 
vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`, blackAndWhitePixelShader;
var init_blackAndWhite_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name214]) {
    ShaderStore.ShadersStore[name214] = shader213;
  }
  blackAndWhitePixelShader = { name: name214, shader: shader213 };
});

// node_modules/@babylonjs/core/ShadersWGSL/bloomMerge.fragment.js
var exports_bloomMerge_fragment = {};
__export(exports_bloomMerge_fragment, {
  bloomMergePixelShaderWGSL: () => bloomMergePixelShaderWGSL
});
var name215 = "bloomMergePixelShader", shader214 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var bloomBlurSampler: sampler;var bloomBlur: texture_2d<f32>;uniform bloomWeight: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);}
`, bloomMergePixelShaderWGSL;
var init_bloomMerge_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name215]) {
    ShaderStore.ShadersStoreWGSL[name215] = shader214;
  }
  bloomMergePixelShaderWGSL = { name: name215, shader: shader214 };
});

// node_modules/@babylonjs/core/Shaders/bloomMerge.fragment.js
var exports_bloomMerge_fragment2 = {};
__export(exports_bloomMerge_fragment2, {
  bloomMergePixelShader: () => bloomMergePixelShader
});
var name216 = "bloomMergePixelShader", shader215 = `uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }
`, bloomMergePixelShader;
var init_bloomMerge_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name216]) {
    ShaderStore.ShadersStore[name216] = shader215;
  }
  bloomMergePixelShader = { name: name216, shader: shader215 };
});

// node_modules/@babylonjs/core/ShadersWGSL/extractHighlights.fragment.js
var exports_extractHighlights_fragment = {};
__export(exports_extractHighlights_fragment, {
  extractHighlightsPixelShaderWGSL: () => extractHighlightsPixelShaderWGSL
});
var name217 = "extractHighlightsPixelShader", shader216 = `#include<helperFunctions>
varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform threshold: f32;uniform exposure: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}`, extractHighlightsPixelShaderWGSL;
var init_extractHighlights_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name217]) {
    ShaderStore.ShadersStoreWGSL[name217] = shader216;
  }
  extractHighlightsPixelShaderWGSL = { name: name217, shader: shader216 };
});

// node_modules/@babylonjs/core/Shaders/extractHighlights.fragment.js
var exports_extractHighlights_fragment2 = {};
__export(exports_extractHighlights_fragment2, {
  extractHighlightsPixelShader: () => extractHighlightsPixelShader
});
var name218 = "extractHighlightsPixelShader", shader217 = `#include<helperFunctions>
varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`, extractHighlightsPixelShader;
var init_extractHighlights_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name218]) {
    ShaderStore.ShadersStore[name218] = shader217;
  }
  extractHighlightsPixelShader = { name: name218, shader: shader217 };
});

// node_modules/@babylonjs/core/ShadersWGSL/chromaticAberration.fragment.js
var exports_chromaticAberration_fragment = {};
__export(exports_chromaticAberration_fragment, {
  chromaticAberrationPixelShaderWGSL: () => chromaticAberrationPixelShaderWGSL
});
var name219 = "chromaticAberrationPixelShader", shader218 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}
var radius2: f32=centered_screen_pos.x*centered_screen_pos.x
+ centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}`, chromaticAberrationPixelShaderWGSL;
var init_chromaticAberration_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name219]) {
    ShaderStore.ShadersStoreWGSL[name219] = shader218;
  }
  chromaticAberrationPixelShaderWGSL = { name: name219, shader: shader218 };
});

// node_modules/@babylonjs/core/Shaders/chromaticAberration.fragment.js
var exports_chromaticAberration_fragment2 = {};
__export(exports_chromaticAberration_fragment2, {
  chromaticAberrationPixelShader: () => chromaticAberrationPixelShader
});
var name220 = "chromaticAberrationPixelShader", shader219 = `uniform sampler2D textureSampler; 
uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}
float radius2=centered_screen_pos.x*centered_screen_pos.x
+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}`, chromaticAberrationPixelShader;
var init_chromaticAberration_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name220]) {
    ShaderStore.ShadersStore[name220] = shader219;
  }
  chromaticAberrationPixelShader = { name: name220, shader: shader219 };
});

// node_modules/@babylonjs/core/ShadersWGSL/circleOfConfusion.fragment.js
var exports_circleOfConfusion_fragment = {};
__export(exports_circleOfConfusion_fragment, {
  circleOfConfusionPixelShaderWGSL: () => circleOfConfusionPixelShaderWGSL
});
var name221 = "circleOfConfusionPixelShader", shader220 = `varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;
#ifndef COC_DEPTH_NOT_NORMALIZED
uniform cameraMinMaxZ: vec2f;
#endif
uniform focusDistance: f32;uniform cocPrecalculation: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;
#define CUSTOM_COC_DEPTH
#ifdef COC_DEPTH_NOT_NORMALIZED
let pixelDistance=depth*1000.0;
#else
let pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; 
#endif
#define CUSTOM_COC_PIXELDISTANCE
var coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);}
`, circleOfConfusionPixelShaderWGSL;
var init_circleOfConfusion_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name221]) {
    ShaderStore.ShadersStoreWGSL[name221] = shader220;
  }
  circleOfConfusionPixelShaderWGSL = { name: name221, shader: shader220 };
});

// node_modules/@babylonjs/core/Shaders/circleOfConfusion.fragment.js
var exports_circleOfConfusion_fragment2 = {};
__export(exports_circleOfConfusion_fragment2, {
  circleOfConfusionPixelShader: () => circleOfConfusionPixelShader
});
var name222 = "circleOfConfusionPixelShader", shader221 = `uniform sampler2D depthSampler;varying vec2 vUV;
#ifndef COC_DEPTH_NOT_NORMALIZED
uniform vec2 cameraMinMaxZ;
#endif
uniform float focusDistance;uniform float cocPrecalculation;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float depth=texture2D(depthSampler,vUV).r;
#define CUSTOM_COC_DEPTH
#ifdef COC_DEPTH_NOT_NORMALIZED
float pixelDistance=depth*1000.0;
#else
float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; 
#endif
#define CUSTOM_COC_PIXELDISTANCE
float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}
`, circleOfConfusionPixelShader;
var init_circleOfConfusion_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name222]) {
    ShaderStore.ShadersStore[name222] = shader221;
  }
  circleOfConfusionPixelShader = { name: name222, shader: shader221 };
});

// node_modules/@babylonjs/core/ShadersWGSL/depthOfFieldMerge.fragment.js
var exports_depthOfFieldMerge_fragment = {};
__export(exports_depthOfFieldMerge_fragment, {
  depthOfFieldMergePixelShaderWGSL: () => depthOfFieldMergePixelShaderWGSL
});
var name223 = "depthOfFieldMergePixelShader", shader222 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d<f32>;var blurStep0Sampler: sampler;var blurStep0: texture_2d<f32>;
#if BLUR_LEVEL>0
var blurStep1Sampler: sampler;var blurStep1: texture_2d<f32>;
#endif
#if BLUR_LEVEL>1
var blurStep2Sampler: sampler;var blurStep2: texture_2d<f32>;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r;
#if BLUR_LEVEL==0
var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc);
#endif
#if BLUR_LEVEL==1
if(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);}
#endif
#if BLUR_LEVEL==2
if(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);}
#endif
}
`, depthOfFieldMergePixelShaderWGSL;
var init_depthOfFieldMerge_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name223]) {
    ShaderStore.ShadersStoreWGSL[name223] = shader222;
  }
  depthOfFieldMergePixelShaderWGSL = { name: name223, shader: shader222 };
});

// node_modules/@babylonjs/core/Shaders/depthOfFieldMerge.fragment.js
var exports_depthOfFieldMerge_fragment2 = {};
__export(exports_depthOfFieldMerge_fragment2, {
  depthOfFieldMergePixelShader: () => depthOfFieldMergePixelShader
});
var name224 = "depthOfFieldMergePixelShader", shader223 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;
#if BLUR_LEVEL>0
uniform sampler2D blurStep1;
#endif
#if BLUR_LEVEL>1
uniform sampler2D blurStep2;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;
#if BLUR_LEVEL==0
vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);
#endif
#if BLUR_LEVEL==1
if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}
#endif
#if BLUR_LEVEL==2
if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}
#endif
}
`, depthOfFieldMergePixelShader;
var init_depthOfFieldMerge_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name224]) {
    ShaderStore.ShadersStore[name224] = shader223;
  }
  depthOfFieldMergePixelShader = { name: name224, shader: shader223 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBRDFFunctions.js
var name225 = "pbrBRDFFunctions", shader224 = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
#ifdef MS_BRDF_ENERGY_CONSERVATION
fn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}
#endif
#ifdef ENVIRONMENTBRDF
fn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a);
#endif
return brdfLookup.rgb;}
fn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f {
#ifdef BRDF_V_HEIGHT_CORRELATED
var reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
#else
var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;}
fn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {
#ifdef BRDF_V_HEIGHT_CORRELATED
var reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;}
#endif
/* NOT USED
#if defined(SHEEN) && defined(SHEEN_SOFTER)
fn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32
{var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}
#endif
*/
#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
fn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f
{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
/**
* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.
* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table
*/
fn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}
#endif
fn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
fn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
#ifdef CLEARCOAT
fn getR0RemappedForClearCoat(f0: vec3f)->vec3f {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
var s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t);
#endif
}
#endif
#ifdef IRIDESCENCE
const XYZ_TO_REC709: mat3x3f= mat3x3f(
3.2404542,-0.9692660, 0.0556434,
-1.5371385, 1.8760108,-0.2040259,
-0.4985314, 0.0415560, 1.0572252
);fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}
fn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));}
fn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));}
fn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;}
fn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}
var cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIOR<outsideIOR) {phi12=PI;}
var phi21: f32=PI-phi12;var baseIOR: vec3f=getIORTfromAirToSurfaceR0(clamp(baseF0,vec3f(0.0),vec3f(0.9999))); 
var R1: vec3f=getR0fromIORsVec3(baseIOR,iridescenceIOR);var R23: vec3f=fresnelSchlickGGXVec3(cosTheta2,R1, vec3f(1.));var phi23: vec3f= vec3f(0.0);if (baseIOR[0]<iridescenceIOR) {phi23[0]=PI;}
if (baseIOR[1]<iridescenceIOR) {phi23[1]=PI;}
if (baseIOR[2]<iridescenceIOR) {phi23[2]=PI;}
var opd: f32=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;var phi: vec3f= vec3f(phi21)+phi23;var R123: vec3f=clamp(R12*R23,vec3f(1e-5),vec3f(0.9999));var r123: vec3f=sqrt(R123);var Rs: vec3f=(T121*T121)*R23/( vec3f(1.0)-R123);var C0: vec3f=R12+Rs;I=C0;var Cm: vec3f=Rs-T121;for (var m: i32=1; m<=2; m++)
{Cm*=r123;var Sm: vec3f=2.0*evalSensitivity( f32(m)*opd, f32(m)*phi);I+=Cm*Sm;}
return max(I, vec3f(0.0));}
#endif
fn normalDistributionFunction_TrowbridgeReitzGGX(NdotH: f32,alphaG: f32)->f32
{var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}
#ifdef SHEEN
fn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32
{var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}
#endif
#ifdef ANISOTROPIC
fn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}
#endif
#ifdef BRDF_V_HEIGHT_CORRELATED
fn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {
#ifdef MOBILE
var GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);
#else
var a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);
#endif
}
#else
fn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32
{
#ifdef MOBILE
return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
var alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
fn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32
{var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}
#endif
#ifdef ANISOTROPIC
fn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;}
#endif
#ifdef CLEARCOAT
fn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); }
#endif
#ifdef SHEEN
fn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32
{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}
/* NOT USED
#ifdef SHEEN_SOFTER
fn l(x: f32,alphaG: f32)->f32
{var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}
fn lambdaSheen(cosTheta: f32,alphaG: f32)->f32
{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}
fn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32
{var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}
#endif
*/
#endif
fn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}
#ifdef SS_TRANSLUCENCY
fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}
fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);}
#endif
`;
var init_pbrBRDFFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name225]) {
    ShaderStore.IncludesShadersStoreWGSL[name225] = shader224;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/screenSpaceRayTrace.js
var name226 = "screenSpaceRayTrace", shader225 = `fn distanceSquared(a: vec2f,b: vec2f)->f32 { 
var temp=a-b; 
return dot(temp,temp); }
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
fn linearizeDepth(depth: f32,near: f32,far: f32)->f32 {
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
return -(near*far)/(far-depth*(far-near));
#else
return (near*far)/(far-depth*(far-near));
#endif
}
#endif
/**
param csOrigin Camera-space ray origin,which must be 
within the view volume and must have z>0.01 and project within the valid screen rectangle
param csDirection Unit length camera-space ray direction
param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates 
(**not** [-1,+1] normalized device coordinates).
param csZBuffer The camera-space Z buffer
param csZBufferSize Dimensions of csZBuffer
param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer
param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value
for clipping rays headed towards the camera. Should be the actual near plane if screen-space depth is enabled.
param farPlaneZ The far plane for the camera. Used when screen-space depth is enabled.
param stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1
param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units
to conceal banding artifacts,plus the stride ray offset.
param maxSteps Maximum number of iterations. Higher gives better images but may be slow
param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss
param selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions.
1 is a reasonable value,depending on the scene you may need to set this value to 2
param hitPixel Pixel coordinates of the first intersection with the scene
param numIterations number of iterations performed
param csHitPovar Camera: i32 space location of the ray hit
*/
fn traceScreenSpaceRay1(
csOrigin: vec3f,
csDirection: vec3f,
projectToPixelMatrix: mat4x4f,
csZBuffer: texture_2d<f32>,
csZBufferSize: vec2f,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
csZBackBuffer: texture_2d<f32>,
csZBackSizeFactor: f32,
#endif
csZThickness: f32,
nearPlaneZ: f32,
farPlaneZ: f32,
stride: f32,
jitterFraction: f32,
maxSteps: f32,
maxRayTraceDistance: f32,
selfCollisionNumSkip: f32,
startPixel: ptr<function,vec2f>,
hitPixel: ptr<function,vec2f>,
csHitPoint: ptr<function,vec3f>,
numIterations: ptr<function,f32>
#ifdef SSRAYTRACE_DEBUG
,debugColor: ptr<function,vec3f>
#endif
)->bool
{
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
var rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ);
#else
var rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ);
#endif
var csEndPoint: vec3f=csOrigin+csDirection*rayLength;*hitPixel= vec2f(-1.0,-1.0);var H0: vec4f=projectToPixelMatrix* vec4f(csOrigin,1.0);var H1: vec4f=projectToPixelMatrix* vec4f(csEndPoint,1.0);var k0: f32=1.0/H0.w;var k1: f32=1.0/H1.w;var Q0: vec3f=csOrigin*k0;var Q1: vec3f=csEndPoint*k1;var P0: vec2f=H0.xy*k0;var P1: vec2f=H1.xy*k1;
#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM
var xMax: f32=csZBufferSize.x-0.5;var xMin=0.5;var yMax=csZBufferSize.y-0.5;var yMin=0.5;var alpha: f32=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-select(yMin,yMax,(P1.y>yMax)))/(P1.y-P0.y);}
if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-select(xMin,xMax,(P1.x>xMax)))/(P1.x-P0.x));}
P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);
#endif
P1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)<abs(delta.y)) { 
permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; }
var stepDirection: f32=sign(delta.x);var invdx: f32=stepDirection/delta.x;var dP: vec2f= vec2f(stepDirection,delta.y*invdx);var dQ: vec3f=(Q1-Q0)*invdx;var dk: f32=(k1-k0)*invdx;var zMin: f32=min(csEndPoint.z,csOrigin.z);var zMax: f32=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;var pqk: vec4f= vec4f(P0,Q0.z,k0);var dPQK: vec4f= vec4f(dP,dQ.z,dk);*startPixel=select(P0.xy,P0.yx,permute);var prevZMaxEstimate: f32=csOrigin.z;var rayZMin: f32=prevZMaxEstimate;var rayZMax=prevZMaxEstimate;var sceneZMax: f32=rayZMax+1e4;var end: f32=P1.x*stepDirection;var hit: bool=false;var stepCount: f32;for (stepCount=0.0;(stepCount<=selfCollisionNumSkip) ||
((pqk.x*stepDirection)<=end &&
stepCount<maxSteps &&
!hit &&
sceneZMax != 0.0);pqk+=dPQK 
)
{*hitPixel=select(pqk.xy,pqk.yx,permute);rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { 
var t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;}
sceneZMax=textureLoad(csZBuffer,vec2<i32>(*hitPixel),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);
#endif
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2<i32>(*hitPixel/csZBackSizeFactor),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);
#endif
hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);
#else
hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);
#endif
#else
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2<i32>(*hitPixel/csZBackSizeFactor),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);
#endif
hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);
#else
hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);
#endif
#endif
stepCount+=1.0;}
pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}
#ifdef SSRAYTRACE_ENABLE_REFINEMENT
if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||
((refinementStepCount<=stride*1.4) &&
(rayZMax<sceneZMax) && (sceneZMax != 0.0));pqk+=dPQK)
{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);*hitPixel=select(pqk.xy,pqk.yx,permute);sceneZMax=textureLoad(csZBuffer,vec2<i32>(*hitPixel),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);
#endif
refinementStepCount+=1.0;}
pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}
#endif
Q0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0;
#ifdef SSRAYTRACE_DEBUG
if (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);}
#endif
return hit;}
/**
texCoord: in the [0,1] range
depth: depth in view space (range [znear,zfar]])
*/
fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32;
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
#ifdef ORTHOGRAPHIC_CAMERA
z=-projection[2].z*depth+projection[3].z;
#else
z=-projection[2].z-projection[3].z/depth;
#endif
#else
#ifdef ORTHOGRAPHIC_CAMERA
z=projection[2].z*depth+projection[3].z;
#else
z=projection[2].z+projection[3].z/depth;
#endif
#endif
var w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;}
`;
var init_screenSpaceRayTrace = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name226]) {
    ShaderStore.IncludesShadersStoreWGSL[name226] = shader225;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2.fragment.js
var exports_screenSpaceReflection2_fragment = {};
__export(exports_screenSpaceReflection2_fragment, {
  screenSpaceReflection2PixelShaderWGSL: () => screenSpaceReflection2PixelShaderWGSL
});
var name227 = "screenSpaceReflection2PixelShader", shader226 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;varying vUV: vec2f;
#ifdef SSR_SUPPORTED
var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d<f32>;var normalSampler: texture_2d<f32>;var depthSampler: texture_2d<f32>;
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
var backDepthSampler: texture_2d<f32>;uniform backSizeFactor: f32;
#endif
#ifdef SSR_USE_ENVIRONMENT_CUBE
var envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube<f32>;
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;
#endif
#endif
uniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform farPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32;
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
fn hash(a: vec3f)->vec3f
{var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);}
fn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0;
#ifdef SSR_ATTENUATE_SCREEN_BORDERS
var dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE
attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS
attenuation*=1.0-(numIterations/uniforms.maxSteps);
#endif
#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION
var reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;
#endif
return attenuation;}
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#ifdef SSR_SUPPORTED
var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=max(textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0),vec4f(0.0));
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {
#ifdef SSR_USE_BLUR
fragmentOutputs.color= vec4f(0.);
#else
fragmentOutputs.color=colorFull;
#endif
return fragmentOutputs;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpaceVec3(color);
#endif
var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2<i32>(input.vUV*texSize),0).xyz; 
#ifdef SSR_DECODE_NORMAL
csNormal=csNormal*2.0-1.0;
#endif
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
csNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz;
#endif
var depth: f32=textureLoad(depthSampler,vec2<i32>(input.vUV*texSize),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);
#endif
var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);
#ifdef ORTHOGRAPHIC_CAMERA
var csViewDirection: vec3f= vec3f(0.,0.,1.);
#else
var csViewDirection: vec3f=normalize(csPosition);
#endif
var csReflectedVector: vec3f=reflect(csViewDirection,csNormal);
#ifdef SSR_USE_ENVIRONMENT_CUBE
var wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz;
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
var worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition);
#endif
#ifdef SSR_INVERTCUBICMAP
wReflectedVector.y*=-1.0;
#endif
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
wReflectedVector.z*=-1.0;
#endif
var envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz;
#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE
envColor=toLinearSpaceVec3(envColor);
#endif
#else
var envColor: vec3f=color;
#endif
var reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32;
#ifdef SSRAYTRACE_DEBUG
var debugColor: vec3f;
#endif
#ifdef SSR_ATTENUATE_FACING_CAMERA
reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));
#endif
if (reflectionAttenuation>0.0) {
#ifdef SSR_USE_BLUR
var jitt: vec3f= vec3f(0.);
#else
var roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; 
#endif
var uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); 
rayHasHit=traceScreenSpaceRay1(
csPosition,
normalize(csReflectedVector+jitt),
uniforms.projectionPixel,
depthSampler,
texSize,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
backDepthSampler,
uniforms.backSizeFactor,
#endif
uniforms.thickness,
uniforms.nearPlaneZ,
uniforms.farPlaneZ,
uniforms.stepSize,
jitter,
uniforms.maxSteps,
uniforms.maxDistance,
uniforms.selfCollisionNumSkip,
&startPixel,
&hitPixel,
&hitPoint,
&numIterations
#ifdef SSRAYTRACE_DEBUG
,&debugColor
#endif
);}
#ifdef SSRAYTRACE_DEBUG
fragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs;
#endif
var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2<i32>(hitPixel),0).rgb;
#ifdef SSR_INPUT_IS_GAMMA_SPACE
reflectedColor=toLinearSpaceVec3(reflectedColor);
#endif
reflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}
#ifndef SSR_BLEND_WITH_FRESNEL
SSR*=fresnel;
#endif
#ifdef SSR_USE_BLUR
var blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; 
var a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}
fragmentOutputs.color= vec4f(SSR,blur_radius/255.0); 
#else
#ifdef SSR_BLEND_WITH_FRESNEL
var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));
#else
var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));
#endif
var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpaceVec3(finalColor);
#endif
fragmentOutputs.color= vec4f(finalColor,colorFull.a);
#endif
#else
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);
#endif
}
`, screenSpaceReflection2PixelShaderWGSL;
var init_screenSpaceReflection2_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  init_pbrBRDFFunctions();
  init_screenSpaceRayTrace();
  if (!ShaderStore.ShadersStoreWGSL[name227]) {
    ShaderStore.ShadersStoreWGSL[name227] = shader226;
  }
  screenSpaceReflection2PixelShaderWGSL = { name: name227, shader: shader226 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBRDFFunctions.js
var name228 = "pbrBRDFFunctions", shader227 = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}
#endif
#ifdef ENVIRONMENTBRDF
vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);
#ifdef ENVIRONMENTBRDF_RGBD
brdfLookup.rgb=fromRGBD(brdfLookup.rgba);
#endif
return brdfLookup.rgb;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;
#endif
return reflectance;}
vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {
#ifdef BRDF_V_HEIGHT_CORRELATED
vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);
#else
vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;
#endif
return reflectance;}
#endif
/* NOT USED
#if defined(SHEEN) && defined(SHEEN_SOFTER)
float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)
{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}
#endif
*/
#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)
vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
/**
* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.
* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table
*/
vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}
#endif
vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)
{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}
#ifdef CLEARCOAT
vec3 getR0RemappedForClearCoat(vec3 f0) {
#ifdef CLEARCOAT_DEFAULTIOR
#ifdef MOBILE
return saturate(f0*(f0*0.526868+0.529324)-0.0482256);
#else
return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);
#endif
#else
vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);
#endif
}
#endif
#ifdef IRIDESCENCE
const mat3 XYZ_TO_REC709=mat3(
3.2404542,-0.9692660, 0.0556434,
-1.5371385, 1.8760108,-0.2040259,
-0.4985314, 0.0415560, 1.0572252
);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}
vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}
float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}
vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}
vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}
float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); 
vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)
{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}
return max(I,vec3(0.0));}
#endif
float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)
{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}
#ifdef SHEEN
float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)
{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}
#endif
#ifdef ANISOTROPIC
float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}
#endif
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {
#ifdef MOBILE
float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);
#else
float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);
#endif
}
#else
float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)
{
#ifdef MOBILE
return 1.0/(dot+alphaG+(1.0-alphaG)*dot ));
#else
float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));
#endif
}
float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)
{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}
#endif
#ifdef ANISOTROPIC
float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}
#endif
#ifdef CLEARCOAT
float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }
#endif
#ifdef SHEEN
float visibility_Ashikhmin(float NdotL,float NdotV)
{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}
/* NOT USED
#ifdef SHEEN_SOFTER
float l(float x,float alphaG)
{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}
float lambdaSheen(float cosTheta,float alphaG)
{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}
float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)
{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}
#endif
*/
#endif
float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *
(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}
#ifdef SS_TRANSLUCENCY
vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}
float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}
#endif
`;
var init_pbrBRDFFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name228]) {
    ShaderStore.IncludesShadersStore[name228] = shader227;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js
var name229 = "screenSpaceRayTrace", shader228 = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
float linearizeDepth(float depth,float near,float far) {
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
return -(near*far)/(far-depth*(far-near));
#else
return (near*far)/(far-depth*(far-near));
#endif
}
#endif
/**
param csOrigin Camera-space ray origin,which must be 
within the view volume and must have z>0.01 and project within the valid screen rectangle
param csDirection Unit length camera-space ray direction
param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates 
(**not** [-1,+1] normalized device coordinates).
param csZBuffer The camera-space Z buffer
param csZBufferSize Dimensions of csZBuffer
param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer
param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value
for clipping rays headed towards the camera
param stride Step in horizontal or vertical pixels between samples. This is a float
because integer math is slow on GPUs,but should be set to an integer>=1
param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units
to conceal banding artifacts,plus the stride ray offset.
param maxSteps Maximum number of iterations. Higher gives better images but may be slow
param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss
param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.
1 is a reasonable value,depending on the scene you may need to set this value to 2
param hitPixel Pixel coordinates of the first intersection with the scene
param numIterations number of iterations performed
param csHitPoint Camera space location of the ray hit
*/
#define inline
bool traceScreenSpaceRay1(
vec3 csOrigin,
vec3 csDirection,
mat4 projectToPixelMatrix,
sampler2D csZBuffer,
vec2 csZBufferSize,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
sampler2D csZBackBuffer,
float csZBackSizeFactor,
#endif
float csZThickness,
float nearPlaneZ,
float farPlaneZ,
float stride,
float jitterFraction,
float maxSteps,
float maxRayTraceDistance,
float selfCollisionNumSkip,
out vec2 startPixel,
out vec2 hitPixel,
out vec3 csHitPoint,
out float numIterations
#ifdef SSRAYTRACE_DEBUG
,out vec3 debugColor
#endif
)
{
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;
#else
float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;
#endif
vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1;
#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM
float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);}
if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));}
P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);
#endif
P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { 
permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; }
float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip ||
(pqk.x*stepDirection)<=end &&
stepCount<maxSteps &&
!hit &&
sceneZMax != 0.0; 
pqk+=dPQK,++stepCount)
{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { 
float t=rayZMin; rayZMin=rayZMax; rayZMax=t;}
sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);
#endif
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);
#endif
hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);
#else
hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);
#endif
#else
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ);
#endif
hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);
#else
hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);
#endif
#endif
}
pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}
#ifdef SSRAYTRACE_ENABLE_REFINEMENT
if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||
(refinementStepCount<=stride*1.4) &&
(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0)
{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ);
#endif
}
pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}
#endif
Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0;
#ifdef SSRAYTRACE_DEBUG
if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}
#endif
return hit;}
/**
texCoord: in the [0,1] range
depth: depth in view space (range [znear,zfar]])
*/
vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
#ifdef ORTHOGRAPHIC_CAMERA
ndc.z=-projection[2].z*depth+projection[3].z;
#else
ndc.z=-projection[2].z-projection[3].z/depth;
#endif
#else
#ifdef ORTHOGRAPHIC_CAMERA
ndc.z=projection[2].z*depth+projection[3].z;
#else
ndc.z=projection[2].z+projection[3].z/depth;
#endif
#endif
ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}
`;
var init_screenSpaceRayTrace2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name229]) {
    ShaderStore.IncludesShadersStore[name229] = shader228;
  }
});

// node_modules/@babylonjs/core/Shaders/screenSpaceReflection2.fragment.js
var exports_screenSpaceReflection2_fragment2 = {};
__export(exports_screenSpaceReflection2_fragment2, {
  screenSpaceReflection2PixelShader: () => screenSpaceReflection2PixelShader
});
var name230 = "screenSpaceReflection2PixelShader", shader229 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSR_SUPPORTED
uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
uniform sampler2D backDepthSampler;uniform float backSizeFactor;
#endif
#ifdef SSR_USE_ENVIRONMENT_CUBE
uniform samplerCube envCubeSampler;
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float farPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;
#include<helperFunctions>
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
vec3 hash(vec3 a)
{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}
float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;
#ifdef SSR_ATTENUATE_SCREEN_BORDERS
vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE
attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);
#endif
#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS
attenuation*=1.0-(numIterations/maxSteps);
#endif
#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION
vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;
#endif
return attenuation;}
#endif
void main()
{
#ifdef SSR_SUPPORTED
vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=max(TEXTUREFUNC(reflectivitySampler,vUV,0.0),vec4(0.));
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {
#ifdef SSR_USE_BLUR
gl_FragColor=vec4(0.);
#else
gl_FragColor=colorFull;
#endif
return;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpace(color);
#endif
vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; 
#ifdef SSR_DECODE_NORMAL
csNormal=csNormal*2.0-1.0;
#endif
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
csNormal=(view*vec4(csNormal,0.0)).xyz;
#endif
float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);
#endif
vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);
#ifdef ORTHOGRAPHIC_CAMERA
vec3 csViewDirection=vec3(0.,0.,1.);
#else
vec3 csViewDirection=normalize(csPosition);
#endif
vec3 csReflectedVector=reflect(csViewDirection,csNormal);
#ifdef SSR_USE_ENVIRONMENT_CUBE
vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));
#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC
vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);
#endif
#ifdef SSR_INVERTCUBICMAP
wReflectedVector.y*=-1.0;
#endif
#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE
wReflectedVector.z*=-1.0;
#endif
vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;
#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE
envColor=toLinearSpace(envColor);
#endif
#else
vec3 envColor=color;
#endif
float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;
#ifdef SSRAYTRACE_DEBUG
vec3 debugColor;
#endif
#ifdef SSR_ATTENUATE_FACING_CAMERA
reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));
#endif
if (reflectionAttenuation>0.0) {
#ifdef SSR_USE_BLUR
vec3 jitt=vec3(0.);
#else
float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; 
#endif
vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); 
rayHasHit=traceScreenSpaceRay1(
csPosition,
normalize(csReflectedVector+jitt),
projectionPixel,
depthSampler,
texSize,
#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER
backDepthSampler,
backSizeFactor,
#endif
thickness,
nearPlaneZ,
farPlaneZ,
stepSize,
jitter,
maxSteps,
maxDistance,
selfCollisionNumSkip,
startPixel,
hitPixel,
hitPoint,
numIterations
#ifdef SSRAYTRACE_DEBUG
,debugColor
#endif
);}
#ifdef SSRAYTRACE_DEBUG
gl_FragColor=vec4(debugColor,1.);return;
#endif
vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;
#ifdef SSR_INPUT_IS_GAMMA_SPACE
reflectedColor=toLinearSpace(reflectedColor);
#endif
reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}
#ifndef SSR_BLEND_WITH_FRESNEL
SSR*=fresnel;
#endif
#ifdef SSR_USE_BLUR
float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; 
float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}
gl_FragColor=vec4(SSR,blur_radius/255.0); 
#else
#ifdef SSR_BLEND_WITH_FRESNEL
vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#else
vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#endif
vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpace(finalColor);
#endif
gl_FragColor=vec4(finalColor,colorFull.a);
#endif
#else
gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);
#endif
}
`, screenSpaceReflection2PixelShader;
var init_screenSpaceReflection2_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  init_pbrBRDFFunctions2();
  init_screenSpaceRayTrace2();
  if (!ShaderStore.ShadersStore[name230]) {
    ShaderStore.ShadersStore[name230] = shader229;
  }
  screenSpaceReflection2PixelShader = { name: name230, shader: shader229 };
});

// node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2Blur.fragment.js
var exports_screenSpaceReflection2Blur_fragment = {};
__export(exports_screenSpaceReflection2Blur_fragment, {
  screenSpaceReflection2BlurPixelShaderWGSL: () => screenSpaceReflection2BlurPixelShaderWGSL
});
var name231 = "screenSpaceReflection2BlurPixelShader", shader230 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array<f32,8>=array<f32,8>(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr<function,vec4f>,denominator: ptr<function,f32>)
{var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;}
var blurRadius: f32=colorFull.a*255.0; 
var stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);}
`, screenSpaceReflection2BlurPixelShaderWGSL;
var init_screenSpaceReflection2Blur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name231]) {
    ShaderStore.ShadersStoreWGSL[name231] = shader230;
  }
  screenSpaceReflection2BlurPixelShaderWGSL = { name: name231, shader: shader230 };
});

// node_modules/@babylonjs/core/Shaders/screenSpaceReflection2Blur.fragment.js
var exports_screenSpaceReflection2Blur_fragment2 = {};
__export(exports_screenSpaceReflection2Blur_fragment2, {
  screenSpaceReflection2BlurPixelShader: () => screenSpaceReflection2BlurPixelShader
});
var name232 = "screenSpaceReflection2BlurPixelShader", shader231 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)
#else
#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)
#endif
uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)
{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}
void main()
{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}
float blurRadius=colorFull.a*255.0; 
vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}
`, screenSpaceReflection2BlurPixelShader;
var init_screenSpaceReflection2Blur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name232]) {
    ShaderStore.ShadersStore[name232] = shader231;
  }
  screenSpaceReflection2BlurPixelShader = { name: name232, shader: shader231 };
});

// node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2BlurCombiner.fragment.js
var exports_screenSpaceReflection2BlurCombiner_fragment = {};
__export(exports_screenSpaceReflection2BlurCombiner_fragment, {
  screenSpaceReflection2BlurCombinerPixelShaderWGSL: () => screenSpaceReflection2BlurCombinerPixelShaderWGSL
});
var name233 = "screenSpaceReflection2BlurCombinerPixelShader", shader232 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>; 
var mainSamplerSampler: sampler;var mainSampler: texture_2d<f32>;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d<f32>;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f;
#include<helperFunctions>
#ifdef SSR_BLEND_WITH_FRESNEL
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
uniform view: mat4x4f;
#endif
var normalSampler: texture_2d<f32>;var depthSampler: texture_2d<f32>;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
uniform nearPlaneZ: f32;uniform farPlaneZ: f32;
#endif
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#ifdef SSRAYTRACE_DEBUG
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);
#else
var SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV);
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpaceVec4(color);
#endif
#ifdef SSR_BLEND_WITH_FRESNEL
var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2<i32>(input.vUV*texSize),0).xyz;
#ifdef SSR_DECODE_NORMAL
csNormal=csNormal*2.0-1.0;
#endif
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
csNormal=(uniforms.view*vec4f(csNormal,0.0)).xyz;
#endif
var depth: f32=textureLoad(depthSampler,vec2<i32>(input.vUV*texSize),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ);
#endif
var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));
#else
var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0));
#endif
var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpaceVec3(finalColor);
#endif
fragmentOutputs.color= vec4f(finalColor,color.a);
#endif
}
`, screenSpaceReflection2BlurCombinerPixelShaderWGSL;
var init_screenSpaceReflection2BlurCombiner_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  init_pbrBRDFFunctions();
  init_screenSpaceRayTrace();
  if (!ShaderStore.ShadersStoreWGSL[name233]) {
    ShaderStore.ShadersStoreWGSL[name233] = shader232;
  }
  screenSpaceReflection2BlurCombinerPixelShaderWGSL = { name: name233, shader: shader232 };
});

// node_modules/@babylonjs/core/Shaders/screenSpaceReflection2BlurCombiner.fragment.js
var exports_screenSpaceReflection2BlurCombiner_fragment2 = {};
__export(exports_screenSpaceReflection2BlurCombiner_fragment2, {
  screenSpaceReflection2BlurCombinerPixelShader: () => screenSpaceReflection2BlurCombinerPixelShader
});
var name234 = "screenSpaceReflection2BlurCombinerPixelShader", shader233 = `uniform sampler2D textureSampler; 
uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;
#include<helperFunctions>
#ifdef SSR_BLEND_WITH_FRESNEL
#include<pbrBRDFFunctions>
#include<screenSpaceRayTrace>
uniform mat4 projection;uniform mat4 invProjectionMatrix;
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
uniform mat4 view;
#endif
uniform sampler2D normalSampler;uniform sampler2D depthSampler;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
uniform float nearPlaneZ;uniform float farPlaneZ;
#endif
#endif
void main()
{
#ifdef SSRAYTRACE_DEBUG
gl_FragColor=texture2D(textureSampler,vUV);
#else
vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);
#ifndef SSR_DISABLE_REFLECTIVITY_TEST
if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}
#endif
#ifdef SSR_INPUT_IS_GAMMA_SPACE
color=toLinearSpace(color);
#endif
#ifdef SSR_BLEND_WITH_FRESNEL
vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;
#ifdef SSR_DECODE_NORMAL
csNormal=csNormal*2.0-1.0;
#endif
#ifdef SSR_NORMAL_IS_IN_WORLDSPACE
csNormal=(view*vec4(csNormal,0.0)).xyz;
#endif
float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;
#ifdef SSRAYTRACE_SCREENSPACE_DEPTH
depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ);
#endif
vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#else
vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);
#endif
vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);
#ifdef SSR_OUTPUT_IS_GAMMA_SPACE
finalColor=toGammaSpace(finalColor);
#endif
gl_FragColor=vec4(finalColor,color.a);
#endif
}
`, screenSpaceReflection2BlurCombinerPixelShader;
var init_screenSpaceReflection2BlurCombiner_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  init_pbrBRDFFunctions2();
  init_screenSpaceRayTrace2();
  if (!ShaderStore.ShadersStore[name234]) {
    ShaderStore.ShadersStore[name234] = shader233;
  }
  screenSpaceReflection2BlurCombinerPixelShader = { name: name234, shader: shader233 };
});

// node_modules/@babylonjs/core/ShadersWGSL/taa.fragment.js
var exports_taa_fragment = {};
__export(exports_taa_fragment, {
  taaPixelShaderWGSL: () => taaPixelShaderWGSL
});
var name235 = "taaPixelShader", shader234 = `var textureSampler: texture_2d<f32>;var historySampler: texture_2d<f32>;uniform factor: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let c=textureLoad(textureSampler,vec2<i32>(fragmentInputs.position.xy),0);let h=textureLoad(historySampler,vec2<i32>(fragmentInputs.position.xy),0);fragmentOutputs.color= mix(h,c,uniforms.factor);}
`, taaPixelShaderWGSL;
var init_taa_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name235]) {
    ShaderStore.ShadersStoreWGSL[name235] = shader234;
  }
  taaPixelShaderWGSL = { name: name235, shader: shader234 };
});

// node_modules/@babylonjs/core/Shaders/taa.fragment.js
var exports_taa_fragment2 = {};
__export(exports_taa_fragment2, {
  taaPixelShader: () => taaPixelShader
});
var name236 = "taaPixelShader", shader235 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}
`, taaPixelShader;
var init_taa_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name236]) {
    ShaderStore.ShadersStore[name236] = shader235;
  }
  taaPixelShader = { name: name236, shader: shader235 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/backgroundUboDeclaration.js
var name237 = "backgroundUboDeclaration", shader236 = `uniform vPrimaryColor: vec4f;uniform vPrimaryColorShadow: vec4f;uniform vDiffuseInfos: vec2f;uniform vReflectionInfos: vec2f;uniform diffuseMatrix: mat4x4f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform fFovMultiplier: f32;uniform pointSize: f32;uniform shadowLevel: f32;uniform alpha: f32;uniform vBackgroundCenter: vec3f;uniform vReflectionControl: vec4f;uniform projectedGroundInfos: vec2f;
#include<sceneUboDeclaration>
`;
var init_backgroundUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration();
  if (!ShaderStore.IncludesShadersStoreWGSL[name237]) {
    ShaderStore.IncludesShadersStoreWGSL[name237] = shader236;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/background.vertex.js
var exports_background_vertex = {};
__export(exports_background_vertex, {
  backgroundVertexShaderWGSL: () => backgroundVertexShaderWGSL
});
var name238 = "backgroundVertexShader", shader237 = `#include<backgroundUboDeclaration>
#include<helperFunctions>
attribute position: vec3f;
#ifdef NORMAL
attribute normal: vec3f;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
varying vPositionW: vec3f;
#ifdef NORMAL
varying vNormalW: vec3f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#ifdef MAINUV1
varying vMainUV1: vec2f;
#endif
#ifdef MAINUV2
varying vMainUV2: vec2f;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
varying vDiffuseUV: vec2f;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<lightVxUboDeclaration>[0..maxSimultaneousLights]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=input.position;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);} else {vertexOutputs.position=scene.viewProjectionR*finalWorld* vec4f(input.position,1.0);}
#else
vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(input.position,1.0);
#endif
var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);vertexOutputs.vPositionW= worldPos.xyz;
#ifdef NORMAL
var normalWorld: mat3x3f=mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*input.normal);
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(input.position,0.0)).xyz);
#ifdef EQUIRECTANGULAR_RELFECTION_FOV
var screenToWorld: mat3x3f=inverseMat3( mat3x3f(finalWorld*scene.viewProjection));var segment: vec3f=mix(vertexOutputs.vDirectionW,screenToWorld* vec3f(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vertexOutputs.vDirectionW=normalize(segment);} else {vertexOutputs.vDirectionW=normalize(vertexOutputs.vDirectionW+(vertexOutputs.vDirectionW-segment));}
#endif
#endif
#ifndef UV1
var uv: vec2f=vec2f(0.,0.);
#else
var uv=input.uv;
#endif
#ifndef UV2
var uv2: vec2f=vec2f(0.,0.);
#else
var uv2=input.uv2;
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uv;
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
if (uniforms.vDiffuseInfos.x==0.)
{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv,1.0,0.0)).xy;}
else
{vertexOutputs.vDiffuseUV= (uniforms.diffuseMatrix* vec4f(uv2,1.0,0.0)).xy;}
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#ifdef VERTEXCOLOR
vertexOutputs.vColor=vertexInputs.color;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`, backgroundVertexShaderWGSL;
var init_background_vertex = __esm(() => {
  init_shaderStore();
  init_backgroundUboDeclaration();
  init_helperFunctions();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_instancesDeclaration();
  init_clipPlaneVertexDeclaration();
  init_fogVertexDeclaration();
  init_lightVxUboDeclaration();
  init_logDepthDeclaration();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  init_fogVertex();
  init_shadowsVertex();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name238]) {
    ShaderStore.ShadersStoreWGSL[name238] = shader237;
  }
  backgroundVertexShaderWGSL = { name: name238, shader: shader237 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/intersectionFunctions.js
var name239 = "intersectionFunctions", shader238 = `fn diskIntersectWithBackFaceCulling(ro: vec3f,rd: vec3f,c: vec3f,r: f32)->f32 {var d: f32=rd.y;if(d>0.0) { return 1e6; }
var o: vec3f=ro-c;var t: f32=-o.y/d;var q: vec3f=o+rd*t;return select(1e6,t,(dot(q,q)<r*r));}
fn sphereIntersect(ro: vec3f,rd: vec3f,ce: vec3f,ra: f32)->vec2f {var oc: vec3f=ro-ce;var b: f32=dot(oc,rd);var c: f32=dot(oc,oc)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return vec2f(-1.,-1.); }
h=sqrt(h);return vec2f(-b+h,-b-h);}
fn sphereIntersectFromOrigin(ro: vec3f,rd: vec3f,ra: f32)->vec2f {var b: f32=dot(ro,rd);var c: f32=dot(ro,ro)-ra*ra;var h: f32=b*b-c;if(h<0.0) { return vec2f(-1.,-1.); }
h=sqrt(h);return vec2f(-b+h,-b-h);}`;
var init_intersectionFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name239]) {
    ShaderStore.IncludesShadersStoreWGSL[name239] = shader238;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/background.fragment.js
var exports_background_fragment = {};
__export(exports_background_fragment, {
  backgroundPixelShaderWGSL: () => backgroundPixelShaderWGSL
});
var name240 = "backgroundPixelShader", shader239 = `#include<backgroundUboDeclaration>
#include<helperFunctions>
varying vPositionW: vec3f;
#ifdef MAINUV1
varying vMainUV1: vec2f;
#endif 
#ifdef MAINUV2 
varying vMainUV2: vec2f; 
#endif 
#ifdef NORMAL
varying vNormalW: vec3f;
#endif
#ifdef DIFFUSE
#if DIFFUSEDIRECTUV==1
#define vDiffuseUV vMainUV1
#elif DIFFUSEDIRECTUV==2
#define vDiffuseUV vMainUV2
#else
varying vDiffuseUV: vec2f;
#endif
var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube<f32>;
#ifdef TEXTURELODSUPPORT
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube<f32>;
#endif
#else
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d<f32>;
#ifdef TEXTURELODSUPPORT
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d<f32>;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#endif
#include<reflectionFunction>
#endif
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE;
#endif
#ifndef SHADOWONLY
#define SHADOWONLY;
#endif
#include<imageProcessingDeclaration>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<imageProcessingFunctions>
#include<logDepthDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#ifdef REFLECTIONFRESNEL
#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
fn fresnelSchlickEnvironmentGGX(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f
{var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#ifdef PROJECTED_GROUND
#include<intersectionFunctions>
fn project(viewDirectionW: vec3f,eyePosition: vec3f)->vec3f {var radius: f32=uniforms.projectedGroundInfos.x;var height: f32=uniforms.projectedGroundInfos.y;var camDir: vec3f=-viewDirectionW;var skySphereDistance: f32=sphereIntersectFromOrigin(eyePosition,camDir,radius).x;var skySpherePositionW: vec3f=eyePosition+camDir*skySphereDistance;var p: vec3f=normalize(skySpherePositionW);var upEyePosition=vec3f(eyePosition.x,eyePosition.y-height,eyePosition.z);var sIntersection: f32=sphereIntersectFromOrigin(upEyePosition,p,radius).x;var h: vec3f= vec3f(0.0,-height,0.0);var dIntersection: f32=diskIntersectWithBackFaceCulling(upEyePosition,p,h,radius);p=(upEyePosition+min(sIntersection,dIntersection)*p);return p;}
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);
#ifdef NORMAL
var normalW: vec3f=normalize(fragmentInputs.vNormalW);
#else
var normalW: vec3f= vec3f(0.0,1.0,0.0);
#endif
var shadow: f32=1.;var globalShadow: f32=0.;var shadowLightCount: f32=0.;var aggShadow: f32=0.;var numLights: f32=0.;
#include<lightFragment>[0..maxSimultaneousLights]
#ifdef SHADOWINUSE
globalShadow/=shadowLightCount;
#else
globalShadow=1.0;
#endif
#ifndef BACKMAT_SHADOWONLY
var reflectionColor: vec4f= vec4f(1.,1.,1.,1.);
#ifdef REFLECTION
#ifdef PROJECTED_GROUND
var reflectionVector: vec3f=project(viewDirectionW,scene.vEyePosition.xyz);reflectionVector= (uniforms.reflectionMatrix*vec4f(reflectionVector,1.)).xyz;
#else
var reflectionVector: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f=reflectionVector;
#else
var reflectionCoords: vec2f=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
#ifdef REFLECTIONBLUR
var reflectionLOD: f32=uniforms.vReflectionInfos.y;
#ifdef TEXTURELODSUPPORT
reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);
#else
var lodReflectionNormalized: f32=saturate(reflectionLOD);var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var reflectionSpecularMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(
textureSample(reflectionrHighSampler,reflectionrHighSamplerSampler,reflectionCoords),
reflectionSpecularMid,
lodReflectionNormalizedDoubled
);} else {reflectionColor=mix(
reflectionSpecularMid,
textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#else
var reflectionSample: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);reflectionColor=reflectionSample;
#endif
#ifdef RGBDREFLECTION
reflectionColor=vec4f(fromRGBD(reflectionColor).rgb,reflectionColor.a);
#endif
#ifdef GAMMAREFLECTION
reflectionColor=vec4f(toLinearSpaceVec3(reflectionColor.rgb),reflectionColor.a);
#endif
#ifdef REFLECTIONBGR
reflectionColor=vec4f(reflectionColor.bgr,reflectionColor.a);
#endif
reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a);
#endif
var diffuseColor: vec3f= vec3f(1.,1.,1.);var finalAlpha: f32=uniforms.alpha;
#ifdef DIFFUSE
var diffuseMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vDiffuseUV);
#ifdef GAMMADIFFUSE
diffuseMap=vec4f(toLinearSpaceVec3(diffuseMap.rgb),diffuseMap.a);
#endif
diffuseMap=vec4f(diffuseMap.rgb *uniforms.vDiffuseInfos.y,diffuseMap.a);
#ifdef DIFFUSEHASALPHA
finalAlpha*=diffuseMap.a;
#endif
diffuseColor=diffuseMap.rgb;
#endif
#ifdef REFLECTIONFRESNEL
var colorBase: vec3f=diffuseColor;
#else
var colorBase: vec3f=reflectionColor.rgb*diffuseColor;
#endif
colorBase=max(colorBase,vec3f(0.0));
#ifdef USERGBCOLOR
var finalColor: vec3f=colorBase;
#else
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
var mainColor: vec3f=mix(uniforms.vPrimaryColorShadow.rgb,uniforms.vPrimaryColor.rgb,colorBase);
#else
var mainColor: vec3f=uniforms.vPrimaryColor.rgb;
#endif
var finalColor: vec3f=colorBase*mainColor;
#endif
#ifdef REFLECTIONFRESNEL
var reflectionAmount: vec3f=uniforms.vReflectionControl.xxx;var reflectionReflectance0: vec3f=uniforms.vReflectionControl.yyy;var reflectionReflectance90: vec3f=uniforms.vReflectionControl.zzz;var VdotN: f32=dot(normalize(scene.vEyePosition.xyz),normalW);var planarReflectionFresnel: vec3f=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;
#ifdef REFLECTIONFALLOFF
var reflectionDistanceFalloff: f32=1.0-saturate(length(vPositionW.xyz-uniforms.vBackgroundCenter)*uniforms.vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;
#endif
finalColor=mix(finalColor,reflectionColor.rgb,saturateVec3(reflectionAmount));
#endif
#ifdef OPACITYFRESNEL
var viewAngleToFloor: f32=dot(normalW,normalize(scene.vEyePosition.xyz-uniforms.vBackgroundCenter));const startAngle: f32=0.1;var fadeFactor: f32=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;
#endif
#ifdef SHADOWINUSE
finalColor=mix(finalColor*uniforms.shadowLevel,finalColor,globalShadow);
#endif
var color: vec4f= vec4f(finalColor,finalAlpha);
#else
var color: vec4f= vec4f(uniforms.vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*uniforms.alpha);
#endif
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
#if !defined(SKIPFINALCOLORCLAMP)
color=vec4f(clamp(color.rgb,vec3f(0.),vec3f(30.0)),color.a);
#endif
#else
color=applyImageProcessing(color);
#endif
#ifdef PREMULTIPLYALPHA
color=vec4f(color.rgb *color.a,color.a);
#endif
#ifdef NOISE
color=vec4f(color.rgb+dither(fragmentInputs.vPositionW.xy,0.5),color.a);color=max(color,vec4f(0.0));
#endif
fragmentOutputs.color=color;
#define CUSTOM_FRAGMENT_MAIN_END
}
`, backgroundPixelShaderWGSL;
var init_background_fragment = __esm(() => {
  init_shaderStore();
  init_backgroundUboDeclaration();
  init_helperFunctions();
  init_reflectionFunction();
  init_imageProcessingDeclaration();
  init_lightUboDeclaration();
  init_lightsFragmentFunctions();
  init_shadowsFragmentFunctions();
  init_imageProcessingFunctions();
  init_logDepthDeclaration();
  init_clipPlaneFragmentDeclaration();
  init_fogFragmentDeclaration();
  init_intersectionFunctions();
  init_clipPlaneFragment();
  init_lightFragment();
  init_logDepthFragment();
  init_fogFragment();
  if (!ShaderStore.ShadersStoreWGSL[name240]) {
    ShaderStore.ShadersStoreWGSL[name240] = shader239;
  }
  backgroundPixelShaderWGSL = { name: name240, shader: shader239 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundVertexDeclaration.js
var name241 = "backgroundVertexDeclaration", shader240 = `uniform mat4 view;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
uniform float shadowLevel;
#ifdef DIFFUSE
uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
`;
var init_backgroundVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name241]) {
    ShaderStore.IncludesShadersStore[name241] = shader240;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundUboDeclaration.js
var name242 = "backgroundUboDeclaration", shader241 = `layout(std140,column_major) uniform;uniform Material
{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};
#include<sceneUboDeclaration>
`;
var init_backgroundUboDeclaration2 = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name242]) {
    ShaderStore.IncludesShadersStore[name242] = shader241;
  }
});

// node_modules/@babylonjs/core/Shaders/background.vertex.js
var exports_background_vertex2 = {};
__export(exports_background_vertex2, {
  backgroundVertexShader: () => backgroundVertexShader
});
var name243 = "backgroundVertexShader", shader242 = `precision highp float;
#include<__decl__backgroundVertex>
#include<helperFunctions>
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
varying vec3 vPositionW;
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif
#ifdef MAINUV2
varying vec2 vMainUV2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
varying vec2 vDiffuseUV;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=position;
#endif
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}
#else
gl_Position=viewProjection*finalWorld*vec4(position,1.0);
#endif
vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normal);
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));
#ifdef EQUIRECTANGULAR_RELFECTION_FOV
mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}
#endif
#endif
#ifndef UV1
vec2 uv=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uv;
#endif
#ifdef MAINUV2
vMainUV2=uv2;
#endif
#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0
if (vDiffuseInfos.x==0.)
{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}
else
{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#ifdef VERTEXCOLOR
vColor=colorUpdated;
#endif
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}
`, backgroundVertexShader;
var init_background_vertex2 = __esm(() => {
  init_shaderStore();
  init_backgroundVertexDeclaration();
  init_backgroundUboDeclaration2();
  init_helperFunctions2();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_instancesDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_lightVxFragmentDeclaration2();
  init_lightVxUboDeclaration2();
  init_logDepthDeclaration2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_shadowsVertex2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name243]) {
    ShaderStore.ShadersStore[name243] = shader242;
  }
  backgroundVertexShader = { name: name243, shader: shader242 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundFragmentDeclaration.js
var name244 = "backgroundFragmentDeclaration", shader243 = `uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
uniform vec4 vPrimaryColorShadow;
#endif
uniform float shadowLevel;uniform float alpha;
#ifdef DIFFUSE
uniform vec2 vDiffuseInfos;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#endif
#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)
uniform vec3 vBackgroundCenter;
#endif
#ifdef REFLECTIONFRESNEL
uniform vec4 vReflectionControl;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)
uniform mat4 view;
#endif
#ifdef PROJECTED_GROUND
uniform vec2 projectedGroundInfos;
#endif
`;
var init_backgroundFragmentDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name244]) {
    ShaderStore.IncludesShadersStore[name244] = shader243;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/intersectionFunctions.js
var name245 = "intersectionFunctions", shader244 = `float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }
vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)<r*r) ? t : 1e6;}
vec2 sphereIntersect(vec3 ro,vec3 rd,vec3 ce,float ra) {vec3 oc=ro-ce;float b=dot(oc,rd);float c=dot(oc,oc)-ra*ra;float h=b*b-c;if(h<0.0) { return vec2(-1.0,-1.0); }
h=sqrt(h);return vec2(-b+h,-b-h);}
vec2 sphereIntersectFromOrigin(vec3 ro,vec3 rd,float ra) {float b=dot(ro,rd);float c=dot(ro,ro)-ra*ra;float h=b*b-c;if(h<0.0) { return vec2(-1.0,-1.0); }
h=sqrt(h);return vec2(-b+h,-b-h);}`;
var init_intersectionFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name245]) {
    ShaderStore.IncludesShadersStore[name245] = shader244;
  }
});

// node_modules/@babylonjs/core/Shaders/background.fragment.js
var exports_background_fragment2 = {};
__export(exports_background_fragment2, {
  backgroundPixelShader: () => backgroundPixelShader
});
var name246 = "backgroundPixelShader", shader245 = `#ifdef TEXTURELODSUPPORT
#extension GL_EXT_shader_texture_lod : enable
#endif
precision highp float;
#include<__decl__backgroundFragment>
#include<helperFunctions>
varying vec3 vPositionW;
#ifdef MAINUV1
varying vec2 vMainUV1;
#endif 
#ifdef MAINUV2 
varying vec2 vMainUV2; 
#endif 
#ifdef NORMAL
varying vec3 vNormalW;
#endif
#ifdef DIFFUSE
#if DIFFUSEDIRECTUV==1
#define vDiffuseUV vMainUV1
#elif DIFFUSEDIRECTUV==2
#define vDiffuseUV vMainUV2
#else
varying vec2 vDiffuseUV;
#endif
uniform sampler2D diffuseSampler;
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef TEXTURELODSUPPORT
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#include<reflectionFunction>
#endif
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE;
#endif
#ifndef SHADOWONLY
#define SHADOWONLY;
#endif
#include<imageProcessingDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<lightsFragmentFunctions>
#include<shadowsFragmentFunctions>
#include<imageProcessingFunctions>
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<logDepthDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<fogFragmentDeclaration>
#ifdef REFLECTIONFRESNEL
#define FRESNEL_MAXIMUM_ON_ROUGH 0.25
vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)
{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}
#endif
#ifdef PROJECTED_GROUND
#include<intersectionFunctions>
vec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersectFromOrigin(eyePosition,camDir,radius).x;vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersectFromOrigin(eyePosition,p,radius).x;vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;}
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=vec3(0.0,1.0,0.0);
#endif
float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;
#include<lightFragment>[0..maxSimultaneousLights]
#ifdef SHADOWINUSE
globalShadow/=shadowLightCount;
#else
globalShadow=1.0;
#endif
#ifndef BACKMAT_SHADOWONLY
vec4 reflectionColor=vec4(1.,1.,1.,1.);
#ifdef REFLECTION
#ifdef PROJECTED_GROUND
vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=reflectionVector;
#else
vec2 reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
#ifdef REFLECTIONBLUR
float reflectionLOD=vReflectionInfos.y;
#ifdef TEXTURELODSUPPORT
reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#else
float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
reflectionSpecularMid,
lodReflectionNormalizedDoubled
);} else {reflectionColor=mix(
reflectionSpecularMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#else
vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;
#endif
#ifdef RGBDREFLECTION
reflectionColor.rgb=fromRGBD(reflectionColor);
#endif
#ifdef GAMMAREFLECTION
reflectionColor.rgb=toLinearSpace(reflectionColor.rgb);
#endif
#ifdef REFLECTIONBGR
reflectionColor.rgb=reflectionColor.bgr;
#endif
reflectionColor.rgb*=vReflectionInfos.x;
#endif
vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;
#ifdef DIFFUSE
vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);
#ifdef GAMMADIFFUSE
diffuseMap.rgb=toLinearSpace(diffuseMap.rgb);
#endif
diffuseMap.rgb*=vDiffuseInfos.y;
#ifdef DIFFUSEHASALPHA
finalAlpha*=diffuseMap.a;
#endif
diffuseColor=diffuseMap.rgb;
#endif
#ifdef REFLECTIONFRESNEL
vec3 colorBase=diffuseColor;
#else
vec3 colorBase=reflectionColor.rgb*diffuseColor;
#endif
colorBase=max(colorBase,0.0);
#ifdef USERGBCOLOR
vec3 finalColor=colorBase;
#else
#ifdef USEHIGHLIGHTANDSHADOWCOLORS
vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);
#else
vec3 mainColor=vPrimaryColor.rgb;
#endif
vec3 finalColor=colorBase*mainColor;
#endif
#ifdef REFLECTIONFRESNEL
vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;
#ifdef REFLECTIONFALLOFF
float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;
#endif
finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));
#endif
#ifdef OPACITYFRESNEL
float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;
#endif
#ifdef SHADOWINUSE
finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);
#endif
vec4 color=vec4(finalColor,finalAlpha);
#else
vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);
#endif
#include<logDepthFragment>
#include<fogFragment>
#ifdef IMAGEPROCESSINGPOSTPROCESS
#if !defined(SKIPFINALCOLORCLAMP)
color.rgb=clamp(color.rgb,0.,30.0);
#endif
#else
color=applyImageProcessing(color);
#endif
#ifdef PREMULTIPLYALPHA
color.rgb*=color.a;
#endif
#ifdef NOISE
color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);
#endif
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}
`, backgroundPixelShader;
var init_background_fragment2 = __esm(() => {
  init_shaderStore();
  init_backgroundFragmentDeclaration();
  init_backgroundUboDeclaration2();
  init_helperFunctions2();
  init_reflectionFunction2();
  init_imageProcessingDeclaration2();
  init_lightFragmentDeclaration();
  init_lightUboDeclaration2();
  init_lightsFragmentFunctions2();
  init_shadowsFragmentFunctions2();
  init_imageProcessingFunctions2();
  init_logDepthDeclaration2();
  init_clipPlaneFragmentDeclaration2();
  init_fogFragmentDeclaration2();
  init_intersectionFunctions2();
  init_clipPlaneFragment2();
  init_lightFragment2();
  init_logDepthFragment2();
  init_fogFragment2();
  if (!ShaderStore.ShadersStore[name246]) {
    ShaderStore.ShadersStore[name246] = shader245;
  }
  backgroundPixelShader = { name: name246, shader: shader245 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrUboDeclaration.js
var name247 = "pbrUboDeclaration", shader246 = `uniform vAlbedoInfos: vec2f;uniform vBaseWeightInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vReflectionInfos: vec2f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform baseWeightMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionColor: vec3f;uniform vAlbedoColor: vec4f;uniform baseWeight: f32;uniform vLightingIntensity: vec4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;
#define ADDITIONAL_UBO_DECLARATION
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
var init_pbrUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration();
  init_meshUboDeclaration();
  if (!ShaderStore.IncludesShadersStoreWGSL[name247]) {
    ShaderStore.IncludesShadersStoreWGSL[name247] = shader246;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/harmonicsFunctions.js
var name248 = "harmonicsFunctions", shader247 = `#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00
+ uniforms.vSphericalL1_1*(normal.y)
+ uniforms.vSphericalL10*(normal.z)
+ uniforms.vSphericalL11*(normal.x)
+ uniforms.vSphericalL2_2*(normal.y*normal.x)
+ uniforms.vSphericalL2_1*(normal.y*normal.z)
+ uniforms.vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+ uniforms.vSphericalL21*(normal.z*normal.x)
+ uniforms.vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}
#else
fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;}
#endif
#endif
`;
var init_harmonicsFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name248]) {
    ShaderStore.IncludesShadersStoreWGSL[name248] = shader247;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/pbr.vertex.js
var exports_pbr_vertex = {};
__export(exports_pbr_vertex, {
  pbrVertexShaderWGSL: () => pbrVertexShaderWGSL
});
var name249 = "pbrVertexShader", shader248 = `#include<pbrUboDeclaration>
#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<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute color: vec4f;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)
#endif
varying vPositionW: vec3f;
#if DEBUGMODE>0
varying vClipSpacePosition: vec4f;
#endif
#ifdef NORMAL
varying vNormalW: vec3f;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vEnvironmentIrradiance: vec3f;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<lightVxUboDeclaration>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#include<logDepthDeclaration>
#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<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vertexOutputs.vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#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<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);vertexOutputs.vPositionW= worldPos.xyz;
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
var reflectionVector: vec3f= (uniforms.reflectionMatrix* vec4f(vertexOutputs.vNormalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;}
#else
vertexOutputs.position=scene.viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vertexOutputs.vClipSpacePosition=vertexOutputs.position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vertexOutputs.vDirectionW=normalize((finalWorld*vec4f(positionUpdated,0.0)).xyz);
#endif
#ifndef UV1
var uvUpdated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV1
vertexOutputs.vMainUV1=uvUpdated;
#endif
#ifndef UV2
var uv2Updated: vec2f= vec2f(0.,0.);
#endif
#ifdef MAINUV2
vertexOutputs.vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)
#endif
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, pbrVertexShaderWGSL;
var init_pbr_vertex = __esm(() => {
  init_shaderStore();
  init_pbrUboDeclaration();
  init_uvAttributeDeclaration();
  init_mainUVVaryingDeclaration();
  init_helperFunctions();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_instancesDeclaration();
  init_prePassVertexDeclaration();
  init_samplerVertexDeclaration();
  init_harmonicsFunctions();
  init_bumpVertexDeclaration();
  init_clipPlaneVertexDeclaration();
  init_fogVertexDeclaration();
  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[name249]) {
    ShaderStore.ShadersStoreWGSL[name249] = shader248;
  }
  pbrVertexShaderWGSL = { name: name249, shader: shader248 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrFragmentExtraDeclaration.js
var name250 = "pbrFragmentExtraDeclaration", shader249 = `varying vPositionW: vec3f;
#if DEBUGMODE>0
varying vClipSpacePosition: vec4f;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vNormalW: vec3f;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vEnvironmentIrradiance: vec3f;
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vColor: vec4f;
#endif
`;
var init_pbrFragmentExtraDeclaration = __esm(() => {
  init_shaderStore();
  init_mainUVVaryingDeclaration();
  if (!ShaderStore.IncludesShadersStoreWGSL[name250]) {
    ShaderStore.IncludesShadersStoreWGSL[name250] = shader249;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerFragmentAlternateDeclaration.js
var name251 = "samplerFragmentAlternateDeclaration", shader250 = `#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying v_VARYINGNAME_UV: vec2f;
#endif
#endif
`;
var init_samplerFragmentAlternateDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name251]) {
    ShaderStore.IncludesShadersStoreWGSL[name251] = shader250;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrFragmentSamplersDeclaration.js
var name252 = "pbrFragmentSamplersDeclaration", shader251 = `#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)
var clearCoatRoughnessSamplerSampler: sampler;var clearCoatRoughnessSampler: texture_2d<f32>;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)
var sheenRoughnessSamplerSampler: sampler;var sheenRoughnessSampler: texture_2d<f32>;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_cube<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_cube<f32>;
#endif
#ifdef USEIRRADIANCEMAP
var irradianceSamplerSampler: sampler;var irradianceSampler: texture_cube<f32>;
#endif
#else
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_2d<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var reflectionLowSamplerSampler: sampler;var reflectionLowSampler: texture_2d<f32>;var reflectionHighSamplerSampler: sampler;var reflectionHighSampler: texture_2d<f32>;
#endif
#ifdef USEIRRADIANCEMAP
var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d<f32>;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vPositionUVW: vec3f;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vDirectionW: vec3f;
#endif
#endif
#endif
#ifdef ENVIRONMENTBRDF
var environmentBrdfSamplerSampler: sampler;var environmentBrdfSampler: texture_2d<f32>;
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d<f32>;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d<f32>;
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
var refractionSamplerSampler: sampler;var refractionSampler: texture_cube<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_cube<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_cube<f32>;
#endif
#else
var refractionSamplerSampler: sampler;var refractionSampler: texture_2d<f32>;
#ifdef LODBASEDMICROSFURACE
#else
var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d<f32>;var refractionHighSamplerSampler: sampler;var refractionHighSampler: texture_2d<f32>;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)
#endif
#ifdef IBL_CDF_FILTERING
var icdfSamplerSampler: sampler;var icdfSampler: texture_2d<f32>;
#endif
`;
var init_pbrFragmentSamplersDeclaration = __esm(() => {
  init_shaderStore();
  init_samplerFragmentDeclaration();
  init_samplerFragmentAlternateDeclaration();
  if (!ShaderStore.IncludesShadersStoreWGSL[name252]) {
    ShaderStore.IncludesShadersStoreWGSL[name252] = shader251;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/subSurfaceScatteringFunctions.js
var name253 = "subSurfaceScatteringFunctions", shader252 = `fn testLightingForSSS(diffusionProfile: f32)->bool
{return diffusionProfile<1.;}`;
var init_subSurfaceScatteringFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name253]) {
    ShaderStore.IncludesShadersStoreWGSL[name253] = shader252;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/importanceSampling.js
var name254 = "importanceSampling", shader253 = `fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
fn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
fn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { 
var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;
var init_importanceSampling = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name254]) {
    ShaderStore.IncludesShadersStoreWGSL[name254] = shader253;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrHelperFunctions.js
var name255 = "pbrHelperFunctions", shader254 = `#define MINIMUMVARIANCE 0.0005
fn convertRoughnessToAverageSlope(roughness: f32)->f32
{return roughness*roughness+MINIMUMVARIANCE;}
fn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;}
fn getAARoughnessFactors(normalVector: vec3f)->vec2f {
#ifdef SPECULARAA
var nDfdx: vec3f=dpdx(normalVector.xyz);var nDfdy: vec3f=dpdy(normalVector.xyz);var slopeSquare: f32=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));var geometricRoughnessFactor: f32=pow(saturate(slopeSquare),0.333);var geometricAlphaGFactor: f32=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2f(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2f(0.);
#endif
}
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_LEGACY
fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}
fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var anisotropicFrameDirection: vec3f=select(T,B,anisotropy>=0.0);var anisotropicFrameTangent: vec3f=cross(normalize(anisotropicFrameDirection),V);var anisotropicFrameNormal: vec3f=cross(anisotropicFrameTangent,anisotropicFrameDirection);var anisotropicNormal: vec3f=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}
#else
fn getAnisotropicRoughness(alphaG: f32,anisotropy: f32)->vec2f {var alphaT: f32=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);var alphaB: f32=max(alphaG,MINIMUMVARIANCE);return vec2f(alphaT,alphaB);}
fn getAnisotropicBentNormals(T: vec3f,B: vec3f,N: vec3f,V: vec3f,anisotropy: f32,roughness: f32)->vec3f {var bentNormal: vec3f=cross(B,V);bentNormal=normalize(cross(bentNormal,B));var sq=1.0-anisotropy*(1.0-roughness);var a: f32=sq*sq*sq*sq;bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}
#endif
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)
fn cocaLambertVec3(alpha: vec3f,distance: f32)->vec3f {return exp(-alpha*distance);}
fn cocaLambert(NdotVRefract: f32,NdotLRefract: f32,alpha: vec3f,thickness: f32)->vec3f {return cocaLambertVec3(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}
fn computeColorAtDistanceInMedia(color: vec3f,distance: f32)->vec3f {return -log(color)/distance;}
fn computeClearCoatAbsorption(NdotVRefract: f32,NdotLRefract: f32,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var clearCoatAbsorption: vec3f=mix( vec3f(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);return clearCoatAbsorption;}
#endif
#ifdef MICROSURFACEAUTOMATIC
fn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32
{const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;}
#endif
`;
var init_pbrHelperFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name255]) {
    ShaderStore.IncludesShadersStoreWGSL[name255] = shader254;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrDirectLightingSetupFunctions.js
var name256 = "pbrDirectLightingSetupFunctions", shader255 = `struct preLightingInfo
{lightOffset: vec3f,
lightDistanceSquared: f32,
lightDistance: f32,
attenuation: f32,
L: vec3f,
H: vec3f,
NdotV: f32,
NdotLUnclamped: f32,
NdotL: f32,
VdotH: f32,
roughness: f32,
#ifdef IRIDESCENCE
iridescenceIntensity: f32
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
areaLightDiffuse: vec3f,
#ifdef SPECULARTERM
areaLightSpecular: vec3f,
areaLightFresnel: vec4f
#endif
#endif
};fn computePointAndSpotPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f,posW: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
fn computeDirectionalPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
fn computeHemisphericPreLightingInfo(lightData: vec4f,V: vec3f,N: vec3f)->preLightingInfo {var result: preLightingInfo;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));
#endif
return result;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
fn computeAreaPreLightingInfo(ltc1: texture_2d<f32>,ltc1Sampler:sampler,ltc2:texture_2d<f32>,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightCenter:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->preLightingInfo {var result: preLightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightCenter,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular;
#endif
result.areaLightDiffuse+=data.Diffuse;return result;}
#endif
`;
var init_pbrDirectLightingSetupFunctions = __esm(() => {
  init_shaderStore();
  init_ltcHelperFunctions();
  if (!ShaderStore.IncludesShadersStoreWGSL[name256]) {
    ShaderStore.IncludesShadersStoreWGSL[name256] = shader255;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrDirectLightingFalloffFunctions.js
var name257 = "pbrDirectLightingFalloffFunctions", shader256 = `fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32
{return max(0.,1.0-length(lightOffset)/range);}
fn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32
{return 1.0/maxEps(lightDistanceSquared);}
fn computeDistanceLightFalloff_GLTF(lightDistanceSquared: f32,inverseSquaredRange: f32)->f32
{var lightDistanceFalloff: f32=1.0/maxEps(lightDistanceSquared);var factor: f32=lightDistanceSquared*inverseSquaredRange;var attenuation: f32=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}
fn computeDirectionalLightFalloff_IES(lightDirection: vec3f,directionToLightCenterW: vec3f,iesLightTexture: texture_2d<f32>,iesLightTextureSampler: sampler)->f32
{var cosAngle: f32=dot(-lightDirection,directionToLightCenterW);var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;}
fn computeDistanceLightFalloff(lightOffset: vec3f,lightDistanceSquared: f32,range: f32,inverseSquaredRange: f32)->f32
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
fn computeDirectionalLightFalloff_Standard(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32)->f32
{var falloff: f32=0.0;var cosAngle: f32=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)
{falloff=max(0.,pow(cosAngle,exponent));}
return falloff;}
fn computeDirectionalLightFalloff_Physical(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32)->f32
{const kMinusLog2ConeAngleIntensityRatio: f32=6.64385618977; 
var concentrationKappa: f32=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);var lightDirectionSpreadSG: vec4f= vec4f(-lightDirection*concentrationKappa,-concentrationKappa);var falloff: f32=exp2(dot( vec4f(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}
fn computeDirectionalLightFalloff_GLTF(lightDirection: vec3f,directionToLightCenterW: vec3f,lightAngleScale: f32,lightAngleOffset: f32)->f32
{var cd: f32=dot(-lightDirection,directionToLightCenterW);var falloff: f32=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}
fn computeDirectionalLightFalloff(lightDirection: vec3f,directionToLightCenterW: vec3f,cosHalfAngle: f32,exponent: f32,lightAngleScale: f32,lightAngleOffset: f32)->f32
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;
var init_pbrDirectLightingFalloffFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name257]) {
    ShaderStore.IncludesShadersStoreWGSL[name257] = shader256;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/hdrFilteringFunctions.js
var name258 = "hdrFilteringFunctions", shader257 = `#ifdef NUM_SAMPLES
#if NUM_SAMPLES>0
fn radicalInverse_VdC(value: u32)->f32 
{var bits=(value<<16u) | (value>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10; }
fn hammersley(i: u32,N: u32)->vec2f
{return vec2f( f32(i)/ f32(N),radicalInverse_VdC(i));}
fn log4(x: f32)->f32 {return log2(x)/2.;}
fn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}
const NUM_SAMPLES_FLOAT: f32= f32(NUM_SAMPLES);const NUM_SAMPLES_FLOAT_INVERSED: f32=1./NUM_SAMPLES_FLOAT;const K: f32=4.;fn irradiance(inputTexture: texture_cube<f32>,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>,icdfSamplerSampler: sampler
#endif
)->vec3f
{var n: vec3f=normalize(inputN);var result: vec3f= vec3f(0.0);
#ifndef IBL_CDF_FILTERING
var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);
#endif
var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);for(var i: u32=0u; i<NUM_SAMPLES; i++)
{var Xi: vec2f=hammersley(i,NUM_SAMPLES);
#ifdef IBL_CDF_FILTERING
var T: vec2f;T.x=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2(Xi.x,0.0),0.0).x;T.y=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2(T.x,Xi.y),0.0).y;var Ls: vec3f=uv_to_normal(vec2f(1.0-fract(T.x+0.25),T.y));var NoL: f32=dot(n,Ls);
#else
var Ls: vec3f=hemisphereCosSample(Xi);Ls=normalize(Ls);var Ns: vec3f= vec3f(0.,0.,1.);var NoL: f32=dot(Ns,Ls);
#endif
if (NoL>0.) {
#ifdef IBL_CDF_FILTERING
var pdf: f32=textureSampleLevel(icdfSampler,icdfSamplerSampler,T,0.0).z;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,Ls,0.0).rgb;
#else
var pdf_inversed: f32=PI/NoL;var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp(l,0.0,maxLevel);var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*Ls,mipLevel).rgb;
#endif
#ifdef GAMMA_INPUT
c=toLinearSpaceVec3(c);
#endif
#ifdef IBL_CDF_FILTERING
var light: vec3f=vec3f(0.0);if (pdf>1e-6) {light=vec3f(1.0)/vec3f(pdf)*c;}
result+=NoL*light;
#else
result+=c;
#endif
}}
result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}
fn radiance(alphaG: f32,inputTexture: texture_cube<f32>,inputSampler: sampler,inputN: vec3f,filteringInfo: vec2f)->vec3f
{var n: vec3f=normalize(inputN);var c: vec3f=textureSample(inputTexture,inputSampler,n).rgb; 
if (alphaG==0.) {
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
return c;} else {var result: vec3f= vec3f(0.);var tangent: vec3f=select(vec3f(1.,0.,0.),vec3f(0.,0.,1.),abs(n.z)<0.999);tangent=normalize(cross(tangent,n));var bitangent: vec3f=cross(n,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,n);var maxLevel: f32=filteringInfo.y;var dim0: f32=filteringInfo.x;var omegaP: f32=(4.*PI)/(6.*dim0*dim0);var weight: f32=0.;for(var i: u32=0u; i<NUM_SAMPLES; i++)
{var Xi: vec2f=hammersley(i,NUM_SAMPLES);var H: vec3f=hemisphereImportanceSampleDggx(Xi,alphaG);var NoV: f32=1.;var NoH: f32=H.z;var NoH2: f32=H.z*H.z;var NoL: f32=2.*NoH2-1.;var L: vec3f= vec3f(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {var pdf_inversed: f32=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);var omegaS: f32=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;var l: f32=log4(omegaS)-log4(omegaP)+log4(K);var mipLevel: f32=clamp( f32(l),0.0,maxLevel);weight+=NoL;var c: vec3f=textureSampleLevel(inputTexture,inputSampler,tbn*L,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}}
#endif
#endif
`;
var init_hdrFilteringFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name258]) {
    ShaderStore.IncludesShadersStoreWGSL[name258] = shader257;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrDirectLightingFunctions.js
var name259 = "pbrDirectLightingFunctions", shader258 = `#define CLEARCOATREFLECTANCE90 1.0
struct lightingInfo
{diffuse: vec3f,
#ifdef SPECULARTERM
specular: vec3f,
#endif
#ifdef CLEARCOAT
clearCoat: vec4f,
#endif
#ifdef SHEEN
sheen: vec3f
#endif
};fn adjustRoughnessFromLightProperties(roughness: f32,lightRadius: f32,lightDistance: f32)->f32 {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
var lightRoughness: f32=lightRadius/lightDistance;var totalRoughness: f32=saturate(lightRoughness+roughness);return totalRoughness;
#else
return roughness;
#endif
}
fn computeHemisphericDiffuseLighting(info: preLightingInfo,lightColor: vec3f,groundColor: vec3f)->vec3f {return mix(groundColor,lightColor,info.NdotL);}
fn computeDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {var diffuseTerm: f32=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}
fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d<f32>,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f{var strq: vec4f=textureProjectionMatrix* vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return toLinearSpaceVec3(textureColor);}
#ifdef SS_TRANSLUCENCY
fn computeDiffuseAndTransmittedLighting(info: preLightingInfo,lightColor: vec3f,transmittance: vec3f,transmittanceIntensity: f32,surfaceAlbedo: vec3f)->vec3f {var transmittanceNdotL=vec3f(0.0);var NdotL: f32=absEps(info.NdotLUnclamped);if (info.NdotLUnclamped<0.0) {var wrapNdotL: f32=computeWrappedDiffuseNdotL(NdotL,0.02);var trAdapt: f32=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL, vec3f(wrapNdotL),trAdapt);}
var diffuseTerm: f32=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return (transmittanceNdotL/PI+(1.0-transmittanceIntensity)*diffuseTerm*surfaceAlbedo*info.NdotL)*info.attenuation*lightColor;}
#endif
#ifdef SPECULARTERM
fn computeSpecularLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
var smithVisibility: f32=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
var smithVisibility: f32=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef ANISOTROPIC
fn computeAnisotropicSpecularLighting(info: preLightingInfo,V: vec3f,N: vec3f,T: vec3f,B: vec3f,anisotropy: f32,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var TdotH: f32=dot(T,info.H);var BdotH: f32=dot(B,info.H);var TdotV: f32=dot(T,V);var BdotV: f32=dot(B,V);var TdotL: f32=dot(T,info.L);var BdotL: f32=dot(B,info.L);var alphaG: f32=convertRoughnessToAverageSlope(info.roughness);var alphaTB: vec2f=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,vec2f(geometricRoughnessFactor*geometricRoughnessFactor));var fresnel: vec3f=fresnelSchlickGGXVec3(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
var distribution: f32=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);var smithVisibility: f32=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);var specTerm: vec3f=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef CLEARCOAT
fn computeClearCoatLighting(info: preLightingInfo,Ncc: vec3f,geometricRoughnessFactor: f32,clearCoatIntensity: f32,lightColor: vec3f)->vec4f {var NccdotL: f32=saturateEps(dot(Ncc,info.L));var NccdotH: f32=saturateEps(dot(Ncc,info.H));var clearCoatRoughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);var fresnel: f32=fresnelSchlickGGX(info.VdotH,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;var distribution: f32=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);var kelemenVisibility: f32=visibility_Kelemen(info.VdotH);var clearCoatTerm: f32=fresnel*distribution*kelemenVisibility;return vec4f(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);}
fn computeClearCoatLightingAbsorption(NdotVRefract: f32,L: vec3f,Ncc: vec3f,clearCoatColor: vec3f,clearCoatThickness: f32,clearCoatIntensity: f32)->vec3f {var LRefract: vec3f=-refract(L,Ncc,uniforms.vClearCoatRefractionParams.y);var NdotLRefract: f32=saturateEps(dot(Ncc,LRefract));var absorption: vec3f=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}
#endif
#ifdef SHEEN
fn computeSheenLighting(info: preLightingInfo,N: vec3f,reflectance0: vec3f,reflectance90: vec3f,geometricRoughnessFactor: f32,lightColor: vec3f)->vec3f {var NdotH: f32=saturateEps(dot(N,info.H));var roughness: f32=max(info.roughness,geometricRoughnessFactor);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var fresnel: f32=1.;var distribution: f32=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER
var visibility: f32=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);
#else */
var visibility: f32=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */
var sheenTerm: f32=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
fn computeAreaDiffuseLighting(info: preLightingInfo,lightColor: vec3f)->vec3f {return info.areaLightDiffuse*lightColor;}
fn computeAreaSpecularLighting(info: preLightingInfo,specularColor: vec3f)->vec3f {var fresnel:vec3f =( specularColor*info.areaLightFresnel.x+( vec3f( 1.0 )-specularColor )*info.areaLightFresnel.y );return specularColor*fresnel*info.areaLightSpecular;}
#endif
`;
var init_pbrDirectLightingFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name259]) {
    ShaderStore.IncludesShadersStoreWGSL[name259] = shader258;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrIBLFunctions.js
var name260 = "pbrIBLFunctions", shader259 = `#if defined(REFLECTION) || defined(SS_REFRACTION)
fn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;}
fn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
fn environmentRadianceOcclusion(ambientOcclusion: f32,NdotVUnclamped: f32)->f32 {var temp: f32=NdotVUnclamped+ambientOcclusion;return saturate(temp*temp-1.0+ambientOcclusion);}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
fn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f)->f32 {var reflection: vec3f=reflect(view,normal);var temp: f32=saturate(1.0+1.1*dot(reflection,geometricNormal));return temp*temp;}
#endif
#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
fn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;}
fn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}
#endif
`;
var init_pbrIBLFunctions = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name260]) {
    ShaderStore.IncludesShadersStoreWGSL[name260] = shader259;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockAlbedoOpacity.js
var name261 = "pbrBlockAlbedoOpacity", shader260 = `struct albedoOpacityOutParams
{surfaceAlbedo: vec3f,
alpha: f32};
#define pbr_inline
fn albedoOpacityBlock(
vAlbedoColor: vec4f
#ifdef ALBEDO
,albedoTexture: vec4f
,albedoInfos: vec2f
#endif
,baseWeight: f32
#ifdef BASEWEIGHT
,baseWeightTexture: vec4f
,vBaseWeightInfos: vec2f
#endif
#ifdef OPACITY
,opacityMap: vec4f
,vOpacityInfos: vec2f
#endif
#ifdef DETAIL
,detailColor: vec4f
,vDetailInfos: vec4f
#endif
#ifdef DECAL
,decalColor: vec4f
,vDecalInfos: vec4f
#endif
)->albedoOpacityOutParams
{var outParams: albedoOpacityOutParams;var surfaceAlbedo: vec3f=vAlbedoColor.rgb;var alpha: f32=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpaceVec3(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifndef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
surfaceAlbedo*=fragmentInputs.vColor.rgb;
#endif
#ifdef DETAIL
var detailAlbedo: f32=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; 
#endif
#ifdef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO
surfaceAlbedo*=baseWeight;
#ifdef BASEWEIGHT
surfaceAlbedo*=baseWeightTexture.r;
#endif
#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=fragmentInputs.vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE) {discard;}
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}
`;
var init_pbrBlockAlbedoOpacity = __esm(() => {
  init_shaderStore();
  init_decalFragment();
  if (!ShaderStore.IncludesShadersStoreWGSL[name261]) {
    ShaderStore.IncludesShadersStoreWGSL[name261] = shader260;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockReflectivity.js
var name262 = "pbrBlockReflectivity", shader261 = `struct reflectivityOutParams
{microSurface: f32,
roughness: f32,
surfaceReflectivityColor: vec3f,
#ifdef METALLICWORKFLOW
surfaceAlbedo: vec3f,
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
ambientOcclusionColor: vec3f,
#endif
#if DEBUGMODE>0
#ifdef METALLICWORKFLOW
metallicRoughness: vec2f,
#ifdef REFLECTIVITY
surfaceMetallicColorMap: vec4f,
#endif
#ifndef FROSTBITE_REFLECTANCE
metallicF0: vec3f,
#endif
#else
#ifdef REFLECTIVITY
surfaceReflectivityColorMap: vec4f,
#endif
#endif
#endif
};
#define pbr_inline
fn reflectivityBlock(
vReflectivityColor: vec4f
#ifdef METALLICWORKFLOW
,surfaceAlbedo: vec3f
,metallicReflectanceFactors: vec4f
#endif
#ifdef REFLECTIVITY
,reflectivityInfos: vec3f
,surfaceMetallicOrReflectivityColorMap: vec4f
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,ambientOcclusionColorIn: vec3f
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel: vec4f
#endif
#ifdef DETAIL
,detailColor: vec4f
,vDetailInfos: vec4f
#endif
)->reflectivityOutParams
{var outParams: reflectivityOutParams;var microSurface: f32=vReflectivityColor.a;var surfaceReflectivityColor: vec3f=vReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
var metallicRoughness: vec2f=surfaceReflectivityColor.rg;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
var aoStoreInMetalMap: vec3f= vec3f(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
var detailRoughness: f32=mix(0.5,detailColor.b,vDetailInfos.w);var loLerp: f32=mix(0.,metallicRoughness.g,detailRoughness*2.);var hiLerp: f32=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#if DEBUGMODE>0
outParams.metallicRoughness=metallicRoughness;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
microSurface=1.0-metallicRoughness.g;var baseColor: vec3f=surfaceAlbedo;
#ifdef FROSTBITE_REFLECTANCE
outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);
#else
var metallicF0: vec3f=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=metallicF0;
#endif
outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0), vec3f(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);
#endif
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
#endif
microSurface=saturate(microSurface);var roughness: f32=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;}
`;
var init_pbrBlockReflectivity = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name262]) {
    ShaderStore.IncludesShadersStoreWGSL[name262] = shader261;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockAmbientOcclusion.js
var name263 = "pbrBlockAmbientOcclusion", shader262 = `struct ambientOcclusionOutParams
{ambientOcclusionColor: vec3f,
#if DEBUGMODE>0 && defined(AMBIENT)
ambientOcclusionColorMap: vec3f
#endif
};
#define pbr_inline
fn ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap_: vec3f,
vAmbientInfos: vec4f
#endif
)->ambientOcclusionOutParams
{ 
var outParams: ambientOcclusionOutParams;var ambientOcclusionColor: vec3f= vec3f(1.,1.,1.);
#ifdef AMBIENT
var ambientOcclusionColorMap: vec3f=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap= vec3f(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}
`;
var init_pbrBlockAmbientOcclusion = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name263]) {
    ShaderStore.IncludesShadersStoreWGSL[name263] = shader262;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockAlphaFresnel.js
var name264 = "pbrBlockAlphaFresnel", shader263 = `#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{alpha: f32};fn faceforward(N: vec3<f32>,I: vec3<f32>,Nref: vec3<f32>)->vec3<f32> {return select(N,-N,dot(Nref,I)>0.0);}
#define pbr_inline
fn alphaFresnelBlock(
normalW: vec3f,
viewDirectionW: vec3f,
alpha: f32,
microSurface: f32
)->alphaFresnelOutParams
{var outParams: alphaFresnelOutParams;var opacityPerceptual: f32=alpha;
#ifdef LINEARALPHAFRESNEL
var opacity0: f32=opacityPerceptual;
#else
var opacity0: f32=opacityPerceptual*opacityPerceptual;
#endif
var opacity90: f32=fresnelGrazingReflectance(opacity0);var normalForward: vec3f=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)), vec3f(opacity0), vec3f(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE) {discard;}
#ifndef ALPHABLEND
outParams.alpha=1.0;
#endif
#endif
return outParams;}
#endif
#endif
`;
var init_pbrBlockAlphaFresnel = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name264]) {
    ShaderStore.IncludesShadersStoreWGSL[name264] = shader263;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockAnisotropic.js
var name265 = "pbrBlockAnisotropic", shader264 = `#ifdef ANISOTROPIC
struct anisotropicOutParams
{anisotropy: f32,
anisotropicTangent: vec3f,
anisotropicBitangent: vec3f,
anisotropicNormal: vec3f,
#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)
anisotropyMapData: vec3f
#endif
};
#define pbr_inline
fn anisotropicBlock(
vAnisotropy: vec3f,
roughness: f32,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData: vec3f,
#endif
TBN: mat3x3f,
normalW: vec3f,
viewDirectionW: vec3f
)->anisotropicOutParams
{ 
var outParams: anisotropicOutParams;var anisotropy: f32=vAnisotropy.b;var anisotropyDirection: vec3f= vec3f(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
var amd=anisotropyMapData.rg;anisotropy*=anisotropyMapData.b;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
amd=amd*2.0-1.0;
#ifdef ANISOTROPIC_LEGACY
anisotropyDirection=vec3f(anisotropyDirection.xy*amd,anisotropyDirection.z);
#else
anisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(amd),anisotropyDirection.z);
#endif
#endif
var anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}
#endif
`;
var init_pbrBlockAnisotropic = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name265]) {
    ShaderStore.IncludesShadersStoreWGSL[name265] = shader264;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockReflection.js
var name266 = "pbrBlockReflection", shader265 = `#ifdef REFLECTION
struct reflectionOutParams
{environmentRadiance: vec4f
,environmentIrradiance: vec3f
#ifdef REFLECTIONMAP_3D
,reflectionCoords: vec3f
#else
,reflectionCoords: vec2f
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,irradianceVector: vec3f
#endif
#endif
#endif
};
#define pbr_inline
#ifdef REFLECTIONMAP_3D
fn createReflectionCoords(
vPositionW: vec3f,
normalW: vec3f,
#ifdef ANISOTROPIC
anisotropicOut: anisotropicOutParams,
#endif
)->vec3f
{var reflectionCoords: vec3f;
#else
fn createReflectionCoords(
vPositionW: vec3f,
normalW: vec3f,
#ifdef ANISOTROPIC
anisotropicOut: anisotropicOutParams,
#endif
)->vec2f
{ 
var reflectionCoords: vec2f;
#endif
#ifdef ANISOTROPIC
var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
var reflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
return reflectionCoords;}
#define pbr_inline
fn sampleReflectionTexture(
alphaG: f32
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped: f32
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness: f32
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec3f
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec2f
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif 
)->vec4f
{var environmentRadiance: vec4f;
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
var reflectionLOD: f32=getLodFromAlphaGNdotV(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
var reflectionLOD: f32=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
var reflectionLOD: f32=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA
var automaticReflectionLOD: f32=UNPACK_LOD(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords).a);var requestedReflectionLOD: f32=max(automaticReflectionLOD,reflectionLOD);
#else
var requestedReflectionLOD: f32=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance= vec4f(radiance(alphaG,reflectionSampler,reflectionSamplerSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=textureSampleLevel(reflectionSampler,reflectionSamplerSampler,reflectionCoords,reflectionLOD);
#endif
#else
var lodReflectionNormalized: f32=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));var lodReflectionNormalizedDoubled: f32=lodReflectionNormalized*2.0;var environmentMid: vec4f=textureSample(reflectionSampler,reflectionSamplerSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(
textureSample(reflectionHighSampler,reflectionHighSamplerSampler,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);} else {environmentRadiance=mix(
environmentMid,
textureSample(reflectionLowSampler,reflectionLowSamplerSampler,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
var envRadiance=environmentRadiance.rgb;
#ifdef RGBDREFLECTION
envRadiance=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
envRadiance=toLinearSpaceVec3(environmentRadiance.rgb);
#endif
envRadiance*=vReflectionInfos.x;envRadiance*=vReflectionColor.rgb;return vec4f(envRadiance,environmentRadiance.a);}
#define pbr_inline
fn reflectionBlock(
vPositionW: vec3f
,normalW: vec3f
,alphaG: f32
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped: f32
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness: f32
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance: vec3f
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix: mat4x4f
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,irradianceSampler: texture_cube<f32>
,irradianceSamplerSampler: sampler 
#else
,irradianceSampler: texture_2d<f32>
,irradianceSamplerSampler: sampler 
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler 
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler 
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>
,icdfSamplerSampler: sampler
#endif
#endif
)->reflectionOutParams
{var outParams: reflectionOutParams;var environmentRadiance: vec4f= vec4f(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
var reflectionCoords: vec3f= vec3f(0.);
#else
var reflectionCoords: vec2f= vec2f(0.);
#endif
reflectionCoords=createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif 
);environmentRadiance=sampleReflectionTexture(
alphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
#ifdef REFLECTIONMAP_3D
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#else
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif 
);var environmentIrradiance: vec3f= vec3f(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
#ifdef ANISOTROPIC
var irradianceVector: vec3f= (reflectionMatrix* vec4f(anisotropicOut.anisotropicNormal,0)).xyz;
#else
var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,reflectionSamplerSampler,irradianceVector,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,irradianceVector);
#else
var environmentIrradiance4: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,reflectionCoords);
#endif
environmentIrradiance=environmentIrradiance4.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance=toLinearSpaceVec3(environmentIrradiance.rgb);
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb;
#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE
outParams.environmentRadiance=vec4f(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a);
#else
outParams.environmentRadiance=environmentRadiance;
#endif
outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}
#endif
`;
var init_pbrBlockReflection = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name266]) {
    ShaderStore.IncludesShadersStoreWGSL[name266] = shader265;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockSheen.js
var name267 = "pbrBlockSheen", shader266 = `#ifdef SHEEN
struct sheenOutParams
{sheenIntensity: f32
,sheenColor: vec3f
,sheenRoughness: f32
#ifdef SHEEN_LINKWITHALBEDO
,surfaceAlbedo: vec3f
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
,sheenAlbedoScaling: f32
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,finalSheenRadianceScaled: vec3f
#endif
#if DEBUGMODE>0
#ifdef SHEEN_TEXTURE
,sheenMapData: vec4f
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,sheenEnvironmentReflectance: vec3f
#endif
#endif
};
#define pbr_inline
fn sheenBlock(
vSheenColor: vec4f
#ifdef SHEEN_ROUGHNESS
,vSheenRoughness: f32
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData: vec4f
#endif
#endif
,roughness: f32
#ifdef SHEEN_TEXTURE
,sheenMapData: vec4f
,sheenMapLevel: f32
#endif
,reflectance: f32
#ifdef SHEEN_LINKWITHALBEDO
,baseColor: vec3f
,surfaceAlbedo: vec3f
#endif
#ifdef ENVIRONMENTBRDF
,NdotV: f32
,environmentBrdf: vec3f
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors: vec2f
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
,vLightingIntensity: vec4f
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec3f
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
,reflectionCoords: vec2f
#endif
,NdotVUnclamped: f32
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler 
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler 
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo: f32
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho: f32
#endif
#endif
)->sheenOutParams
{var outParams: sheenOutParams;var sheenIntensity: f32=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
var sheenFactor: f32=pow5(1.0-sheenIntensity);var sheenColor: vec3f=baseColor.rgb*(1.0-sheenFactor);var sheenRoughness: f32=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
var sheenColor: vec3f=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor*=toLinearSpaceVec3(sheenMapData.rgb);
#else
sheenColor*=sheenMapData.rgb;
#endif
sheenColor*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
var sheenRoughness: f32=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#else
var sheenRoughness: f32=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif
#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif
sheenColor*=sheenIntensity;
#endif
#ifdef ENVIRONMENTBRDF
/*#ifdef SHEEN_SOFTER
var environmentSheenBrdf: vec3f= vec3f(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));
#else*/
#ifdef SHEEN_ROUGHNESS
var environmentSheenBrdf: vec3f=getBRDFLookup(NdotV,sheenRoughness);
#else
var environmentSheenBrdf: vec3f=environmentBrdf;
#endif
/*#endif*/
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
var sheenAlphaG: f32=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA
sheenAlphaG+=AARoughnessFactors.y;
#endif
var environmentSheenRadiance: vec4f= vec4f(0.,0.,0.,0.);environmentSheenRadiance=sampleReflectionTexture(
sheenAlphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,sheenRoughness
#endif
,reflectionSampler
,reflectionSamplerSampler
,reflectionCoords
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
);var sheenEnvironmentReflectance: vec3f=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif
outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}
#endif
`;
var init_pbrBlockSheen = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name267]) {
    ShaderStore.IncludesShadersStoreWGSL[name267] = shader266;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockClearcoat.js
var name268 = "pbrBlockClearcoat", shader267 = `struct clearcoatOutParams
{specularEnvironmentR0: vec3f,
conservationFactor: f32,
clearCoatNormalW: vec3f,
clearCoatAARoughnessFactors: vec2f,
clearCoatIntensity: f32,
clearCoatRoughness: f32,
#ifdef REFLECTION
finalClearCoatRadianceScaled: vec3f,
#endif
#ifdef CLEARCOAT_TINT
absorption: vec3f,
clearCoatNdotVRefract: f32,
clearCoatColor: vec3f,
clearCoatThickness: f32,
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
energyConservationFactorClearCoat: vec3f,
#endif
#if DEBUGMODE>0
#ifdef CLEARCOAT_BUMP
TBNClearCoat: mat3x3f,
#endif
#ifdef CLEARCOAT_TEXTURE
clearCoatMapData: vec2f,
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
clearCoatTintMapData: vec4f,
#endif
#ifdef REFLECTION
environmentClearCoatRadiance: vec4f,
clearCoatEnvironmentReflectance: vec3f,
#endif
clearCoatNdotV: f32
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
fn clearcoatBlock(
vPositionW: vec3f
,geometricNormalW: vec3f
,viewDirectionW: vec3f
,vClearCoatParams: vec2f
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData: vec4f
#endif
,specularEnvironmentR0: vec3f
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData: vec2f
#endif
#ifdef CLEARCOAT_TINT
,vClearCoatTintParams: vec4f
,clearCoatColorAtDistance: f32
,vClearCoatRefractionParams: vec4f
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData: vec4f
#endif
#endif
#ifdef CLEARCOAT_BUMP
,vClearCoatBumpInfos: vec2f
,clearCoatBumpMapData: vec4f
,vClearCoatBumpUV: vec2f
#if defined(TANGENT) && defined(NORMAL)
,vTBN: mat3x3f
#else
,vClearCoatTangentSpaceParams: vec2f
#endif
#ifdef OBJECTSPACE_NORMALMAP
,normalMatrix: mat4x4f
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal: vec3f
#endif
#ifdef REFLECTION
,vReflectionMicrosurfaceInfos: vec3f
,vReflectionInfos: vec2f
,vReflectionColor: vec3f
,vLightingIntensity: vec4f
#ifdef REFLECTIONMAP_3D
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
#else
,reflectionSampler: texture_2d<f32>
,reflectionSamplerSampler: sampler
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,reflectionLowSampler: texture_cube<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_cube<f32>
,reflectionHighSamplerSampler: sampler 
#else
,reflectionLowSampler: texture_2d<f32>
,reflectionLowSamplerSampler: sampler 
,reflectionHighSampler: texture_2d<f32>
,reflectionHighSamplerSampler: sampler 
#endif
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo: vec2f
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,frontFacingMultiplier: f32
#endif 
)->clearcoatOutParams
{var outParams: clearcoatOutParams;var clearCoatIntensity: f32=vClearCoatParams.x;var clearCoatRoughness: f32=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
var clearCoatColor: vec3f=vClearCoatTintParams.rgb;var clearCoatThickness: f32=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpaceVec3(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;
#endif
#ifdef CLEARCOAT_REMAP_F0
var specularEnvironmentR0Updated: vec3f=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
var specularEnvironmentR0Updated: vec3f=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);var clearCoatNormalW: vec3f=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
var clearCoatNormalScale: f32=1.0;
#else
var clearCoatNormalScale: f32=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
var TBNClearCoat: mat3x3f=vTBN;
#else
var TBNClearCoatUV: vec2f=vClearCoatBumpUV*frontFacingMultiplier;var TBNClearCoat: mat3x3f=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize( mat3x3f(normalMatrix[0].xyz,normalMatrix[1].xyz,normalMatrix[2].xyz)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);var clearCoatNdotVUnclamped: f32=dot(clearCoatNormalW,viewDirectionW);var clearCoatNdotV: f32=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT
var clearCoatVRefract: vec3f=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
var environmentClearCoatBrdf: vec3f=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif
#if defined(REFLECTION)
var clearCoatAlphaG: f32=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA
clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
var environmentClearCoatRadiance: vec4f= vec4f(0.,0.,0.,0.);var clearCoatReflectionVector: vec3f=computeReflectionCoords( vec4f(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
var clearCoatReflectionCoords: vec3f=clearCoatReflectionVector;
#else
var clearCoatReflectionCoords: vec2f=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
environmentClearCoatRadiance=sampleReflectionTexture(
clearCoatAlphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,clearCoatNdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,clearCoatRoughness
#endif
,reflectionSampler
,reflectionSamplerSampler
,clearCoatReflectionCoords
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif 
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromBRDFLookup(vec3f(uniforms.vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
var clearCoatEho: f32=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else
var clearCoatEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV, vec3f(1.), vec3f(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)
outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif
var fresnelIBLClearCoat: f32=fresnelSchlickGGX(clearCoatNdotV,uniforms.vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
return outParams;}
#endif
`;
var init_pbrBlockClearcoat = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name268]) {
    ShaderStore.IncludesShadersStoreWGSL[name268] = shader267;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockIridescence.js
var name269 = "pbrBlockIridescence", shader268 = `struct iridescenceOutParams
{iridescenceIntensity: f32,
iridescenceIOR: f32,
iridescenceThickness: f32,
specularEnvironmentR0: vec3f};
#ifdef IRIDESCENCE
fn iridescenceBlock(
vIridescenceParams: vec4f
,viewAngle_: f32
,specularEnvironmentR0: vec3f
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData: vec2f
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData: vec2f
#endif
#ifdef CLEARCOAT
,NdotVUnclamped: f32
,vClearCoatParams: vec2f
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData: vec2f
#endif
#endif
)->iridescenceOutParams
{var outParams: iridescenceOutParams;var iridescenceIntensity: f32=vIridescenceParams.x;var iridescenceIOR: f32=vIridescenceParams.y;var iridescenceThicknessMin: f32=vIridescenceParams.z;var iridescenceThicknessMax: f32=vIridescenceParams.w;var iridescenceThicknessWeight: f32=1.;var viewAngle=viewAngle_;
#ifdef IRIDESCENCE_TEXTURE
iridescenceIntensity*=iridescenceMapData.x;
#endif
#if defined(IRIDESCENCE_THICKNESS_TEXTURE)
iridescenceThicknessWeight=iridescenceThicknessMapData.g;
#endif
var iridescenceThickness: f32=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);var topIor: f32=1.; 
#ifdef CLEARCOAT
var clearCoatIntensity: f32=vClearCoatParams.x;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#endif
topIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+((1.0/topIor)*(1.0/topIor))*((NdotVUnclamped*NdotVUnclamped)-1.0));
#endif
var iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}
#endif
`;
var init_pbrBlockIridescence = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name269]) {
    ShaderStore.IncludesShadersStoreWGSL[name269] = shader268;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockSubSurface.js
var name270 = "pbrBlockSubSurface", shader269 = `struct subSurfaceOutParams
{specularEnvironmentReflectance: vec3f,
#ifdef SS_REFRACTION
finalRefraction: vec3f,
surfaceAlbedo: vec3f,
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha: f32,
#endif
#ifdef REFLECTION
refractionFactorForIrradiance: f32,
#endif
#endif
#ifdef SS_TRANSLUCENCY
transmittance: vec3f,
translucencyIntensity: f32,
#ifdef REFLECTION
refractionIrradiance: vec3f,
#endif
#endif
#if DEBUGMODE>0
#ifdef SS_THICKNESSANDMASK_TEXTURE
thicknessMap: vec4f,
#endif
#ifdef SS_REFRACTION
environmentRefraction: vec4f,
refractionTransmittance: vec3f
#endif
#endif
};
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#define pbr_inline
fn sampleEnvironmentRefraction(
ior: f32
,thickness: f32
,refractionLOD: f32
,normalW: vec3f
,vPositionW: vec3f
,viewDirectionW: vec3f
,view: mat4x4f
,vRefractionInfos: vec4f
,refractionMatrix: mat4x4f
,vRefractionMicrosurfaceInfos: vec4f
,alphaG: f32
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler: texture_cube<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_cube<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_cube<f32>
,refractionHighSamplerSampler: sampler 
#endif
#else
,refractionSampler: texture_2d<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_2d<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_2d<f32>
,refractionHighSamplerSampler: sampler 
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo: vec2f
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition: vec3f
,refractionSize: vec3f
#endif
)->vec4f {var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);
#ifdef ANISOTROPIC
var refractionVector: vec3f=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);
#else
var refractionVector: vec3f=refract(-viewDirectionW,normalW,ior);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif
#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;var refractionCoords: vec3f=refractionVector;refractionCoords= (refractionMatrix* vec4f(refractionCoords,0)).xyz;
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*thickness,1.0))).xyz;
#else
var vRefractionUVW: vec3f= (refractionMatrix*(view* vec4f(vPositionW+refractionVector*vRefractionInfos.z,1.0))).xyz;
#endif
var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;
#endif
#ifdef LODBASEDMICROSFURACE
var lod=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA
var automaticRefractionLOD: f32=UNPACK_LOD(textureSample(refractionSampler,refractionSamplerSampler,refractionCoords).a);var requestedRefractionLOD: f32=max(automaticRefractionLOD,lod);
#else
var requestedRefractionLOD: f32=lod;
#endif
#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)
environmentRefraction= vec4f(radiance(alphaG,refractionSampler,refractionSamplerSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=textureSampleLevel(refractionSampler,refractionSamplerSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
var lodRefractionNormalized: f32=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));var lodRefractionNormalizedDoubled: f32=lodRefractionNormalized*2.0;var environmentRefractionMid: vec4f=textureSample(refractionSampler,refractionSamplerSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(
textureSample(refractionHighSampler,refractionHighSamplerSampler,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);} else {environmentRefraction=mix(
environmentRefractionMid,
textureSample(refractionLowSampler,refractionLowSamplerSampler,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);}
#endif
var refraction=environmentRefraction.rgb;
#ifdef SS_RGBDREFRACTION
refraction=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
refraction=toLinearSpaceVec3(environmentRefraction.rgb);
#endif
return vec4f(refraction,environmentRefraction.a);}
#endif
#define pbr_inline
fn subSurfaceBlock(
vSubSurfaceIntensity: vec3f
,vThicknessParam: vec2f
,vTintColor: vec4f
,normalW: vec3f
,specularEnvironmentReflectance: vec3f
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap: vec4f
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap: vec4f
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap: vec4f
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,reflectionMatrix: mat4x4f
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,irradianceVector_: vec3f
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler: texture_cube<f32>
,reflectionSamplerSampler: sampler
,vReflectionFilteringInfo: vec2f
#ifdef IBL_CDF_FILTERING
,icdfSampler: texture_2d<f32>
,icdfSamplerSampler: sampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,irradianceSampler: texture_cube<f32>
,irradianceSamplerSampler: sampler
#else
,irradianceSampler: texture_2d<f32>
,irradianceSamplerSampler: sampler
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo: vec3f
#endif
#ifdef SS_REFRACTION
,vPositionW: vec3f
,viewDirectionW: vec3f
,view: mat4x4f
,vRefractionInfos: vec4f
,refractionMatrix: mat4x4f
,vRefractionMicrosurfaceInfos: vec4f
,vLightingIntensity: vec4f
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha: f32
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped: f32
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness: f32
#endif
,alphaG: f32
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler: texture_cube<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_cube<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_cube<f32>
,refractionHighSamplerSampler: sampler 
#endif
#else
,refractionSampler: texture_2d<f32>
,refractionSamplerSampler: sampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler: texture_2d<f32>
,refractionLowSamplerSampler: sampler
,refractionHighSampler: texture_2d<f32>
,refractionHighSamplerSampler: sampler 
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut: anisotropicOutParams
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo: vec2f
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition: vec3f
,refractionSize: vec3f
#endif
#ifdef SS_DISPERSION
,dispersion: f32
#endif
#endif
#ifdef SS_TRANSLUCENCY
,vDiffusionDistance: vec3f
,vTranslucencyColor: vec4f
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap: vec4f
#endif
#endif
)->subSurfaceOutParams
{var outParams: subSurfaceOutParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;
#ifdef SS_REFRACTION
var refractionIntensity: f32=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
var translucencyIntensity: f32=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
var thickness: f32=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
var thickness: f32=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=thicknessMap.a;
#else
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
var thickness: f32=vThicknessParam.y;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=translucencyIntensityMap.a;
#else
translucencyIntensity*=translucencyIntensityMap.b;
#endif
#endif
#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);var translucencyColor: vec4f=vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
translucencyColor*=translucencyColorMap;
#endif
var transmittance: vec3f=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;
#endif
#ifdef SS_REFRACTION
var environmentRefraction: vec4f= vec4f(0.,0.,0.,0.);
#ifdef SS_HAS_THICKNESS
var ior: f32=vRefractionInfos.y;
#else
var ior: f32=vRefractionMicrosurfaceInfos.w;
#endif
#ifdef SS_LODINREFRACTIONALPHA
var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaGNdotV(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
var refractionRoughness: f32=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
var refractionAlphaG: f32=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));var refractionLOD: f32=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
var refraction_ior: f32=vRefractionInfos.y;
#ifdef SS_DISPERSION
var realIOR: f32=1.0/refraction_ior;var iorDispersionSpread: f32=0.04*dispersion*(realIOR-1.0);var iors: vec3f= vec3f(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (var i: i32=0; i<3; i++) {refraction_ior=iors[i];
#endif
var envSample: vec4f=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#else
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition
,refractionSize
#endif
);
#ifdef SS_DISPERSION
environmentRefraction[i]=envSample[i];}
#else
environmentRefraction=envSample;
#endif
environmentRefraction=vec4f(environmentRefraction.rgb*vRefractionInfos.x,environmentRefraction.a);
#endif
#ifdef SS_REFRACTION
var refractionTransmittance: vec3f= vec3f(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
var maxChannel: f32=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);var volumeAlbedo: vec3f=saturateVec3(maxChannel*surfaceAlbedo);environmentRefraction=vec4f(environmentRefraction.rgb*volumeAlbedo,environmentRefraction.a);
#else
var volumeAlbedo: vec3f=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambertVec3(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT
environmentRefraction=vec4f(environmentRefraction.rgb*surfaceAlbedo.rgb,environmentRefraction.a);
#endif
outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);
#ifdef REFLECTION
outParams.refractionFactorForIrradiance=(1.-refractionIntensity);
#endif
#ifdef UNUSED_MULTIPLEBOUNCES
var bounceSpecularEnvironmentReflectance: vec3f=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
#endif
refractionTransmittance*=1.0-max(outParams.specularEnvironmentReflectance.r,max(outParams.specularEnvironmentReflectance.g,outParams.specularEnvironmentReflectance.b));
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif
#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
var irradianceVector: vec3f= (reflectionMatrix* vec4f(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
var irradianceVector: vec3f=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
var refractionIrradiance: vec3f=irradiance(reflectionSampler,reflectionSamplerSampler,-irradianceVector,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
);
#else
var refractionIrradiance: vec3f=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
var irradianceCoords: vec3f=irradianceVector;
#else
var irradianceCoords: vec2f=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
var temp: vec4f=textureSample(irradianceSampler,irradianceSamplerSampler,-irradianceCoords);var refractionIrradiance=temp.rgb;
#ifdef RGBDREFLECTION
refractionIrradiance=fromRGBD(temp).rgb;
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance=toLinearSpaceVec3(refractionIrradiance);
#endif
#else
var refractionIrradiance: vec3f= vec3f(0.);
#endif
refractionIrradiance*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT
refractionIrradiance*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance;
#endif
return outParams;}
#endif
`;
var init_pbrBlockSubSurface = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name270]) {
    ShaderStore.IncludesShadersStoreWGSL[name270] = shader269;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockNormalGeometric.js
var name271 = "pbrBlockNormalGeometric", shader270 = `var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW);
#ifdef NORMAL
var normalW: vec3f=normalize(input.vNormalW);
#else
var normalW: vec3f=normalize(cross(dpdx(input.vPositionW),dpdy(input.vPositionW)))*scene.vEyePosition.w;
#endif
var geometricNormalW: vec3f=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing);
#endif
`;
var init_pbrBlockNormalGeometric = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name271]) {
    ShaderStore.IncludesShadersStoreWGSL[name271] = shader270;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockNormalFinal.js
var name272 = "pbrBlockNormalFinal", shader271 = `#if defined(FORCENORMALFORWARD) && defined(NORMAL)
var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing);
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
normalW=select(-normalW,normalW,fragmentInputs.frontFacing);
#endif
`;
var init_pbrBlockNormalFinal = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name272]) {
    ShaderStore.IncludesShadersStoreWGSL[name272] = shader271;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockLightmapInit.js
var name273 = "pbrBlockLightmapInit", shader272 = `#ifdef LIGHTMAP
var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a);
#endif
lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a);
#endif
`;
var init_pbrBlockLightmapInit = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name273]) {
    ShaderStore.IncludesShadersStoreWGSL[name273] = shader272;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockGeometryInfo.js
var name274 = "pbrBlockGeometryInfo", shader273 = `var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA
alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)
var environmentBrdf: vec3f=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
var ambientMonochrome: f32=aoOut.ambientOcclusionColor.r;
#else
var ambientMonochrome: f32=getLuminance(aoOut.ambientOcclusionColor);
#endif
var seo: f32=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
var eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;
var init_pbrBlockGeometryInfo = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name274]) {
    ShaderStore.IncludesShadersStoreWGSL[name274] = shader273;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockReflectance0.js
var name275 = "pbrBlockReflectance0", shader274 = `var reflectance: f32=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);var specularEnvironmentR0: vec3f=reflectivityOut.surfaceReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
var specularEnvironmentR90: vec3f= vec3f(metallicReflectanceFactors.a);
#else 
var specularEnvironmentR90: vec3f= vec3f(1.0,1.0,1.0);
#endif
#ifdef ALPHAFRESNEL
var reflectance90: f32=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;
var init_pbrBlockReflectance0 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name275]) {
    ShaderStore.IncludesShadersStoreWGSL[name275] = shader274;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockReflectance.js
var name276 = "pbrBlockReflectance", shader275 = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
var specularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);
#ifdef RADIANCEOCCLUSION
specularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
specularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else
var specularEnvironmentReflectance: vec3f=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));
#endif
#ifdef CLEARCOAT
specularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
specularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;
var init_pbrBlockReflectance = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name276]) {
    ShaderStore.IncludesShadersStoreWGSL[name276] = shader275;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockDirectLighting.js
var name277 = "pbrBlockDirectLighting", shader276 = `var diffuseBase: vec3f=vec3f(0.,0.,0.);
#ifdef SPECULARTERM
var specularBase: vec3f=vec3f(0.,0.,0.);
#endif
#ifdef CLEARCOAT
var clearCoatBase: vec3f=vec3f(0.,0.,0.);
#endif
#ifdef SHEEN
var sheenBase: vec3f=vec3f(0.,0.,0.);
#endif
var preInfo: preLightingInfo;var info: lightingInfo;var shadow: f32=1.; 
var aggShadow: f32=0.;var numLights: f32=0.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
var absorption: vec3f=vec3f(0.);
#endif
`;
var init_pbrBlockDirectLighting = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name277]) {
    ShaderStore.IncludesShadersStoreWGSL[name277] = shader276;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockFinalLitComponents.js
var name278 = "pbrBlockFinalLitComponents", shader277 = `aggShadow=aggShadow/numLights;
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
var energyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo=(1.-reflectance)*surfaceAlbedo.rgb;
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif
#ifdef REFLECTION
var finalIrradiance: vec3f=reflectionOut.environmentIrradiance;
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
finalIrradiance*=surfaceAlbedo.rgb;
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
finalIrradiance*=uniforms.vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;
#endif
#ifdef SPECULARTERM
var finalSpecular: vec3f=specularBase;finalSpecular=max(finalSpecular,vec3f(0.0));var finalSpecularScaled: vec3f=finalSpecular*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef REFLECTION
var finalRadiance: vec3f=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;var finalRadianceScaled: vec3f=finalRadiance*uniforms.vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef SHEEN
var finalSheen: vec3f=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,vec3f(0.0));var finalSheenScaled: vec3f=finalSheen*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef CLEARCOAT
var finalClearCoat: vec3f=clearCoatBase;finalClearCoat=max(finalClearCoat,vec3f(0.0));var finalClearCoatScaled: vec3f=finalClearCoat*uniforms.vLightingIntensity.x*uniforms.vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef ALPHABLEND
var luminanceOverAlpha: f32=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;
var init_pbrBlockFinalLitComponents = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name278]) {
    ShaderStore.IncludesShadersStoreWGSL[name278] = shader277;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockFinalUnlitComponents.js
var name279 = "pbrBlockFinalUnlitComponents", shader278 = `var finalDiffuse: vec3f=diffuseBase;
#if !defined(SS_TRANSLUCENCY)
finalDiffuse*=surfaceAlbedo.rgb;
#endif
finalDiffuse=max(finalDiffuse,vec3f(0.0));finalDiffuse*=uniforms.vLightingIntensity.x;var finalAmbient: vec3f=uniforms.vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;var finalEmissive: vec3f=uniforms.vEmissiveColor;
#ifdef EMISSIVE
var emissiveColorTex: vec3f=textureSample(emissiveSampler,emissiveSamplerSampler,fragmentInputs.vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpaceVec3(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*= uniforms.vEmissiveInfos.y;
#endif
finalEmissive*=uniforms.vLightingIntensity.y;
#ifdef AMBIENT
var ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusionColor,uniforms.vAmbientInfos.w);
#else
var ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;
var init_pbrBlockFinalUnlitComponents = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name279]) {
    ShaderStore.IncludesShadersStoreWGSL[name279] = shader278;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockFinalColorComposition.js
var name280 = "pbrBlockFinalColorComposition", shader279 = `var finalColor: vec4f= vec4f(
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalAmbient +
finalDiffuse,
alpha);
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor=vec4f(finalColor.rgb*lightmapColor.rgb,finalColor.a);
#else
finalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a);
#endif
#endif
#endif
finalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a);
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,vec4f(0.0));
`;
var init_pbrBlockFinalColorComposition = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name280]) {
    ShaderStore.IncludesShadersStoreWGSL[name280] = shader279;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockImageProcessing.js
var name281 = "pbrBlockImageProcessing", shader280 = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
#if !defined(SKIPFINALCOLORCLAMP)
finalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a);
#endif
#else
finalColor=applyImageProcessing(finalColor);
#endif
finalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility);
#ifdef PREMULTIPLYALPHA
finalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);;
#endif
`;
var init_pbrBlockImageProcessing = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name281]) {
    ShaderStore.IncludesShadersStoreWGSL[name281] = shader280;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBlockPrePass.js
var name282 = "pbrBlockPrePass", shader281 = `var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef PREPASS_POSITION
fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo);
#endif
#ifdef PREPASS_VELOCITY
var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) -
(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
fragData[PREPASS_ALBEDO_INDEX]=vec4f(surfaceAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
var sqAlbedo : vec3f=sqrt(surfaceAlbedo); 
#endif
#ifdef PREPASS_IRRADIANCE
var irradiance : vec3f=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb-irradiance,finalColor.a); 
#endif
irradiance/=sqAlbedo;fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo*uniforms.scatteringDiffusionProfile/255.); 
#else
#ifdef PREPASS_COLOR
fragData[PREPASS_COLOR_INDEX]=finalColor; 
#endif
fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(clamp(irradiance,vec3f(0.),vec3f(1.)),writeGeometryInfo); 
#endif
#elif defined(PREPASS_COLOR)
fragData[PREPASS_COLOR_INDEX]=vec4f(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo);
#else
fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(0.0,0.0,0.0,1.0)*writeGeometryInfo;
#endif
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
`;
var init_pbrBlockPrePass = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name282]) {
    ShaderStore.IncludesShadersStoreWGSL[name282] = shader281;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrDebug.js
var name283 = "pbrDebug", shader282 = `#if DEBUGMODE>0
if (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f;
#if DEBUGMODE==1
color=fragmentInputs.vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==2 && defined(NORMAL)
color=fragmentInputs.vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)
color=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)
color=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==5
color=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==6 && defined(MAINUV1)
color= vec3f(input.vMainUV1,0.0);
#elif DEBUGMODE==7 && defined(MAINUV2)
color= vec3f(input.vMainUV2,0.0);
#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
color=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
color=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==10 && defined(CLEARCOAT)
color=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==11 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==12 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==13 && defined(ANISOTROPIC)
color=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==20 && defined(ALBEDO)
color=albedoTexture.rgb;
#ifndef GAMMAALBEDO
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==21 && defined(AMBIENT)
color=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE==22 && defined(OPACITY)
color=opacityMap.rgb;
#elif DEBUGMODE==23 && defined(EMISSIVE)
color=emissiveColorTex.rgb;
#ifndef GAMMAEMISSIVE
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==24 && defined(LIGHTMAP)
color=lightmapColor;
#ifndef GAMMALIGHTMAP
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
color=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
color=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
color= vec3f(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
color=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
color=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
color=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
color=subSurfaceOut.thicknessMap.rgb;
#elif DEBUGMODE==32 && defined(BUMP)
color=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).rgb;
#elif DEBUGMODE==40 && defined(SS_REFRACTION)
color=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==41 && defined(REFLECTION)
color=reflectionOut.environmentRadiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)
color=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==50
color=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==51 && defined(SPECULARTERM)
color=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==52 && defined(CLEARCOAT)
color=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==53 && defined(SHEEN)
color=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==54 && defined(REFLECTION)
color=reflectionOut.environmentIrradiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==60
color=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==61
color=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)
color= vec3f(reflectivityOut.metallicRoughness.r);
#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)
color=reflectivityOut.metallicF0;
#elif DEBUGMODE==63
color= vec3f(roughness);
#elif DEBUGMODE==64
color= vec3f(alphaG);
#elif DEBUGMODE==65
color= vec3f(NdotV);
#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
color=clearcoatOut.clearCoatColor;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==67 && defined(CLEARCOAT)
color= vec3f(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE==68 && defined(CLEARCOAT)
color= vec3f(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
color=subSurfaceOut.transmittance;
#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
color=subSurfaceOut.refractionTransmittance;
#elif DEBUGMODE==72
color= vec3f(microSurface);
#elif DEBUGMODE==73
color=uniforms.vAlbedoColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)
color=uniforms.vReflectivityColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==75
color=uniforms.vEmissiveColor;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)
color= vec3f(seo);
#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
color= vec3f(eho);
#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)
color= vec3f(energyConservationFactor);
#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
color=specularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
color=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)
color=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==86 && defined(ALPHABLEND)
color= vec3f(luminanceOverAlpha);
#elif DEBUGMODE==87
color= vec3f(alpha);
#elif DEBUGMODE==88 && defined(ALBEDO)
color= vec3f(albedoTexture.a);
#elif DEBUGMODE==89
color=aoOut.ambientOcclusionColor;
#else
var stripeWidth: f32=30.;var stripePos: f32=abs(floor(input.position.x/stripeWidth));var whichColor: f32=((stripePos)%(2.));var color1: vec3f= vec3f(.6,.2,.2);var color2: vec3f= vec3f(.3,.1,.1);color=mix(color1,color2,whichColor);
#endif
color*=uniforms.vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
color=normalize(color)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
color=toGammaSpaceVec3(color);
#endif
fragmentOutputs.color=vec4f(color,1.0);
#ifdef PREPASS
fragmentOutputs.fragData0=toLinearSpaceVec3(color); 
fragmentOutputs.fragData1=vec4f(0.,0.,0.,0.); 
#endif
#ifdef DEBUGMODE_FORCERETURN
return fragmentOutputs;
#endif
}
#endif
`;
var init_pbrDebug = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name283]) {
    ShaderStore.IncludesShadersStoreWGSL[name283] = shader282;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/pbr.fragment.js
var exports_pbr_fragment = {};
__export(exports_pbr_fragment, {
  pbrPixelShaderWGSL: () => pbrPixelShaderWGSL
});
var name284 = "pbrPixelShader", shader283 = `#define CUSTOM_FRAGMENT_BEGIN
#include<prePassDeclaration>[SCENE_MRT_COUNT]
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<pbrUboDeclaration>
#include<pbrFragmentExtraDeclaration>
#include<lightUboDeclaration>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockIridescence>
#include<pbrBlockSubSurface>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>
var albedoOpacityOut: albedoOpacityOutParams;
#ifdef ALBEDO
var albedoTexture: vec4f=textureSample(albedoSampler,albedoSamplerSampler,fragmentInputs.vAlbedoUV+uvOffset);
#endif
#ifdef BASEWEIGHT
var baseWeightTexture: vec4f=textureSample(baseWeightSampler,baseWeightSamplerSampler,fragmentInputs.vBaseWeightUV+uvOffset);
#endif
#ifdef OPACITY
var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset);
#endif
#ifdef DECAL
var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset);
#endif
albedoOpacityOut=albedoOpacityBlock(
uniforms.vAlbedoColor
#ifdef ALBEDO
,albedoTexture
,uniforms.vAlbedoInfos
#endif
,uniforms.baseWeight
#ifdef BASEWEIGHT
,baseWeightTexture
,uniforms.vBaseWeightInfos
#endif
#ifdef OPACITY
,opacityMap
,uniforms.vOpacityInfos
#endif
#ifdef DETAIL
,detailColor
,uniforms.vDetailInfos
#endif
#ifdef DECAL
,decalColor
,uniforms.vDecalInfos
#endif
);var surfaceAlbedo: vec3f=albedoOpacityOut.surfaceAlbedo;var alpha: f32=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
var aoOut: ambientOcclusionOutParams;
#ifdef AMBIENT
var ambientOcclusionColorMap: vec3f=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb;
#endif
aoOut=ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
uniforms.vAmbientInfos
#endif
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
var diffuseBase: vec3f= vec3f(1.,1.,1.);
#else
var baseColor: vec3f=surfaceAlbedo;var reflectivityOut: reflectivityOutParams;
#if defined(REFLECTIVITY)
var surfaceMetallicOrReflectivityColorMap: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,fragmentInputs.vReflectivityUV+uvOffset);var baseReflectivity: vec4f=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpaceVec4(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap=vec4f(surfaceMetallicOrReflectivityColorMap.rgb*uniforms.vReflectivityInfos.y,surfaceMetallicOrReflectivityColorMap.a);
#endif
#endif
#if defined(MICROSURFACEMAP)
var microSurfaceTexel: vec4f=textureSample(microSurfaceSampler,microSurfaceSamplerSampler,fragmentInputs.vMicroSurfaceSamplerUV+uvOffset)*uniforms.vMicroSurfaceSamplerInfos.y;
#endif
#ifdef METALLICWORKFLOW
var metallicReflectanceFactors: vec4f=uniforms.vMetallicReflectanceFactors;
#ifdef REFLECTANCE
var reflectanceFactorsMap: vec4f=textureSample(reflectanceSampler,reflectanceSamplerSampler,fragmentInputs.vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpaceVec4(reflectanceFactorsMap);
#endif
metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*reflectanceFactorsMap.rgb,metallicReflectanceFactors.a);
#endif
#ifdef METALLIC_REFLECTANCE
var metallicReflectanceFactorsMap: vec4f=textureSample(metallicReflectanceSampler,metallicReflectanceSamplerSampler,fragmentInputs.vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpaceVec4(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors=vec4f(metallicReflectanceFactors.rgb*metallicReflectanceFactorsMap.rgb,metallicReflectanceFactors.a);
#endif
metallicReflectanceFactors*=metallicReflectanceFactorsMap.a;
#endif
#endif
reflectivityOut=reflectivityBlock(
uniforms.vReflectivityColor
#ifdef METALLICWORKFLOW
,surfaceAlbedo
,metallicReflectanceFactors
#endif
#ifdef REFLECTIVITY
,uniforms.vReflectivityInfos
,surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,aoOut.ambientOcclusionColor
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel
#endif
#ifdef DETAIL
,detailColor
,uniforms.vDetailInfos
#endif
);var microSurface: f32=reflectivityOut.microSurface;var roughness: f32=reflectivityOut.roughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif
#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
var alphaFresnelOut: alphaFresnelOutParams;alphaFresnelOut=alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface
);alpha=alphaFresnelOut.alpha;
#endif
#endif
#include<pbrBlockGeometryInfo>
#ifdef ANISOTROPIC
var anisotropicOut: anisotropicOutParams;
#ifdef ANISOTROPIC_TEXTURE
var anisotropyMapData: vec3f=textureSample(anisotropySampler,anisotropySamplerSampler,fragmentInputs.vAnisotropyUV+uvOffset).rgb*uniforms.vAnisotropyInfos.y;
#endif
anisotropicOut=anisotropicBlock(
uniforms.vAnisotropy,
roughness,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW
);
#endif
#ifdef REFLECTION
var reflectionOut: reflectionOutParams;
#ifndef USE_CUSTOM_REFLECTION
reflectionOut=reflectionBlock(
fragmentInputs.vPositionW
,normalW
,alphaG
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
,reflectionSampler
,reflectionSamplerSampler
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,fragmentInputs.vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,uniforms.reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
);
#else
#define CUSTOM_REFLECTION
#endif
#endif
#include<pbrBlockReflectance0>
#ifdef SHEEN
var sheenOut: sheenOutParams;
#ifdef SHEEN_TEXTURE
var sheenMapData: vec4f=textureSample(sheenSampler,sheenSamplerSampler,fragmentInputs.vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
var sheenMapRoughnessData: vec4f=textureSample(sheenRoughnessSampler,sheenRoughnessSamplerSampler,fragmentInputs.vSheenRoughnessUV+uvOffset)*uniforms.vSheenInfos.w;
#endif
sheenOut=sheenBlock(
uniforms.vSheenColor
#ifdef SHEEN_ROUGHNESS
,uniforms.vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData
#endif
#endif
,roughness
#ifdef SHEEN_TEXTURE
,sheenMapData
,uniforms.vSheenInfos.y
#endif
,reflectance
#ifdef SHEEN_LINKWITHALBEDO
,baseColor
,surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,NdotV
,environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
,uniforms.vLightingIntensity
,reflectionSampler
,reflectionSamplerSampler
,reflectionOut.reflectionCoords
,NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho
#endif
#endif
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
var clearCoatMapData: vec2f=textureSample(clearCoatSampler,clearCoatSamplerSampler,fragmentInputs.vClearCoatUV+uvOffset).rg*uniforms.vClearCoatInfos.y;
#endif
#endif
#ifdef IRIDESCENCE
var iridescenceOut: iridescenceOutParams;
#ifdef IRIDESCENCE_TEXTURE
var iridescenceMapData: vec2f=textureSample(iridescenceSampler,iridescenceSamplerSampler,fragmentInputs.vIridescenceUV+uvOffset).rg*uniforms.vIridescenceInfos.y;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
var iridescenceThicknessMapData: vec2f=textureSample(iridescenceThicknessSampler,iridescenceThicknessSamplerSampler,fragmentInputs.vIridescenceThicknessUV+uvOffset).rg*uniforms.vIridescenceInfos.w;
#endif
iridescenceOut=iridescenceBlock(
uniforms.vIridescenceParams
,NdotV
,specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,NdotVUnclamped
,uniforms.vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#endif
);var iridescenceIntensity: f32=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;
#endif
var clearcoatOut: clearcoatOutParams;
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
var clearCoatMapRoughnessData: vec4f=textureSample(clearCoatRoughnessSampler,clearCoatRoughnessSamplerSampler,fragmentInputs.vClearCoatRoughnessUV+uvOffset)*uniforms.vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
var clearCoatTintMapData: vec4f=textureSample(clearCoatTintSampler,clearCoatTintSamplerSampler,fragmentInputs.vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
var clearCoatBumpMapData: vec4f=textureSample(clearCoatBumpSampler,clearCoatBumpSamplerSampler,fragmentInputs.vClearCoatBumpUV+uvOffset);
#endif
clearcoatOut=clearcoatBlock(
fragmentInputs.vPositionW
,geometricNormalW
,viewDirectionW
,uniforms.vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData
#endif
,specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,uniforms.vClearCoatTintParams
,uniforms.clearCoatColorAtDistance
,uniforms.vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,uniforms.vClearCoatBumpInfos
,clearCoatBumpMapData
,fragmentInputs.vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,mat3x3<f32>(input.vTBN0,input.vTBN1,input.vTBN2)
#else
,uniforms.vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,uniforms.normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal
#endif
#ifdef REFLECTION
,uniforms.vReflectionMicrosurfaceInfos
,uniforms.vReflectionInfos
,uniforms.vReflectionColor
,uniforms.vLightingIntensity
,reflectionSampler
,reflectionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,reflectionLowSampler
,reflectionLowSamplerSampler
,reflectionHighSampler
,reflectionHighSamplerSampler
#endif
#ifdef REALTIME_FILTERING
,uniforms.vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,select(-1.,1.,fragmentInputs.frontFacing)
#endif
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif
#include<pbrBlockReflectance>
var subSurfaceOut: subSurfaceOutParams;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
var thicknessMap: vec4f=textureSample(thicknessSampler,thicknessSamplerSampler,fragmentInputs.vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
var refractionIntensityMap: vec4f=textureSample(refractionIntensitySampler,refractionIntensitySamplerSampler,fragmentInputs.vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
var translucencyIntensityMap: vec4f=textureSample(translucencyIntensitySampler,translucencyIntensitySamplerSampler,fragmentInputs.vTranslucencyIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
var translucencyColorMap: vec4f=textureSample(translucencyColorSampler,translucencyColorSamplerSampler,fragmentInputs.vTranslucencyColorUV+uvOffset);
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA
translucencyColorMap=toLinearSpaceVec4(translucencyColorMap);
#endif
#endif
subSurfaceOut=subSurfaceBlock(
uniforms.vSubSurfaceIntensity
,uniforms.vThicknessParam
,uniforms.vTintColor
,normalW
,specularEnvironmentReflectance
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,uniforms.reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,reflectionOut.irradianceVector
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler
,reflectionSamplerSampler
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
,icdfSamplerSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
,irradianceSamplerSampler
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,fragmentInputs.vPositionW
,viewDirectionW
,scene.view
,uniforms.vRefractionInfos
,uniforms.refractionMatrix
,uniforms.vRefractionMicrosurfaceInfos
,uniforms.vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness
#endif
,alphaG
,refractionSampler
,refractionSamplerSampler
#ifndef LODBASEDMICROSFURACE
,refractionLowSampler
,refractionLowSamplerSampler
,refractionHighSampler
,refractionHighSamplerSampler
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,uniforms.vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,uniforms.vRefractionPosition
,uniforms.vRefractionSize
#endif
#ifdef SS_DISPERSION
,dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,uniforms.vDiffusionDistance
,uniforms.vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap
#endif
#endif
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;
#endif
#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]
#include<pbrBlockFinalLitComponents>
#endif 
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<pbrBlockPrePass>
#endif
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+finalColor.rgb*finalColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-finalColor.a));} else {fragmentOutputs.backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`, pbrPixelShaderWGSL;
var init_pbr_fragment = __esm(() => {
  init_shaderStore();
  init_prePassDeclaration();
  init_oitDeclaration();
  init_pbrUboDeclaration();
  init_pbrFragmentExtraDeclaration();
  init_lightUboDeclaration();
  init_pbrFragmentSamplersDeclaration();
  init_imageProcessingDeclaration();
  init_clipPlaneFragmentDeclaration();
  init_logDepthDeclaration();
  init_fogFragmentDeclaration();
  init_helperFunctions();
  init_subSurfaceScatteringFunctions();
  init_importanceSampling();
  init_pbrHelperFunctions();
  init_imageProcessingFunctions();
  init_shadowsFragmentFunctions();
  init_harmonicsFunctions();
  init_pbrDirectLightingSetupFunctions();
  init_pbrDirectLightingFalloffFunctions();
  init_pbrBRDFFunctions();
  init_hdrFilteringFunctions();
  init_pbrDirectLightingFunctions();
  init_pbrIBLFunctions();
  init_bumpFragmentMainFunctions();
  init_bumpFragmentFunctions();
  init_reflectionFunction();
  init_pbrBlockAlbedoOpacity();
  init_pbrBlockReflectivity();
  init_pbrBlockAmbientOcclusion();
  init_pbrBlockAlphaFresnel();
  init_pbrBlockAnisotropic();
  init_pbrBlockReflection();
  init_pbrBlockSheen();
  init_pbrBlockClearcoat();
  init_pbrBlockIridescence();
  init_pbrBlockSubSurface();
  init_clipPlaneFragment();
  init_pbrBlockNormalGeometric();
  init_bumpFragment();
  init_pbrBlockNormalFinal();
  init_depthPrePass();
  init_pbrBlockLightmapInit();
  init_pbrBlockGeometryInfo();
  init_pbrBlockReflectance0();
  init_pbrBlockReflectance();
  init_pbrBlockDirectLighting();
  init_lightFragment();
  init_pbrBlockFinalLitComponents();
  init_pbrBlockFinalUnlitComponents();
  init_pbrBlockFinalColorComposition();
  init_logDepthFragment();
  init_fogFragment();
  init_pbrBlockImageProcessing();
  init_pbrBlockPrePass();
  init_oitFragment();
  init_pbrDebug();
  if (!ShaderStore.ShadersStoreWGSL[name284]) {
    ShaderStore.ShadersStoreWGSL[name284] = shader283;
  }
  pbrPixelShaderWGSL = { name: name284, shader: shader283 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrVertexDeclaration.js
var name285 = "pbrVertexDeclaration", shader284 = `uniform mat4 view;uniform mat4 viewProjection;
#ifdef MULTIVIEW
mat4 viewProjectionR;
#endif
#ifdef ALBEDO
uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;
#endif
#ifdef BASEWEIGHT
uniform mat4 baseWeightMatrix;uniform vec2 vBaseWeightInfos;
#endif
#ifdef AMBIENT
uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;
#endif
#ifdef OPACITY
uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;
#endif
#ifdef METALLIC_REFLECTANCE
uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;
#endif
#ifdef REFLECTANCE
uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform mat4 bumpMatrix;
#endif
#ifdef POINTSIZE
uniform float pointSize;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;
#endif
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#ifdef IRIDESCENCE
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;
#endif
#endif
#ifdef NORMAL
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#endif
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;uniform mat4 detailMatrix;
#endif
#include<decalVertexDeclaration>
#define ADDITIONAL_VERTEX_DECLARATION
`;
var init_pbrVertexDeclaration = __esm(() => {
  init_shaderStore();
  init_decalVertexDeclaration();
  if (!ShaderStore.IncludesShadersStore[name285]) {
    ShaderStore.IncludesShadersStore[name285] = shader284;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrUboDeclaration.js
var name286 = "pbrUboDeclaration", shader285 = `layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec2 vBaseWeightInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 baseWeightMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;float baseWeight;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;
#define ADDITIONAL_UBO_DECLARATION
};
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
var init_pbrUboDeclaration2 = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  init_meshUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name286]) {
    ShaderStore.IncludesShadersStore[name286] = shader285;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/harmonicsFunctions.js
var name287 = "harmonicsFunctions", shader286 = `#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00
+ vSphericalL1_1*(normal.y)
+ vSphericalL10*(normal.z)
+ vSphericalL11*(normal.x)
+ vSphericalL2_2*(normal.y*normal.x)
+ vSphericalL2_1*(normal.y*normal.z)
+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)
+ vSphericalL21*(normal.z*normal.x)
+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}
#else
vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}
#endif
#endif
`;
var init_harmonicsFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name287]) {
    ShaderStore.IncludesShadersStore[name287] = shader286;
  }
});

// node_modules/@babylonjs/core/Shaders/pbr.vertex.js
var exports_pbr_vertex2 = {};
__export(exports_pbr_vertex2, {
  pbrVertexShader: () => pbrVertexShader
});
var name288 = "pbrVertexShader", shader287 = `#define CUSTOM_VERTEX_EXTENSION
precision highp float;
#include<__decl__pbrVertex>
#define CUSTOM_VERTEX_BEGIN
attribute vec3 position;
#ifdef NORMAL
attribute vec3 normal;
#endif
#ifdef TANGENT
attribute vec4 tangent;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#include<uvAttributeDeclaration>[2..7]
#include<mainUVVaryingDeclaration>[1..7]
#ifdef VERTEXCOLOR
attribute vec4 color;
#endif
#include<helperFunctions>
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<instancesDeclaration>
#include<prePassVertexDeclaration>
#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)
#include<samplerVertexDeclaration>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight)
#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)
#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)
#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)
#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)
#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)
#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)
#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)
#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)
#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)
#ifdef CLEARCOAT
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)
#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)
#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)
#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)
#endif
#ifdef SUBSURFACE
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)
#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)
#endif
varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#include<harmonicsFunctions>
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
#include<bumpVertexDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<__decl__lightVxFragment>[0..maxSimultaneousLights]
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#ifdef NORMAL
vec3 normalUpdated=normal;
#endif
#ifdef TANGENT
vec4 tangentUpdated=tangent;
#endif
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#ifdef VERTEXCOLOR
vec4 colorUpdated=color;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#ifdef REFLECTIONMAP_SKYBOX
vPositionUVW=positionUpdated;
#endif
#define CUSTOM_VERTEX_UPDATE_POSITION
#define CUSTOM_VERTEX_UPDATE_NORMAL
#include<instancesVertex>
#if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);
#ifdef PREPASS
#include<prePassVertex>
#endif
#ifdef NORMAL
mat3 normalWorld=mat3(finalWorld);
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normalWorld=transposeMat3(inverseMat3(normalWorld));
#endif
vNormalW=normalize(normalWorld*normalUpdated);
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);
#endif
#endif
#define CUSTOM_VERTEX_UPDATE_WORLDPOS
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#if DEBUGMODE>0
vClipSpacePosition=gl_Position;
#endif
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));
#endif
#ifndef UV1
vec2 uvUpdated=vec2(0.,0.);
#endif
#ifndef UV2
vec2 uv2Updated=vec2(0.,0.);
#endif
#ifdef MAINUV1
vMainUV1=uvUpdated;
#endif
#ifdef MAINUV2
vMainUV2=uv2Updated;
#endif
#include<uvVariableDeclaration>[3..7]
#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_MATRIXNAME_,baseWeight,_INFONAME_,BaseWeightInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)
#ifdef CLEARCOAT
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)
#endif
#ifdef IRIDESCENCE
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)
#endif
#ifdef SHEEN
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)
#endif
#ifdef ANISOTROPIC
#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)
#endif
#ifdef SUBSURFACE
#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)
#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)
#endif
#include<bumpVertex>
#include<clipPlaneVertex>
#include<fogVertex>
#include<shadowsVertex>[0..maxSimultaneousLights]
#include<vertexColorMixing>
#if defined(POINTSIZE) && !defined(WEBGPU)
gl_PointSize=pointSize;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, pbrVertexShader;
var init_pbr_vertex2 = __esm(() => {
  init_shaderStore();
  init_pbrVertexDeclaration();
  init_pbrUboDeclaration2();
  init_uvAttributeDeclaration2();
  init_mainUVVaryingDeclaration2();
  init_helperFunctions2();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_instancesDeclaration2();
  init_prePassVertexDeclaration2();
  init_samplerVertexDeclaration2();
  init_harmonicsFunctions2();
  init_bumpVertexDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_lightVxFragmentDeclaration2();
  init_lightVxUboDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_logDepthDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_prePassVertex2();
  init_uvVariableDeclaration2();
  init_samplerVertexImplementation2();
  init_bumpVertex2();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_shadowsVertex2();
  init_vertexColorMixing2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name288]) {
    ShaderStore.ShadersStore[name288] = shader287;
  }
  pbrVertexShader = { name: name288, shader: shader287 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentDeclaration.js
var name289 = "pbrFragmentDeclaration", shader288 = `uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform float baseWeight;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;
#ifdef ALBEDO
uniform vec2 vAlbedoInfos;
#endif
#ifdef BASEWEIGHT
uniform vec2 vBaseWeightInfos;
#endif
#ifdef AMBIENT
uniform vec4 vAmbientInfos;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#ifdef OPACITY
uniform vec2 vOpacityInfos;
#endif
#ifdef EMISSIVE
uniform vec2 vEmissiveInfos;
#endif
#ifdef LIGHTMAP
uniform vec2 vLightmapInfos;
#endif
#ifdef REFLECTIVITY
uniform vec3 vReflectivityInfos;
#endif
#ifdef MICROSURFACEMAP
uniform vec2 vMicroSurfaceSamplerInfos;
#endif
#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)
uniform mat4 view;
#endif
#ifdef REFLECTION
uniform vec2 vReflectionInfos;
#ifdef REALTIME_FILTERING
uniform vec2 vReflectionFilteringInfo;
#endif
uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;
#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)
uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;
#endif
#endif
#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)
uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize;
#endif
#ifdef CLEARCOAT
uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;
#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform vec4 vClearCoatInfos;
#endif
#ifdef CLEARCOAT_TEXTURE
uniform mat4 clearCoatMatrix;
#endif
#ifdef CLEARCOAT_TEXTURE_ROUGHNESS
uniform mat4 clearCoatRoughnessMatrix;
#endif
#ifdef CLEARCOAT_BUMP
uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;
#endif
#ifdef CLEARCOAT_TINT
uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;
#ifdef CLEARCOAT_TINT_TEXTURE
uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;
#endif
#endif
#endif
#ifdef IRIDESCENCE
uniform vec4 vIridescenceParams;
#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)
uniform vec4 vIridescenceInfos;
#endif
#ifdef IRIDESCENCE_TEXTURE
uniform mat4 iridescenceMatrix;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
uniform mat4 iridescenceThicknessMatrix;
#endif
#endif
#ifdef ANISOTROPIC
uniform vec3 vAnisotropy;
#ifdef ANISOTROPIC_TEXTURE
uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;
#endif
#endif
#ifdef SHEEN
uniform vec4 vSheenColor;
#ifdef SHEEN_ROUGHNESS
uniform float vSheenRoughness;
#endif
#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)
uniform vec4 vSheenInfos;
#endif
#ifdef SHEEN_TEXTURE
uniform mat4 sheenMatrix;
#endif
#ifdef SHEEN_TEXTURE_ROUGHNESS
uniform mat4 sheenRoughnessMatrix;
#endif
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;
#ifdef REALTIME_FILTERING
uniform vec2 vRefractionFilteringInfo;
#endif
#ifdef SS_DISPERSION
uniform float dispersion;
#endif
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;
#endif
uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
uniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;
#endif
#endif
#ifdef PREPASS
#ifdef SS_SCATTERING
uniform float scatteringDiffusionProfile;
#endif
#endif
#if DEBUGMODE>0
uniform vec2 vDebugMode;
#endif
#ifdef DETAIL
uniform vec4 vDetailInfos;
#endif
#include<decalFragmentDeclaration>
#ifdef USESPHERICALFROMREFLECTIONMAP
#ifdef SPHERICAL_HARMONICS
uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;
#else
uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;
#endif
#endif
#define ADDITIONAL_FRAGMENT_DECLARATION
`;
var init_pbrFragmentDeclaration = __esm(() => {
  init_shaderStore();
  init_decalFragmentDeclaration();
  if (!ShaderStore.IncludesShadersStore[name289]) {
    ShaderStore.IncludesShadersStore[name289] = shader288;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentExtraDeclaration.js
var name290 = "pbrFragmentExtraDeclaration", shader289 = `varying vec3 vPositionW;
#if DEBUGMODE>0
varying vec4 vClipSpacePosition;
#endif
#include<mainUVVaryingDeclaration>[1..7]
#ifdef NORMAL
varying vec3 vNormalW;
#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
varying vec3 vEnvironmentIrradiance;
#endif
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
varying vec4 vColor;
#endif
`;
var init_pbrFragmentExtraDeclaration2 = __esm(() => {
  init_shaderStore();
  init_mainUVVaryingDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name290]) {
    ShaderStore.IncludesShadersStore[name290] = shader289;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerFragmentAlternateDeclaration.js
var name291 = "samplerFragmentAlternateDeclaration", shader290 = `#ifdef _DEFINENAME_
#if _DEFINENAME_DIRECTUV==1
#define v_VARYINGNAME_UV vMainUV1
#elif _DEFINENAME_DIRECTUV==2
#define v_VARYINGNAME_UV vMainUV2
#elif _DEFINENAME_DIRECTUV==3
#define v_VARYINGNAME_UV vMainUV3
#elif _DEFINENAME_DIRECTUV==4
#define v_VARYINGNAME_UV vMainUV4
#elif _DEFINENAME_DIRECTUV==5
#define v_VARYINGNAME_UV vMainUV5
#elif _DEFINENAME_DIRECTUV==6
#define v_VARYINGNAME_UV vMainUV6
#else
varying vec2 v_VARYINGNAME_UV;
#endif
#endif
`;
var init_samplerFragmentAlternateDeclaration2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name291]) {
    ShaderStore.IncludesShadersStore[name291] = shader290;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentSamplersDeclaration.js
var name292 = "pbrFragmentSamplersDeclaration", shader291 = `#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)
#include<samplerFragmentDeclaration>(_DEFINENAME_,BASEWEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight)
#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)
#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)
#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)
#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)
#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)
#ifdef CLEARCOAT
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)
uniform sampler2D clearCoatRoughnessSampler;
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)
#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)
#endif
#ifdef IRIDESCENCE
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)
#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)
#endif
#ifdef SHEEN
#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)
#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)
uniform sampler2D sheenRoughnessSampler;
#endif
#endif
#ifdef ANISOTROPIC
#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)
#endif
#ifdef REFLECTION
#ifdef REFLECTIONMAP_3D
#define sampleReflection(s,c) textureCube(s,c)
uniform samplerCube reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform samplerCube irradianceSampler;
#endif
#else
#define sampleReflection(s,c) texture2D(s,c)
uniform sampler2D reflectionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;
#endif
#ifdef USEIRRADIANCEMAP
uniform sampler2D irradianceSampler;
#endif
#endif
#ifdef REFLECTIONMAP_SKYBOX
varying vec3 vPositionUVW;
#else
#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)
varying vec3 vDirectionW;
#endif
#endif
#endif
#ifdef ENVIRONMENTBRDF
uniform sampler2D environmentBrdfSampler;
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler;
#endif
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#ifdef SS_REFRACTIONMAP_3D
#define sampleRefraction(s,c) textureCube(s,c)
uniform samplerCube refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)
#else
uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;
#endif
#else
#define sampleRefraction(s,c) texture2D(s,c)
uniform sampler2D refractionSampler;
#ifdef LODBASEDMICROSFURACE
#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)
#else
uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;
#endif
#endif
#endif
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)
#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)
#endif
#ifdef IBL_CDF_FILTERING
uniform sampler2D icdfSampler;
#endif
`;
var init_pbrFragmentSamplersDeclaration2 = __esm(() => {
  init_shaderStore();
  init_samplerFragmentDeclaration2();
  init_samplerFragmentAlternateDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name292]) {
    ShaderStore.IncludesShadersStore[name292] = shader291;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/subSurfaceScatteringFunctions.js
var name293 = "subSurfaceScatteringFunctions", shader292 = `bool testLightingForSSS(float diffusionProfile)
{return diffusionProfile<1.;}`;
var init_subSurfaceScatteringFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name293]) {
    ShaderStore.IncludesShadersStore[name293] = shader292;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/importanceSampling.js
var name294 = "importanceSampling", shader293 = `vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}
vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { 
float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;
var init_importanceSampling2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name294]) {
    ShaderStore.IncludesShadersStore[name294] = shader293;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrHelperFunctions.js
var name295 = "pbrHelperFunctions", shader294 = `#define MINIMUMVARIANCE 0.0005
float convertRoughnessToAverageSlope(float roughness)
{return square(roughness)+MINIMUMVARIANCE;}
float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}
vec2 getAARoughnessFactors(vec3 normalVector) {
#ifdef SPECULARAA
vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);
#else
return vec2(0.);
#endif
}
#ifdef ANISOTROPIC
#ifdef ANISOTROPIC_LEGACY
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection;if (anisotropy>=0.0) {anisotropicFrameDirection=B;} else {anisotropicFrameDirection=T;}
vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}
#else
vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}
vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}
#endif
#endif
#if defined(CLEARCOAT) || defined(SS_REFRACTION)
vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}
vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}
vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}
vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),
cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),
clearCoatIntensity);return clearCoatAbsorption;}
#endif
#ifdef MICROSURFACEAUTOMATIC
float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)
{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}
#endif
`;
var init_pbrHelperFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name295]) {
    ShaderStore.IncludesShadersStore[name295] = shader294;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingSetupFunctions.js
var name296 = "pbrDirectLightingSetupFunctions", shader295 = `struct preLightingInfo
{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;
#ifdef IRIDESCENCE
float iridescenceIntensity;
#endif
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 areaLightDiffuse;
#ifdef SPECULARTERM
vec3 areaLightSpecular;vec4 areaLightFresnel;
#endif
#endif
};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N,vec3 posW) {preLightingInfo result;result.lightOffset=lightData.xyz-posW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}
preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;
#ifdef SPECULARTERM
result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));
#endif
return result;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
#include<ltcHelperFunctions>
preLightingInfo computeAreaPreLightingInfo(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec4 lightData,vec3 halfWidth,vec3 halfHeight,float roughness ) 
{preLightingInfo result;result.lightOffset=lightData.xyz-vPosition;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightData.xyz,halfWidth,halfHeight,roughness);
#ifdef SPECULARTERM
result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular; 
#endif
result.areaLightDiffuse=data.Diffuse;return result;}
#endif
`;
var init_pbrDirectLightingSetupFunctions2 = __esm(() => {
  init_shaderStore();
  init_ltcHelperFunctions2();
  if (!ShaderStore.IncludesShadersStore[name296]) {
    ShaderStore.IncludesShadersStore[name296] = shader295;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFalloffFunctions.js
var name297 = "pbrDirectLightingFalloffFunctions", shader296 = `float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)
{return max(0.,1.0-length(lightOffset)/range);}
float computeDistanceLightFalloff_Physical(float lightDistanceSquared)
{return 1.0/maxEps(lightDistanceSquared);}
float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)
{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}
float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDistanceLightFalloff_Physical(lightDistanceSquared);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);
#else
return computeDistanceLightFalloff_Standard(lightOffset,range);
#endif
}
float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)
{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)
{falloff=max(0.,pow(cosAngle,exponent));}
return falloff;}
float computeDirectionalLightFalloff_IES(vec3 lightDirection,vec3 directionToLightCenterW,sampler2D iesLightSampler)
{float cosAngle=dot(-lightDirection,directionToLightCenterW);float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;}
float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)
{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; 
float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}
float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)
{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}
float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)
{
#ifdef USEPHYSICALLIGHTFALLOFF
return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);
#elif defined(USEGLTFLIGHTFALLOFF)
return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);
#else
return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);
#endif
}`;
var init_pbrDirectLightingFalloffFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name297]) {
    ShaderStore.IncludesShadersStore[name297] = shader296;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/hdrFilteringFunctions.js
var name298 = "hdrFilteringFunctions", shader297 = `#ifdef NUM_SAMPLES
#if NUM_SAMPLES>0
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
float radicalInverse_VdC(uint bits) 
{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; }
vec2 hammersley(uint i,uint N)
{return vec2(float(i)/float(N),radicalInverse_VdC(i));}
#else
float vanDerCorpus(int n,int base)
{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)
{if(n>0)
{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}
return result;}
vec2 hammersley(int i,int N)
{return vec2(float(i)/float(N),vanDerCorpus(i,2));}
#endif
float log4(float x) {return log2(x)/2.;}
vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}
const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;
#define inline
vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo
#ifdef IBL_CDF_FILTERING
,sampler2D icdfSampler
#endif
)
{vec3 n=normalize(inputN);vec3 result=vec3(0.0);
#ifndef IBL_CDF_FILTERING
vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);
#endif
float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);
#ifdef IBL_CDF_FILTERING
vec2 T;T.x=textureLod(icdfSampler,vec2(Xi.x,0.0),0.0).x;T.y=textureLod(icdfSampler,vec2(T.x,Xi.y),0.0).y;vec3 Ls=uv_to_normal(vec2(1.0-fract(T.x+0.25),T.y));float NoL=dot(n,Ls);
#else
vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);
#endif
if (NoL>0.) {
#ifdef IBL_CDF_FILTERING
float pdf=textureLod(icdfSampler,T,0.0).z;vec3 c=textureCubeLodEXT(inputTexture,Ls,0.0).rgb;
#else
float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;
#endif
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
#ifdef IBL_CDF_FILTERING
vec3 light=pdf<1e-6 ? vec3(0.0) : vec3(1.0)/vec3(pdf)*c;result+=NoL*light;
#else
result+=c;
#endif
}}
result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}
#define inline
vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)
{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; 
if (alphaG==0.) {
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.;
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
for(uint i=0u; i<NUM_SAMPLES; ++i)
#else
for(int i=0; i<NUM_SAMPLES; ++i)
#endif
{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;
#ifdef GAMMA_INPUT
c=toLinearSpace(c);
#endif
result+=c*NoL;}}
result=result/weight;return result;}}
#endif
#endif
`;
var init_hdrFilteringFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name298]) {
    ShaderStore.IncludesShadersStore[name298] = shader297;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFunctions.js
var name299 = "pbrDirectLightingFunctions", shader298 = `#define CLEARCOATREFLECTANCE90 1.0
struct lightingInfo
{vec3 diffuse;
#ifdef SPECULARTERM
vec3 specular;
#endif
#ifdef CLEARCOAT
vec4 clearCoat;
#endif
#ifdef SHEEN
vec3 sheen;
#endif
};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {
#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)
float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;
#else
return roughness;
#endif
}
vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 computeAreaDiffuseLighting(preLightingInfo info,vec3 lightColor) {return info.areaLightDiffuse*lightColor;}
#endif
vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}
#define inline
vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}
#ifdef SS_TRANSLUCENCY
vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance,float transmittanceIntensity,vec3 surfaceAlbedo) {vec3 transmittanceNdotL=vec3(0.);float NdotL=absEps(info.NdotLUnclamped);if (info.NdotLUnclamped<0.0) {float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);}
float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return (transmittanceNdotL/PI+(1.0-transmittanceIntensity)*diffuseTerm*surfaceAlbedo*info.NdotL)*info.attenuation*lightColor;}
#endif
#ifdef SPECULARTERM
vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);
#ifdef BRDF_V_HEIGHT_CORRELATED
float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);
#else
float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);
#endif
vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)
vec3 computeAreaSpecularLighting(preLightingInfo info,vec3 specularColor) {vec3 fresnel=( specularColor*info.areaLightFresnel.x+( vec3( 1.0 )-specularColor )*info.areaLightFresnel.y );return specularColor*fresnel*info.areaLightSpecular;}
#endif
#endif
#ifdef ANISOTROPIC
vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);
#ifdef IRIDESCENCE
fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);
#endif
float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}
#endif
#ifdef CLEARCOAT
vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4(
clearCoatTerm*info.attenuation*NccdotL*lightColor,
1.0-fresnel
);}
vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}
#endif
#ifdef SHEEN
vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER
float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);
#else */
float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */
float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}
#endif
`;
var init_pbrDirectLightingFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name299]) {
    ShaderStore.IncludesShadersStore[name299] = shader298;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrIBLFunctions.js
var name300 = "pbrIBLFunctions", shader299 = `#if defined(REFLECTION) || defined(SS_REFRACTION)
float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}
float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}
#endif
#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)
float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}
#endif
#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)
float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);}
#endif
#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)
#define UNPACK_LOD(x) (1.0-x)*255.0
float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}
#endif
`;
var init_pbrIBLFunctions2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name300]) {
    ShaderStore.IncludesShadersStore[name300] = shader299;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlbedoOpacity.js
var name301 = "pbrBlockAlbedoOpacity", shader300 = `struct albedoOpacityOutParams
{vec3 surfaceAlbedo;float alpha;};
#define pbr_inline
albedoOpacityOutParams albedoOpacityBlock(
in vec4 vAlbedoColor
#ifdef ALBEDO
,in vec4 albedoTexture
,in vec2 albedoInfos
#endif
,in float baseWeight
#ifdef BASEWEIGHT
,in vec4 baseWeightTexture
,in vec2 vBaseWeightInfos
#endif
#ifdef OPACITY
,in vec4 opacityMap
,in vec2 vOpacityInfos
#endif
#ifdef DETAIL
,in vec4 detailColor
,in vec4 vDetailInfos
#endif
#ifdef DECAL
,in vec4 decalColor
,in vec4 vDecalInfos
#endif
)
{albedoOpacityOutParams outParams;vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;
#ifdef ALBEDO
#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)
alpha*=albedoTexture.a;
#endif
#ifdef GAMMAALBEDO
surfaceAlbedo*=toLinearSpace(albedoTexture.rgb);
#else
surfaceAlbedo*=albedoTexture.rgb;
#endif
surfaceAlbedo*=albedoInfos.y;
#endif
#ifndef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)
surfaceAlbedo*=vColor.rgb;
#endif
#ifdef DETAIL
float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; 
#endif
#ifdef DECAL_AFTER_DETAIL
#include<decalFragment>
#endif
#define CUSTOM_FRAGMENT_UPDATE_ALBEDO
surfaceAlbedo*=baseWeight;
#ifdef BASEWEIGHT
surfaceAlbedo*=baseWeightTexture.r;
#endif
#ifdef OPACITY
#ifdef OPACITYRGB
alpha=getLuminance(opacityMap.rgb);
#else
alpha*=opacityMap.a;
#endif
alpha*=vOpacityInfos.y;
#endif
#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)
alpha*=vColor.a;
#endif
#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)
#ifdef ALPHATEST
#if DEBUGMODE != 88
if (alpha<ALPHATESTVALUE)
discard;
#endif
#ifndef ALPHABLEND
alpha=1.0;
#endif
#endif
#endif
outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;}
`;
var init_pbrBlockAlbedoOpacity2 = __esm(() => {
  init_shaderStore();
  init_decalFragment2();
  if (!ShaderStore.IncludesShadersStore[name301]) {
    ShaderStore.IncludesShadersStore[name301] = shader300;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectivity.js
var name302 = "pbrBlockReflectivity", shader301 = `struct reflectivityOutParams
{float microSurface;float roughness;vec3 surfaceReflectivityColor;
#ifdef METALLICWORKFLOW
vec3 surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
vec3 ambientOcclusionColor;
#endif
#if DEBUGMODE>0
#ifdef METALLICWORKFLOW
vec2 metallicRoughness;
#ifdef REFLECTIVITY
vec4 surfaceMetallicColorMap;
#endif
#ifndef FROSTBITE_REFLECTANCE
vec3 metallicF0;
#endif
#else
#ifdef REFLECTIVITY
vec4 surfaceReflectivityColorMap;
#endif
#endif
#endif
};
#define pbr_inline
reflectivityOutParams reflectivityBlock(
in vec4 vReflectivityColor
#ifdef METALLICWORKFLOW
,in vec3 surfaceAlbedo
,in vec4 metallicReflectanceFactors
#endif
#ifdef REFLECTIVITY
,in vec3 reflectivityInfos
,in vec4 surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,in vec3 ambientOcclusionColorIn
#endif
#ifdef MICROSURFACEMAP
,in vec4 microSurfaceTexel
#endif
#ifdef DETAIL
,in vec4 detailColor
,in vec4 vDetailInfos
#endif
)
{reflectivityOutParams outParams;float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec2 metallicRoughness=surfaceReflectivityColor.rg;
#ifdef REFLECTIVITY
#if DEBUGMODE>0
outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef AOSTOREINMETALMAPRED
vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);
#endif
#ifdef METALLNESSSTOREINMETALMAPBLUE
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;
#else
metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;
#endif
#ifdef ROUGHNESSSTOREINMETALMAPALPHA
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;
#else
#ifdef ROUGHNESSSTOREINMETALMAPGREEN
metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;
#endif
#endif
#endif
#ifdef DETAIL
float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));
#endif
#ifdef MICROSURFACEMAP
metallicRoughness.g*=microSurfaceTexel.r;
#endif
#if DEBUGMODE>0
outParams.metallicRoughness=metallicRoughness;
#endif
#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS
microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;
#ifdef FROSTBITE_REFLECTANCE
outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);
#else
vec3 metallicF0=metallicReflectanceFactors.rgb;
#if DEBUGMODE>0
outParams.metallicF0=metallicF0;
#endif
outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);
#endif
#else
#ifdef REFLECTIVITY
surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;
#if DEBUGMODE>0
outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;
#endif
#ifdef MICROSURFACEFROMREFLECTIVITYMAP
microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;
#else
#ifdef MICROSURFACEAUTOMATIC
microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);
#endif
#ifdef MICROSURFACEMAP
microSurface*=microSurfaceTexel.r;
#endif
#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE
#endif
#endif
#endif
microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;return outParams;}
`;
var init_pbrBlockReflectivity2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name302]) {
    ShaderStore.IncludesShadersStore[name302] = shader301;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAmbientOcclusion.js
var name303 = "pbrBlockAmbientOcclusion", shader302 = `struct ambientOcclusionOutParams
{vec3 ambientOcclusionColor;
#if DEBUGMODE>0 && defined(AMBIENT)
vec3 ambientOcclusionColorMap;
#endif
};ambientOcclusionOutParams ambientOcclusionBlock(
#ifdef AMBIENT
in vec3 ambientOcclusionColorMap_,
in vec4 vAmbientInfos
#endif
)
{ambientOcclusionOutParams outParams;vec3 ambientOcclusionColor=vec3(1.,1.,1.);
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;
#ifdef AMBIENTINGRAYSCALE
ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);
#endif
ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);
#if DEBUGMODE>0
outParams.ambientOcclusionColorMap=ambientOcclusionColorMap;
#endif
#endif
outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;}
`;
var init_pbrBlockAmbientOcclusion2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name303]) {
    ShaderStore.IncludesShadersStore[name303] = shader302;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlphaFresnel.js
var name304 = "pbrBlockAlphaFresnel", shader303 = `#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
struct alphaFresnelOutParams
{float alpha;};
#define pbr_inline
alphaFresnelOutParams alphaFresnelBlock(
in vec3 normalW,
in vec3 viewDirectionW,
in float alpha,
in float microSurface
)
{alphaFresnelOutParams outParams;float opacityPerceptual=alpha;
#ifdef LINEARALPHAFRESNEL
float opacity0=opacityPerceptual;
#else
float opacity0=opacityPerceptual*opacityPerceptual;
#endif
float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;
#ifdef ALPHATEST
if (outParams.alpha<ALPHATESTVALUE)
discard;
#ifndef ALPHABLEND
outParams.alpha=1.0;
#endif
#endif
return outParams;}
#endif
#endif
`;
var init_pbrBlockAlphaFresnel2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name304]) {
    ShaderStore.IncludesShadersStore[name304] = shader303;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAnisotropic.js
var name305 = "pbrBlockAnisotropic", shader304 = `#ifdef ANISOTROPIC
struct anisotropicOutParams
{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;
#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)
vec3 anisotropyMapData;
#endif
};
#define pbr_inline
anisotropicOutParams anisotropicBlock(
in vec3 vAnisotropy,
in float roughness,
#ifdef ANISOTROPIC_TEXTURE
in vec3 anisotropyMapData,
#endif
in mat3 TBN,
in vec3 normalW,
in vec3 viewDirectionW
)
{anisotropicOutParams outParams;float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);
#ifdef ANISOTROPIC_TEXTURE
anisotropy*=anisotropyMapData.b;
#if DEBUGMODE>0
outParams.anisotropyMapData=anisotropyMapData;
#endif
anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;
#ifdef ANISOTROPIC_LEGACY
anisotropyDirection.rg*=anisotropyMapData.rg;
#else
anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);
#endif
#endif
mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;}
#endif
`;
var init_pbrBlockAnisotropic2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name305]) {
    ShaderStore.IncludesShadersStore[name305] = shader304;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflection.js
var name306 = "pbrBlockReflection", shader305 = `#ifdef REFLECTION
struct reflectionOutParams
{vec4 environmentRadiance;vec3 environmentIrradiance;
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords;
#else
vec2 reflectionCoords;
#endif
#ifdef SS_TRANSLUCENCY
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
vec3 irradianceVector;
#endif
#endif
#endif
};
#define pbr_inline
void createReflectionCoords(
in vec3 vPositionW,
in vec3 normalW,
#ifdef ANISOTROPIC
in anisotropicOutParams anisotropicOut,
#endif
#ifdef REFLECTIONMAP_3D
out vec3 reflectionCoords
#else
out vec2 reflectionCoords
#endif
)
{
#ifdef ANISOTROPIC
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);
#else
vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
reflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
reflectionCoords=reflectionVector;
#else
reflectionCoords=reflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
reflectionCoords/=reflectionVector.z;
#endif
reflectionCoords.y=1.0-reflectionCoords.y;
#endif
}
#define pbr_inline
#define inline
void sampleReflectionTexture(
in float alphaG,
in vec3 vReflectionMicrosurfaceInfos,
in vec2 vReflectionInfos,
in vec3 vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
in float NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
in float roughness,
#endif
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSampler,
const vec3 reflectionCoords,
#else
in sampler2D reflectionSampler,
const vec2 reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
in samplerCube reflectionSamplerLow,
in samplerCube reflectionSamplerHigh,
#else
in sampler2D reflectionSamplerLow,
in sampler2D reflectionSamplerHigh,
#endif
#endif
#ifdef REALTIME_FILTERING
in vec2 vReflectionFilteringInfo,
#endif
out vec4 environmentRadiance
)
{
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);
#elif defined(LINEARSPECULARREFLECTION)
float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);
#else
float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);
#endif
#ifdef LODBASEDMICROSFURACE
reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;
#ifdef LODINREFLECTIONALPHA
float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);
#else
float requestedReflectionLOD=reflectionLOD;
#endif
#ifdef REALTIME_FILTERING
environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);
#else
environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);
#endif
#else
float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(
sampleReflection(reflectionSamplerHigh,reflectionCoords),
environmentMid,
lodReflectionNormalizedDoubled
);} else {environmentRadiance=mix(
environmentMid,
sampleReflection(reflectionSamplerLow,reflectionCoords),
lodReflectionNormalizedDoubled-1.0
);}
#endif
#ifdef RGBDREFLECTION
environmentRadiance.rgb=fromRGBD(environmentRadiance);
#endif
#ifdef GAMMAREFLECTION
environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);
#endif
environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}
#define pbr_inline
#define inline
reflectionOutParams reflectionBlock(
in vec3 vPositionW
,in vec3 normalW
,in float alphaG
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,in float NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,in float roughness
#endif
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
#else
,in sampler2D reflectionSampler
#endif
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,in vec3 vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,in mat4 reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,in samplerCube irradianceSampler
#else
,in sampler2D irradianceSampler
#endif
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,in sampler2D icdfSampler
#endif
#endif
)
{reflectionOutParams outParams;vec4 environmentRadiance=vec4(0.,0.,0.,0.);
#ifdef REFLECTIONMAP_3D
vec3 reflectionCoords=vec3(0.);
#else
vec2 reflectionCoords=vec2(0.);
#endif
createReflectionCoords(
vPositionW,
normalW,
#ifdef ANISOTROPIC
anisotropicOut,
#endif
reflectionCoords
);sampleReflectionTexture(
alphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
roughness,
#endif
#ifdef REFLECTIONMAP_3D
reflectionSampler,
reflectionCoords,
#else
reflectionSampler,
reflectionCoords,
#endif
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentRadiance
);vec3 environmentIrradiance=vec3(0.,0.,0.);
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
#ifdef ANISOTROPIC
vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;
#else
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#endif
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#endif
#ifdef USESPHERICALFROMREFLECTIONMAP
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
environmentIrradiance=vEnvironmentIrradiance;
#else
#if defined(REALTIME_FILTERING)
environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
);
#else
environmentIrradiance=computeEnvironmentIrradiance(irradianceVector);
#endif
#ifdef SS_TRANSLUCENCY
outParams.irradianceVector=irradianceVector;
#endif
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,irradianceVector);
#else
vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);
#endif
environmentIrradiance=environmentIrradiance4.rgb;
#ifdef RGBDREFLECTION
environmentIrradiance.rgb=fromRGBD(environmentIrradiance4);
#endif
#ifdef GAMMAREFLECTION
environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);
#endif
#endif
environmentIrradiance*=vReflectionColor.rgb*vReflectionInfos.x;
#ifdef MIX_IBL_RADIANCE_WITH_IRRADIANCE
outParams.environmentRadiance=vec4(mix(environmentRadiance.rgb,environmentIrradiance,alphaG),environmentRadiance.a);
#else
outParams.environmentRadiance=environmentRadiance;
#endif
outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;}
#endif
`;
var init_pbrBlockReflection2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name306]) {
    ShaderStore.IncludesShadersStore[name306] = shader305;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSheen.js
var name307 = "pbrBlockSheen", shader306 = `#ifdef SHEEN
struct sheenOutParams
{float sheenIntensity;vec3 sheenColor;float sheenRoughness;
#ifdef SHEEN_LINKWITHALBEDO
vec3 surfaceAlbedo;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
float sheenAlbedoScaling;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 finalSheenRadianceScaled;
#endif
#if DEBUGMODE>0
#ifdef SHEEN_TEXTURE
vec4 sheenMapData;
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
vec3 sheenEnvironmentReflectance;
#endif
#endif
};
#define pbr_inline
#define inline
sheenOutParams sheenBlock(
in vec4 vSheenColor
#ifdef SHEEN_ROUGHNESS
,in float vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,in vec4 sheenMapRoughnessData
#endif
#endif
,in float roughness
#ifdef SHEEN_TEXTURE
,in vec4 sheenMapData
,in float sheenMapLevel
#endif
,in float reflectance
#ifdef SHEEN_LINKWITHALBEDO
,in vec3 baseColor
,in vec3 surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,in float NdotV
,in vec3 environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,in vec2 AARoughnessFactors
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
,in vec4 vLightingIntensity
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
,in vec3 reflectionCoords
#else
,in sampler2D reflectionSampler
,in vec2 reflectionCoords
#endif
,in float NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,in float seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,in float eho
#endif
#endif
)
{sheenOutParams outParams;float sheenIntensity=vSheenColor.a;
#ifdef SHEEN_TEXTURE
#if DEBUGMODE>0
outParams.sheenMapData=sheenMapData;
#endif
#endif
#ifdef SHEEN_LINKWITHALBEDO
float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#else
vec3 sheenColor=vSheenColor.rgb;
#ifdef SHEEN_TEXTURE
#ifdef SHEEN_GAMMATEXTURE
sheenColor.rgb*=toLinearSpace(sheenMapData.rgb);
#else
sheenColor.rgb*=sheenMapData.rgb;
#endif
sheenColor.rgb*=sheenMapLevel;
#endif
#ifdef SHEEN_ROUGHNESS
float sheenRoughness=vSheenRoughness;
#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE
#if defined(SHEEN_TEXTURE)
sheenRoughness*=sheenMapData.a;
#endif
#elif defined(SHEEN_TEXTURE_ROUGHNESS)
sheenRoughness*=sheenMapRoughnessData.a;
#endif
#else
float sheenRoughness=roughness;
#ifdef SHEEN_TEXTURE
sheenIntensity*=sheenMapData.a;
#endif
#endif
#if !defined(SHEEN_ALBEDOSCALING)
sheenIntensity*=(1.-reflectance);
#endif
sheenColor*=sheenIntensity;
#endif
#ifdef ENVIRONMENTBRDF
/*#ifdef SHEEN_SOFTER
vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));
#else*/
#ifdef SHEEN_ROUGHNESS
vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);
#else
vec3 environmentSheenBrdf=environmentBrdf;
#endif
/*#endif*/
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);
#ifdef SPECULARAA
sheenAlphaG+=AARoughnessFactors.y;
#endif
vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(
sheenAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
NdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
sheenRoughness,
#endif
reflectionSampler,
reflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentSheenRadiance
);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
sheenEnvironmentReflectance*=seo;
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
sheenEnvironmentReflectance*=eho;
#endif
#if DEBUGMODE>0
outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;
#endif
outParams.finalSheenRadianceScaled=
environmentSheenRadiance.rgb *
sheenEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;
#endif
outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;}
#endif
`;
var init_pbrBlockSheen2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name307]) {
    ShaderStore.IncludesShadersStore[name307] = shader306;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockClearcoat.js
var name308 = "pbrBlockClearcoat", shader307 = `struct clearcoatOutParams
{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;
#ifdef REFLECTION
vec3 finalClearCoatRadianceScaled;
#endif
#ifdef CLEARCOAT_TINT
vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;
#endif
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
vec3 energyConservationFactorClearCoat;
#endif
#if DEBUGMODE>0
#ifdef CLEARCOAT_BUMP
mat3 TBNClearCoat;
#endif
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData;
#endif
#ifdef REFLECTION
vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;
#endif
float clearCoatNdotV;
#endif
};
#ifdef CLEARCOAT
#define pbr_inline
#define inline
clearcoatOutParams clearcoatBlock(
in vec3 vPositionW
,in vec3 geometricNormalW
,in vec3 viewDirectionW
,in vec2 vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,in vec4 clearCoatMapRoughnessData
#endif
,in vec3 specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,in vec2 clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,in vec4 vClearCoatTintParams
,in float clearCoatColorAtDistance
,in vec4 vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,in vec4 clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,in vec2 vClearCoatBumpInfos
,in vec4 clearCoatBumpMapData
,in vec2 vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,in mat3 vTBN
#else
,in vec2 vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,in mat4 normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,in vec3 faceNormal
#endif
#ifdef REFLECTION
,in vec3 vReflectionMicrosurfaceInfos
,in vec2 vReflectionInfos
,in vec3 vReflectionColor
,in vec4 vLightingIntensity
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSampler
#else
,in sampler2D reflectionSampler
#endif
#ifndef LODBASEDMICROSFURACE
#ifdef REFLECTIONMAP_3D
,in samplerCube reflectionSamplerLow
,in samplerCube reflectionSamplerHigh
#else
,in sampler2D reflectionSamplerLow
,in sampler2D reflectionSamplerHigh
#endif
#endif
#ifdef REALTIME_FILTERING
,in vec2 vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,in float frontFacingMultiplier
#endif
)
{clearcoatOutParams outParams;float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE
clearCoatRoughness*=clearCoatMapData.y;
#endif
#if DEBUGMODE>0
outParams.clearCoatMapData=clearCoatMapData;
#endif
#endif
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
clearCoatRoughness*=clearCoatMapRoughnessData.y;
#endif
outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;
#ifdef CLEARCOAT_TINT
vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;
#ifdef CLEARCOAT_TINT_TEXTURE
#ifdef CLEARCOAT_TINT_GAMMATEXTURE
clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);
#else
clearCoatColor*=clearCoatTintMapData.rgb;
#endif
clearCoatThickness*=clearCoatTintMapData.a;
#if DEBUGMODE>0
outParams.clearCoatTintMapData=clearCoatTintMapData;
#endif
#endif
outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;
#endif
#ifdef CLEARCOAT_REMAP_F0
vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);
#else
vec3 specularEnvironmentR0Updated=specularEnvironmentR0;
#endif
outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;
#ifdef CLEARCOAT_BUMP
#ifdef NORMALXYSCALE
float clearCoatNormalScale=1.0;
#else
float clearCoatNormalScale=vClearCoatBumpInfos.y;
#endif
#if defined(TANGENT) && defined(NORMAL)
mat3 TBNClearCoat=vTBN;
#else
vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);
#endif
#if DEBUGMODE>0
outParams.TBNClearCoat=TBNClearCoat;
#endif
#ifdef OBJECTSPACE_NORMALMAP
clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);
#else
clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;
#endif
outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);
#if DEBUGMODE>0
outParams.clearCoatNdotV=clearCoatNdotV;
#endif
#ifdef CLEARCOAT_TINT
vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));
#endif
#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))
vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);
#endif
#if defined(REFLECTION)
float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);
#ifdef SPECULARAA
clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;
#endif
vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);
#ifdef REFLECTIONMAP_OPPOSITEZ
clearCoatReflectionVector.z*=-1.0;
#endif
#ifdef REFLECTIONMAP_3D
vec3 clearCoatReflectionCoords=clearCoatReflectionVector;
#else
vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
clearCoatReflectionCoords/=clearCoatReflectionVector.z;
#endif
clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;
#endif
sampleReflectionTexture(
clearCoatAlphaG,
vReflectionMicrosurfaceInfos,
vReflectionInfos,
vReflectionColor,
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
clearCoatNdotVUnclamped,
#endif
#ifdef LINEARSPECULARREFLECTION
clearCoatRoughness,
#endif
reflectionSampler,
clearCoatReflectionCoords,
#ifndef LODBASEDMICROSFURACE
reflectionSamplerLow,
reflectionSamplerHigh,
#endif
#ifdef REALTIME_FILTERING
vReflectionFilteringInfo,
#endif
environmentClearCoatRadiance
);
#if DEBUGMODE>0
outParams.environmentClearCoatRadiance=environmentClearCoatRadiance;
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;
#endif
#endif
#endif
#else
vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));
#endif
clearCoatEnvironmentReflectance*=clearCoatIntensity;
#if DEBUGMODE>0
outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;
#endif
outParams.finalClearCoatRadianceScaled=
environmentClearCoatRadiance.rgb *
clearCoatEnvironmentReflectance *
vLightingIntensity.z;
#endif
#if defined(CLEARCOAT_TINT)
outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);
#endif
float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);
#endif
return outParams;}
#endif
`;
var init_pbrBlockClearcoat2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name308]) {
    ShaderStore.IncludesShadersStore[name308] = shader307;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockIridescence.js
var name309 = "pbrBlockIridescence", shader308 = `struct iridescenceOutParams
{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};
#ifdef IRIDESCENCE
#define pbr_inline
#define inline
iridescenceOutParams iridescenceBlock(
in vec4 vIridescenceParams
,in float viewAngle
,in vec3 specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,in vec2 iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,in vec2 iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,in float NdotVUnclamped
,in vec2 vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,in vec2 clearCoatMapData
#endif
#endif
)
{iridescenceOutParams outParams;float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;
#ifdef IRIDESCENCE_TEXTURE
iridescenceIntensity*=iridescenceMapData.x;
#endif
#if defined(IRIDESCENCE_THICKNESS_TEXTURE)
iridescenceThicknessWeight=iridescenceThicknessMapData.g;
#endif
float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; 
#ifdef CLEARCOAT
float clearCoatIntensity=vClearCoatParams.x;
#ifdef CLEARCOAT_TEXTURE
clearCoatIntensity*=clearCoatMapData.x;
#endif
topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));
#endif
vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;}
#endif
`;
var init_pbrBlockIridescence2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name309]) {
    ShaderStore.IncludesShadersStore[name309] = shader308;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSubSurface.js
var name310 = "pbrBlockSubSurface", shader309 = `struct subSurfaceOutParams
{vec3 specularEnvironmentReflectance;
#ifdef SS_REFRACTION
vec3 finalRefraction;vec3 surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
float alpha;
#endif
#ifdef REFLECTION
float refractionFactorForIrradiance;
#endif
#endif
#ifdef SS_TRANSLUCENCY
vec3 transmittance;float translucencyIntensity;
#ifdef REFLECTION
vec3 refractionIrradiance;
#endif
#endif
#if DEBUGMODE>0
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction;vec3 refractionTransmittance;
#endif
#endif
};
#ifdef SUBSURFACE
#ifdef SS_REFRACTION
#define pbr_inline
#define inline
vec4 sampleEnvironmentRefraction(
in float ior
,in float thickness
,in float refractionLOD
,in vec3 normalW
,in vec3 vPositionW
,in vec3 viewDirectionW
,in mat4 view
,in vec4 vRefractionInfos
,in mat4 refractionMatrix
,in vec4 vRefractionMicrosurfaceInfos
,in float alphaG
#ifdef SS_REFRACTIONMAP_3D
,in samplerCube refractionSampler
#ifndef LODBASEDMICROSFURACE
,in samplerCube refractionSamplerLow
,in samplerCube refractionSamplerHigh
#endif
#else
,in sampler2D refractionSampler
#ifndef LODBASEDMICROSFURACE
,in sampler2D refractionSamplerLow
,in sampler2D refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,in vec2 vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,in vec3 refractionPosition
,in vec3 refractionSize
#endif
) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef ANISOTROPIC
vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);
#else
vec3 refractionVector=refract(-viewDirectionW,normalW,ior);
#endif
#ifdef SS_REFRACTIONMAP_OPPOSITEZ
refractionVector.z*=-1.0;
#endif
#ifdef SS_REFRACTIONMAP_3D
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);
#endif
refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));
#else
#ifdef SS_USE_THICKNESS_AS_DEPTH
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));
#else
vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));
#endif
vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;
#endif
#ifdef LODBASEDMICROSFURACE
refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;
#ifdef SS_LODINREFRACTIONALPHA
float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);
#else
float requestedRefractionLOD=refractionLOD;
#endif
#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)
environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);
#else
environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);
#endif
#else
float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(
sampleRefraction(refractionSamplerHigh,refractionCoords),
environmentRefractionMid,
lodRefractionNormalizedDoubled
);} else {environmentRefraction=mix(
environmentRefractionMid,
sampleRefraction(refractionSamplerLow,refractionCoords),
lodRefractionNormalizedDoubled-1.0
);}
#endif
#ifdef SS_RGBDREFRACTION
environmentRefraction.rgb=fromRGBD(environmentRefraction);
#endif
#ifdef SS_GAMMAREFRACTION
environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);
#endif
return environmentRefraction;}
#endif
#define pbr_inline
#define inline
subSurfaceOutParams subSurfaceBlock(
in vec3 vSubSurfaceIntensity
,in vec2 vThicknessParam
,in vec4 vTintColor
,in vec3 normalW
,in vec3 specularEnvironmentReflectance
#ifdef SS_THICKNESSANDMASK_TEXTURE
,in vec4 thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,in vec4 refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,in vec4 translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,in mat4 reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,in vec3 irradianceVector_
#endif
#if defined(REALTIME_FILTERING)
,in samplerCube reflectionSampler
,in vec2 vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,in sampler2D icdfSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
#ifdef REFLECTIONMAP_3D
,in samplerCube irradianceSampler
#else
,in sampler2D irradianceSampler
#endif
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,in vec3 surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,in vec3 vPositionW
,in vec3 viewDirectionW
,in mat4 view
,in vec4 vRefractionInfos
,in mat4 refractionMatrix
,in vec4 vRefractionMicrosurfaceInfos
,in vec4 vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,in float alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,in float NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,in float roughness
#endif
,in float alphaG
#ifdef SS_REFRACTIONMAP_3D
,in samplerCube refractionSampler
#ifndef LODBASEDMICROSFURACE
,in samplerCube refractionSamplerLow
,in samplerCube refractionSamplerHigh
#endif
#else
,in sampler2D refractionSampler
#ifndef LODBASEDMICROSFURACE
,in sampler2D refractionSamplerLow
,in sampler2D refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,in anisotropicOutParams anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,in vec2 vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,in vec3 refractionPosition
,in vec3 refractionSize
#endif
#ifdef SS_DISPERSION
,in float dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,in vec3 vDiffusionDistance
,in vec4 vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,in vec4 translucencyColorMap
#endif
#endif
)
{subSurfaceOutParams outParams;outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;
#ifdef SS_REFRACTION
float refractionIntensity=vSubSurfaceIntensity.x;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
refractionIntensity*=(1.0-alpha);outParams.alpha=1.0;
#endif
#endif
#ifdef SS_TRANSLUCENCY
float translucencyIntensity=vSubSurfaceIntensity.y;
#endif
#ifdef SS_THICKNESSANDMASK_TEXTURE
#ifdef SS_USE_GLTF_TEXTURES
float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;
#else
float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;
#endif
#if DEBUGMODE>0
outParams.thicknessMap=thicknessMap;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=thicknessMap.r;
#else
refractionIntensity*=thicknessMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=thicknessMap.a;
#else
translucencyIntensity*=thicknessMap.b;
#endif
#endif
#else
float thickness=vThicknessParam.y;
#endif
#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
refractionIntensity*=refractionIntensityMap.r;
#else
refractionIntensity*=refractionIntensityMap.g;
#endif
#endif
#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)
#ifdef SS_USE_GLTF_TEXTURES
translucencyIntensity*=translucencyIntensityMap.a;
#else
translucencyIntensity*=translucencyIntensityMap.b;
#endif
#endif
#ifdef SS_TRANSLUCENCY
thickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor;
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
translucencyColor*=translucencyColorMap;
#endif
vec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;
#endif
#ifdef SS_REFRACTION
vec4 environmentRefraction=vec4(0.,0.,0.,0.);
#ifdef SS_HAS_THICKNESS
float ior=vRefractionInfos.y;
#else
float ior=vRefractionMicrosurfaceInfos.w;
#endif
#ifdef SS_LODINREFRACTIONALPHA
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);
#elif defined(SS_LINEARSPECULARREFRACTION)
float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);
#else
float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);
#endif
float refraction_ior=vRefractionInfos.y;
#ifdef SS_DISPERSION
float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];
#endif
vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG
#ifdef SS_REFRACTIONMAP_3D
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#else
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,refractionPosition
,refractionSize
#endif
);
#ifdef SS_DISPERSION
environmentRefraction[i]=envSample[i];}
#else
environmentRefraction=envSample;
#endif
environmentRefraction.rgb*=vRefractionInfos.x;
#endif
#ifdef SS_REFRACTION
vec3 refractionTransmittance=vec3(refractionIntensity);
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);
#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)
float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;
#else
vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);
#endif
#ifdef SS_ALBEDOFORREFRACTIONTINT
environmentRefraction.rgb*=surfaceAlbedo.rgb;
#endif
outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);
#ifdef REFLECTION
outParams.refractionFactorForIrradiance=(1.-refractionIntensity);
#endif
#ifdef UNUSED_MULTIPLEBOUNCES
vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);
#endif
refractionTransmittance*=1.0-max(outParams.specularEnvironmentReflectance.r,max(outParams.specularEnvironmentReflectance.g,outParams.specularEnvironmentReflectance.b));
#if DEBUGMODE>0
outParams.refractionTransmittance=refractionTransmittance;
#endif
outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;
#if DEBUGMODE>0
outParams.environmentRefraction=environmentRefraction;
#endif
#endif
#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)
#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)
vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;
#ifdef REFLECTIONMAP_OPPOSITEZ
irradianceVector.z*=-1.0;
#endif
#ifdef INVERTCUBICMAP
irradianceVector.y*=-1.0;
#endif
#else
vec3 irradianceVector=irradianceVector_;
#endif
#if defined(USESPHERICALFROMREFLECTIONMAP)
#if defined(REALTIME_FILTERING)
vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
);
#else
vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);
#endif
#elif defined(USEIRRADIANCEMAP)
#ifdef REFLECTIONMAP_3D
vec3 irradianceCoords=irradianceVector;
#else
vec2 irradianceCoords=irradianceVector.xy;
#ifdef REFLECTIONMAP_PROJECTION
irradianceCoords/=irradianceVector.z;
#endif
irradianceCoords.y=1.0-irradianceCoords.y;
#endif
vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);
#ifdef RGBDREFLECTION
refractionIrradiance.rgb=fromRGBD(refractionIrradiance);
#endif
#ifdef GAMMAREFLECTION
refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);
#endif
#else
vec4 refractionIrradiance=vec4(0.);
#endif
refractionIrradiance.rgb*=transmittance;
#ifdef SS_ALBEDOFORTRANSLUCENCYTINT
refractionIrradiance.rgb*=surfaceAlbedo.rgb;
#endif
outParams.refractionIrradiance=refractionIrradiance.rgb;
#endif
return outParams;}
#endif
`;
var init_pbrBlockSubSurface2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name310]) {
    ShaderStore.IncludesShadersStore[name310] = shader309;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalGeometric.js
var name311 = "pbrBlockNormalGeometric", shader310 = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);
#ifdef NORMAL
vec3 normalW=normalize(vNormalW);
#else
vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#endif
vec3 geometricNormalW=normalW;
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;
#endif
`;
var init_pbrBlockNormalGeometric2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name311]) {
    ShaderStore.IncludesShadersStore[name311] = shader310;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalFinal.js
var name312 = "pbrBlockNormalFinal", shader311 = `#if defined(FORCENORMALFORWARD) && defined(NORMAL)
vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;
#if defined(TWOSIDEDLIGHTING)
faceNormal=gl_FrontFacing ? faceNormal : -faceNormal;
#endif
normalW*=sign(dot(normalW,faceNormal));
#endif
#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)
normalW=gl_FrontFacing ? normalW : -normalW;
#endif
`;
var init_pbrBlockNormalFinal2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name312]) {
    ShaderStore.IncludesShadersStore[name312] = shader311;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockLightmapInit.js
var name313 = "pbrBlockLightmapInit", shader312 = `#ifdef LIGHTMAP
vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);
#ifdef RGBDLIGHTMAP
lightmapColor.rgb=fromRGBD(lightmapColor);
#endif
#ifdef GAMMALIGHTMAP
lightmapColor.rgb=toLinearSpace(lightmapColor.rgb);
#endif
lightmapColor.rgb*=vLightmapInfos.y;
#endif
`;
var init_pbrBlockLightmapInit2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name313]) {
    ShaderStore.IncludesShadersStore[name313] = shader312;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockGeometryInfo.js
var name314 = "pbrBlockGeometryInfo", shader313 = `float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);
#ifdef SPECULARAA
alphaG+=AARoughnessFactors.y;
#endif
#if defined(ENVIRONMENTBRDF)
vec3 environmentBrdf=getBRDFLookup(NdotV,roughness);
#endif
#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
#ifdef RADIANCEOCCLUSION
#ifdef AMBIENTINGRAYSCALE
float ambientMonochrome=aoOut.ambientOcclusionColor.r;
#else
float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);
#endif
float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);
#endif
#endif
#endif
#endif
`;
var init_pbrBlockGeometryInfo2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name314]) {
    ShaderStore.IncludesShadersStore[name314] = shader313;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance0.js
var name315 = "pbrBlockReflectance0", shader314 = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;
#ifdef METALLICWORKFLOW
vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);
#else 
vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);
#endif
#ifdef ALPHAFRESNEL
float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;
#endif
`;
var init_pbrBlockReflectance02 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name315]) {
    ShaderStore.IncludesShadersStore[name315] = shader314;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance.js
var name316 = "pbrBlockReflectance", shader315 = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);
#ifdef RADIANCEOCCLUSION
specularEnvironmentReflectance*=seo;
#endif
#ifdef HORIZONOCCLUSION
#ifdef BUMP
#ifdef REFLECTIONMAP_3D
specularEnvironmentReflectance*=eho;
#endif
#endif
#endif
#else
vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));
#endif
#ifdef CLEARCOAT
specularEnvironmentReflectance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
specularEnvironmentReflectance*=clearcoatOut.absorption;
#endif
#endif
`;
var init_pbrBlockReflectance2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name316]) {
    ShaderStore.IncludesShadersStore[name316] = shader315;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockDirectLighting.js
var name317 = "pbrBlockDirectLighting", shader316 = `vec3 diffuseBase=vec3(0.,0.,0.);
#ifdef SPECULARTERM
vec3 specularBase=vec3(0.,0.,0.);
#endif
#ifdef CLEARCOAT
vec3 clearCoatBase=vec3(0.,0.,0.);
#endif
#ifdef SHEEN
vec3 sheenBase=vec3(0.,0.,0.);
#endif
preLightingInfo preInfo;lightingInfo info;float shadow=1.; 
float aggShadow=0.;float numLights=0.;
#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
vec3 absorption=vec3(0.);
#endif
`;
var init_pbrBlockDirectLighting2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name317]) {
    ShaderStore.IncludesShadersStore[name317] = shader316;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalLitComponents.js
var name318 = "pbrBlockFinalLitComponents", shader317 = `aggShadow=aggShadow/numLights;
#if defined(ENVIRONMENTBRDF)
#ifdef MS_BRDF_ENERGY_CONSERVATION
vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);
#endif
#endif
#ifndef METALLICWORKFLOW
#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION
surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;
#endif
#endif
#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)
surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;
#endif
#ifdef REFLECTION
vec3 finalIrradiance=reflectionOut.environmentIrradiance;
#if defined(CLEARCOAT)
finalIrradiance*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
finalIrradiance*=clearcoatOut.absorption;
#endif
#endif
finalIrradiance*=surfaceAlbedo.rgb;
#if defined(SS_REFRACTION)
finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;
#endif
#if defined(SS_TRANSLUCENCY)
finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;
#endif
finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;
#endif
#ifdef SPECULARTERM
vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalSpecularScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalSpecularScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef REFLECTION
vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalRadianceScaled*=energyConservationFactor;
#endif
#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)
finalRadianceScaled*=sheenOut.sheenAlbedoScaling;
#endif
#endif
#ifdef SHEEN
vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;
#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;
#if defined(CLEARCOAT_TINT)
sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef CLEARCOAT
vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;
#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)
finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;
#ifdef CLEARCOAT_TINT
subSurfaceOut.finalRefraction*=clearcoatOut.absorption;
#endif
#endif
#endif
#ifdef ALPHABLEND
float luminanceOverAlpha=0.0;
#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)
luminanceOverAlpha+=getLuminance(finalRadianceScaled);
#if defined(CLEARCOAT)
luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);
#endif
#endif
#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)
luminanceOverAlpha+=getLuminance(finalSpecularScaled);
#endif
#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)
luminanceOverAlpha+=getLuminance(finalClearCoatScaled);
#endif
#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)
alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);
#endif
#endif
`;
var init_pbrBlockFinalLitComponents2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name318]) {
    ShaderStore.IncludesShadersStore[name318] = shader317;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalUnlitComponents.js
var name319 = "pbrBlockFinalUnlitComponents", shader318 = `vec3 finalDiffuse=diffuseBase;
#if !defined(SS_TRANSLUCENCY)
finalDiffuse*=surfaceAlbedo.rgb;
#endif
finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;
#ifdef EMISSIVE
vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;
#ifdef GAMMAEMISSIVE
finalEmissive*=toLinearSpace(emissiveColorTex.rgb);
#else
finalEmissive*=emissiveColorTex.rgb;
#endif
finalEmissive*= vEmissiveInfos.y;
#endif
finalEmissive*=vLightingIntensity.y;
#ifdef AMBIENT
vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);
#else
vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;
#endif
finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;
`;
var init_pbrBlockFinalUnlitComponents2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name319]) {
    ShaderStore.IncludesShadersStore[name319] = shader318;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalColorComposition.js
var name320 = "pbrBlockFinalColorComposition", shader319 = `vec4 finalColor=vec4(
#ifndef UNLIT
#ifdef REFLECTION
finalIrradiance +
#endif
#ifdef SPECULARTERM
finalSpecularScaled +
#endif
#ifdef SHEEN
finalSheenScaled +
#endif
#ifdef CLEARCOAT
finalClearCoatScaled +
#endif
#ifdef REFLECTION
finalRadianceScaled +
#if defined(SHEEN) && defined(ENVIRONMENTBRDF)
sheenOut.finalSheenRadianceScaled +
#endif
#ifdef CLEARCOAT
clearcoatOut.finalClearCoatRadianceScaled +
#endif
#endif
#ifdef SS_REFRACTION
subSurfaceOut.finalRefraction +
#endif
#endif
finalAmbient +
finalDiffuse,
alpha);
#ifdef LIGHTMAP
#ifndef LIGHTMAPEXCLUDED
#ifdef USELIGHTMAPASSHADOWMAP
finalColor.rgb*=lightmapColor.rgb;
#else
finalColor.rgb+=lightmapColor.rgb;
#endif
#endif
#endif
finalColor.rgb+=finalEmissive;
#define CUSTOM_FRAGMENT_BEFORE_FOG
finalColor=max(finalColor,0.0);
`;
var init_pbrBlockFinalColorComposition2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name320]) {
    ShaderStore.IncludesShadersStore[name320] = shader319;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockImageProcessing.js
var name321 = "pbrBlockImageProcessing", shader320 = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)
#if !defined(SKIPFINALCOLORCLAMP)
finalColor.rgb=clamp(finalColor.rgb,0.,30.0);
#endif
#else
finalColor=applyImageProcessing(finalColor);
#endif
finalColor.a*=visibility;
#ifdef PREMULTIPLYALPHA
finalColor.rgb*=finalColor.a;
#endif
`;
var init_pbrBlockImageProcessing2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name321]) {
    ShaderStore.IncludesShadersStore[name321] = shader320;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockPrePass.js
var name322 = "pbrBlockPrePass", shader321 = `float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0;
#ifdef PREPASS_POSITION
gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);
#endif
#ifdef PREPASS_LOCAL_POSITION
gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo);
#endif
#if defined(PREPASS_VELOCITY)
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#elif defined(PREPASS_VELOCITY_LINEAR)
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO
gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(surfaceAlbedo,writeGeometryInfo);
#endif
#ifdef PREPASS_ALBEDO_SQRT
vec3 sqAlbedo=sqrt(surfaceAlbedo); 
#endif
#ifdef PREPASS_IRRADIANCE
vec3 irradiance=finalDiffuse;
#ifndef UNLIT
#ifdef REFLECTION
irradiance+=finalIrradiance;
#endif
#endif
#ifdef SS_SCATTERING
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb-irradiance,finalColor.a); 
#endif
irradiance/=sqAlbedo;
#else
#ifdef PREPASS_COLOR
gl_FragData[PREPASS_COLOR_INDEX]=finalColor; 
#endif
float scatteringDiffusionProfile=255.;
#endif
gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); 
#elif defined(PREPASS_COLOR)
gl_FragData[PREPASS_COLOR_INDEX]=vec4(finalColor.rgb,finalColor.a);
#endif
#ifdef PREPASS_DEPTH
gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); 
#endif
#ifdef PREPASS_SCREENSPACE_DEPTH
gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo);
#endif
#ifdef PREPASS_NORMAL
#ifdef PREPASS_NORMAL_WORLDSPACE
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo);
#else
gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo);
#endif
#endif
#ifdef PREPASS_WORLD_NORMAL
gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo); 
#endif
#ifdef PREPASS_ALBEDO_SQRT
gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); 
#endif
#ifdef PREPASS_REFLECTIVITY
#ifndef UNLIT
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;
#else
gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;
#endif
#endif
`;
var init_pbrBlockPrePass2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name322]) {
    ShaderStore.IncludesShadersStore[name322] = shader321;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDebug.js
var name323 = "pbrDebug", shader322 = `#if DEBUGMODE>0
if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {
#if DEBUGMODE==1
gl_FragColor.rgb=vPositionW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==2 && defined(NORMAL)
gl_FragColor.rgb=vNormalW.rgb;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)
gl_FragColor.rgb=TBN[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==5
gl_FragColor.rgb=normalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==6 && defined(MAINUV1)
gl_FragColor.rgb=vec3(vMainUV1,0.0);
#elif DEBUGMODE==7 && defined(MAINUV2)
gl_FragColor.rgb=vec3(vMainUV2,0.0);
#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)
gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==10 && defined(CLEARCOAT)
gl_FragColor.rgb=clearcoatOut.clearCoatNormalW;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==11 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicNormal;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==12 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicTangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==13 && defined(ANISOTROPIC)
gl_FragColor.rgb=anisotropicOut.anisotropicBitangent;
#define DEBUGMODE_NORMALIZE
#elif DEBUGMODE==20 && defined(ALBEDO)
gl_FragColor.rgb=albedoTexture.rgb;
#ifndef GAMMAALBEDO
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==21 && defined(AMBIENT)
gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;
#elif DEBUGMODE==22 && defined(OPACITY)
gl_FragColor.rgb=opacityMap.rgb;
#elif DEBUGMODE==23 && defined(EMISSIVE)
gl_FragColor.rgb=emissiveColorTex.rgb;
#ifndef GAMMAEMISSIVE
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==24 && defined(LIGHTMAP)
gl_FragColor.rgb=lightmapColor.rgb;
#ifndef GAMMALIGHTMAP
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;
#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);
#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;
#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)
gl_FragColor.rgb=sheenOut.sheenMapData.rgb;
#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)
gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;
#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)
gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;
#elif DEBUGMODE==32 && defined(BUMP)
gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;
#elif DEBUGMODE==40 && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==41 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)
gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==50
gl_FragColor.rgb=diffuseBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==51 && defined(SPECULARTERM)
gl_FragColor.rgb=specularBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==52 && defined(CLEARCOAT)
gl_FragColor.rgb=clearCoatBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==53 && defined(SHEEN)
gl_FragColor.rgb=sheenBase.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==54 && defined(REFLECTION)
gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;
#ifndef GAMMAREFLECTION
#define DEBUGMODE_GAMMA
#endif
#elif DEBUGMODE==60
gl_FragColor.rgb=surfaceAlbedo.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==61
gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);
#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)
gl_FragColor.rgb=reflectivityOut.metallicF0;
#elif DEBUGMODE==63
gl_FragColor.rgb=vec3(roughness);
#elif DEBUGMODE==64
gl_FragColor.rgb=vec3(alphaG);
#elif DEBUGMODE==65
gl_FragColor.rgb=vec3(NdotV);
#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)
gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==67 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);
#elif DEBUGMODE==68 && defined(CLEARCOAT)
gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);
#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)
gl_FragColor.rgb=subSurfaceOut.transmittance;
#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)
gl_FragColor.rgb=subSurfaceOut.refractionTransmittance;
#elif DEBUGMODE==72
gl_FragColor.rgb=vec3(microSurface);
#elif DEBUGMODE==73
gl_FragColor.rgb=vAlbedoColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)
gl_FragColor.rgb=vReflectivityColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==75
gl_FragColor.rgb=vEmissiveColor.rgb;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)
gl_FragColor.rgb=vec3(seo);
#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
gl_FragColor.rgb=vec3(eho);
#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)
gl_FragColor.rgb=vec3(energyConservationFactor);
#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=specularEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)
gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)
gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;
#define DEBUGMODE_GAMMA
#elif DEBUGMODE==86 && defined(ALPHABLEND)
gl_FragColor.rgb=vec3(luminanceOverAlpha);
#elif DEBUGMODE==87
gl_FragColor.rgb=vec3(alpha);
#elif DEBUGMODE==88 && defined(ALBEDO)
gl_FragColor.rgb=vec3(albedoTexture.a);
#elif DEBUGMODE==89
gl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb;
#else
float stripeWidth=30.;float stripePos=floor(gl_FragCoord.x/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);
#endif
gl_FragColor.rgb*=vDebugMode.y;
#ifdef DEBUGMODE_NORMALIZE
gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;
#endif
#ifdef DEBUGMODE_GAMMA
gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);
#endif
gl_FragColor.a=1.0;
#ifdef PREPASS
gl_FragData[0]=toLinearSpace(gl_FragColor); 
gl_FragData[1]=vec4(0.,0.,0.,0.); 
#endif
#ifdef DEBUGMODE_FORCERETURN
return;
#endif
}
#endif
`;
var init_pbrDebug2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name323]) {
    ShaderStore.IncludesShadersStore[name323] = shader322;
  }
});

// node_modules/@babylonjs/core/Shaders/pbr.fragment.js
var exports_pbr_fragment2 = {};
__export(exports_pbr_fragment2, {
  pbrPixelShader: () => pbrPixelShader
});
var name324 = "pbrPixelShader", shader323 = `#define CUSTOM_FRAGMENT_EXTENSION
#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)
#extension GL_OES_standard_derivatives : enable
#endif
#ifdef LODBASEDMICROSFURACE
#extension GL_EXT_shader_texture_lod : enable
#endif
#define CUSTOM_FRAGMENT_BEGIN
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<prePassDeclaration>[SCENE_MRT_COUNT]
precision highp float;
#include<oitDeclaration>
#ifndef FROMLINEARSPACE
#define FROMLINEARSPACE
#endif
#include<__decl__pbrFragment>
#include<pbrFragmentExtraDeclaration>
#include<__decl__lightFragment>[0..maxSimultaneousLights]
#include<pbrFragmentSamplersDeclaration>
#include<imageProcessingDeclaration>
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
#include<helperFunctions>
#include<subSurfaceScatteringFunctions>
#include<importanceSampling>
#include<pbrHelperFunctions>
#include<imageProcessingFunctions>
#include<shadowsFragmentFunctions>
#include<harmonicsFunctions>
#include<pbrDirectLightingSetupFunctions>
#include<pbrDirectLightingFalloffFunctions>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
#include<pbrDirectLightingFunctions>
#include<pbrIBLFunctions>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#ifdef REFLECTION
#include<reflectionFunction>
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
#include<pbrBlockAlbedoOpacity>
#include<pbrBlockReflectivity>
#include<pbrBlockAmbientOcclusion>
#include<pbrBlockAlphaFresnel>
#include<pbrBlockAnisotropic>
#include<pbrBlockReflection>
#include<pbrBlockSheen>
#include<pbrBlockClearcoat>
#include<pbrBlockIridescence>
#include<pbrBlockSubSurface>
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#include<pbrBlockNormalGeometric>
#include<bumpFragment>
#include<pbrBlockNormalFinal>
albedoOpacityOutParams albedoOpacityOut;
#ifdef ALBEDO
vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);
#endif
#ifdef BASEWEIGHT
vec4 baseWeightTexture=texture2D(baseWeightSampler,vBaseWeightUV+uvOffset);
#endif
#ifdef OPACITY
vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);
#endif
#ifdef DECAL
vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);
#endif
albedoOpacityOut=albedoOpacityBlock(
vAlbedoColor
#ifdef ALBEDO
,albedoTexture
,vAlbedoInfos
#endif
,baseWeight
#ifdef BASEWEIGHT
,baseWeightTexture
,vBaseWeightInfos
#endif
#ifdef OPACITY
,opacityMap
,vOpacityInfos
#endif
#ifdef DETAIL
,detailColor
,vDetailInfos
#endif
#ifdef DECAL
,decalColor
,vDecalInfos
#endif
);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;
#define CUSTOM_FRAGMENT_UPDATE_ALPHA
#include<depthPrePass>
#define CUSTOM_FRAGMENT_BEFORE_LIGHTS
ambientOcclusionOutParams aoOut;
#ifdef AMBIENT
vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;
#endif
aoOut=ambientOcclusionBlock(
#ifdef AMBIENT
ambientOcclusionColorMap,
vAmbientInfos
#endif
);
#include<pbrBlockLightmapInit>
#ifdef UNLIT
vec3 diffuseBase=vec3(1.,1.,1.);
#else 
vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;
#if defined(REFLECTIVITY)
vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;
#ifndef METALLICWORKFLOW
#ifdef REFLECTIVITY_GAMMA
surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);
#endif
surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;
#endif
#endif
#if defined(MICROSURFACEMAP)
vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;
#endif
#ifdef METALLICWORKFLOW
vec4 metallicReflectanceFactors=vMetallicReflectanceFactors;
#ifdef REFLECTANCE
vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);
#ifdef REFLECTANCE_GAMMA
reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);
#endif
metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;
#endif
#ifdef METALLIC_REFLECTANCE
vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);
#ifdef METALLIC_REFLECTANCE_GAMMA
metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);
#endif
#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY
metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;
#endif
metallicReflectanceFactors*=metallicReflectanceFactorsMap.a;
#endif
#endif
reflectivityOut=reflectivityBlock(
vReflectivityColor
#ifdef METALLICWORKFLOW
,surfaceAlbedo
,metallicReflectanceFactors
#endif
#ifdef REFLECTIVITY
,vReflectivityInfos
,surfaceMetallicOrReflectivityColorMap
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
,aoOut.ambientOcclusionColor
#endif
#ifdef MICROSURFACEMAP
,microSurfaceTexel
#endif
#ifdef DETAIL
,detailColor
,vDetailInfos
#endif
);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;
#ifdef METALLICWORKFLOW
surfaceAlbedo=reflectivityOut.surfaceAlbedo;
#endif
#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;
#endif
#ifdef ALPHAFRESNEL
#if defined(ALPHATEST) || defined(ALPHABLEND)
alphaFresnelOutParams alphaFresnelOut;alphaFresnelOut=alphaFresnelBlock(
normalW,
viewDirectionW,
alpha,
microSurface
);alpha=alphaFresnelOut.alpha;
#endif
#endif
#include<pbrBlockGeometryInfo>
#ifdef ANISOTROPIC
anisotropicOutParams anisotropicOut;
#ifdef ANISOTROPIC_TEXTURE
vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;
#endif
anisotropicOut=anisotropicBlock(
vAnisotropy,
roughness,
#ifdef ANISOTROPIC_TEXTURE
anisotropyMapData,
#endif
TBN,
normalW,
viewDirectionW
);
#endif
#ifdef REFLECTION
reflectionOutParams reflectionOut;
#ifndef USE_CUSTOM_REFLECTION
reflectionOut=reflectionBlock(
vPositionW
,normalW
,alphaG
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)
,NdotVUnclamped
#endif
#ifdef LINEARSPECULARREFLECTION
,roughness
#endif
,reflectionSampler
#if defined(NORMAL) && defined(USESPHERICALINVERTEX)
,vEnvironmentIrradiance
#endif
#if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
,reflectionMatrix
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#endif
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
);
#else
#define CUSTOM_REFLECTION
#endif
#endif
#include<pbrBlockReflectance0>
#ifdef SHEEN
sheenOutParams sheenOut;
#ifdef SHEEN_TEXTURE
vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);
#endif
#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;
#endif
sheenOut=sheenBlock(
vSheenColor
#ifdef SHEEN_ROUGHNESS
,vSheenRoughness
#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)
,sheenMapRoughnessData
#endif
#endif
,roughness
#ifdef SHEEN_TEXTURE
,sheenMapData
,vSheenInfos.y
#endif
,reflectance
#ifdef SHEEN_LINKWITHALBEDO
,baseColor
,surfaceAlbedo
#endif
#ifdef ENVIRONMENTBRDF
,NdotV
,environmentBrdf
#endif
#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
,AARoughnessFactors
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
,vLightingIntensity
,reflectionSampler
,reflectionOut.reflectionCoords
,NdotVUnclamped
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)
,seo
#endif
#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)
,eho
#endif
#endif
);
#ifdef SHEEN_LINKWITHALBEDO
surfaceAlbedo=sheenOut.surfaceAlbedo;
#endif
#endif
#ifdef CLEARCOAT
#ifdef CLEARCOAT_TEXTURE
vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;
#endif
#endif
#ifdef IRIDESCENCE
iridescenceOutParams iridescenceOut;
#ifdef IRIDESCENCE_TEXTURE
vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;
#endif
iridescenceOut=iridescenceBlock(
vIridescenceParams
,NdotV
,specularEnvironmentR0
#ifdef IRIDESCENCE_TEXTURE
,iridescenceMapData
#endif
#ifdef IRIDESCENCE_THICKNESS_TEXTURE
,iridescenceThicknessMapData
#endif
#ifdef CLEARCOAT
,NdotVUnclamped
,vClearCoatParams
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#endif
);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;
#endif
clearcoatOutParams clearcoatOut;
#ifdef CLEARCOAT
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;
#endif
#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)
vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);
#endif
#ifdef CLEARCOAT_BUMP
vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);
#endif
clearcoatOut=clearcoatBlock(
vPositionW
,geometricNormalW
,viewDirectionW
,vClearCoatParams
#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)
,clearCoatMapRoughnessData
#endif
,specularEnvironmentR0
#ifdef CLEARCOAT_TEXTURE
,clearCoatMapData
#endif
#ifdef CLEARCOAT_TINT
,vClearCoatTintParams
,clearCoatColorAtDistance
,vClearCoatRefractionParams
#ifdef CLEARCOAT_TINT_TEXTURE
,clearCoatTintMapData
#endif
#endif
#ifdef CLEARCOAT_BUMP
,vClearCoatBumpInfos
,clearCoatBumpMapData
,vClearCoatBumpUV
#if defined(TANGENT) && defined(NORMAL)
,vTBN
#else
,vClearCoatTangentSpaceParams
#endif
#ifdef OBJECTSPACE_NORMALMAP
,normalMatrix
#endif
#endif
#if defined(FORCENORMALFORWARD) && defined(NORMAL)
,faceNormal
#endif
#ifdef REFLECTION
,vReflectionMicrosurfaceInfos
,vReflectionInfos
,vReflectionColor
,vLightingIntensity
,reflectionSampler
#ifndef LODBASEDMICROSFURACE
,reflectionSamplerLow
,reflectionSamplerHigh
#endif
#ifdef REALTIME_FILTERING
,vReflectionFilteringInfo
#endif
#endif
#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
,(gl_FrontFacing ? 1. : -1.)
#endif
);
#else
clearcoatOut.specularEnvironmentR0=specularEnvironmentR0;
#endif
#include<pbrBlockReflectance>
subSurfaceOutParams subSurfaceOut;
#ifdef SUBSURFACE
#ifdef SS_THICKNESSANDMASK_TEXTURE
vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);
#endif
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
vec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset);
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA
translucencyColorMap=toLinearSpace(translucencyColorMap);
#endif
#endif
subSurfaceOut=subSurfaceBlock(
vSubSurfaceIntensity
,vThicknessParam
,vTintColor
,normalW
,specularEnvironmentReflectance
#ifdef SS_THICKNESSANDMASK_TEXTURE
,thicknessMap
#endif
#ifdef SS_REFRACTIONINTENSITY_TEXTURE
,refractionIntensityMap
#endif
#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE
,translucencyIntensityMap
#endif
#ifdef REFLECTION
#ifdef SS_TRANSLUCENCY
,reflectionMatrix
#ifdef USESPHERICALFROMREFLECTIONMAP
#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
,reflectionOut.irradianceVector
#endif
#if defined(REALTIME_FILTERING)
,reflectionSampler
,vReflectionFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfSampler
#endif
#endif
#endif
#ifdef USEIRRADIANCEMAP
,irradianceSampler
#endif
#endif
#endif
#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
,surfaceAlbedo
#endif
#ifdef SS_REFRACTION
,vPositionW
,viewDirectionW
,view
,vRefractionInfos
,refractionMatrix
,vRefractionMicrosurfaceInfos
,vLightingIntensity
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
,alpha
#endif
#ifdef SS_LODINREFRACTIONALPHA
,NdotVUnclamped
#endif
#ifdef SS_LINEARSPECULARREFRACTION
,roughness
#endif
,alphaG
,refractionSampler
#ifndef LODBASEDMICROSFURACE
,refractionSamplerLow
,refractionSamplerHigh
#endif
#ifdef ANISOTROPIC
,anisotropicOut
#endif
#ifdef REALTIME_FILTERING
,vRefractionFilteringInfo
#endif
#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
,vRefractionPosition
,vRefractionSize
#endif
#ifdef SS_DISPERSION
,dispersion
#endif
#endif
#ifdef SS_TRANSLUCENCY
,vDiffusionDistance
,vTranslucencyColor
#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
,translucencyColorMap
#endif
#endif
);
#ifdef SS_REFRACTION
surfaceAlbedo=subSurfaceOut.surfaceAlbedo;
#ifdef SS_LINKREFRACTIONTOTRANSPARENCY
alpha=subSurfaceOut.alpha;
#endif
#endif
#else
subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;
#endif
#include<pbrBlockDirectLighting>
#include<lightFragment>[0..maxSimultaneousLights]
#include<pbrBlockFinalLitComponents>
#endif 
#include<pbrBlockFinalUnlitComponents>
#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION
#include<pbrBlockFinalColorComposition>
#include<logDepthFragment>
#include<fogFragment>(color,finalColor)
#include<pbrBlockImageProcessing>
#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR
#ifdef PREPASS
#include<pbrBlockPrePass>
#endif
#if !defined(PREPASS) || defined(WEBGL2)
gl_FragColor=finalColor;
#endif
#include<oitFragment>
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}
#endif
#include<pbrDebug>
#define CUSTOM_FRAGMENT_MAIN_END
}
`, pbrPixelShader;
var init_pbr_fragment2 = __esm(() => {
  init_shaderStore();
  init_prePassDeclaration2();
  init_oitDeclaration2();
  init_pbrFragmentDeclaration();
  init_pbrUboDeclaration2();
  init_pbrFragmentExtraDeclaration2();
  init_lightFragmentDeclaration();
  init_lightUboDeclaration2();
  init_pbrFragmentSamplersDeclaration2();
  init_imageProcessingDeclaration2();
  init_clipPlaneFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_fogFragmentDeclaration2();
  init_helperFunctions2();
  init_subSurfaceScatteringFunctions2();
  init_importanceSampling2();
  init_pbrHelperFunctions2();
  init_imageProcessingFunctions2();
  init_shadowsFragmentFunctions2();
  init_harmonicsFunctions2();
  init_pbrDirectLightingSetupFunctions2();
  init_pbrDirectLightingFalloffFunctions2();
  init_pbrBRDFFunctions2();
  init_hdrFilteringFunctions2();
  init_pbrDirectLightingFunctions2();
  init_pbrIBLFunctions2();
  init_bumpFragmentMainFunctions2();
  init_bumpFragmentFunctions2();
  init_reflectionFunction2();
  init_pbrBlockAlbedoOpacity2();
  init_pbrBlockReflectivity2();
  init_pbrBlockAmbientOcclusion2();
  init_pbrBlockAlphaFresnel2();
  init_pbrBlockAnisotropic2();
  init_pbrBlockReflection2();
  init_pbrBlockSheen2();
  init_pbrBlockClearcoat2();
  init_pbrBlockIridescence2();
  init_pbrBlockSubSurface2();
  init_clipPlaneFragment2();
  init_pbrBlockNormalGeometric2();
  init_bumpFragment2();
  init_pbrBlockNormalFinal2();
  init_depthPrePass2();
  init_pbrBlockLightmapInit2();
  init_pbrBlockGeometryInfo2();
  init_pbrBlockReflectance02();
  init_pbrBlockReflectance2();
  init_pbrBlockDirectLighting2();
  init_lightFragment2();
  init_pbrBlockFinalLitComponents2();
  init_pbrBlockFinalUnlitComponents2();
  init_pbrBlockFinalColorComposition2();
  init_logDepthFragment2();
  init_fogFragment2();
  init_pbrBlockImageProcessing2();
  init_pbrBlockPrePass2();
  init_oitFragment2();
  init_pbrDebug2();
  if (!ShaderStore.ShadersStore[name324]) {
    ShaderStore.ShadersStore[name324] = shader323;
  }
  pbrPixelShader = { name: name324, shader: shader323 };
});

// node_modules/@babylonjs/core/ShadersWGSL/procedural.vertex.js
var exports_procedural_vertex = {};
__export(exports_procedural_vertex, {
  proceduralVertexShaderWGSL: () => proceduralVertexShaderWGSL
});
var name325 = "proceduralVertexShader", shader324 = `attribute position: vec2f;varying vPosition: vec2f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vPosition=input.position;vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, proceduralVertexShaderWGSL;
var init_procedural_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name325]) {
    ShaderStore.ShadersStoreWGSL[name325] = shader324;
  }
  proceduralVertexShaderWGSL = { name: name325, shader: shader324 };
});

// node_modules/@babylonjs/core/Shaders/procedural.vertex.js
var exports_procedural_vertex2 = {};
__export(exports_procedural_vertex2, {
  proceduralVertexShader: () => proceduralVertexShader
});
var name326 = "proceduralVertexShader", shader325 = `attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, proceduralVertexShader;
var init_procedural_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name326]) {
    ShaderStore.ShadersStore[name326] = shader325;
  }
  proceduralVertexShader = { name: name326, shader: shader325 };
});

// node_modules/@babylonjs/core/ShadersWGSL/layer.vertex.js
var exports_layer_vertex = {};
__export(exports_layer_vertex, {
  layerVertexShaderWGSL: () => layerVertexShaderWGSL
});
var name327 = "layerVertexShader", shader326 = `attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, layerVertexShaderWGSL;
var init_layer_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name327]) {
    ShaderStore.ShadersStoreWGSL[name327] = shader326;
  }
  layerVertexShaderWGSL = { name: name327, shader: shader326 };
});

// node_modules/@babylonjs/core/ShadersWGSL/layer.fragment.js
var exports_layer_fragment = {};
__export(exports_layer_fragment, {
  layerPixelShaderWGSL: () => layerPixelShaderWGSL
});
var name328 = "layerPixelShader", shader327 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform color: vec4f;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);
#if defined(CONVERT_TO_GAMMA)
baseColor=toGammaSpace(baseColor);
#elif defined(CONVERT_TO_LINEAR)
baseColor=toLinearSpaceVec4(baseColor);
#endif
#ifdef ALPHATEST
if (baseColor.a<0.4) {discard;}
#endif
fragmentOutputs.color=baseColor*uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, layerPixelShaderWGSL;
var init_layer_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name328]) {
    ShaderStore.ShadersStoreWGSL[name328] = shader327;
  }
  layerPixelShaderWGSL = { name: name328, shader: shader327 };
});

// node_modules/@babylonjs/core/Shaders/layer.vertex.js
var exports_layer_vertex2 = {};
__export(exports_layer_vertex2, {
  layerVertexShader: () => layerVertexShader
});
var name329 = "layerVertexShader", shader328 = `attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, layerVertexShader;
var init_layer_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name329]) {
    ShaderStore.ShadersStore[name329] = shader328;
  }
  layerVertexShader = { name: name329, shader: shader328 };
});

// node_modules/@babylonjs/core/Shaders/layer.fragment.js
var exports_layer_fragment2 = {};
__export(exports_layer_fragment2, {
  layerPixelShader: () => layerPixelShader
});
var name330 = "layerPixelShader", shader329 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;
#include<helperFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);
#if defined(CONVERT_TO_GAMMA)
baseColor.rgb=toGammaSpace(baseColor.rgb);
#elif defined(CONVERT_TO_LINEAR)
baseColor.rgb=toLinearSpace(baseColor.rgb);
#endif
#ifdef ALPHATEST
if (baseColor.a<0.4)
discard;
#endif
gl_FragColor=baseColor*color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, layerPixelShader;
var init_layer_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name330]) {
    ShaderStore.ShadersStore[name330] = shader329;
  }
  layerPixelShader = { name: name330, shader: shader329 };
});

// node_modules/@babylonjs/core/ShadersWGSL/lensFlare.fragment.js
var exports_lensFlare_fragment = {};
__export(exports_lensFlare_fragment, {
  lensFlarePixelShaderWGSL: () => lensFlarePixelShaderWGSL
});
var name331 = "lensFlarePixelShader", shader330 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform color: vec4f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=baseColor*uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, lensFlarePixelShaderWGSL;
var init_lensFlare_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name331]) {
    ShaderStore.ShadersStoreWGSL[name331] = shader330;
  }
  lensFlarePixelShaderWGSL = { name: name331, shader: shader330 };
});

// node_modules/@babylonjs/core/ShadersWGSL/lensFlare.vertex.js
var exports_lensFlare_vertex = {};
__export(exports_lensFlare_vertex, {
  lensFlareVertexShaderWGSL: () => lensFlareVertexShaderWGSL
});
var name332 = "lensFlareVertexShader", shader331 = `attribute position: vec2f;uniform viewportMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position=uniforms.viewportMatrix* vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, lensFlareVertexShaderWGSL;
var init_lensFlare_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name332]) {
    ShaderStore.ShadersStoreWGSL[name332] = shader331;
  }
  lensFlareVertexShaderWGSL = { name: name332, shader: shader331 };
});

// node_modules/@babylonjs/core/Shaders/lensFlare.fragment.js
var exports_lensFlare_fragment2 = {};
__export(exports_lensFlare_fragment2, {
  lensFlarePixelShader: () => lensFlarePixelShader
});
var name333 = "lensFlarePixelShader", shader332 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, lensFlarePixelShader;
var init_lensFlare_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name333]) {
    ShaderStore.ShadersStore[name333] = shader332;
  }
  lensFlarePixelShader = { name: name333, shader: shader332 };
});

// node_modules/@babylonjs/core/Shaders/lensFlare.vertex.js
var exports_lensFlare_vertex2 = {};
__export(exports_lensFlare_vertex2, {
  lensFlareVertexShader: () => lensFlareVertexShader
});
var name334 = "lensFlareVertexShader", shader333 = `attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, lensFlareVertexShader;
var init_lensFlare_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name334]) {
    ShaderStore.ShadersStore[name334] = shader333;
  }
  lensFlareVertexShader = { name: name334, shader: shader333 };
});

// node_modules/@babylonjs/core/ShadersWGSL/hdrFiltering.vertex.js
var exports_hdrFiltering_vertex = {};
__export(exports_hdrFiltering_vertex, {
  hdrFilteringVertexShaderWGSL: () => hdrFilteringVertexShaderWGSL
});
var name335 = "hdrFilteringVertexShader", shader334 = `attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, hdrFilteringVertexShaderWGSL;
var init_hdrFiltering_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name335]) {
    ShaderStore.ShadersStoreWGSL[name335] = shader334;
  }
  hdrFilteringVertexShaderWGSL = { name: name335, shader: shader334 };
});

// node_modules/@babylonjs/core/ShadersWGSL/hdrFiltering.fragment.js
var exports_hdrFiltering_fragment = {};
__export(exports_hdrFiltering_fragment, {
  hdrFilteringPixelShaderWGSL: () => hdrFilteringPixelShaderWGSL
});
var name336 = "hdrFilteringPixelShader", shader335 = `#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
uniform alphaG: f32;var inputTextureSampler: sampler;var inputTexture: texture_cube<f32>;uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=radiance(uniforms.alphaG,inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}`, hdrFilteringPixelShaderWGSL;
var init_hdrFiltering_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  init_importanceSampling();
  init_pbrBRDFFunctions();
  init_hdrFilteringFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name336]) {
    ShaderStore.ShadersStoreWGSL[name336] = shader335;
  }
  hdrFilteringPixelShaderWGSL = { name: name336, shader: shader335 };
});

// node_modules/@babylonjs/core/Shaders/hdrFiltering.vertex.js
var exports_hdrFiltering_vertex2 = {};
__export(exports_hdrFiltering_vertex2, {
  hdrFilteringVertexShader: () => hdrFilteringVertexShader
});
var name337 = "hdrFilteringVertexShader", shader336 = `attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, hdrFilteringVertexShader;
var init_hdrFiltering_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name337]) {
    ShaderStore.ShadersStore[name337] = shader336;
  }
  hdrFilteringVertexShader = { name: name337, shader: shader336 };
});

// node_modules/@babylonjs/core/Shaders/hdrFiltering.fragment.js
var exports_hdrFiltering_fragment2 = {};
__export(exports_hdrFiltering_fragment2, {
  hdrFilteringPixelShader: () => hdrFilteringPixelShader
});
var name338 = "hdrFilteringPixelShader", shader337 = `#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`, hdrFilteringPixelShader;
var init_hdrFiltering_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  init_importanceSampling2();
  init_pbrBRDFFunctions2();
  init_hdrFilteringFunctions2();
  if (!ShaderStore.ShadersStore[name338]) {
    ShaderStore.ShadersStore[name338] = shader337;
  }
  hdrFilteringPixelShader = { name: name338, shader: shader337 };
});

// node_modules/@babylonjs/core/ShadersWGSL/iblCdfx.fragment.js
var exports_iblCdfx_fragment = {};
__export(exports_iblCdfx_fragment, {
  iblCdfxPixelShaderWGSL: () => iblCdfxPixelShaderWGSL
});
var name339 = "iblCdfxPixelShader", shader338 = `#define PI 3.1415927
varying vUV: vec2f;var cdfy: texture_2d<f32>;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var cdfyRes=textureDimensions(cdfy,0);var currentPixel=vec2u(fragmentInputs.position.xy);var cdfx: f32=0.0;for (var x: u32=1; x<=currentPixel.x; x++) {cdfx+=textureLoad(cdfy, vec2u(x-1,cdfyRes.y-1),0).x;}
fragmentOutputs.color= vec4f( vec3f(cdfx),1.0);}`, iblCdfxPixelShaderWGSL;
var init_iblCdfx_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name339]) {
    ShaderStore.ShadersStoreWGSL[name339] = shader338;
  }
  iblCdfxPixelShaderWGSL = { name: name339, shader: shader338 };
});

// node_modules/@babylonjs/core/ShadersWGSL/iblCdfy.fragment.js
var exports_iblCdfy_fragment = {};
__export(exports_iblCdfy_fragment, {
  iblCdfyPixelShaderWGSL: () => iblCdfyPixelShaderWGSL
});
var name340 = "iblCdfyPixelShader", shader339 = `varying vUV : vec2f;
#include <helperFunctions>
#ifdef IBL_USE_CUBE_MAP
var iblSourceSampler: sampler;var iblSource: texture_cube<f32>;
#else
var iblSourceSampler: sampler;var iblSource: texture_2d<f32>;
#endif
uniform iblHeight: i32;
#ifdef IBL_USE_CUBE_MAP
fn fetchCube(uv: vec2f)->f32 {var direction: vec3f=equirectangularToCubemapDirection(uv);return sin(PI*uv.y) *
dot(textureSampleLevel(iblSource,iblSourceSampler,direction,0.0)
.rgb,
LuminanceEncodeApprox);}
#else
fn fetchPanoramic(Coords: vec2i,envmapHeight: f32)->f32 {return sin(PI*(f32(Coords.y)+0.5)/envmapHeight) *
dot(textureLoad(iblSource,Coords,0).rgb,LuminanceEncodeApprox);}
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var coords: vec2i= vec2i(fragmentInputs.position.xy);var cdfy: f32=0.0;for (var y: i32=1; y<=coords.y; y++) {
#ifdef IBL_USE_CUBE_MAP
var uv: vec2f= vec2f(input.vUV.x,( f32(y-1)+0.5)/ f32(uniforms.iblHeight));cdfy+=fetchCube(uv);
#else
cdfy+=fetchPanoramic( vec2i(coords.x,y-1), f32(uniforms.iblHeight));
#endif
}
fragmentOutputs.color= vec4f(cdfy,0.0,0.0,1.0);}`, iblCdfyPixelShaderWGSL;
var init_iblCdfy_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name340]) {
    ShaderStore.ShadersStoreWGSL[name340] = shader339;
  }
  iblCdfyPixelShaderWGSL = { name: name340, shader: shader339 };
});

// node_modules/@babylonjs/core/ShadersWGSL/iblScaledLuminance.fragment.js
var exports_iblScaledLuminance_fragment = {};
__export(exports_iblScaledLuminance_fragment, {
  iblScaledLuminancePixelShaderWGSL: () => iblScaledLuminancePixelShaderWGSL
});
var name341 = "iblScaledLuminancePixelShader", shader340 = `#include<helperFunctions>
#ifdef IBL_USE_CUBE_MAP
var iblSourceSampler: sampler;var iblSource: texture_cube<f32>;
#else
var iblSourceSampler: sampler;var iblSource: texture_2d<f32>;
#endif
uniform iblHeight: i32;uniform iblWidth: i32;fn fetchLuminance(coords: vec2f)->f32 {
#ifdef IBL_USE_CUBE_MAP
var direction: vec3f=equirectangularToCubemapDirection(coords);var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb;
#else
var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,coords,0.0).rgb;
#endif
return dot(color,LuminanceEncodeApprox);}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var deform: f32=sin(input.vUV.y*PI);var luminance: f32=fetchLuminance(input.vUV);fragmentOutputs.color=vec4f(vec3f(deform*luminance),1.0);}`, iblScaledLuminancePixelShaderWGSL;
var init_iblScaledLuminance_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name341]) {
    ShaderStore.ShadersStoreWGSL[name341] = shader340;
  }
  iblScaledLuminancePixelShaderWGSL = { name: name341, shader: shader340 };
});

// node_modules/@babylonjs/core/Shaders/iblCdfx.fragment.js
var exports_iblCdfx_fragment2 = {};
__export(exports_iblCdfx_fragment2, {
  iblCdfxPixelShader: () => iblCdfxPixelShader
});
var name342 = "iblCdfxPixelShader", shader341 = `precision highp sampler2D;
#define PI 3.1415927
varying vec2 vUV;uniform sampler2D cdfy;void main(void) {ivec2 cdfyRes=textureSize(cdfy,0);ivec2 currentPixel=ivec2(gl_FragCoord.xy);float cdfx=0.0;for (int x=1; x<=currentPixel.x; x++) {cdfx+=texelFetch(cdfy,ivec2(x-1,cdfyRes.y-1),0).x;}
gl_FragColor=vec4(vec3(cdfx),1.0);}`, iblCdfxPixelShader;
var init_iblCdfx_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name342]) {
    ShaderStore.ShadersStore[name342] = shader341;
  }
  iblCdfxPixelShader = { name: name342, shader: shader341 };
});

// node_modules/@babylonjs/core/Shaders/iblCdfy.fragment.js
var exports_iblCdfy_fragment2 = {};
__export(exports_iblCdfy_fragment2, {
  iblCdfyPixelShader: () => iblCdfyPixelShader
});
var name343 = "iblCdfyPixelShader", shader342 = `precision highp sampler2D;precision highp samplerCube;
#include<helperFunctions>
#define PI 3.1415927
varying vec2 vUV;
#ifdef IBL_USE_CUBE_MAP
uniform samplerCube iblSource;
#else
uniform sampler2D iblSource;
#endif
uniform int iblHeight;
#ifdef IBL_USE_CUBE_MAP
float fetchCube(vec2 uv) {vec3 direction=equirectangularToCubemapDirection(uv);return sin(PI*uv.y)*dot(textureCubeLodEXT(iblSource,direction,0.0).rgb,LuminanceEncodeApprox);}
#else
float fetchPanoramic(ivec2 Coords,float envmapHeight) {return sin(PI*(float(Coords.y)+0.5)/envmapHeight) *
dot(texelFetch(iblSource,Coords,0).rgb,LuminanceEncodeApprox);}
#endif
void main(void) {ivec2 coords=ivec2(gl_FragCoord.x,gl_FragCoord.y);float cdfy=0.0;for (int y=1; y<=coords.y; y++) {
#ifdef IBL_USE_CUBE_MAP
vec2 uv=vec2(vUV.x,(float(y-1)+0.5)/float(iblHeight));cdfy+=fetchCube(uv);
#else
cdfy+=fetchPanoramic(ivec2(coords.x,y-1),float(iblHeight));
#endif
}
gl_FragColor=vec4(cdfy,0.0,0.0,1.0);}`, iblCdfyPixelShader;
var init_iblCdfy_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name343]) {
    ShaderStore.ShadersStore[name343] = shader342;
  }
  iblCdfyPixelShader = { name: name343, shader: shader342 };
});

// node_modules/@babylonjs/core/Shaders/iblScaledLuminance.fragment.js
var exports_iblScaledLuminance_fragment2 = {};
__export(exports_iblScaledLuminance_fragment2, {
  iblScaledLuminancePixelShader: () => iblScaledLuminancePixelShader
});
var name344 = "iblScaledLuminancePixelShader", shader343 = `precision highp sampler2D;precision highp samplerCube;
#include<helperFunctions>
varying vec2 vUV;
#ifdef IBL_USE_CUBE_MAP
uniform samplerCube iblSource;
#else
uniform sampler2D iblSource;
#endif
uniform int iblWidth;uniform int iblHeight;float fetchLuminance(vec2 coords) {
#ifdef IBL_USE_CUBE_MAP
vec3 direction=equirectangularToCubemapDirection(coords);vec3 color=textureCubeLodEXT(iblSource,direction,0.0).rgb;
#else
vec3 color=textureLod(iblSource,coords,0.0).rgb;
#endif
return dot(color,LuminanceEncodeApprox);}
void main(void) {float deform=sin(vUV.y*PI);float luminance=fetchLuminance(vUV);gl_FragColor=vec4(vec3(deform*luminance),1.0);}`, iblScaledLuminancePixelShader;
var init_iblScaledLuminance_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name344]) {
    ShaderStore.ShadersStore[name344] = shader343;
  }
  iblScaledLuminancePixelShader = { name: name344, shader: shader343 };
});

// node_modules/@babylonjs/core/ShadersWGSL/iblIcdf.fragment.js
var exports_iblIcdf_fragment = {};
__export(exports_iblIcdf_fragment, {
  iblIcdfPixelShaderWGSL: () => iblIcdfPixelShaderWGSL
});
var name345 = "iblIcdfPixelShader", shader344 = `#include<helperFunctions>
varying vUV: vec2f;
#ifdef IBL_USE_CUBE_MAP
var iblSourceSampler: sampler;var iblSource: texture_cube<f32>;
#else
var iblSourceSampler: sampler;var iblSource: texture_2d<f32>;
#endif
var scaledLuminanceSamplerSampler : sampler;var scaledLuminanceSampler : texture_2d<f32>;var cdfx: texture_2d<f32>;var cdfy: texture_2d<f32>;fn fetchLuminance(coords: vec2f)->f32 {
#ifdef IBL_USE_CUBE_MAP
var direction: vec3f=equirectangularToCubemapDirection(coords);var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb;
#else
var color: vec3f=textureSampleLevel(iblSource,iblSourceSampler,coords,0.0).rgb;
#endif
return dot(color,LuminanceEncodeApprox);}
fn fetchCDFx(x: u32)->f32 {return textureLoad(cdfx, vec2u(x,0),0).x;}
fn bisectx(size: u32,targetValue: f32)->f32
{var a: u32=0;var b=size-1;while (b-a>1) {var c: u32=(a+b)>>1;if (fetchCDFx(c)<targetValue) {a=c;}
else {b=c;}}
return mix( f32(a), f32(b),(targetValue-fetchCDFx(a))/(fetchCDFx(b)-fetchCDFx(a)))/ f32(size-1);}
fn fetchCDFy(y: u32,invocationId: u32)->f32 {return textureLoad(cdfy, vec2u(invocationId,y),0).x;}
fn bisecty(size: u32,targetValue: f32,invocationId: u32)->f32
{var a: u32=0;var b=size-1;while (b-a>1) {var c=(a+b)>>1;if (fetchCDFy(c,invocationId)<targetValue) {a=c;}
else {b=c;}}
return mix( f32(a), f32(b),(targetValue-fetchCDFy(a,invocationId))/(fetchCDFy(b,invocationId)-fetchCDFy(a,invocationId)))/ f32(size-1);}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var cdfxSize: vec2u=textureDimensions(cdfx,0);var cdfWidth: u32=cdfxSize.x;var icdfWidth: u32=cdfWidth-1;var currentPixel: vec2u= vec2u(fragmentInputs.position.xy);var outputColor: vec3f=vec3f(1.0);if (currentPixel.x==0)
{outputColor.x= 0.0;}
else if (currentPixel.x==icdfWidth-1) {outputColor.x= 1.0;} else {var targetValue: f32=fetchCDFx(cdfWidth-1)*input.vUV.x;outputColor.x= bisectx(cdfWidth,targetValue);}
var cdfySize: vec2u=textureDimensions(cdfy,0);var cdfHeight: u32=cdfySize.y;if (currentPixel.y==0) {outputColor.y= 0.0;}
else if (currentPixel.y==cdfHeight-2) {outputColor.y= 1.0;} else {var targetValue: f32=fetchCDFy(cdfHeight-1,currentPixel.x)*input.vUV.y;outputColor.y= max(bisecty(cdfHeight,targetValue,currentPixel.x),0.0);}
var size : vec2f=vec2f(textureDimensions(scaledLuminanceSampler,0));var highestMip: f32=floor(log2(size.x));var normalization : f32=textureSampleLevel(scaledLuminanceSampler,
scaledLuminanceSamplerSampler,
input.vUV,highestMip)
.r;var pixelLuminance: f32=fetchLuminance(input.vUV);outputColor.z=pixelLuminance/(2.0*PI*normalization);fragmentOutputs.color=vec4( outputColor,1.0);}`, iblIcdfPixelShaderWGSL;
var init_iblIcdf_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name345]) {
    ShaderStore.ShadersStoreWGSL[name345] = shader344;
  }
  iblIcdfPixelShaderWGSL = { name: name345, shader: shader344 };
});

// node_modules/@babylonjs/core/Shaders/iblIcdf.fragment.js
var exports_iblIcdf_fragment2 = {};
__export(exports_iblIcdf_fragment2, {
  iblIcdfPixelShader: () => iblIcdfPixelShader
});
var name346 = "iblIcdfPixelShader", shader345 = `precision highp sampler2D;
#include<helperFunctions>
varying vec2 vUV;
#ifdef IBL_USE_CUBE_MAP
uniform samplerCube iblSource;
#else
uniform sampler2D iblSource;
#endif
uniform sampler2D scaledLuminanceSampler;uniform int iblWidth;uniform int iblHeight;uniform sampler2D cdfx;uniform sampler2D cdfy;float fetchLuminance(vec2 coords) {
#ifdef IBL_USE_CUBE_MAP
vec3 direction=equirectangularToCubemapDirection(coords);vec3 color=textureCubeLodEXT(iblSource,direction,0.0).rgb;
#else
vec3 color=textureLod(iblSource,coords,0.0).rgb;
#endif
return dot(color,LuminanceEncodeApprox);}
float fetchCDFx(int x) { return texelFetch(cdfx,ivec2(x,0),0).x; }
float bisectx(int size,float targetValue) {int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDFx(c)<targetValue)
a=c;else
b=c;}
return mix(float(a),float(b),
(targetValue-fetchCDFx(a))/(fetchCDFx(b)-fetchCDFx(a))) /
float(size-1);}
float fetchCDFy(int y,int invocationId) {return texelFetch(cdfy,ivec2(invocationId,y),0).x;}
float bisecty(int size,float targetValue,int invocationId) {int a=0,b=size-1;while (b-a>1) {int c=a+b>>1;if (fetchCDFy(c,invocationId)<targetValue)
a=c;else
b=c;}
return mix(float(a),float(b),
(targetValue-fetchCDFy(a,invocationId)) /
(fetchCDFy(b,invocationId)-fetchCDFy(a,invocationId))) /
float(size-1);}
void main(void) {ivec2 cdfxSize=textureSize(cdfx,0);int cdfWidth=cdfxSize.x;int icdfWidth=cdfWidth-1;ivec2 currentPixel=ivec2(gl_FragCoord.xy);vec3 outputColor=vec3(1.0);if (currentPixel.x==0) {outputColor.x=0.0;} else if (currentPixel.x==icdfWidth-1) {outputColor.x=1.0;} else {float targetValue=fetchCDFx(cdfWidth-1)*vUV.x;outputColor.x=bisectx(cdfWidth,targetValue);}
ivec2 cdfySize=textureSize(cdfy,0);int cdfHeight=cdfySize.y;if (currentPixel.y==0) {outputColor.y=0.0;} else if (currentPixel.y==cdfHeight-2) {outputColor.y=1.0;} else {float targetValue=fetchCDFy(cdfHeight-1,currentPixel.x)*vUV.y;outputColor.y=max(bisecty(cdfHeight,targetValue,currentPixel.x),0.0);}
vec2 size=vec2(textureSize(scaledLuminanceSampler,0));float highestMip=floor(log2(size.x));float normalization=texture(scaledLuminanceSampler,vUV,highestMip).r;float pixelLuminance=fetchLuminance(vUV);outputColor.z=pixelLuminance/(2.0*PI*normalization);gl_FragColor=vec4(outputColor,1.0);}
`, iblIcdfPixelShader;
var init_iblIcdf_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name346]) {
    ShaderStore.ShadersStore[name346] = shader345;
  }
  iblIcdfPixelShader = { name: name346, shader: shader345 };
});

// node_modules/@babylonjs/core/ShadersWGSL/iblCdfDebug.fragment.js
var exports_iblCdfDebug_fragment = {};
__export(exports_iblCdfDebug_fragment, {
  iblCdfDebugPixelShaderWGSL: () => iblCdfDebugPixelShaderWGSL
});
var name347 = "iblCdfDebugPixelShader", shader346 = `#define PI 3.1415927
varying vUV: vec2f;var cdfySampler: sampler;var cdfy: texture_2d<f32>;var cdfxSampler: sampler;var cdfx: texture_2d<f32>;var icdfSampler: sampler;var icdf: texture_2d<f32>;
#ifdef IBL_USE_CUBE_MAP
var iblSourceSampler: sampler;var iblSource: texture_cube<f32>;
#else
var iblSourceSampler: sampler;var iblSource: texture_2d<f32>;
#endif
var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#define cdfyVSize (0.8/3.0)
#define cdfxVSize 0.1
#define cdfyHSize 0.5
uniform sizeParams: vec4f;
#ifdef IBL_USE_CUBE_MAP
fn equirectangularToCubemapDirection(uv: vec2f)->vec3f {var longitude: f32=uv.x*2.0*PI-PI;var latitude: f32=PI*0.5-uv.y*PI;var direction: vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs { 
var colour: vec3f= vec3f(0.0);var uv: vec2f =
vec2f((uniforms.sizeParams.x+input.vUV.x)*uniforms.sizeParams.z,(uniforms.sizeParams.y+input.vUV.y)*uniforms.sizeParams.w);var backgroundColour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var cdfxWidth: u32=textureDimensions(cdfx,0).x;var cdfyHeight: u32=textureDimensions(cdfy,0).y;const iblStart: f32=1.0-cdfyVSize;const pdfStart: f32=1.0-2.0*cdfyVSize;const cdfyStart: f32=1.0-3.0*cdfyVSize;const cdfxStart: f32=1.0-3.0*cdfyVSize-cdfxVSize;const icdfxStart: f32=1.0-3.0*cdfyVSize-2.0*cdfxVSize;
#ifdef IBL_USE_CUBE_MAP
var direction: vec3f=equirectangularToCubemapDirection(
(uv- vec2f(0.0,iblStart))* vec2f(1.0,1.0/cdfyVSize));var iblColour: vec3f=textureSampleLevel(iblSource,iblSourceSampler,direction,0.0).rgb;
#else
var iblColour: vec3f=textureSample(iblSource,iblSourceSampler,(uv- vec2f(0.0,iblStart)) *
vec2f(1.0,1.0/cdfyVSize))
.rgb;
#endif
var pdfColour: vec3f =
textureSample(icdf,icdfSampler,(uv- vec2f(0.0,pdfStart))* vec2f(1.0,1.0/cdfyVSize)).zzz;var cdfyColour: f32 =
textureSample(cdfy,cdfySampler,(uv- vec2f(0.0,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).r;var icdfyColour: f32 =
textureSample(icdf,icdfSampler,(uv- vec2f(0.5,cdfyStart))* vec2f(2.0,1.0/cdfyVSize)).g;var cdfxColour: f32 =
textureSample(cdfx,cdfxSampler,(uv- vec2f(0.0,cdfxStart))* vec2f(1.0,1.0/cdfxVSize)).r;var icdfxColour: f32=textureSample(icdf,icdfSampler,(uv- vec2f(0.0,icdfxStart)) *
vec2f(1.0,1.0/cdfxVSize)).r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>pdfStart) {colour+=pdfColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=cdfyColour/f32(cdfyHeight);} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=cdfxColour/f32(cdfxWidth);} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}
fragmentOutputs.color =vec4(mix(colour,backgroundColour,0.5),1.0);}`, iblCdfDebugPixelShaderWGSL;
var init_iblCdfDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name347]) {
    ShaderStore.ShadersStoreWGSL[name347] = shader346;
  }
  iblCdfDebugPixelShaderWGSL = { name: name347, shader: shader346 };
});

// node_modules/@babylonjs/core/Shaders/iblCdfDebug.fragment.js
var exports_iblCdfDebug_fragment2 = {};
__export(exports_iblCdfDebug_fragment2, {
  iblCdfDebugPixelShader: () => iblCdfDebugPixelShader
});
var name348 = "iblCdfDebugPixelShader", shader347 = `precision highp samplerCube;
#define PI 3.1415927
varying vec2 vUV;uniform sampler2D cdfy;uniform sampler2D cdfx;uniform sampler2D icdf;uniform sampler2D pdf;
#ifdef IBL_USE_CUBE_MAP
uniform samplerCube iblSource;
#else
uniform sampler2D iblSource;
#endif
uniform sampler2D textureSampler;
#define cdfyVSize (0.8/3.0)
#define cdfxVSize 0.1
#define cdfyHSize 0.5
uniform vec4 sizeParams;
#define offsetX sizeParams.x
#define offsetY sizeParams.y
#define widthScale sizeParams.z
#define heightScale sizeParams.w
#ifdef IBL_USE_CUBE_MAP
vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*2.0*PI-PI;float latitude=PI*0.5-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;}
#endif
void main(void) {vec3 colour=vec3(0.0);vec2 uv =
vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec3 backgroundColour=texture2D(textureSampler,vUV).rgb;int cdfxWidth=textureSize(cdfx,0).x;int cdfyHeight=textureSize(cdfy,0).y;const float iblStart=1.0-cdfyVSize;const float pdfStart=1.0-2.0*cdfyVSize;const float cdfyStart=1.0-3.0*cdfyVSize;const float cdfxStart=1.0-3.0*cdfyVSize-cdfxVSize;const float icdfxStart=1.0-3.0*cdfyVSize-2.0*cdfxVSize;
#ifdef IBL_USE_CUBE_MAP
vec3 direction=equirectangularToCubemapDirection(
(uv-vec2(0.0,iblStart))*vec2(1.0,1.0/cdfyVSize));vec3 iblColour=textureCubeLodEXT(iblSource,direction,0.0).rgb;
#else
vec3 iblColour=texture2D(iblSource,(uv-vec2(0.0,iblStart)) *
vec2(1.0,1.0/cdfyVSize))
.rgb;
#endif
vec3 pdfColour=texture(icdf,(uv-vec2(0.0,pdfStart)) *
vec2(1.0,1.0/cdfyVSize)).zzz;float cdfyColour =
texture2D(cdfy,(uv-vec2(0.0,cdfyStart))*vec2(2.0,1.0/cdfyVSize))
.r;float icdfyColour =
texture2D(icdf,(uv-vec2(0.5,cdfyStart))*vec2(2.0,1.0/cdfyVSize))
.g;float cdfxColour =
texture2D(cdfx,(uv-vec2(0.0,cdfxStart))*vec2(1.0,1.0/cdfxVSize))
.r;float icdfxColour=texture2D(icdf,(uv-vec2(0.0,icdfxStart)) *
vec2(1.0,1.0/cdfxVSize))
.r;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {colour=backgroundColour;} else if (uv.y>iblStart) {colour+=iblColour;} else if (uv.y>pdfStart) {colour+=pdfColour;} else if (uv.y>cdfyStart && uv.x<0.5) {colour.r+=cdfyColour/float(cdfyHeight);} else if (uv.y>cdfyStart && uv.x>0.5) {colour.r+=icdfyColour;} else if (uv.y>cdfxStart) {colour.r+=cdfxColour/float(cdfxWidth);} else if (uv.y>icdfxStart) {colour.r+=icdfxColour;}
gl_FragColor=vec4(colour,1.0);glFragColor.rgb=mix(gl_FragColor.rgb,backgroundColour,0.5);}
`, iblCdfDebugPixelShader;
var init_iblCdfDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name348]) {
    ShaderStore.ShadersStore[name348] = shader347;
  }
  iblCdfDebugPixelShader = { name: name348, shader: shader347 };
});

// node_modules/@babylonjs/core/ShadersWGSL/hdrIrradianceFiltering.vertex.js
var exports_hdrIrradianceFiltering_vertex = {};
__export(exports_hdrIrradianceFiltering_vertex, {
  hdrIrradianceFilteringVertexShaderWGSL: () => hdrIrradianceFilteringVertexShaderWGSL
});
var name349 = "hdrIrradianceFilteringVertexShader", shader348 = `attribute position: vec2f;varying direction: vec3f;uniform up: vec3f;uniform right: vec3f;uniform front: vec3f;
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var view: mat3x3f= mat3x3f(uniforms.up,uniforms.right,uniforms.front);vertexOutputs.direction=view*vec3f(input.position,1.0);vertexOutputs.position= vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, hdrIrradianceFilteringVertexShaderWGSL;
var init_hdrIrradianceFiltering_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name349]) {
    ShaderStore.ShadersStoreWGSL[name349] = shader348;
  }
  hdrIrradianceFilteringVertexShaderWGSL = { name: name349, shader: shader348 };
});

// node_modules/@babylonjs/core/ShadersWGSL/hdrIrradianceFiltering.fragment.js
var exports_hdrIrradianceFiltering_fragment = {};
__export(exports_hdrIrradianceFiltering_fragment, {
  hdrIrradianceFilteringPixelShaderWGSL: () => hdrIrradianceFilteringPixelShaderWGSL
});
var name350 = "hdrIrradianceFilteringPixelShader", shader349 = `#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
var inputTextureSampler: sampler;var inputTexture: texture_cube<f32>;
#ifdef IBL_CDF_FILTERING
var icdfTextureSampler: sampler;var icdfTexture: texture_2d<f32>;
#endif
uniform vFilteringInfo: vec2f;uniform hdrScale: f32;varying direction: vec3f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=irradiance(inputTexture,inputTextureSampler,input.direction,uniforms.vFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfTexture,icdfTextureSampler
#endif
);fragmentOutputs.color= vec4f(color*uniforms.hdrScale,1.0);}`, hdrIrradianceFilteringPixelShaderWGSL;
var init_hdrIrradianceFiltering_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  init_importanceSampling();
  init_pbrBRDFFunctions();
  init_hdrFilteringFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name350]) {
    ShaderStore.ShadersStoreWGSL[name350] = shader349;
  }
  hdrIrradianceFilteringPixelShaderWGSL = { name: name350, shader: shader349 };
});

// node_modules/@babylonjs/core/Shaders/hdrIrradianceFiltering.vertex.js
var exports_hdrIrradianceFiltering_vertex2 = {};
__export(exports_hdrIrradianceFiltering_vertex2, {
  hdrIrradianceFilteringVertexShader: () => hdrIrradianceFilteringVertexShader
});
var name351 = "hdrIrradianceFilteringVertexShader", shader350 = `attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, hdrIrradianceFilteringVertexShader;
var init_hdrIrradianceFiltering_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name351]) {
    ShaderStore.ShadersStore[name351] = shader350;
  }
  hdrIrradianceFilteringVertexShader = { name: name351, shader: shader350 };
});

// node_modules/@babylonjs/core/Shaders/hdrIrradianceFiltering.fragment.js
var exports_hdrIrradianceFiltering_fragment2 = {};
__export(exports_hdrIrradianceFiltering_fragment2, {
  hdrIrradianceFilteringPixelShader: () => hdrIrradianceFilteringPixelShader
});
var name352 = "hdrIrradianceFilteringPixelShader", shader351 = `#include<helperFunctions>
#include<importanceSampling>
#include<pbrBRDFFunctions>
#include<hdrFilteringFunctions>
uniform samplerCube inputTexture;
#ifdef IBL_CDF_FILTERING
uniform sampler2D icdfTexture;
#endif
uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=irradiance(inputTexture,direction,vFilteringInfo
#ifdef IBL_CDF_FILTERING
,icdfTexture
#endif
);gl_FragColor=vec4(color*hdrScale,1.0);}`, hdrIrradianceFilteringPixelShader;
var init_hdrIrradianceFiltering_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  init_importanceSampling2();
  init_pbrBRDFFunctions2();
  init_hdrFilteringFunctions2();
  if (!ShaderStore.ShadersStore[name352]) {
    ShaderStore.ShadersStore[name352] = shader351;
  }
  hdrIrradianceFilteringPixelShader = { name: name352, shader: shader351 };
});

// node_modules/@babylonjs/core/ShadersWGSL/sprites.vertex.js
var exports_sprites_vertex = {};
__export(exports_sprites_vertex, {
  spritesVertexShaderWGSL: () => spritesVertexShaderWGSL
});
var name353 = "spritesVertexShader", shader352 = `attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f;
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; 
var cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); 
vertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y;
#ifdef FOG
vertexOutputs.vFogDistance=viewPos;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, spritesVertexShaderWGSL;
var init_sprites_vertex = __esm(() => {
  init_shaderStore();
  init_fogVertexDeclaration();
  init_logDepthDeclaration();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name353]) {
    ShaderStore.ShadersStoreWGSL[name353] = shader352;
  }
  spritesVertexShaderWGSL = { name: name353, shader: shader352 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingCompatibility.js
var name354 = "imageProcessingCompatibility", shader353 = `#ifdef IMAGEPROCESSINGPOSTPROCESS
fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a);
#endif
`;
var init_imageProcessingCompatibility = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name354]) {
    ShaderStore.IncludesShadersStoreWGSL[name354] = shader353;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/sprites.fragment.js
var exports_sprites_fragment = {};
__export(exports_sprites_fragment, {
  spritesPixelShaderWGSL: () => spritesPixelShaderWGSL
});
var name355 = "spritesPixelShader", shader354 = `uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#include<fogFragmentDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
#ifdef PIXEL_PERFECT
fn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;}
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#ifdef PIXEL_PERFECT
var uv: vec2f=uvPixelPerfect(input.vUV);
#else
var uv: vec2f=input.vUV;
#endif
var color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.)
{if (color.a<0.95) {discard;}}
color*=input.vColor;
#include<logDepthFragment>
#include<fogFragment>
fragmentOutputs.color=color;
#include<imageProcessingCompatibility>
#define CUSTOM_FRAGMENT_MAIN_END
}`, spritesPixelShaderWGSL;
var init_sprites_fragment = __esm(() => {
  init_shaderStore();
  init_fogFragmentDeclaration();
  init_logDepthDeclaration();
  init_logDepthFragment();
  init_fogFragment();
  init_imageProcessingCompatibility();
  if (!ShaderStore.ShadersStoreWGSL[name355]) {
    ShaderStore.ShadersStoreWGSL[name355] = shader354;
  }
  spritesPixelShaderWGSL = { name: name355, shader: shader354 };
});

// node_modules/@babylonjs/core/Shaders/sprites.vertex.js
var exports_sprites_vertex2 = {};
__export(exports_sprites_vertex2, {
  spritesVertexShader: () => spritesVertexShader
});
var name356 = "spritesVertexShader", shader355 = `attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; 
vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); 
vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;
#ifdef FOG
vFogDistance=viewPos;
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, spritesVertexShader;
var init_sprites_vertex2 = __esm(() => {
  init_shaderStore();
  init_fogVertexDeclaration2();
  init_logDepthDeclaration2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name356]) {
    ShaderStore.ShadersStore[name356] = shader355;
  }
  spritesVertexShader = { name: name356, shader: shader355 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js
var name357 = "imageProcessingCompatibility", shader356 = `#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));
#endif
`;
var init_imageProcessingCompatibility2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name357]) {
    ShaderStore.IncludesShadersStore[name357] = shader356;
  }
});

// node_modules/@babylonjs/core/Shaders/sprites.fragment.js
var exports_sprites_fragment2 = {};
__export(exports_sprites_fragment2, {
  spritesPixelShader: () => spritesPixelShader
});
var name358 = "spritesPixelShader", shader357 = `#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;
#include<fogFragmentDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
#ifdef PIXEL_PERFECT
vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}
#endif
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#ifdef PIXEL_PERFECT
vec2 uv=uvPixelPerfect(vUV);
#else
vec2 uv=vUV;
#endif
vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)
{if (color.a<0.95)
discard;}
color*=vColor;
#include<logDepthFragment>
#include<fogFragment>
gl_FragColor=color;
#include<imageProcessingCompatibility>
#define CUSTOM_FRAGMENT_MAIN_END
}`, spritesPixelShader;
var init_sprites_fragment2 = __esm(() => {
  init_shaderStore();
  init_fogFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_logDepthFragment2();
  init_fogFragment2();
  init_imageProcessingCompatibility2();
  if (!ShaderStore.ShadersStore[name358]) {
    ShaderStore.ShadersStore[name358] = shader357;
  }
  spritesPixelShader = { name: name358, shader: shader357 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/gaussianSplattingFragmentDeclaration.js
var name360 = "gaussianSplattingFragmentDeclaration", shader359 = `vec4 gaussianColor(vec4 inColor)
{float A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*inColor.a;
#include<logDepthFragment>
vec3 color=inColor.rgb;
#ifdef FOG
#include<fogFragment>
#endif
return vec4(color,B);}
`;
var init_gaussianSplattingFragmentDeclaration = __esm(() => {
  init_shaderStore();
  init_logDepthFragment2();
  init_fogFragment2();
  if (!ShaderStore.IncludesShadersStore[name360]) {
    ShaderStore.IncludesShadersStore[name360] = shader359;
  }
});

// node_modules/@babylonjs/core/Shaders/gaussianSplatting.fragment.js
var exports_gaussianSplatting_fragment = {};
__export(exports_gaussianSplatting_fragment, {
  gaussianSplattingPixelShader: () => gaussianSplattingPixelShader
});
var name361 = "gaussianSplattingPixelShader", shader360 = `#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
varying vec4 vColor;varying vec2 vPosition;
#include<gaussianSplattingFragmentDeclaration>
void main () { 
#include<clipPlaneFragment>
gl_FragColor=gaussianColor(vColor);}
`, gaussianSplattingPixelShader;
var init_gaussianSplatting_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_fogFragmentDeclaration2();
  init_gaussianSplattingFragmentDeclaration();
  init_clipPlaneFragment2();
  if (!ShaderStore.ShadersStore[name361]) {
    ShaderStore.ShadersStore[name361] = shader360;
  }
  gaussianSplattingPixelShader = { name: name361, shader: shader360 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/gaussianSplattingVertexDeclaration.js
var name362 = "gaussianSplattingVertexDeclaration", shader361 = `attribute vec2 position;uniform mat4 view;uniform mat4 projection;uniform mat4 world;uniform vec4 vEyePosition;`;
var init_gaussianSplattingVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name362]) {
    ShaderStore.IncludesShadersStore[name362] = shader361;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/gaussianSplattingUboDeclaration.js
var name363 = "gaussianSplattingUboDeclaration", shader362 = `#include<sceneUboDeclaration>
#include<meshUboDeclaration>
attribute vec2 position;`;
var init_gaussianSplattingUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  init_meshUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name363]) {
    ShaderStore.IncludesShadersStore[name363] = shader362;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/gaussianSplatting.js
var name364 = "gaussianSplatting", shader363 = `#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)
mat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],
matrix[0][1],matrix[1][1],matrix[2][1],
matrix[0][2],matrix[1][2],matrix[2][2]);}
#endif
vec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);}
#if SH_DEGREE>0
ivec2 getDataUVint(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return ivec2(uint(x+0.5),uint(y+0.5));}
#endif
struct Splat {vec4 center;vec4 color;vec4 covA;vec4 covB;
#if SH_DEGREE>0
uvec4 sh0; 
#endif
#if SH_DEGREE>1
uvec4 sh1;
#endif
#if SH_DEGREE>2
uvec4 sh2;
#endif
};Splat readSplat(float splatIndex)
{Splat splat;vec2 splatUV=getDataUV(splatIndex,dataTextureSize);splat.center=texture2D(centersTexture,splatUV);splat.color=texture2D(colorsTexture,splatUV);splat.covA=texture2D(covariancesATexture,splatUV)*splat.center.w;splat.covB=texture2D(covariancesBTexture,splatUV)*splat.center.w;
#if SH_DEGREE>0
ivec2 splatUVint=getDataUVint(splatIndex,dataTextureSize);splat.sh0=texelFetch(shTexture0,splatUVint,0);
#endif
#if SH_DEGREE>1
splat.sh1=texelFetch(shTexture1,splatUVint,0);
#endif
#if SH_DEGREE>2
splat.sh2=texelFetch(shTexture2,splatUVint,0);
#endif
return splat;}
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
vec3 computeColorFromSHDegree(vec3 dir,const vec3 sh[16])
{const float SH_C0=0.28209479;const float SH_C1=0.48860251;float SH_C2[5];SH_C2[0]=1.092548430;SH_C2[1]=-1.09254843;SH_C2[2]=0.315391565;SH_C2[3]=-1.09254843;SH_C2[4]=0.546274215;float SH_C3[7];SH_C3[0]=-0.59004358;SH_C3[1]=2.890611442;SH_C3[2]=-0.45704579;SH_C3[3]=0.373176332;SH_C3[4]=-0.45704579;SH_C3[5]=1.445305721;SH_C3[6]=-0.59004358;vec3 result=/*SH_C0**/sh[0];
#if SH_DEGREE>0
float x=dir.x;float y=dir.y;float z=dir.z;result+=- SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3];
#if SH_DEGREE>1
float xx=x*x,yy=y*y,zz=z*z;float xy=x*y,yz=y*z,xz=x*z;result+=
SH_C2[0]*xy*sh[4] +
SH_C2[1]*yz*sh[5] +
SH_C2[2]*(2.0*zz-xx-yy)*sh[6] +
SH_C2[3]*xz*sh[7] +
SH_C2[4]*(xx-yy)*sh[8];
#if SH_DEGREE>2
result+=
SH_C3[0]*y*(3.0*xx-yy)*sh[9] +
SH_C3[1]*xy*z*sh[10] +
SH_C3[2]*y*(4.0*zz-xx-yy)*sh[11] +
SH_C3[3]*z*(2.0*zz-3.0*xx-3.0*yy)*sh[12] +
SH_C3[4]*x*(4.0*zz-xx-yy)*sh[13] +
SH_C3[5]*z*(xx-yy)*sh[14] +
SH_C3[6]*x*(xx-3.0*yy)*sh[15];
#endif
#endif
#endif
return result;}
vec4 decompose(uint value)
{vec4 components=vec4(
float((value ) & 255u),
float((value>>uint( 8)) & 255u),
float((value>>uint(16)) & 255u),
float((value>>uint(24)) & 255u));return components*vec4(2./255.)-vec4(1.);}
vec3 computeSH(Splat splat,vec3 color,vec3 dir)
{vec3 sh[16];sh[0]=color;
#if SH_DEGREE>0
vec4 sh00=decompose(splat.sh0.x);vec4 sh01=decompose(splat.sh0.y);vec4 sh02=decompose(splat.sh0.z);sh[1]=vec3(sh00.x,sh00.y,sh00.z);sh[2]=vec3(sh00.w,sh01.x,sh01.y);sh[3]=vec3(sh01.z,sh01.w,sh02.x);
#endif
#if SH_DEGREE>1
vec4 sh03=decompose(splat.sh0.w);vec4 sh04=decompose(splat.sh1.x);vec4 sh05=decompose(splat.sh1.y);sh[4]=vec3(sh02.y,sh02.z,sh02.w);sh[5]=vec3(sh03.x,sh03.y,sh03.z);sh[6]=vec3(sh03.w,sh04.x,sh04.y);sh[7]=vec3(sh04.z,sh04.w,sh05.x);sh[8]=vec3(sh05.y,sh05.z,sh05.w);
#endif
#if SH_DEGREE>2
vec4 sh06=decompose(splat.sh1.z);vec4 sh07=decompose(splat.sh1.w);vec4 sh08=decompose(splat.sh2.x);vec4 sh09=decompose(splat.sh2.y);vec4 sh10=decompose(splat.sh2.z);vec4 sh11=decompose(splat.sh2.w);sh[9]=vec3(sh06.x,sh06.y,sh06.z);sh[10]=vec3(sh06.w,sh07.x,sh07.y);sh[11]=vec3(sh07.z,sh07.w,sh08.x);sh[12]=vec3(sh08.y,sh08.z,sh08.w);sh[13]=vec3(sh09.x,sh09.y,sh09.z);sh[14]=vec3(sh09.w,sh10.x,sh10.y);sh[15]=vec3(sh10.z,sh10.w,sh11.x); 
#endif
return computeColorFromSHDegree(dir,sh);}
#else
vec3 computeSH(Splat splat,vec3 color,vec3 dir)
{return color;}
#endif
vec4 gaussianSplatting(vec2 meshPos,vec3 worldPos,vec2 scale,vec3 covA,vec3 covB,mat4 worldMatrix,mat4 viewMatrix,mat4 projectionMatrix)
{mat4 modelView=viewMatrix*worldMatrix;vec4 camspace=viewMatrix*vec4(worldPos,1.);vec4 pos2d=projectionMatrix*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds
|| pos2d.y<-bounds || pos2d.y>bounds) {return vec4(0.0,0.0,2.0,1.0);}
mat3 Vrk=mat3(
covA.x,covA.y,covA.z,
covA.y,covB.x,covB.y,
covA.z,covB.y,covB.z
);mat3 J=mat3(
focal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),
0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),
0.,0.,0.
);mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float epsilon=0.0001;float lambda1=mid+radius+epsilon,lambda2=mid-radius+epsilon;if (lambda2<0.0)
{return vec4(0.0,0.0,2.0,1.0);}
vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vec2 vCenter=vec2(pos2d);return vec4(
vCenter 
+ ((meshPos.x*majorAxis
+ meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,pos2d.zw);}`;
var init_gaussianSplatting = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name364]) {
    ShaderStore.IncludesShadersStore[name364] = shader363;
  }
});

// node_modules/@babylonjs/core/Shaders/gaussianSplatting.vertex.js
var exports_gaussianSplatting_vertex = {};
__export(exports_gaussianSplatting_vertex, {
  gaussianSplattingVertexShader: () => gaussianSplattingVertexShader
});
var name365 = "gaussianSplattingVertexShader", shader364 = `#include<__decl__gaussianSplattingVertex>
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
attribute float splatIndex;uniform vec2 invViewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;
#if SH_DEGREE>0
uniform highp usampler2D shTexture0;
#endif
#if SH_DEGREE>1
uniform highp usampler2D shTexture1;
#endif
#if SH_DEGREE>2
uniform highp usampler2D shTexture2;
#endif
varying vec4 vColor;varying vec2 vPosition;
#include<gaussianSplatting>
void main () {Splat splat=readSplat(splatIndex);vec3 covA=splat.covA.xyz;vec3 covB=vec3(splat.covA.w,splat.covB.xy);vec4 worldPos=world*vec4(splat.center.xyz,1.0);vColor=splat.color;vPosition=position;
#if SH_DEGREE>0
mat3 worldRot=mat3(world);mat3 normWorldRot=inverseMat3(worldRot);vec3 dir=normalize(normWorldRot*(worldPos.xyz-vEyePosition.xyz));dir.y*=-1.; 
vColor.xyz=computeSH(splat,splat.color.xyz,dir);
#endif
gl_Position=gaussianSplatting(position,worldPos.xyz,vec2(1.,1.),covA,covB,world,view,projection);
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}
`, gaussianSplattingVertexShader;
var init_gaussianSplatting_vertex = __esm(() => {
  init_shaderStore();
  init_gaussianSplattingVertexDeclaration();
  init_gaussianSplattingUboDeclaration();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_logDepthDeclaration2();
  init_helperFunctions2();
  init_gaussianSplatting();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name365]) {
    ShaderStore.ShadersStore[name365] = shader364;
  }
  gaussianSplattingVertexShader = { name: name365, shader: shader364 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/gaussianSplattingFragmentDeclaration.js
var name366 = "gaussianSplattingFragmentDeclaration", shader365 = `fn gaussianColor(inColor: vec4f,inPosition: vec2f)->vec4f
{var A : f32=-dot(inPosition,inPosition);if (A>-4.0)
{var B: f32=exp(A)*inColor.a;
#include<logDepthFragment>
var color: vec3f=inColor.rgb;
#ifdef FOG
#include<fogFragment>
#endif
return vec4f(color,B);} else {return vec4f(0.0);}}
`;
var init_gaussianSplattingFragmentDeclaration2 = __esm(() => {
  init_shaderStore();
  init_logDepthFragment();
  init_fogFragment();
  if (!ShaderStore.IncludesShadersStoreWGSL[name366]) {
    ShaderStore.IncludesShadersStoreWGSL[name366] = shader365;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/gaussianSplatting.fragment.js
var exports_gaussianSplatting_fragment2 = {};
__export(exports_gaussianSplatting_fragment2, {
  gaussianSplattingPixelShaderWGSL: () => gaussianSplattingPixelShaderWGSL
});
var name367 = "gaussianSplattingPixelShader", shader366 = `#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#include<fogFragmentDeclaration>
varying vColor: vec4f;varying vPosition: vec2f;
#include<gaussianSplattingFragmentDeclaration>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
fragmentOutputs.color=gaussianColor(input.vColor,input.vPosition);}
`, gaussianSplattingPixelShaderWGSL;
var init_gaussianSplatting_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_logDepthDeclaration();
  init_fogFragmentDeclaration();
  init_gaussianSplattingFragmentDeclaration2();
  init_clipPlaneFragment();
  if (!ShaderStore.ShadersStoreWGSL[name367]) {
    ShaderStore.ShadersStoreWGSL[name367] = shader366;
  }
  gaussianSplattingPixelShaderWGSL = { name: name367, shader: shader366 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/gaussianSplatting.js
var name368 = "gaussianSplatting", shader367 = `fn getDataUV(index: f32,dataTextureSize: vec2f)->vec2<f32> {let y: f32=floor(index/dataTextureSize.x);let x: f32=index-y*dataTextureSize.x;return vec2f((x+0.5),(y+0.5));}
struct Splat {center: vec4f,
color: vec4f,
covA: vec4f,
covB: vec4f,
#if SH_DEGREE>0
sh0: vec4<u32>,
#endif
#if SH_DEGREE>1
sh1: vec4<u32>,
#endif
#if SH_DEGREE>2
sh2: vec4<u32>,
#endif
};fn readSplat(splatIndex: f32,dataTextureSize: vec2f)->Splat {var splat: Splat;let splatUV=getDataUV(splatIndex,dataTextureSize);let splatUVi32=vec2<i32>(i32(splatUV.x),i32(splatUV.y));splat.center=textureLoad(centersTexture,splatUVi32,0);splat.color=textureLoad(colorsTexture,splatUVi32,0);splat.covA=textureLoad(covariancesATexture,splatUVi32,0)*splat.center.w;splat.covB=textureLoad(covariancesBTexture,splatUVi32,0)*splat.center.w;
#if SH_DEGREE>0
splat.sh0=textureLoad(shTexture0,splatUVi32,0);
#endif
#if SH_DEGREE>1
splat.sh1=textureLoad(shTexture1,splatUVi32,0);
#endif
#if SH_DEGREE>2
splat.sh2=textureLoad(shTexture2,splatUVi32,0);
#endif
return splat;}
fn computeColorFromSHDegree(dir: vec3f,sh: array<vec3<f32>,16>)->vec3f
{let SH_C0: f32=0.28209479;let SH_C1: f32=0.48860251;var SH_C2: array<f32,5>=array<f32,5>(
1.092548430,
-1.09254843,
0.315391565,
-1.09254843,
0.546274215
);var SH_C3: array<f32,7>=array<f32,7>(
-0.59004358,
2.890611442,
-0.45704579,
0.373176332,
-0.45704579,
1.445305721,
-0.59004358
);var result: vec3f=/*SH_C0**/sh[0];
#if SH_DEGREE>0
let x: f32=dir.x;let y: f32=dir.y;let z: f32=dir.z;result+=-SH_C1*y*sh[1]+SH_C1*z*sh[2]-SH_C1*x*sh[3];
#if SH_DEGREE>1
let xx: f32=x*x;let yy: f32=y*y;let zz: f32=z*z;let xy: f32=x*y;let yz: f32=y*z;let xz: f32=x*z;result+=
SH_C2[0]*xy*sh[4] +
SH_C2[1]*yz*sh[5] +
SH_C2[2]*(2.0f*zz-xx-yy)*sh[6] +
SH_C2[3]*xz*sh[7] +
SH_C2[4]*(xx-yy)*sh[8];
#if SH_DEGREE>2
result+=
SH_C3[0]*y*(3.0f*xx-yy)*sh[9] +
SH_C3[1]*xy*z*sh[10] +
SH_C3[2]*y*(4.0f*zz-xx-yy)*sh[11] +
SH_C3[3]*z*(2.0f*zz-3.0f*xx-3.0f*yy)*sh[12] +
SH_C3[4]*x*(4.0f*zz-xx-yy)*sh[13] +
SH_C3[5]*z*(xx-yy)*sh[14] +
SH_C3[6]*x*(xx-3.0f*yy)*sh[15];
#endif
#endif
#endif
return result;}
fn decompose(value: u32)->vec4f
{let components : vec4f=vec4f(
f32((value ) & 255u),
f32((value>>u32( 8)) & 255u),
f32((value>>u32(16)) & 255u),
f32((value>>u32(24)) & 255u));return components*vec4f(2./255.)-vec4f(1.);}
fn computeSH(splat: Splat,color: vec3f,dir: vec3f)->vec3f
{var sh: array<vec3<f32>,16>;sh[0]=color;
#if SH_DEGREE>0
let sh00: vec4f=decompose(splat.sh0.x);let sh01: vec4f=decompose(splat.sh0.y);let sh02: vec4f=decompose(splat.sh0.z);sh[1]=vec3f(sh00.x,sh00.y,sh00.z);sh[2]=vec3f(sh00.w,sh01.x,sh01.y);sh[3]=vec3f(sh01.z,sh01.w,sh02.x);
#endif
#if SH_DEGREE>1
let sh03: vec4f=decompose(splat.sh0.w);let sh04: vec4f=decompose(splat.sh1.x);let sh05: vec4f=decompose(splat.sh1.y);sh[4]=vec3f(sh02.y,sh02.z,sh02.w);sh[5]=vec3f(sh03.x,sh03.y,sh03.z);sh[6]=vec3f(sh03.w,sh04.x,sh04.y);sh[7]=vec3f(sh04.z,sh04.w,sh05.x);sh[8]=vec3f(sh05.y,sh05.z,sh05.w);
#endif
#if SH_DEGREE>2
let sh06: vec4f=decompose(splat.sh1.z);let sh07: vec4f=decompose(splat.sh1.w);let sh08: vec4f=decompose(splat.sh2.x);let sh09: vec4f=decompose(splat.sh2.y);let sh10: vec4f=decompose(splat.sh2.z);let sh11: vec4f=decompose(splat.sh2.w);sh[9]=vec3f(sh06.x,sh06.y,sh06.z);sh[10]=vec3f(sh06.w,sh07.x,sh07.y);sh[11]=vec3f(sh07.z,sh07.w,sh08.x);sh[12]=vec3f(sh08.y,sh08.z,sh08.w);sh[13]=vec3f(sh09.x,sh09.y,sh09.z);sh[14]=vec3f(sh09.w,sh10.x,sh10.y);sh[15]=vec3f(sh10.z,sh10.w,sh11.x); 
#endif
return computeColorFromSHDegree(dir,sh);}
fn gaussianSplatting(
meshPos: vec2<f32>,
worldPos: vec3<f32>,
scale: vec2<f32>,
covA: vec3<f32>,
covB: vec3<f32>,
worldMatrix: mat4x4<f32>,
viewMatrix: mat4x4<f32>,
projectionMatrix: mat4x4<f32>,
focal: vec2f,
invViewport: vec2f
)->vec4f {let modelView=viewMatrix*worldMatrix;let camspace=viewMatrix*vec4f(worldPos,1.0);let pos2d=projectionMatrix*camspace;let bounds=1.2*pos2d.w;if (pos2d.z<0. || pos2d.x<-bounds || pos2d.x>bounds || pos2d.y<-bounds || pos2d.y>bounds) {return vec4f(0.0,0.0,2.0,1.0);}
let Vrk=mat3x3<f32>(
covA.x,covA.y,covA.z,
covA.y,covB.x,covB.y,
covA.z,covB.y,covB.z
);let J=mat3x3<f32>(
focal.x/camspace.z,0.0,-(focal.x*camspace.x)/(camspace.z*camspace.z),
0.0,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),
0.0,0.0,0.0
);let invy=mat3x3<f32>(
1.0,0.0,0.0,
0.0,-1.0,0.0,
0.0,0.0,1.0
);let T=invy*transpose(mat3x3<f32>(
modelView[0].xyz,
modelView[1].xyz,
modelView[2].xyz))*J;let cov2d=transpose(T)*Vrk*T;let mid=(cov2d[0][0]+cov2d[1][1])/2.0;let radius=length(vec2<f32>((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));let lambda1=mid+radius;let lambda2=mid-radius;if (lambda2<0.0) {return vec4f(0.0,0.0,2.0,1.0);}
let diagonalVector=normalize(vec2<f32>(cov2d[0][1],lambda1-cov2d[0][0]));let majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;let minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2<f32>(diagonalVector.y,-diagonalVector.x);let vCenter=vec2<f32>(pos2d.x,pos2d.y);return vec4f(
vCenter+((meshPos.x*majorAxis+meshPos.y*minorAxis)*invViewport*pos2d.w)*scale,
pos2d.z,
pos2d.w
);}
`;
var init_gaussianSplatting2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStoreWGSL[name368]) {
    ShaderStore.IncludesShadersStoreWGSL[name368] = shader367;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/gaussianSplatting.vertex.js
var exports_gaussianSplatting_vertex2 = {};
__export(exports_gaussianSplatting_vertex2, {
  gaussianSplattingVertexShaderWGSL: () => gaussianSplattingVertexShaderWGSL
});
var name369 = "gaussianSplattingVertexShader", shader368 = `#include<sceneUboDeclaration>
#include<meshUboDeclaration>
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
attribute splatIndex: f32;attribute position: vec2f;uniform invViewport: vec2f;uniform dataTextureSize: vec2f;uniform focal: vec2f;var covariancesATexture: texture_2d<f32>;var covariancesBTexture: texture_2d<f32>;var centersTexture: texture_2d<f32>;var colorsTexture: texture_2d<f32>;
#if SH_DEGREE>0
var shTexture0: texture_2d<u32>;
#endif
#if SH_DEGREE>1
var shTexture1: texture_2d<u32>;
#endif
#if SH_DEGREE>2
var shTexture2: texture_2d<u32>;
#endif
varying vColor: vec4f;varying vPosition: vec2f;
#include<gaussianSplatting>
@vertex
fn main(input : VertexInputs)->FragmentInputs {var splat: Splat=readSplat(input.splatIndex,uniforms.dataTextureSize);var covA: vec3f=splat.covA.xyz;var covB: vec3f=vec3f(splat.covA.w,splat.covB.xy);let worldPos: vec4f=mesh.world*vec4f(splat.center.xyz,1.0);vertexOutputs.vPosition=input.position;
#if SH_DEGREE>0
let dir: vec3f=normalize(worldPos.xyz-scene.vEyePosition.xyz);vertexOutputs.vColor=vec4f(computeSH(splat,splat.color.xyz,dir),1.0);
#else
vertexOutputs.vColor=splat.color;
#endif
vertexOutputs.position=gaussianSplatting(input.position,worldPos.xyz,vec2f(1.0,1.0),covA,covB,mesh.world,scene.view,scene.projection,uniforms.focal,uniforms.invViewport);
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}
`, gaussianSplattingVertexShaderWGSL;
var init_gaussianSplatting_vertex2 = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration();
  init_meshUboDeclaration();
  init_clipPlaneVertexDeclaration();
  init_fogVertexDeclaration();
  init_logDepthDeclaration();
  init_gaussianSplatting2();
  init_clipPlaneVertex();
  init_fogVertex();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name369]) {
    ShaderStore.ShadersStoreWGSL[name369] = shader368;
  }
  gaussianSplattingVertexShaderWGSL = { name: name369, shader: shader368 };
});

// node_modules/@babylonjs/core/ShadersWGSL/greasedLine.vertex.js
var exports_greasedLine_vertex = {};
__export(exports_greasedLine_vertex, {
  greasedLineVertexShaderWGSL: () => greasedLineVertexShaderWGSL
});
var name371 = "greasedLineVertexShader", shader370 = `#include<instancesDeclaration>
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
attribute grl_widths: f32;
#ifdef GREASED_LINE_USE_OFFSETS
attribute grl_offsets: vec3f; 
#endif
attribute grl_colorPointers: f32;attribute position: vec3f;varying grlCounters: f32;varying grlColorPointer: f32;
#ifdef GREASED_LINE_CAMERA_FACING
attribute grl_nextAndCounters: vec4f;attribute grl_previousAndSide: vec4f;uniform grlResolution: vec2f;uniform grlAspect: f32;uniform grlWidth: f32;uniform grlSizeAttenuation: f32;fn grlFix(i: vec4f,aspect: f32)->vec2f {var res=i.xy/i.w;res.x*=aspect;return res;}
#else
attribute grl_slopes: vec3f;attribute grl_counters: f32;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#include<instancesVertex>
vertexOutputs.grlColorPointer=input.grl_colorPointers;let grlMatrix: mat4x4f=scene.viewProjection*mesh.world ;
#ifdef GREASED_LINE_CAMERA_FACING
let grlBaseWidth: f32=uniforms.grlWidth;let grlPrevious: vec3f=input.grl_previousAndSide.xyz;let grlSide: f32=input.grl_previousAndSide.w;let grlNext: vec3f=input.grl_nextAndCounters.xyz;vertexOutputs.grlCounters=input.grl_nextAndCounters.w;let grlWidth:f32=grlBaseWidth*input.grl_widths;
#ifdef GREASED_LINE_USE_OFFSETS
var grlPositionOffset: vec3f=input.grl_offsets;
#else
var grlPositionOffset=vec3f(0.);
#endif
let positionUpdated: vec3f=vertexInputs.position+grlPositionOffset;let worldDir: vec3f=normalize(grlNext-grlPrevious);let nearPosition: vec3f=positionUpdated+(worldDir*0.001);let grlFinalPosition: vec4f=grlMatrix*vec4f(positionUpdated,1.0);let screenNearPos: vec4f=grlMatrix*vec4(nearPosition,1.0);let grlLinePosition: vec2f=grlFix(grlFinalPosition,uniforms.grlAspect);let grlLineNearPosition: vec2f=grlFix(screenNearPos,uniforms.grlAspect);let grlDir: vec2f=normalize(grlLineNearPosition-grlLinePosition);var grlNormal: vec4f=vec4f(-grlDir.y,grlDir.x,0.0,1.0);let grlHalfWidth: f32=0.5*grlWidth;
#if defined(GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM)
grlNormal.x*=-grlHalfWidth;grlNormal.y*=-grlHalfWidth;
#else
grlNormal.x*=grlHalfWidth;grlNormal.y*=grlHalfWidth;
#endif
grlNormal*=scene.projection;if (uniforms.grlSizeAttenuation==1.) {grlNormal.x*=grlFinalPosition.w;grlNormal.y*=grlFinalPosition.w;let pr=vec4f(uniforms.grlResolution,0.0,1.0)*scene.projection;grlNormal.x/=pr.x;grlNormal.y/=pr.y;}
vertexOutputs.position=vec4f(grlFinalPosition.xy+grlNormal.xy*grlSide,grlFinalPosition.z,grlFinalPosition.w);
#else
vertexOutputs.grlCounters=input.grl_counters;vertexOutputs.position=grlMatrix*vec4f((vertexInputs.position+input.grl_offsets)+input.grl_slopes*input.grl_widths,1.0) ;
#endif
#define CUSTOM_VERTEX_MAIN_END
}
`, greasedLineVertexShaderWGSL;
var init_greasedLine_vertex = __esm(() => {
  init_shaderStore();
  init_instancesDeclaration();
  init_sceneUboDeclaration();
  init_meshUboDeclaration();
  init_instancesVertex();
  if (!ShaderStore.ShadersStoreWGSL[name371]) {
    ShaderStore.ShadersStoreWGSL[name371] = shader370;
  }
  greasedLineVertexShaderWGSL = { name: name371, shader: shader370 };
});

// node_modules/@babylonjs/core/ShadersWGSL/greasedLine.fragment.js
var exports_greasedLine_fragment = {};
__export(exports_greasedLine_fragment, {
  greasedLinePixelShaderWGSL: () => greasedLinePixelShaderWGSL
});
var name372 = "greasedLinePixelShader", shader371 = `var grlColors: texture_2d<f32>;var grlColorsSampler: sampler;uniform grlUseColors: f32;uniform grlUseDash: f32;uniform grlDashArray: f32;uniform grlDashOffset: f32;uniform grlDashRatio: f32;uniform grlVisibility: f32;uniform grlColorsWidth: f32;uniform grl_colorModeAndColorDistributionType: vec2f;uniform grlColor: vec3f;varying grlCounters: f32;varying grlColorPointer: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
let grlColorMode: f32=uniforms.grl_colorModeAndColorDistributionType.x;let grlColorDistributionType: f32=uniforms.grl_colorModeAndColorDistributionType.y;var outColor=vec4(uniforms.grlColor,1.);outColor.a=step(fragmentInputs.grlCounters,uniforms.grlVisibility);if (outColor.a==0.0) {discard;}
if (uniforms.grlUseDash==1.0) {let dashPosition=(fragmentInputs.grlCounters+uniforms.grlDashOffset) % uniforms.grlDashArray;outColor.a*=ceil(dashPosition-(uniforms.grlDashArray*uniforms.grlDashRatio));if (outColor.a==0.0) {discard;}}
if (uniforms.grlUseColors==1.) {
#ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE
let grlColor: vec4f=textureSample(grlColors,grlColorsSampler,vec2f(fragmentInputs.grlCounters,0.));
#else
let lookup: vec2f=vec2(fract(fragmentInputs.grlColorPointer/uniforms.grlColorsWidth),1.0-floor(fragmentInputs.grlColorPointer/uniforms.grlColorsWidth));let grlColor: vec4f=textureSample(grlColors,grlColorsSampler,lookup);
#endif
if (grlColorMode==COLOR_MODE_SET) {outColor=grlColor;} else if (grlColorMode==COLOR_MODE_ADD) {outColor+=grlColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {outColor*=grlColor;}}
#if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY)
fragmentOutputs.color=outColor;
#endif
#if ORDER_INDEPENDENT_TRANSPARENCY
if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+outColor.rgb*outColor.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-outColor.a));} else {fragmentOutputs.backColor+=outColor;}
#endif
#define CUSTOM_FRAGMENT_MAIN_END
}
`, greasedLinePixelShaderWGSL;
var init_greasedLine_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name372]) {
    ShaderStore.ShadersStoreWGSL[name372] = shader371;
  }
  greasedLinePixelShaderWGSL = { name: name372, shader: shader371 };
});

// node_modules/@babylonjs/core/Shaders/greasedLine.vertex.js
var exports_greasedLine_vertex2 = {};
__export(exports_greasedLine_vertex2, {
  greasedLineVertexShader: () => greasedLineVertexShader
});
var name373 = "greasedLineVertexShader", shader372 = `precision highp float;
#include<instancesDeclaration>
attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;
#ifdef GREASED_LINE_CAMERA_FACING
attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}
#else
attribute vec3 grl_slopes;attribute float grl_counters;
#endif
void main() {
#include<instancesVertex>
grlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;
#ifdef GREASED_LINE_CAMERA_FACING
float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;float grlWidth=grlBaseWidth*grl_widths;vec3 positionUpdated=position+grl_offsets;vec3 worldDir=normalize(grlNext-grlPrevious);vec3 nearPosition=positionUpdated+(worldDir*0.001);vec4 grlFinalPosition=grlMatrix*vec4( positionUpdated ,1.0);vec4 screenNearPos=grlMatrix*vec4(nearPosition,1.0);vec2 grlLinePosition=grlFix(grlFinalPosition,grlAspect);vec2 grlLineNearPosition=grlFix(screenNearPos,grlAspect);vec2 grlDir=normalize(grlLineNearPosition-grlLinePosition);vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );
#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM
grlNormal.xy*=-.5*grlWidth;
#else
grlNormal.xy*=.5*grlWidth;
#endif
grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}
grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;
#else
grlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;
#endif
}
`, greasedLineVertexShader;
var init_greasedLine_vertex2 = __esm(() => {
  init_shaderStore();
  init_instancesDeclaration2();
  init_instancesVertex2();
  if (!ShaderStore.ShadersStore[name373]) {
    ShaderStore.ShadersStore[name373] = shader372;
  }
  greasedLineVertexShader = { name: name373, shader: shader372 };
});

// node_modules/@babylonjs/core/Shaders/greasedLine.fragment.js
var exports_greasedLine_fragment2 = {};
__export(exports_greasedLine_fragment2, {
  greasedLinePixelShader: () => greasedLinePixelShader
});
var name374 = "greasedLinePixelShader", shader373 = `precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}
if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { 
textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}
if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}
`, greasedLinePixelShader;
var init_greasedLine_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name374]) {
    ShaderStore.ShadersStore[name374] = shader373;
  }
  greasedLinePixelShader = { name: name374, shader: shader373 };
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.vertex.js
var name375 = "meshUVSpaceRendererVertexShader", shader374 = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vNormalW=normalize(normWorldSM*normalUpdated);
#endif
vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;
var init_meshUVSpaceRenderer_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_instancesDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  if (!ShaderStore.ShadersStore[name375]) {
    ShaderStore.ShadersStore[name375] = shader374;
  }
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.fragment.js
var name376 = "meshUVSpaceRendererPixelShader", shader375 = `precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}
gl_FragColor=texture2D(textureSampler,vDecalTC);}
`;
var init_meshUVSpaceRenderer_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name376]) {
    ShaderStore.ShadersStore[name376] = shader375;
  }
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRendererMasker.vertex.js
var name377 = "meshUVSpaceRendererMaskerVertexShader", shader376 = `attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}`;
var init_meshUVSpaceRendererMasker_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name377]) {
    ShaderStore.ShadersStore[name377] = shader376;
  }
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRendererMasker.fragment.js
var name378 = "meshUVSpaceRendererMaskerPixelShader", shader377 = `varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}
`;
var init_meshUVSpaceRendererMasker_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name378]) {
    ShaderStore.ShadersStore[name378] = shader377;
  }
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRendererFinaliser.fragment.js
var name379 = "meshUVSpaceRendererFinaliserPixelShader", shader378 = `precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}
if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}
if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}
if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}
if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}
`;
var init_meshUVSpaceRendererFinaliser_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name379]) {
    ShaderStore.ShadersStore[name379] = shader378;
  }
});

// node_modules/@babylonjs/core/Shaders/meshUVSpaceRendererFinaliser.vertex.js
var name380 = "meshUVSpaceRendererFinaliserVertexShader", shader379 = `precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}
`;
var init_meshUVSpaceRendererFinaliser_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name380]) {
    ShaderStore.ShadersStore[name380] = shader379;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRenderer.vertex.js
var name381 = "meshUVSpaceRendererVertexShader", shader380 = `attribute position: vec3f;attribute normal: vec3f;attribute uv: vec2f;uniform projMatrix: mat4x4f;varying vDecalTC: vec2f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0);var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);var vNormalW: vec3f;
#if defined(INSTANCES) && defined(THIN_INSTANCES)
vNormalW=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);
#else
#ifdef NONUNIFORMSCALING
normWorldSM=transposeMat3(inverseMat3(normWorldSM));
#endif
vNormalW=normalize(normWorldSM*normalUpdated);
#endif
var normalView: vec3f=normalize((uniforms.projMatrix* vec4f(vNormalW,0.0)).xyz);var decalTC: vec3f=(uniforms.projMatrix*worldPos).xyz;vertexOutputs.vDecalTC=decalTC.xy;vertexOutputs.position=vec4f(input.uv*2.0-1.0,select(decalTC.z,2.,normalView.z>0.0),1.0);}`;
var init_meshUVSpaceRenderer_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_instancesDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  if (!ShaderStore.ShadersStoreWGSL[name381]) {
    ShaderStore.ShadersStoreWGSL[name381] = shader380;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRenderer.fragment.js
var name382 = "meshUVSpaceRendererPixelShader", shader381 = `varying vDecalTC: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {if (input.vDecalTC.x<0. || input.vDecalTC.x>1. || input.vDecalTC.y<0. || input.vDecalTC.y>1.) {discard;}
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vDecalTC);}
`;
var init_meshUVSpaceRenderer_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name382]) {
    ShaderStore.ShadersStoreWGSL[name382] = shader381;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRendererMasker.vertex.js
var name383 = "meshUVSpaceRendererMaskerVertexShader", shader382 = `attribute uv: vec2f;varying vUV: vec2f;@vertex
fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position= vec4f( vec2f(input.uv.x,input.uv.y)*2.0-1.0,0.,1.0);vertexOutputs.vUV=input.uv;}`;
var init_meshUVSpaceRendererMasker_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name383]) {
    ShaderStore.ShadersStoreWGSL[name383] = shader382;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRendererMasker.fragment.js
var name384 = "meshUVSpaceRendererMaskerPixelShader", shader383 = `varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color= vec4f(1.0,1.0,1.0,1.0);}
`;
var init_meshUVSpaceRendererMasker_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name384]) {
    ShaderStore.ShadersStoreWGSL[name384] = shader383;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRendererFinaliser.fragment.js
var name385 = "meshUVSpaceRendererFinaliserPixelShader", shader384 = `#define DISABLE_UNIFORMITY_ANALYSIS
varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var maskTextureSamplerSampler: sampler;var maskTextureSampler: texture_2d<f32>;uniform textureSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var mask: vec4f=textureSample(maskTextureSampler,maskTextureSamplerSampler,input.vUV).rgba;if (mask.r>0.5) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);} else {var texelSize: vec2f=4.0/uniforms.textureSize;var uv_p01: vec2f=input.vUV+ vec2f(-1.0,0.0)*texelSize;var uv_p21: vec2f=input.vUV+ vec2f(1.0,0.0)*texelSize;var uv_p10: vec2f=input.vUV+ vec2f(0.0,-1.0)*texelSize;var uv_p12: vec2f=input.vUV+ vec2f(0.0,1.0)*texelSize;var mask_p01: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p01).r;var mask_p21: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p21).r;var mask_p10: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p10).r;var mask_p12: f32=textureSample(maskTextureSampler,maskTextureSamplerSampler,uv_p12).r;var col: vec4f= vec4f(0.0,0.0,0.0,0.0);var total_weight: f32=0.0;if (mask_p01>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p01);total_weight+=1.0;}
if (mask_p21>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p21);total_weight+=1.0;}
if (mask_p10>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p10);total_weight+=1.0;}
if (mask_p12>0.5) {col+=textureSample(textureSampler,textureSamplerSampler,uv_p12);total_weight+=1.0;}
if (total_weight>0.0) {fragmentOutputs.color=col/total_weight;} else {fragmentOutputs.color=col;}}}
`;
var init_meshUVSpaceRendererFinaliser_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name385]) {
    ShaderStore.ShadersStoreWGSL[name385] = shader384;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/meshUVSpaceRendererFinaliser.vertex.js
var name386 = "meshUVSpaceRendererFinaliserVertexShader", shader385 = `attribute position: vec3f;attribute uv: vec2f;uniform worldViewProjection: mat4x4f;varying vUV: vec2f;@vertex
fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.worldViewProjection* vec4f(input.position,1.0);vertexOutputs.positionvUV=input.uv;}
`;
var init_meshUVSpaceRendererFinaliser_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name386]) {
    ShaderStore.ShadersStoreWGSL[name386] = shader385;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/fxaa.fragment.js
var exports_fxaa_fragment = {};
__export(exports_fxaa_fragment, {
  fxaaPixelShaderWGSL: () => fxaaPixelShaderWGSL
});
var name387 = "fxaaPixelShader", shader386 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} 
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
#ifndef MALI
if(range<rangeMaxClamped) 
{fragmentOutputs.color=rgbyM;return fragmentOutputs;}
#endif
var lumaNW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordNW,0.0));var lumaSE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordSE,0.0));var lumaNE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordNE,0.0));var lumaSW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordSW,0.0));var lumaNS: f32=lumaN+lumaS;var lumaWE: f32=lumaW+lumaE;var subpixRcpRange: f32=1.0/range;var subpixNSWE: f32=lumaNS+lumaWE;var edgeHorz1: f32=(-2.0*lumaM)+lumaNS;var edgeVert1: f32=(-2.0*lumaM)+lumaWE;var lumaNESE: f32=lumaNE+lumaSE;var lumaNWNE: f32=lumaNW+lumaNE;var edgeHorz2: f32=(-2.0*lumaE)+lumaNESE;var edgeVert2: f32=(-2.0*lumaN)+lumaNWNE;var lumaNWSW: f32=lumaNW+lumaSW;var lumaSWSE: f32=lumaSW+lumaSE;var edgeHorz4: f32=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);var edgeVert4: f32=(abs(edgeVert1)*2.0)+abs(edgeVert2);var edgeHorz3: f32=(-2.0*lumaW)+lumaNWSW;var edgeVert3: f32=(-2.0*lumaS)+lumaSWSE;var edgeHorz: f32=abs(edgeHorz3)+edgeHorz4;var edgeVert: f32=abs(edgeVert3)+edgeVert4;var subpixNWSWNESE: f32=lumaNWSW+lumaNESE;var lengthSign: f32=uniforms.texelSize.x;var horzSpan: bool=edgeHorz>=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)
{lumaN=lumaW;}
if (!horzSpan) 
{lumaS=lumaE;}
if (horzSpan) 
{lengthSign=uniforms.texelSize.y;}
var subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN)
{lengthSign=-lengthSign;}
var subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) 
{posB.x+=lengthSign*0.5;}
if (horzSpan)
{posB.y+=lengthSign*0.5;}
var posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) 
{lumaNN=lumaSS;}
var gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) 
{posN.x-=offNP.x*3.0;}
if (!doneN) 
{posN.y-=offNP.y*3.0;}
var doneNP: bool=(!doneN) || (!doneP);if (!doneP) 
{posP.x+=offNP.x*3.0;}
if (!doneP)
{posP.y+=offNP.y*3.0;}
if (doneNP)
{if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));}
if (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));}
if (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;}
if (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;}
doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;}
if (!doneN) {posN.y-=offNP.y*12.0;}
doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;}
if (!doneP) {posP.y+=offNP.y*12.0;}}
var dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan)
{dstN=posM.y-posN.y;}
if (!horzSpan) 
{dstP=posP.y-posM.y;}
var goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstN<dstP;var dst: f32=min(dstN,dstP);var goodSpan: bool=select(goodSpanP,goodSpanN,directionN);var subpixG: f32=subpixF*subpixF;var pixelOffset: f32=(dst*(-spanLengthRcp))+0.5;var subpixH: f32=subpixG*fxaaQualitySubpix;var pixelOffsetGood: f32=select(0.0,pixelOffset,goodSpan);var pixelOffsetSubpix: f32=max(pixelOffsetGood,subpixH);if (!horzSpan)
{posM.x+=pixelOffsetSubpix*lengthSign;}
if (horzSpan)
{posM.y+=pixelOffsetSubpix*lengthSign;}
#ifdef MALI
if(range<rangeMaxClamped) 
{fragmentOutputs.color=rgbyM;}
else
{fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,posM,0.0);}
#else
fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,posM,0.0);
#endif
}`, fxaaPixelShaderWGSL;
var init_fxaa_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name387]) {
    ShaderStore.ShadersStoreWGSL[name387] = shader386;
  }
  fxaaPixelShaderWGSL = { name: name387, shader: shader386 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fxaa.vertex.js
var exports_fxaa_vertex = {};
__export(exports_fxaa_vertex, {
  fxaaVertexShaderWGSL: () => fxaaVertexShaderWGSL
});
var name388 = "fxaaVertexShader", shader387 = `attribute position: vec2f;uniform texelSize: vec2f;varying vUV: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const madd: vec2f= vec2f(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, fxaaVertexShaderWGSL;
var init_fxaa_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name388]) {
    ShaderStore.ShadersStoreWGSL[name388] = shader387;
  }
  fxaaVertexShaderWGSL = { name: name388, shader: shader387 };
});

// node_modules/@babylonjs/core/Shaders/fxaa.fragment.js
var exports_fxaa_fragment2 = {};
__export(exports_fxaa_fragment2, {
  fxaaPixelShader: () => fxaaPixelShader
});
var name389 = "fxaaPixelShader", shader388 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);
#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)
void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);
#ifndef MALI
if(range<rangeMaxClamped) 
{gl_FragColor=rgbyM;return;}
#endif
float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)
{lumaN=lumaW;}
if (!horzSpan) 
{lumaS=lumaE;}
if (horzSpan) 
{lengthSign=texelSize.y;}
float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)
{lengthSign=-lengthSign;}
float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) 
{posB.x+=lengthSign*0.5;}
if (horzSpan)
{posB.y+=lengthSign*0.5;}
vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) 
{lumaNN=lumaSS;}
float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) 
{posN.x-=offNP.x*3.0;}
if (!doneN) 
{posN.y-=offNP.y*3.0;}
bool doneNP=(!doneN) || (!doneP);if (!doneP) 
{posP.x+=offNP.x*3.0;}
if (!doneP)
{posP.y+=offNP.y*3.0;}
if (doneNP)
{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}
float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)
{dstN=posM.y-posN.y;}
if (!horzSpan) 
{dstP=posP.y-posM.y;}
bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan)
{posM.x+=pixelOffsetSubpix*lengthSign;}
if (horzSpan)
{posM.y+=pixelOffsetSubpix*lengthSign;}
#ifdef MALI
if(range<rangeMaxClamped) 
{gl_FragColor=rgbyM;}
else
{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);}
#else
gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);
#endif
}`, fxaaPixelShader;
var init_fxaa_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name389]) {
    ShaderStore.ShadersStore[name389] = shader388;
  }
  fxaaPixelShader = { name: name389, shader: shader388 };
});

// node_modules/@babylonjs/core/Shaders/fxaa.vertex.js
var exports_fxaa_vertex2 = {};
__export(exports_fxaa_vertex2, {
  fxaaVertexShader: () => fxaaVertexShader
});
var name390 = "fxaaVertexShader", shader389 = `attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5);
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);
#define CUSTOM_VERTEX_MAIN_END
}`, fxaaVertexShader;
var init_fxaa_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name390]) {
    ShaderStore.ShadersStore[name390] = shader389;
  }
  fxaaVertexShader = { name: name390, shader: shader389 };
});

// node_modules/@babylonjs/core/ShadersWGSL/particles.vertex.js
var exports_particles_vertex = {};
__export(exports_particles_vertex, {
  particlesVertexShaderWGSL: () => particlesVertexShaderWGSL
});
var name391 = "particlesVertexShader", shader390 = `attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f;
#ifdef ANIMATESHEET
attribute cellIndex: f32;
#endif
#ifndef BILLBOARD
attribute direction: vec3f;
#endif
#ifdef BILLBOARDSTRETCHED
attribute direction: vec3f;
#endif
#ifdef RAMPGRADIENT
attribute remapData: vec4f;
#endif
attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f;
#ifdef ANIMATESHEET
uniform particlesInfos: vec3f; 
#endif
varying vUV: vec2f;varying vColor: vec4f;varying vPositionW: vec3f;
#ifdef RAMPGRADIENT
varying remapRanges: vec4f;
#endif
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform invView: mat4x4f;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#ifdef BILLBOARD
uniform eyePosition: vec3f;
#endif
fn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}
#ifdef BILLBOARDSTRETCHED
fn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
#ifdef BILLBOARDSTRETCHED_LOCAL
var row1: vec3f=vertexInputs.direction;
#else
var crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z);
#endif
var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;}
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
var cornerPos: vec2f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size;
#ifdef BILLBOARD
var rotatedCorner: vec3f;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vertexOutputs.vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vertexOutputs.vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vertexOutputs.vPositionW,1.0)).xyz;
#else
rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vertexOutputs.vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz;
#endif
#ifdef RAMPGRADIENT
vertexOutputs.remapRanges=input.remapData;
#endif
vertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0);
#else
var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vertexOutputs.vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vertexOutputs.vPositionW,1.0);
#endif
vertexOutputs.vColor=input.color;
#ifdef ANIMATESHEET
var rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale;
#else
vertexOutputs.vUV=input.offset;
#endif
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)
var worldPos: vec4f= vec4f(vertexOutputs.vPositionW,1.0);
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, particlesVertexShaderWGSL;
var init_particles_vertex = __esm(() => {
  init_shaderStore();
  init_clipPlaneVertexDeclaration();
  init_fogVertexDeclaration();
  init_logDepthDeclaration();
  init_clipPlaneVertex();
  init_fogVertex();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name391]) {
    ShaderStore.ShadersStoreWGSL[name391] = shader390;
  }
  particlesVertexShaderWGSL = { name: name391, shader: shader390 };
});

// node_modules/@babylonjs/core/ShadersWGSL/particles.fragment.js
var exports_particles_fragment = {};
__export(exports_particles_fragment, {
  particlesPixelShaderWGSL: () => particlesPixelShaderWGSL
});
var name392 = "particlesPixelShader", shader391 = `varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#include<clipPlaneFragmentDeclaration>
#include<imageProcessingDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#ifdef RAMPGRADIENT
varying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d<f32>;
#endif
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
var textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor;
#ifdef RAMPGRADIENT
var alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0);
#endif
#ifdef BLENDMULTIPLYMODE
var sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a);
#endif
#include<logDepthFragment>
#include<fogFragment>(color,baseColor)
#ifdef IMAGEPROCESSINGPOSTPROCESS
baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);
#else
#ifdef IMAGEPROCESSING
baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor);
#endif
#endif
fragmentOutputs.color=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`, particlesPixelShaderWGSL;
var init_particles_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_imageProcessingDeclaration();
  init_logDepthDeclaration();
  init_helperFunctions();
  init_imageProcessingFunctions();
  init_fogFragmentDeclaration();
  init_clipPlaneFragment();
  init_logDepthFragment();
  init_fogFragment();
  if (!ShaderStore.ShadersStoreWGSL[name392]) {
    ShaderStore.ShadersStoreWGSL[name392] = shader391;
  }
  particlesPixelShaderWGSL = { name: name392, shader: shader391 };
});

// node_modules/@babylonjs/core/Shaders/particles.vertex.js
var exports_particles_vertex2 = {};
__export(exports_particles_vertex2, {
  particlesVertexShader: () => particlesVertexShader
});
var name393 = "particlesVertexShader", shader392 = `attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
#ifndef BILLBOARD
attribute vec3 direction;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
#ifdef RAMPGRADIENT
attribute vec4 remapData;
#endif
attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;
#ifdef ANIMATESHEET
uniform vec3 particlesInfos; 
#endif
varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;
#ifdef RAMPGRADIENT
varying vec4 remapRanges;
#endif
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);
#ifdef BILLBOARDSTRETCHED_LOCAL
vec3 row1=direction;
#else
vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);
#endif
mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;
#ifdef BILLBOARD
vec3 rotatedCorner;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;
#else
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;
#endif
#ifdef RAMPGRADIENT
remapRanges=remapData;
#endif
gl_Position=projection*vec4(viewPos,1.0);
#else
vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);
#endif
vColor=color;
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=offset;
#endif
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, particlesVertexShader;
var init_particles_vertex2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneVertexDeclaration2();
  init_fogVertexDeclaration2();
  init_logDepthDeclaration2();
  init_clipPlaneVertex2();
  init_fogVertex2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name393]) {
    ShaderStore.ShadersStore[name393] = shader392;
  }
  particlesVertexShader = { name: name393, shader: shader392 };
});

// node_modules/@babylonjs/core/Shaders/particles.fragment.js
var exports_particles_fragment2 = {};
__export(exports_particles_fragment2, {
  particlesPixelShader: () => particlesPixelShader
});
var name394 = "particlesPixelShader", shader393 = `#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;
#include<clipPlaneFragmentDeclaration>
#include<imageProcessingDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#ifdef RAMPGRADIENT
varying vec4 remapRanges;uniform sampler2D rampSampler;
#endif
#include<fogFragmentDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;
#ifdef RAMPGRADIENT
float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);
#endif
#ifdef BLENDMULTIPLYMODE
float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);
#endif
#include<logDepthFragment>
#include<fogFragment>(color,baseColor)
#ifdef IMAGEPROCESSINGPOSTPROCESS
baseColor.rgb=toLinearSpace(baseColor.rgb);
#else
#ifdef IMAGEPROCESSING
baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);
#endif
#endif
gl_FragColor=baseColor;
#define CUSTOM_FRAGMENT_MAIN_END
}`, particlesPixelShader;
var init_particles_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_imageProcessingDeclaration2();
  init_logDepthDeclaration2();
  init_helperFunctions2();
  init_imageProcessingFunctions2();
  init_fogFragmentDeclaration2();
  init_clipPlaneFragment2();
  init_logDepthFragment2();
  init_fogFragment2();
  if (!ShaderStore.ShadersStore[name394]) {
    ShaderStore.ShadersStore[name394] = shader393;
  }
  particlesPixelShader = { name: name394, shader: shader393 };
});

// node_modules/@babylonjs/core/ShadersWGSL/colorCorrection.fragment.js
var exports_colorCorrection_fragment = {};
__export(exports_colorCorrection_fragment, {
  colorCorrectionPixelShaderWGSL: () => colorCorrectionPixelShaderWGSL
});
var name403 = "colorCorrectionPixelShader", shader402 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;varying vUV: vec2f;var colorTableSampler: sampler;var colorTable: texture_2d<f32>;const SLICE_COUNT: f32=16.0; 
fn sampleAs3DTexture(uv: vec3f,width: f32)->vec4f {var sliceSize: f32=1.0/width; 
var slicePixelSize: f32=sliceSize/width; 
var sliceInnerSize: f32=slicePixelSize*(width-1.0); 
var zSlice0: f32=min(floor(uv.z*width),width-1.0);var zSlice1: f32=min(zSlice0+1.0,width-1.0);var xOffset: f32=slicePixelSize*0.5+uv.x*sliceInnerSize;var s0: f32=xOffset+(zSlice0*sliceSize);var s1: f32=xOffset+(zSlice1*sliceSize);var slice0Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s0,uv.y));var slice1Color: vec4f=textureSample(colorTable,colorTableSampler,vec2f(s1,uv.y));var zOffset: f32=((uv.z*width)%(1.0));return mix(slice0Color,slice1Color,zOffset);}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var screen_color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);fragmentOutputs.color=sampleAs3DTexture(screen_color.rgb,SLICE_COUNT);}`, colorCorrectionPixelShaderWGSL;
var init_colorCorrection_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name403]) {
    ShaderStore.ShadersStoreWGSL[name403] = shader402;
  }
  colorCorrectionPixelShaderWGSL = { name: name403, shader: shader402 };
});

// node_modules/@babylonjs/core/Shaders/colorCorrection.fragment.js
var exports_colorCorrection_fragment2 = {};
__export(exports_colorCorrection_fragment2, {
  colorCorrectionPixelShader: () => colorCorrectionPixelShader
});
var name404 = "colorCorrectionPixelShader", shader403 = `uniform sampler2D textureSampler; 
uniform sampler2D colorTable; 
varying vec2 vUV;const float SLICE_COUNT=16.0; 
#define inline
vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; 
float slicePixelSize=sliceSize/width; 
float sliceInnerSize=slicePixelSize*(width-1.0); 
float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`, colorCorrectionPixelShader;
var init_colorCorrection_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name404]) {
    ShaderStore.ShadersStore[name404] = shader403;
  }
  colorCorrectionPixelShader = { name: name404, shader: shader403 };
});

// node_modules/@babylonjs/core/ShadersWGSL/convolution.fragment.js
var exports_convolution_fragment = {};
__export(exports_convolution_fragment, {
  convolutionPixelShaderWGSL: () => convolutionPixelShaderWGSL
});
var name405 = "convolutionPixelShader", shader404 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;uniform kernel: array<f32,9>;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var colorSum: vec4f =
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,-1))*uniforms.kernel[0] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,-1))*uniforms.kernel[1] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,-1))*uniforms.kernel[2] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,0))*uniforms.kernel[3] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,0))*uniforms.kernel[4] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,0))*uniforms.kernel[5] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(-1,1))*uniforms.kernel[6] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(0,1))*uniforms.kernel[7] +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel* vec2f(1,1))*uniforms.kernel[8];var kernelWeight: f32 =
uniforms.kernel[0] +
uniforms.kernel[1] +
uniforms.kernel[2] +
uniforms.kernel[3] +
uniforms.kernel[4] +
uniforms.kernel[5] +
uniforms.kernel[6] +
uniforms.kernel[7] +
uniforms.kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}
fragmentOutputs.color= vec4f((colorSum/kernelWeight).rgb,1);}`, convolutionPixelShaderWGSL;
var init_convolution_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name405]) {
    ShaderStore.ShadersStoreWGSL[name405] = shader404;
  }
  convolutionPixelShaderWGSL = { name: name405, shader: shader404 };
});

// node_modules/@babylonjs/core/Shaders/convolution.fragment.js
var exports_convolution_fragment2 = {};
__export(exports_convolution_fragment2, {
  convolutionPixelShader: () => convolutionPixelShader
});
var name406 = "convolutionPixelShader", shader405 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =
texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +
texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +
texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +
texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +
texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +
texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +
texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +
texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +
texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =
kernel[0] +
kernel[1] +
kernel[2] +
kernel[3] +
kernel[4] +
kernel[5] +
kernel[6] +
kernel[7] +
kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}
gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`, convolutionPixelShader;
var init_convolution_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name406]) {
    ShaderStore.ShadersStore[name406] = shader405;
  }
  convolutionPixelShader = { name: name406, shader: shader405 };
});

// node_modules/@babylonjs/core/ShadersWGSL/displayPass.fragment.js
var exports_displayPass_fragment = {};
__export(exports_displayPass_fragment, {
  displayPassPixelShaderWGSL: () => displayPassPixelShaderWGSL
});
var name407 = "displayPassPixelShader", shader406 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var passSamplerSampler: sampler;var passSampler: texture_2d<f32>;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(passSampler,passSamplerSampler,input.vUV);}`, displayPassPixelShaderWGSL;
var init_displayPass_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name407]) {
    ShaderStore.ShadersStoreWGSL[name407] = shader406;
  }
  displayPassPixelShaderWGSL = { name: name407, shader: shader406 };
});

// node_modules/@babylonjs/core/Shaders/displayPass.fragment.js
var exports_displayPass_fragment2 = {};
__export(exports_displayPass_fragment2, {
  displayPassPixelShader: () => displayPassPixelShader
});
var name408 = "displayPassPixelShader", shader407 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(passSampler,vUV);}`, displayPassPixelShader;
var init_displayPass_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name408]) {
    ShaderStore.ShadersStore[name408] = shader407;
  }
  displayPassPixelShader = { name: name408, shader: shader407 };
});

// node_modules/@babylonjs/core/ShadersWGSL/filter.fragment.js
var exports_filter_fragment = {};
__export(exports_filter_fragment, {
  filterPixelShaderWGSL: () => filterPixelShaderWGSL
});
var name409 = "filterPixelShader", shader408 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform kernelMatrix: mat4x4f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var baseColor: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var updatedColor: vec3f=(uniforms.kernelMatrix* vec4f(baseColor,1.0)).rgb;fragmentOutputs.color= vec4f(updatedColor,1.0);}`, filterPixelShaderWGSL;
var init_filter_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name409]) {
    ShaderStore.ShadersStoreWGSL[name409] = shader408;
  }
  filterPixelShaderWGSL = { name: name409, shader: shader408 };
});

// node_modules/@babylonjs/core/Shaders/filter.fragment.js
var exports_filter_fragment2 = {};
__export(exports_filter_fragment2, {
  filterPixelShader: () => filterPixelShader
});
var name410 = "filterPixelShader", shader409 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`, filterPixelShader;
var init_filter_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name410]) {
    ShaderStore.ShadersStore[name410] = shader409;
  }
  filterPixelShader = { name: name410, shader: shader409 };
});

// node_modules/@babylonjs/core/ShadersWGSL/grain.fragment.js
var exports_grain_fragment = {};
__export(exports_grain_fragment, {
  grainPixelShaderWGSL: () => grainPixelShaderWGSL
});
var name411 = "grainPixelShader", shader410 = `#include<helperFunctions>
varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform intensity: f32;uniform animatedSeed: f32;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}`, grainPixelShaderWGSL;
var init_grain_fragment = __esm(() => {
  init_shaderStore();
  init_helperFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name411]) {
    ShaderStore.ShadersStoreWGSL[name411] = shader410;
  }
  grainPixelShaderWGSL = { name: name411, shader: shader410 };
});

// node_modules/@babylonjs/core/Shaders/grain.fragment.js
var exports_grain_fragment2 = {};
__export(exports_grain_fragment2, {
  grainPixelShader: () => grainPixelShader
});
var name412 = "grainPixelShader", shader411 = `#include<helperFunctions>
uniform sampler2D textureSampler; 
uniform float intensity;uniform float animatedSeed;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`, grainPixelShader;
var init_grain_fragment2 = __esm(() => {
  init_shaderStore();
  init_helperFunctions2();
  if (!ShaderStore.ShadersStore[name412]) {
    ShaderStore.ShadersStore[name412] = shader411;
  }
  grainPixelShader = { name: name412, shader: shader411 };
});

// node_modules/@babylonjs/core/ShadersWGSL/imageProcessing.fragment.js
var exports_imageProcessing_fragment = {};
__export(exports_imageProcessing_fragment, {
  imageProcessingPixelShaderWGSL: () => imageProcessingPixelShaderWGSL
});
var name413 = "imageProcessingPixelShader", shader412 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);result=vec4f(max(result.rgb,vec3f(0.)),result.a);
#ifdef IMAGEPROCESSING
#ifndef FROMLINEARSPACE
result=vec4f(toLinearSpaceVec3(result.rgb),result.a);
#endif
result=applyImageProcessing(result);
#else
#ifdef FROMLINEARSPACE
result=applyImageProcessing(result);
#endif
#endif
fragmentOutputs.color=result;}`, imageProcessingPixelShaderWGSL;
var init_imageProcessing_fragment = __esm(() => {
  init_shaderStore();
  init_imageProcessingDeclaration();
  init_helperFunctions();
  init_imageProcessingFunctions();
  if (!ShaderStore.ShadersStoreWGSL[name413]) {
    ShaderStore.ShadersStoreWGSL[name413] = shader412;
  }
  imageProcessingPixelShaderWGSL = { name: name413, shader: shader412 };
});

// node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js
var exports_imageProcessing_fragment2 = {};
__export(exports_imageProcessing_fragment2, {
  imageProcessingPixelShader: () => imageProcessingPixelShader
});
var name414 = "imageProcessingPixelShader", shader413 = `varying vec2 vUV;uniform sampler2D textureSampler;
#include<imageProcessingDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 result=texture2D(textureSampler,vUV);result.rgb=max(result.rgb,vec3(0.));
#ifdef IMAGEPROCESSING
#ifndef FROMLINEARSPACE
result.rgb=toLinearSpace(result.rgb);
#endif
result=applyImageProcessing(result);
#else
#ifdef FROMLINEARSPACE
result=applyImageProcessing(result);
#endif
#endif
gl_FragColor=result;}`, imageProcessingPixelShader;
var init_imageProcessing_fragment2 = __esm(() => {
  init_shaderStore();
  init_imageProcessingDeclaration2();
  init_helperFunctions2();
  init_imageProcessingFunctions2();
  if (!ShaderStore.ShadersStore[name414]) {
    ShaderStore.ShadersStore[name414] = shader413;
  }
  imageProcessingPixelShader = { name: name414, shader: shader413 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/mrtFragmentDeclaration.js
var name415 = "mrtFragmentDeclaration", shader414 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
layout(location=0) out vec4 glFragData[{X}];
#endif
`;
var init_mrtFragmentDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name415]) {
    ShaderStore.IncludesShadersStore[name415] = shader414;
  }
});

// node_modules/@babylonjs/core/Shaders/geometry.fragment.js
var exports_geometry_fragment = {};
__export(exports_geometry_fragment, {
  geometryPixelShader: () => geometryPixelShader
});
var name416 = "geometryPixelShader", shader415 = `#extension GL_EXT_draw_buffers : require
#if defined(BUMP) || !defined(NORMAL)
#extension GL_OES_standard_derivatives : enable
#endif
precision highp float;
#ifdef BUMP
varying mat4 vWorldView;varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP)
varying vec3 vPositionW;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#ifdef NEED_UV
varying vec2 vUV;
#endif
#ifdef BUMP
uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;
#endif
#if defined(REFLECTIVITY)
#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;
#endif
#ifdef ALBEDOTEXTURE
varying vec2 vAlbedoUV;uniform sampler2D albedoSampler;
#endif
#ifdef REFLECTIVITYCOLOR
uniform vec3 reflectivityColor;
#endif
#ifdef ALBEDOCOLOR
uniform vec3 albedoColor;
#endif
#ifdef METALLIC
uniform float metallic;
#endif
#if defined(ROUGHNESS) || defined(GLOSSINESS)
uniform float glossiness;
#endif
#endif
#if defined(ALPHATEST) && defined(NEED_UV)
uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#include<mrtFragmentDeclaration>[SCENE_MRT_COUNT]
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<helperFunctions>
void main() {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
vec3 normalOutput;
#ifdef BUMP
vec3 normalW=normalize(vNormalW);
#include<bumpFragment>
#ifdef NORMAL_WORLDSPACE
normalOutput=normalW;
#else
normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));
#endif
#else
normalOutput=normalize(vNormalV);
#endif
#ifdef ENCODE_NORMAL
normalOutput=normalOutput*0.5+0.5;
#endif
#ifdef DEPTH
gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);
#endif
#ifdef NORMAL
gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);
#endif
#ifdef SCREENSPACE_DEPTH
gl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0);
#endif
#ifdef POSITION
gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);
#endif
#ifdef VELOCITY
vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);
#endif
#ifdef VELOCITY_LINEAR
vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) -
(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0);
#endif
#ifdef REFLECTIVITY
vec4 reflectivity=vec4(0.0,0.0,0.0,1.0);
#ifdef METALLICWORKFLOW
float metal=1.0;float roughness=1.0;
#ifdef ORMTEXTURE
metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;
#endif
#ifdef METALLIC
metal*=metallic;
#endif
#ifdef ROUGHNESS
roughness*=(1.0-glossiness); 
#endif
reflectivity.a-=roughness;vec3 color=vec3(1.0);
#ifdef ALBEDOTEXTURE
color=texture2D(albedoSampler,vAlbedoUV).rgb;
#ifdef GAMMAALBEDO
color=toLinearSpace(color);
#endif
#endif
#ifdef ALBEDOCOLOR
color*=albedoColor.xyz;
#endif
reflectivity.rgb=mix(vec3(0.04),color,metal);
#else
#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
reflectivity=texture2D(reflectivitySampler,vReflectivityUV);
#ifdef GAMMAREFLECTIVITYTEXTURE
reflectivity.rgb=toLinearSpace(reflectivity.rgb);
#endif
#else 
#ifdef REFLECTIVITYCOLOR
reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;
#endif
#endif
#ifdef GLOSSINESSS
reflectivity.a*=glossiness; 
#endif
#endif
gl_FragData[REFLECTIVITY_INDEX]=reflectivity;
#endif
}
`, geometryPixelShader;
var init_geometry_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_mrtFragmentDeclaration();
  init_bumpFragmentMainFunctions2();
  init_bumpFragmentFunctions2();
  init_helperFunctions2();
  init_clipPlaneFragment2();
  init_bumpFragment2();
  if (!ShaderStore.ShadersStore[name416]) {
    ShaderStore.ShadersStore[name416] = shader415;
  }
  geometryPixelShader = { name: name416, shader: shader415 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryVertexDeclaration.js
var name417 = "geometryVertexDeclaration", shader416 = `uniform mat4 viewProjection;uniform mat4 view;`;
var init_geometryVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name417]) {
    ShaderStore.IncludesShadersStore[name417] = shader416;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryUboDeclaration.js
var name418 = "geometryUboDeclaration", shader417 = `#include<sceneUboDeclaration>
`;
var init_geometryUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name418]) {
    ShaderStore.IncludesShadersStore[name418] = shader417;
  }
});

// node_modules/@babylonjs/core/Shaders/geometry.vertex.js
var exports_geometry_vertex = {};
__export(exports_geometry_vertex, {
  geometryVertexShader: () => geometryVertexShader
});
var name419 = "geometryVertexShader", shader418 = `precision highp float;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
#include<__decl__geometryVertex>
#include<clipPlaneVertexDeclaration>
attribute vec3 position;attribute vec3 normal;
#ifdef NEED_UV
varying vec2 vUV;
#ifdef ALPHATEST
uniform mat4 diffuseMatrix;
#endif
#ifdef BUMP
uniform mat4 bumpMatrix;varying vec2 vBumpUV;
#endif
#ifdef REFLECTIVITY
uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;
#endif
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef BUMP
varying mat4 vWorldView;
#endif
#ifdef BUMP
varying vec3 vNormalW;
#else
varying vec3 vNormalV;
#endif
varying vec4 vViewPos;
#if defined(POSITION) || defined(BUMP)
varying vec3 vPositionW;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;vec3 normalUpdated=normal;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));
#ifdef BUMP
vWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated);
#else
#ifdef NORMAL_WORLDSPACE
vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));
#else
vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));
#endif
#endif
vViewPos=view*worldPos;
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#if NUM_BONE_INFLUENCERS>0
mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);
#else
vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);
#endif
#endif
#if defined(POSITION) || defined(BUMP)
vPositionW=worldPos.xyz/worldPos.w;
#endif
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
#ifdef NEED_UV
#ifdef UV1
#if defined(ALPHATEST) && defined(ALPHATEST_UV1)
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#else
vUV=uvUpdated;
#endif
#ifdef BUMP_UV1
vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV1
vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef ALBEDO_UV1
vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#endif
#ifdef UV2
#if defined(ALPHATEST) && defined(ALPHATEST_UV2)
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#else
vUV=uv2Updated;
#endif
#ifdef BUMP_UV2
vBumpUV=vec2(bumpMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef REFLECTIVITY_UV2
vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#ifdef ALBEDO_UV2
vAlbedoUV=vec2(albedoMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#endif
#include<bumpVertex>
}
`, geometryVertexShader;
var init_geometry_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_instancesDeclaration2();
  init_geometryVertexDeclaration();
  init_geometryUboDeclaration();
  init_clipPlaneVertexDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  init_bumpVertex2();
  if (!ShaderStore.ShadersStore[name419]) {
    ShaderStore.ShadersStore[name419] = shader418;
  }
  geometryVertexShader = { name: name419, shader: shader418 };
});

// node_modules/@babylonjs/core/ShadersWGSL/geometry.vertex.js
var exports_geometry_vertex2 = {};
__export(exports_geometry_vertex2, {
  geometryVertexShaderWGSL: () => geometryVertexShaderWGSL
});
var name420 = "geometryVertexShader", shader419 = `#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
#include<sceneUboDeclaration>
#include<clipPlaneVertexDeclaration>
attribute position: vec3f;attribute normal: vec3f;
#ifdef NEED_UV
varying vUV: vec2f;
#ifdef ALPHATEST
uniform diffuseMatrix: mat4x4f;
#endif
#ifdef BUMP
uniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f;
#endif
#ifdef REFLECTIVITY
uniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f;
#endif
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#ifdef BUMP
varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;
#endif
#ifdef BUMP
varying vNormalW: vec3f;
#else
varying vNormalV: vec3f;
#endif
varying vViewPos: vec4f;
#if defined(POSITION) || defined(BUMP)
varying vPositionW: vec3f;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position;var normalUpdated: vec3f=input.normal;
#ifdef UV1
var uvUpdated: vec2f=input.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=input.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED)
vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0));
#ifdef BUMP
let vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated);
#else
#ifdef NORMAL_WORLDSPACE
vertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz);
#else
vertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz);
#endif
#endif
vertexOutputs.vViewPos=scene.view*worldPos;
#if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED)
vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);
#if NUM_BONE_INFLUENCERS>0
var previousInfluence: mat4x4f;previousInfluence=mPreviousBones[ i32(matricesIndices[0])]*matricesWeights[0];
#if NUM_BONE_INFLUENCERS>1
previousInfluence+=mPreviousBones[ i32(matricesIndices[1])]*matricesWeights[1];
#endif
#if NUM_BONE_INFLUENCERS>2
previousInfluence+=mPreviousBones[ i32(matricesIndices[2])]*matricesWeights[2];
#endif
#if NUM_BONE_INFLUENCERS>3
previousInfluence+=mPreviousBones[ i32(matricesIndices[3])]*matricesWeights[3];
#endif
#if NUM_BONE_INFLUENCERS>4
previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[0])]*matricesWeightsExtra[0];
#endif
#if NUM_BONE_INFLUENCERS>5
previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[1])]*matricesWeightsExtra[1];
#endif
#if NUM_BONE_INFLUENCERS>6
previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[2])]*matricesWeightsExtra[2];
#endif
#if NUM_BONE_INFLUENCERS>7
previousInfluence+=mPreviousBones[ i32(matricesIndicesExtra[3])]*matricesWeightsExtra[3];
#endif
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0);
#else
vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0);
#endif
#endif
#if defined(POSITION) || defined(BUMP)
vertexOutputs.vPositionW=worldPos.xyz/worldPos.w;
#endif
vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0);
#include<clipPlaneVertex>
#ifdef NEED_UV
#ifdef UV1
#if defined(ALPHATEST) && defined(ALPHATEST_UV1)
vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#else
vertexOutputs.vUV=uvUpdated;
#endif
#ifdef BUMP_UV1
vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef REFLECTIVITY_UV1
vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef ALBEDO_UV1
vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#endif
#ifdef UV2
#if defined(ALPHATEST) && defined(ALPHATEST_UV2)
vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#else
vertexOutputs.vUV=uv2Updated;
#endif
#ifdef BUMP_UV2
vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef REFLECTIVITY_UV2
vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#ifdef ALBEDO_UV2
vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#endif
#include<bumpVertex>
}
`, geometryVertexShaderWGSL;
var init_geometry_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_instancesDeclaration();
  init_sceneUboDeclaration();
  init_clipPlaneVertexDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  init_bumpVertex();
  if (!ShaderStore.ShadersStoreWGSL[name420]) {
    ShaderStore.ShadersStoreWGSL[name420] = shader419;
  }
  geometryVertexShaderWGSL = { name: name420, shader: shader419 };
});

// node_modules/@babylonjs/core/ShadersWGSL/geometry.fragment.js
var exports_geometry_fragment2 = {};
__export(exports_geometry_fragment2, {
  geometryPixelShaderWGSL: () => geometryPixelShaderWGSL
});
var name421 = "geometryPixelShader", shader420 = `#ifdef BUMP
varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f;
#else
varying vNormalV: vec3f;
#endif
varying vViewPos: vec4f;
#if defined(POSITION) || defined(BUMP)
varying vPositionW: vec3f;
#endif
#if defined(VELOCITY) || defined(VELOCITY_LINEAR)
varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f;
#endif
#ifdef NEED_UV
varying vUV: vec2f;
#endif
#ifdef BUMP
uniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f;
#endif
#if defined(REFLECTIVITY)
#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d<f32>;varying vReflectivityUV: vec2f;
#endif
#ifdef ALBEDOTEXTURE
varying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d<f32>;
#endif
#ifdef REFLECTIVITYCOLOR
uniform reflectivityColor: vec3f;
#endif
#ifdef ALBEDOCOLOR
uniform albedoColor: vec3f;
#endif
#ifdef METALLIC
uniform metallic: f32;
#endif
#if defined(ROUGHNESS) || defined(GLOSSINESS)
uniform glossiness: f32;
#endif
#endif
#if defined(ALPHATEST) && defined(NEED_UV)
var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
#include<bumpFragmentMainFunctions>
#include<bumpFragmentFunctions>
#include<helperFunctions>
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;}
#endif
var normalOutput: vec3f;
#ifdef BUMP
var normalW: vec3f=normalize(input.vNormalW);
#include<bumpFragment>
#ifdef NORMAL_WORLDSPACE
normalOutput=normalW;
#else
normalOutput=normalize( (mat4x4f(input.vWorldView0,input.vWorldView1,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)).xyz);
#endif
#else
normalOutput=normalize(input.vNormalV);
#endif
#ifdef ENCODE_NORMAL
normalOutput=normalOutput*0.5+0.5;
#endif
var fragData: array<vec4<f32>,SCENE_MRT_COUNT>;
#ifdef DEPTH
fragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0);
#endif
#ifdef NORMAL
fragData[NORMAL_INDEX]=vec4f(normalOutput,1.0);
#endif
#ifdef SCREENSPACE_DEPTH
fragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0);
#endif
#ifdef POSITION
fragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0);
#endif
#ifdef VELOCITY
var a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0);
#endif
#ifdef VELOCITY_LINEAR
var velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy /
input.vPreviousPosition.w) -
(input.vCurrentPosition.xy /
input.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0);
#endif
#ifdef REFLECTIVITY
var reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0);
#ifdef METALLICWORKFLOW
var metal: f32=1.0;var roughness: f32=1.0;
#ifdef ORMTEXTURE
metal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g;
#endif
#ifdef METALLIC
metal*=uniforms.metallic;
#endif
#ifdef ROUGHNESS
roughness*=(1.0-uniforms.glossiness); 
#endif
reflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0);
#ifdef ALBEDOTEXTURE
color=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb;
#ifdef GAMMAALBEDO
color=toLinearSpaceVec4(color);
#endif
#endif
#ifdef ALBEDOCOLOR
color*=uniforms.albedoColor.xyz;
#endif
reflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a);
#else
#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)
reflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV);
#ifdef GAMMAREFLECTIVITYTEXTURE
reflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a);
#endif
#else 
#ifdef REFLECTIVITYCOLOR
reflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0);
#endif
#endif
#ifdef GLOSSINESSS
reflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); 
#endif
#endif
fragData[REFLECTIVITY_INDEX]=reflectivity;
#endif
#if SCENE_MRT_COUNT>0
fragmentOutputs.fragData0=fragData[0];
#endif
#if SCENE_MRT_COUNT>1
fragmentOutputs.fragData1=fragData[1];
#endif
#if SCENE_MRT_COUNT>2
fragmentOutputs.fragData2=fragData[2];
#endif
#if SCENE_MRT_COUNT>3
fragmentOutputs.fragData3=fragData[3];
#endif
#if SCENE_MRT_COUNT>4
fragmentOutputs.fragData4=fragData[4];
#endif
#if SCENE_MRT_COUNT>5
fragmentOutputs.fragData5=fragData[5];
#endif
#if SCENE_MRT_COUNT>6
fragmentOutputs.fragData6=fragData[6];
#endif
#if SCENE_MRT_COUNT>7
fragmentOutputs.fragData7=fragData[7];
#endif
}
`, geometryPixelShaderWGSL;
var init_geometry_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_bumpFragmentMainFunctions();
  init_bumpFragmentFunctions();
  init_helperFunctions();
  init_clipPlaneFragment();
  init_bumpFragment();
  if (!ShaderStore.ShadersStoreWGSL[name421]) {
    ShaderStore.ShadersStoreWGSL[name421] = shader420;
  }
  geometryPixelShaderWGSL = { name: name421, shader: shader420 };
});

// node_modules/@babylonjs/core/ShadersWGSL/motionBlur.fragment.js
var exports_motionBlur_fragment = {};
__export(exports_motionBlur_fragment, {
  motionBlurPixelShaderWGSL: () => motionBlurPixelShaderWGSL
});
var name422 = "motionBlurPixelShader", shader421 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f;
#ifdef OBJECT_BASED
var velocitySamplerSampler: sampler;var velocitySampler: texture_2d<f32>;
#else
var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#ifdef GEOMETRY_SUPPORTED
#ifdef OBJECT_BASED
var texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSample(velocitySampler,velocitySamplerSampler,input.vUV);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);let signs=sign(velocityColor.rg);var velocity=pow(abs(velocityColor.rg),vec2f(3.0))*signs*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++)
{if (i>=samplesCount) {break;}
var offset: vec2f=input.vUV+velocity*(hlim+ f32(i));
#if defined(WEBGPU)
result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0);
#else
result+=textureSample(textureSampler,textureSamplerSampler, offset);
#endif
}
fragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0);
#else
var texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r;depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; 
var cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));var result: vec4f=textureSample(textureSampler,textureSamplerSampler, input.vUV);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;}
var offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5);
#if defined(WEBGPU)
result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0);
#else
result+=textureSample(textureSampler,textureSamplerSampler, offset1);
#endif
}
fragmentOutputs.color=result/ f32(nSamples);
#endif
#else
fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV);
#endif
}
`, motionBlurPixelShaderWGSL;
var init_motionBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name422]) {
    ShaderStore.ShadersStoreWGSL[name422] = shader421;
  }
  motionBlurPixelShaderWGSL = { name: name422, shader: shader421 };
});

// node_modules/@babylonjs/core/Shaders/motionBlur.fragment.js
var exports_motionBlur_fragment2 = {};
__export(exports_motionBlur_fragment2, {
  motionBlurPixelShader: () => motionBlurPixelShader
});
var name423 = "motionBlurPixelShader", shader422 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;
#ifdef OBJECT_BASED
uniform sampler2D velocitySampler;
#else
uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#ifdef GEOMETRY_SUPPORTED
#ifdef OBJECT_BASED
vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 signs=sign(velocityColor.rg);vec2 velocity=pow(abs(velocityColor.rg),vec2(3.0))*signs*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i)
{if (i>=samplesCount)
break;vec2 offset=vUV+velocity*(hlim+float(i));
#if defined(WEBGPU)
result+=texture2DLodEXT(textureSampler,offset,0.0);
#else
result+=texture2D(textureSampler,offset);
#endif
}
gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;
#else
vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; 
vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples)
break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);
#if defined(WEBGPU)
result+=texture2DLodEXT(textureSampler,offset1,0.0);
#else
result+=texture2D(textureSampler,offset1);
#endif
}
gl_FragColor=result/float(nSamples);
#endif
#else
gl_FragColor=texture2D(textureSampler,vUV);
#endif
}
`, motionBlurPixelShader;
var init_motionBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name423]) {
    ShaderStore.ShadersStore[name423] = shader422;
  }
  motionBlurPixelShader = { name: name423, shader: shader422 };
});

// node_modules/@babylonjs/core/Shaders/sharpen.fragment.js
var exports_sharpen_fragment = {};
__export(exports_sharpen_fragment, {
  sharpenPixelShader: () => sharpenPixelShader
});
var name425 = "sharpenPixelShader", shader424 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +
texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(1,0)) +
texture2D(textureSampler,vUV+onePixel*vec2(0,1)) -
color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`, sharpenPixelShader;
var init_sharpen_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name425]) {
    ShaderStore.ShadersStore[name425] = shader424;
  }
  sharpenPixelShader = { name: name425, shader: shader424 };
});

// node_modules/@babylonjs/core/ShadersWGSL/sharpen.fragment.js
var exports_sharpen_fragment2 = {};
__export(exports_sharpen_fragment2, {
  sharpenPixelShaderWGSL: () => sharpenPixelShaderWGSL
});
var name426 = "sharpenPixelShader", shader425 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) +
textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) -
color*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}`, sharpenPixelShaderWGSL;
var init_sharpen_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name426]) {
    ShaderStore.ShadersStoreWGSL[name426] = shader425;
  }
  sharpenPixelShaderWGSL = { name: name426, shader: shader425 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ssao2.fragment.js
var exports_ssao2_fragment = {};
__export(exports_ssao2_fragment, {
  ssao2PixelShaderWGSL: () => ssao2PixelShaderWGSL
});
var name429 = "ssao2PixelShader", shader428 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;
#ifdef SSAO
const scales: array<f32,16>=array<f32,16>(
0.1,
0.11406250000000001,
0.131640625,
0.15625,
0.187890625,
0.2265625,
0.272265625,
0.325,
0.384765625,
0.4515625,
0.525390625,
0.60625,
0.694140625,
0.7890625,
0.891015625,
1.0
);uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;var randomSamplerSampler: sampler;var randomSampler: texture_2d<f32>;var normalSamplerSampler: sampler;var normalSampler: texture_2d<f32>;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array<vec3f,SAMPLES>;uniform totalStrength: f32;uniform base: f32;uniform xViewport: f32;uniform yViewport: f32;uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near);var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign);var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i<SAMPLES; i++) {var samplePosition: vec3f=scales[(i+ i32(random.x*16.0)) % 16]*tbn*uniforms.sampleSphere[(i+ i32(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;var offset: vec4f= vec4f(samplePosition,1.0);offset=uniforms.projection*offset;offset=vec4f(offset.xyz/offset.w,offset.w);offset=vec4f(offset.xy*0.5+0.5,offset.z,offset.w);if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;}
var sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}
occlusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);}
#else
#ifdef BLUR
uniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32;
#ifndef BLUR_BYPASS
var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;
#ifdef BLUR_LEGACY
fn blur13Bilateral(image: texture_2d<f32>,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;}
#endif
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0;
#ifdef BLUR_BYPASS
result=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r;
#else
#ifdef BLUR_H
var step: vec2f= vec2f(1.0/uniforms.outSize,0.0);
#else
var step: vec2f= vec2f(0.0,1.0/uniforms.outSize);
#endif
#ifdef BLUR_LEGACY
result=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step);
#else
var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i<uniforms.samples; i+=2)
{var samplePos: vec2f=input.vUV+step*( f32(i)+0.5);var sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,samplePos,0.0).r);var falloff: f32=smoothstep(0.0,
f32(uniforms.samples),
f32(uniforms.samples)-abs( f32(i))*uniforms.soften);var minDivider: f32=uniforms.tolerance*0.5+0.003;var weight: f32=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureSampleLevel(textureSampler,textureSamplerSampler,samplePos,0.0).r*weight;weightSum+=weight;}
result/=weightSum;
#endif
#endif
fragmentOutputs.color=vec4f(result,result,result,1.0);}
#endif
#endif
`, ssao2PixelShaderWGSL;
var init_ssao2_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name429]) {
    ShaderStore.ShadersStoreWGSL[name429] = shader428;
  }
  ssao2PixelShaderWGSL = { name: name429, shader: shader428 };
});

// node_modules/@babylonjs/core/Shaders/ssao2.fragment.js
var exports_ssao2_fragment2 = {};
__export(exports_ssao2_fragment2, {
  ssao2PixelShader: () => ssao2PixelShader
});
var name430 = "ssao2PixelShader", shader429 = `precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSAO
float scales[16]=float[16](
0.1,
0.11406250000000001,
0.131640625,
0.15625,
0.187890625,
0.2265625,
0.272265625,
0.325,
0.384765625,
0.4515625,
0.525390625,
0.60625,
0.694140625,
0.7890625,
0.891015625,
1.0
);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main()
{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;}
float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}
occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}
#endif
#ifdef BLUR
uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;
#ifndef BLUR_BYPASS
uniform sampler2D depthSampler;
#ifdef BLUR_LEGACY
#define inline
float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}
#endif
#endif
void main()
{float result=0.0;
#ifdef BLUR_BYPASS
result=textureLod(textureSampler,vUV,0.0).r;
#else
#ifdef BLUR_H
vec2 step=vec2(1.0/outSize,0.0);
#else
vec2 step=vec2(0.0,1.0/outSize);
#endif
#ifdef BLUR_LEGACY
result=blur13Bilateral(textureSampler,vUV,step);
#else
float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2)
{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0,
float(samples),
float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;}
result/=weightSum;
#endif
#endif
gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;}
#endif
`, ssao2PixelShader;
var init_ssao2_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name430]) {
    ShaderStore.ShadersStore[name430] = shader429;
  }
  ssao2PixelShader = { name: name430, shader: shader429 };
});

// node_modules/@babylonjs/core/ShadersWGSL/ssaoCombine.fragment.js
var exports_ssaoCombine_fragment = {};
__export(exports_ssaoCombine_fragment, {
  ssaoCombinePixelShaderWGSL: () => ssaoCombinePixelShaderWGSL
});
var name431 = "ssaoCombinePixelShader", shader430 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var originalColorSampler: sampler;var originalColor: texture_2d<f32>;uniform viewport: vec4f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
var uv: vec2f=uniforms.viewport.xy+input.vUV*uniforms.viewport.zw;var ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uv);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,uv);fragmentOutputs.color=sceneColor*ssaoColor;
#define CUSTOM_FRAGMENT_MAIN_END
}
`, ssaoCombinePixelShaderWGSL;
var init_ssaoCombine_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name431]) {
    ShaderStore.ShadersStoreWGSL[name431] = shader430;
  }
  ssaoCombinePixelShaderWGSL = { name: name431, shader: shader430 };
});

// node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js
var exports_ssaoCombine_fragment2 = {};
__export(exports_ssaoCombine_fragment2, {
  ssaoCombinePixelShader: () => ssaoCombinePixelShader
});
var name432 = "ssaoCombinePixelShader", shader431 = `uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec2 uv=viewport.xy+vUV*viewport.zw;vec4 ssaoColor=texture2D(textureSampler,uv);vec4 sceneColor=texture2D(originalColor,uv);gl_FragColor=sceneColor*ssaoColor;
#define CUSTOM_FRAGMENT_MAIN_END
}
`, ssaoCombinePixelShader;
var init_ssaoCombine_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name432]) {
    ShaderStore.ShadersStore[name432] = shader431;
  }
  ssaoCombinePixelShader = { name: name432, shader: shader431 };
});

// node_modules/@babylonjs/core/Shaders/highlights.fragment.js
var name440 = "highlightsPixelShader", shader439 = `varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;
var init_highlights_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name440]) {
    ShaderStore.ShadersStore[name440] = shader439;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/highlights.fragment.js
var name441 = "highlightsPixelShader", shader440 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;const RGBLuminanceCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var tex: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var c: vec3f=tex.rgb;var luma: f32=dot(c.rgb,RGBLuminanceCoefficients);fragmentOutputs.color= vec4f(pow(c, vec3f(25.0-luma*15.0)),tex.a); }`;
var init_highlights_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name441]) {
    ShaderStore.ShadersStoreWGSL[name441] = shader440;
  }
});

// node_modules/@babylonjs/core/Shaders/tonemap.fragment.js
var name442 = "tonemapPixelShader", shader441 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;
#if defined(HABLE_TONEMAPPING)
const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;
#endif
float Luminance(vec3 c)
{return dot(c,vec3(0.22,0.707,0.071));}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec3 colour=texture2D(textureSampler,vUV).rgb;
#if defined(REINHARD_TONEMAPPING)
float lum=Luminance(colour.rgb); 
float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); 
colour*=scale/lum;
#elif defined(HABLE_TONEMAPPING)
colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;
#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)
colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;
#elif defined(PHOTOGRAPHIC_TONEMAPPING)
colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);
#endif
gl_FragColor=vec4(colour.rgb,1.0);}`;
var init_tonemap_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name442]) {
    ShaderStore.ShadersStore[name442] = shader441;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/tonemap.fragment.js
var name443 = "tonemapPixelShader", shader442 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform _ExposureAdjustment: f32;
#if defined(HABLE_TONEMAPPING)
const A: f32=0.15;const B: f32=0.50;const C: f32=0.10;const D: f32=0.20;const E: f32=0.02;const F: f32=0.30;const W: f32=11.2;
#endif
fn Luminance(c: vec3f)->f32
{return dot(c, vec3f(0.22,0.707,0.071));}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var colour: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;
#if defined(REINHARD_TONEMAPPING)
var lum: f32=Luminance(colour.rgb); 
var lumTm: f32=lum*uniforms._ExposureAdjustment;var scale: f32=lumTm/(1.0+lumTm); 
colour*=scale/lum;
#elif defined(HABLE_TONEMAPPING)
colour*=uniforms._ExposureAdjustment;const ExposureBias: f32=2.0;var x: vec3f=ExposureBias*colour;var curr: vec3f=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x= vec3f(W,W,W);var whiteScale: vec3f=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;
#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)
colour*=uniforms._ExposureAdjustment;var X: vec3f=max( vec3f(0.0,0.0,0.0),colour-0.004);var retColor: vec3f=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;
#elif defined(PHOTOGRAPHIC_TONEMAPPING)
colour= vec3f(1.0,1.0,1.0)-exp2(-uniforms._ExposureAdjustment*colour);
#endif
fragmentOutputs.color= vec4f(colour.rgb,1.0);}`;
var init_tonemap_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name443]) {
    ShaderStore.ShadersStoreWGSL[name443] = shader442;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/boundingBoxRenderer.vertex.js
var exports_boundingBoxRenderer_vertex = {};
__export(exports_boundingBoxRenderer_vertex, {
  boundingBoxRendererVertexShaderWGSL: () => boundingBoxRendererVertexShaderWGSL
});
var name444 = "boundingBoxRendererVertexShader", shader443 = `attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f;
#ifdef INSTANCES
attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef INSTANCES
var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);var worldPos: vec4f=finalWorld* vec4f(input.position,1.0);
#else
var worldPos: vec4f=uniforms.world* vec4f(input.position,1.0);
#endif
vertexOutputs.position=uniforms.viewProjection*worldPos;
#define CUSTOM_VERTEX_MAIN_END
}
`, boundingBoxRendererVertexShaderWGSL;
var init_boundingBoxRenderer_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name444]) {
    ShaderStore.ShadersStoreWGSL[name444] = shader443;
  }
  boundingBoxRendererVertexShaderWGSL = { name: name444, shader: shader443 };
});

// node_modules/@babylonjs/core/ShadersWGSL/boundingBoxRenderer.fragment.js
var exports_boundingBoxRenderer_fragment = {};
__export(exports_boundingBoxRenderer_fragment, {
  boundingBoxRendererPixelShaderWGSL: () => boundingBoxRendererPixelShaderWGSL
});
var name445 = "boundingBoxRendererPixelShader", shader444 = `uniform color: vec4f;
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
fragmentOutputs.color=uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, boundingBoxRendererPixelShaderWGSL;
var init_boundingBoxRenderer_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name445]) {
    ShaderStore.ShadersStoreWGSL[name445] = shader444;
  }
  boundingBoxRendererPixelShaderWGSL = { name: name445, shader: shader444 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererVertexDeclaration.js
var name446 = "boundingBoxRendererVertexDeclaration", shader445 = `uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
`;
var init_boundingBoxRendererVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name446]) {
    ShaderStore.IncludesShadersStore[name446] = shader445;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererUboDeclaration.js
var name447 = "boundingBoxRendererUboDeclaration", shader446 = `#ifdef WEBGL2
uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;
#endif
#else
layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};
#endif
`;
var init_boundingBoxRendererUboDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name447]) {
    ShaderStore.IncludesShadersStore[name447] = shader446;
  }
});

// node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.vertex.js
var exports_boundingBoxRenderer_vertex2 = {};
__export(exports_boundingBoxRenderer_vertex2, {
  boundingBoxRendererVertexShader: () => boundingBoxRendererVertexShader
});
var name448 = "boundingBoxRendererVertexShader", shader447 = `attribute vec3 position;
#include<__decl__boundingBoxRendererVertex>
#ifdef INSTANCES
attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#ifdef INSTANCES
mat4 finalWorld=mat4(world0,world1,world2,world3);vec4 worldPos=finalWorld*vec4(position,1.0);
#else
vec4 worldPos=world*vec4(position,1.0);
#endif
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}
#else
gl_Position=viewProjection*worldPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}
`, boundingBoxRendererVertexShader;
var init_boundingBoxRenderer_vertex2 = __esm(() => {
  init_shaderStore();
  init_boundingBoxRendererVertexDeclaration();
  init_boundingBoxRendererUboDeclaration();
  if (!ShaderStore.ShadersStore[name448]) {
    ShaderStore.ShadersStore[name448] = shader447;
  }
  boundingBoxRendererVertexShader = { name: name448, shader: shader447 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererFragmentDeclaration.js
var name449 = "boundingBoxRendererFragmentDeclaration", shader448 = `uniform vec4 color;
`;
var init_boundingBoxRendererFragmentDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name449]) {
    ShaderStore.IncludesShadersStore[name449] = shader448;
  }
});

// node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.fragment.js
var exports_boundingBoxRenderer_fragment2 = {};
__export(exports_boundingBoxRenderer_fragment2, {
  boundingBoxRendererPixelShader: () => boundingBoxRendererPixelShader
});
var name450 = "boundingBoxRendererPixelShader", shader449 = `#include<__decl__boundingBoxRendererFragment>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, boundingBoxRendererPixelShader;
var init_boundingBoxRenderer_fragment2 = __esm(() => {
  init_shaderStore();
  init_boundingBoxRendererFragmentDeclaration();
  init_boundingBoxRendererUboDeclaration();
  if (!ShaderStore.ShadersStore[name450]) {
    ShaderStore.ShadersStore[name450] = shader449;
  }
  boundingBoxRendererPixelShader = { name: name450, shader: shader449 };
});

// node_modules/@babylonjs/core/ShadersWGSL/oitBackBlend.fragment.js
var exports_oitBackBlend_fragment = {};
__export(exports_oitBackBlend_fragment, {
  oitBackBlendPixelShaderWGSL: () => oitBackBlendPixelShaderWGSL
});
var name451 = "oitBackBlendPixelShader", shader450 = `var uBackColor: texture_2d<f32>;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureLoad(uBackColor,vec2i(fragmentInputs.position.xy),0);if (fragmentOutputs.color.a==0.0) {discard;}}
`, oitBackBlendPixelShaderWGSL;
var init_oitBackBlend_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name451]) {
    ShaderStore.ShadersStoreWGSL[name451] = shader450;
  }
  oitBackBlendPixelShaderWGSL = { name: name451, shader: shader450 };
});

// node_modules/@babylonjs/core/Shaders/oitBackBlend.fragment.js
var exports_oitBackBlend_fragment2 = {};
__export(exports_oitBackBlend_fragment2, {
  oitBackBlendPixelShader: () => oitBackBlendPixelShader
});
var name452 = "oitBackBlendPixelShader", shader451 = `precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { 
discard;}}`, oitBackBlendPixelShader;
var init_oitBackBlend_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name452]) {
    ShaderStore.ShadersStore[name452] = shader451;
  }
  oitBackBlendPixelShader = { name: name452, shader: shader451 };
});

// node_modules/@babylonjs/core/ShadersWGSL/oitFinal.fragment.js
var exports_oitFinal_fragment = {};
__export(exports_oitFinal_fragment, {
  oitFinalPixelShaderWGSL: () => oitFinalPixelShaderWGSL
});
var name453 = "oitFinalPixelShader", shader452 = `var uFrontColor: texture_2d<f32>;var uBackColor: texture_2d<f32>;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var frontColor: vec4f=textureLoad(uFrontColor,fragCoord,0);var backColor: vec4f=textureLoad(uBackColor,fragCoord,0);var alphaMultiplier: f32=1.0-frontColor.a;fragmentOutputs.color=vec4f(
frontColor.rgb+alphaMultiplier*backColor.rgb,
frontColor.a+backColor.a
);}
`, oitFinalPixelShaderWGSL;
var init_oitFinal_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name453]) {
    ShaderStore.ShadersStoreWGSL[name453] = shader452;
  }
  oitFinalPixelShaderWGSL = { name: name453, shader: shader452 };
});

// node_modules/@babylonjs/core/Shaders/oitFinal.fragment.js
var exports_oitFinal_fragment2 = {};
__export(exports_oitFinal_fragment2, {
  oitFinalPixelShader: () => oitFinalPixelShader
});
var name454 = "oitFinalPixelShader", shader453 = `precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(
frontColor.rgb+alphaMultiplier*backColor.rgb,
frontColor.a+backColor.a
);}`, oitFinalPixelShader;
var init_oitFinal_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name454]) {
    ShaderStore.ShadersStore[name454] = shader453;
  }
  oitFinalPixelShader = { name: name454, shader: shader453 };
});

// node_modules/@babylonjs/core/ShadersWGSL/line.vertex.js
var exports_line_vertex = {};
__export(exports_line_vertex, {
  lineVertexShaderWGSL: () => lineVertexShaderWGSL
});
var name455 = "lineVertexShader", shader454 = `#define ADDITIONAL_VERTEX_DECLARATION
#include<instancesDeclaration>
#include<clipPlaneVertexDeclaration>
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
attribute position: vec3f;attribute normal: vec4f;uniform width: f32;uniform aspectRatio: f32;
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
#include<instancesVertex>
var worldViewProjection: mat4x4f=scene.viewProjection*finalWorld;var viewPosition: vec4f=worldViewProjection* vec4f(input.position,1.0);var viewPositionNext: vec4f=worldViewProjection* vec4f(input.normal.xyz,1.0);var currentScreen: vec2f=viewPosition.xy/viewPosition.w;var nextScreen: vec2f=viewPositionNext.xy/viewPositionNext.w;currentScreen=vec2f(currentScreen.x*uniforms.aspectRatio,currentScreen.y);nextScreen=vec2f(nextScreen.x*uniforms.aspectRatio,nextScreen.y);var dir: vec2f=normalize(nextScreen-currentScreen);var normalDir: vec2f= vec2f(-dir.y,dir.x);normalDir*=uniforms.width/2.0;normalDir=vec2f(normalDir.x/uniforms.aspectRatio,normalDir.y);var offset: vec4f= vec4f(normalDir*input.normal.w,0.0,0.0);vertexOutputs.position=viewPosition+offset;
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
var worldPos: vec4f=finalWorld*vec4f(input.position,1.0);
#include<clipPlaneVertex>
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, lineVertexShaderWGSL;
var init_line_vertex = __esm(() => {
  init_shaderStore();
  init_instancesDeclaration();
  init_clipPlaneVertexDeclaration();
  init_sceneUboDeclaration();
  init_meshUboDeclaration();
  init_logDepthDeclaration();
  init_instancesVertex();
  init_clipPlaneVertex();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name455]) {
    ShaderStore.ShadersStoreWGSL[name455] = shader454;
  }
  lineVertexShaderWGSL = { name: name455, shader: shader454 };
});

// node_modules/@babylonjs/core/ShadersWGSL/line.fragment.js
var exports_line_fragment = {};
__export(exports_line_fragment, {
  linePixelShaderWGSL: () => linePixelShaderWGSL
});
var name456 = "linePixelShader", shader455 = `#include<clipPlaneFragmentDeclaration>
uniform color: vec4f;
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<logDepthFragment>
#include<clipPlaneFragment>
fragmentOutputs.color=uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, linePixelShaderWGSL;
var init_line_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_logDepthDeclaration();
  init_logDepthFragment();
  init_clipPlaneFragment();
  if (!ShaderStore.ShadersStoreWGSL[name456]) {
    ShaderStore.ShadersStoreWGSL[name456] = shader455;
  }
  linePixelShaderWGSL = { name: name456, shader: shader455 };
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lineVertexDeclaration.js
var name457 = "lineVertexDeclaration", shader456 = `uniform mat4 viewProjection;
#define ADDITIONAL_VERTEX_DECLARATION
`;
var init_lineVertexDeclaration = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.IncludesShadersStore[name457]) {
    ShaderStore.IncludesShadersStore[name457] = shader456;
  }
});

// node_modules/@babylonjs/core/Shaders/ShadersInclude/lineUboDeclaration.js
var name458 = "lineUboDeclaration", shader457 = `layout(std140,column_major) uniform;
#include<sceneUboDeclaration>
#include<meshUboDeclaration>
`;
var init_lineUboDeclaration = __esm(() => {
  init_shaderStore();
  init_sceneUboDeclaration2();
  init_meshUboDeclaration2();
  if (!ShaderStore.IncludesShadersStore[name458]) {
    ShaderStore.IncludesShadersStore[name458] = shader457;
  }
});

// node_modules/@babylonjs/core/Shaders/line.vertex.js
var exports_line_vertex2 = {};
__export(exports_line_vertex2, {
  lineVertexShader: () => lineVertexShader
});
var name459 = "lineVertexShader", shader458 = `#include<__decl__lineVertex>
#include<instancesDeclaration>
#include<clipPlaneVertexDeclaration>
attribute vec3 position;attribute vec4 normal;uniform float width;uniform float aspectRatio;
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
#include<instancesVertex>
mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)
vec4 worldPos=finalWorld*vec4(position,1.0);
#include<clipPlaneVertex>
#endif
#include<logDepthVertex>
#define CUSTOM_VERTEX_MAIN_END
}`, lineVertexShader;
var init_line_vertex2 = __esm(() => {
  init_shaderStore();
  init_lineVertexDeclaration();
  init_lineUboDeclaration();
  init_instancesDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_logDepthDeclaration2();
  init_instancesVertex2();
  init_clipPlaneVertex2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name459]) {
    ShaderStore.ShadersStore[name459] = shader458;
  }
  lineVertexShader = { name: name459, shader: shader458 };
});

// node_modules/@babylonjs/core/Shaders/line.fragment.js
var exports_line_fragment2 = {};
__export(exports_line_fragment2, {
  linePixelShader: () => linePixelShader
});
var name460 = "linePixelShader", shader459 = `#include<clipPlaneFragmentDeclaration>
uniform vec4 color;
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<logDepthFragment>
#include<clipPlaneFragment>
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, linePixelShader;
var init_line_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_logDepthFragment2();
  init_clipPlaneFragment2();
  if (!ShaderStore.ShadersStore[name460]) {
    ShaderStore.ShadersStore[name460] = shader459;
  }
  linePixelShader = { name: name460, shader: shader459 };
});

// node_modules/@babylonjs/core/ShadersWGSL/outline.fragment.js
var exports_outline_fragment = {};
__export(exports_outline_fragment, {
  outlinePixelShaderWGSL: () => outlinePixelShaderWGSL
});
var name467 = "outlinePixelShader", shader466 = `uniform color: vec4f;
#ifdef ALPHATEST
varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#endif
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV).a<0.4) {discard;}
#endif
#include<logDepthFragment>
fragmentOutputs.color=uniforms.color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, outlinePixelShaderWGSL;
var init_outline_fragment = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration();
  init_logDepthDeclaration();
  init_clipPlaneFragment();
  init_logDepthFragment();
  if (!ShaderStore.ShadersStoreWGSL[name467]) {
    ShaderStore.ShadersStoreWGSL[name467] = shader466;
  }
  outlinePixelShaderWGSL = { name: name467, shader: shader466 };
});

// node_modules/@babylonjs/core/ShadersWGSL/outline.vertex.js
var exports_outline_vertex = {};
__export(exports_outline_vertex, {
  outlineVertexShaderWGSL: () => outlineVertexShaderWGSL
});
var name468 = "outlineVertexShader", shader467 = `attribute position: vec3f;attribute normal: vec3f;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
uniform offset: f32;
#include<instancesDeclaration>
uniform viewProjection: mat4x4f;
#ifdef ALPHATEST
varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; 
#ifdef UV1
attribute uv: vec2f;
#endif
#ifdef UV2
attribute uv2: vec2f;
#endif
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input: VertexInputs)->FragmentInputs {var positionUpdated: vec3f=vertexInputs.position;var normalUpdated: vec3f=vertexInputs.normal;
#ifdef UV1
var uvUpdated: vec2f=vertexInputs.uv;
#endif
#ifdef UV2
var uv2Updated: vec2f=vertexInputs.uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
var offsetPosition: vec3f=positionUpdated+(normalUpdated*uniforms.offset);
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
var worldPos: vec4f=finalWorld*vec4f(offsetPosition,1.0);vertexOutputs.position=uniforms.viewProjection*worldPos;
#ifdef ALPHATEST
#ifdef UV1
vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uvUpdated,1.0,0.0)).xy;
#endif
#ifdef UV2
vertexOutputs.vUV=(uniforms.diffuseMatrix*vec4f(uv2Updated,1.0,0.0)).xy;
#endif
#endif
#include<clipPlaneVertex>
#include<logDepthVertex>
}
`, outlineVertexShaderWGSL;
var init_outline_vertex = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration();
  init_bakedVertexAnimationDeclaration();
  init_morphTargetsVertexGlobalDeclaration();
  init_morphTargetsVertexDeclaration();
  init_clipPlaneVertexDeclaration();
  init_instancesDeclaration();
  init_logDepthDeclaration();
  init_morphTargetsVertexGlobal();
  init_morphTargetsVertex();
  init_instancesVertex();
  init_bonesVertex();
  init_bakedVertexAnimation();
  init_clipPlaneVertex();
  init_logDepthVertex();
  if (!ShaderStore.ShadersStoreWGSL[name468]) {
    ShaderStore.ShadersStoreWGSL[name468] = shader467;
  }
  outlineVertexShaderWGSL = { name: name468, shader: shader467 };
});

// node_modules/@babylonjs/core/Shaders/outline.fragment.js
var exports_outline_fragment2 = {};
__export(exports_outline_fragment2, {
  outlinePixelShader: () => outlinePixelShader
});
var name469 = "outlinePixelShader", shader468 = `#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
uniform vec4 color;
#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
#include<logDepthDeclaration>
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#include<logDepthFragment>
gl_FragColor=color;
#define CUSTOM_FRAGMENT_MAIN_END
}`, outlinePixelShader;
var init_outline_fragment2 = __esm(() => {
  init_shaderStore();
  init_clipPlaneFragmentDeclaration2();
  init_logDepthDeclaration2();
  init_clipPlaneFragment2();
  init_logDepthFragment2();
  if (!ShaderStore.ShadersStore[name469]) {
    ShaderStore.ShadersStore[name469] = shader468;
  }
  outlinePixelShader = { name: name469, shader: shader468 };
});

// node_modules/@babylonjs/core/Shaders/outline.vertex.js
var exports_outline_vertex2 = {};
__export(exports_outline_vertex2, {
  outlineVertexShader: () => outlineVertexShader
});
var name470 = "outlineVertexShader", shader469 = `attribute vec3 position;attribute vec3 normal;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
uniform float offset;
#include<instancesDeclaration>
uniform mat4 viewProjection;
#ifdef ALPHATEST
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#include<logDepthDeclaration>
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;vec3 normalUpdated=normal;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
vec3 offsetPosition=positionUpdated+(normalUpdated*offset);
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;
#ifdef ALPHATEST
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<clipPlaneVertex>
#include<logDepthVertex>
}
`, outlineVertexShader;
var init_outline_vertex2 = __esm(() => {
  init_shaderStore();
  init_bonesDeclaration2();
  init_bakedVertexAnimationDeclaration2();
  init_morphTargetsVertexGlobalDeclaration2();
  init_morphTargetsVertexDeclaration2();
  init_clipPlaneVertexDeclaration2();
  init_instancesDeclaration2();
  init_logDepthDeclaration2();
  init_morphTargetsVertexGlobal2();
  init_morphTargetsVertex2();
  init_instancesVertex2();
  init_bonesVertex2();
  init_bakedVertexAnimation2();
  init_clipPlaneVertex2();
  init_logDepthVertex2();
  if (!ShaderStore.ShadersStore[name470]) {
    ShaderStore.ShadersStore[name470] = shader469;
  }
  outlineVertexShader = { name: name470, shader: shader469 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleDepth.vertex.js
var exports_fluidRenderingParticleDepth_vertex = {};
__export(exports_fluidRenderingParticleDepth_vertex, {
  fluidRenderingParticleDepthVertexShaderWGSL: () => fluidRenderingParticleDepthVertexShaderWGSL
});
var name471 = "fluidRenderingParticleDepthVertexShader", shader470 = `attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;
#ifdef FLUIDRENDERING_VELOCITY
attribute velocity: vec3f;varying velocityNorm: f32;
#endif
@vertex
fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(
vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,
0.0
);vertexOutputs.viewPos=(uniforms.view*vec4f(input.position,1.0)).xyz;vertexOutputs.position=uniforms.projection*vec4f(vertexOutputs.viewPos+cornerPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.sphereRadius=uniforms.size.x/2.0;
#ifdef FLUIDRENDERING_VELOCITY
vertexOutputs.velocityNorm=length(velocity);
#endif
}
`, fluidRenderingParticleDepthVertexShaderWGSL;
var init_fluidRenderingParticleDepth_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name471]) {
    ShaderStore.ShadersStoreWGSL[name471] = shader470;
  }
  fluidRenderingParticleDepthVertexShaderWGSL = { name: name471, shader: shader470 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleDepth.fragment.js
var exports_fluidRenderingParticleDepth_fragment = {};
__export(exports_fluidRenderingParticleDepth_fragment, {
  fluidRenderingParticleDepthPixelShaderWGSL: () => fluidRenderingParticleDepthPixelShaderWGSL
});
var name472 = "fluidRenderingParticleDepthPixelShader", shader471 = `uniform projection: mat4x4f;varying uv: vec2f;varying viewPos: vec3f;varying sphereRadius: f32;
#ifdef FLUIDRENDERING_VELOCITY
varying velocityNorm: f32;
#endif
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}
var normal: vec3f=vec3f(normalxy,sqrt(1.0-r2));
#ifndef FLUIDRENDERING_RHS
normal.z=-normal.z;
#endif
var realViewPos: vec4f=vec4f(input.viewPos+normal*input.sphereRadius,1.0);var clipSpacePos: vec4f=uniforms.projection*realViewPos;fragmentOutputs.fragDepth=clipSpacePos.z/clipSpacePos.w;
#ifdef FLUIDRENDERING_RHS
realViewPos.z=-realViewPos.z;
#endif
#ifdef FLUIDRENDERING_VELOCITY
fragmentOutputs.color=vec4f(realViewPos.z,input.velocityNorm,0.,1.);
#else
fragmentOutputs.color=vec4f(realViewPos.z,0.,0.,1.);
#endif
}
`, fluidRenderingParticleDepthPixelShaderWGSL;
var init_fluidRenderingParticleDepth_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name472]) {
    ShaderStore.ShadersStoreWGSL[name472] = shader471;
  }
  fluidRenderingParticleDepthPixelShaderWGSL = { name: name472, shader: shader471 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.vertex.js
var exports_fluidRenderingParticleDepth_vertex2 = {};
__export(exports_fluidRenderingParticleDepth_vertex2, {
  fluidRenderingParticleDepthVertexShader: () => fluidRenderingParticleDepthVertexShader
});
var name473 = "fluidRenderingParticleDepthVertexShader", shader472 = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;
#ifdef FLUIDRENDERING_VELOCITY
attribute vec3 velocity;varying float velocityNorm;
#endif
void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;
#ifdef FLUIDRENDERING_VELOCITY
velocityNorm=length(velocity);
#endif
}
`, fluidRenderingParticleDepthVertexShader;
var init_fluidRenderingParticleDepth_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name473]) {
    ShaderStore.ShadersStore[name473] = shader472;
  }
  fluidRenderingParticleDepthVertexShader = { name: name473, shader: shader472 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.fragment.js
var exports_fluidRenderingParticleDepth_fragment2 = {};
__export(exports_fluidRenderingParticleDepth_fragment2, {
  fluidRenderingParticleDepthPixelShader: () => fluidRenderingParticleDepthPixelShader
});
var name474 = "fluidRenderingParticleDepthPixelShader", shader473 = `uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;
#ifdef FLUIDRENDERING_VELOCITY
varying float velocityNorm;
#endif
void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);
#ifndef FLUIDRENDERING_RHS
normal.z=-normal.z;
#endif
vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;
#ifdef WEBGPU
gl_FragDepth=clipSpacePos.z/clipSpacePos.w;
#else
gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;
#endif
#ifdef FLUIDRENDERING_RHS
realViewPos.z=-realViewPos.z;
#endif
#ifdef FLUIDRENDERING_VELOCITY
glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);
#else
glFragColor=vec4(realViewPos.z,0.,0.,1.);
#endif
}
`, fluidRenderingParticleDepthPixelShader;
var init_fluidRenderingParticleDepth_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name474]) {
    ShaderStore.ShadersStore[name474] = shader473;
  }
  fluidRenderingParticleDepthPixelShader = { name: name474, shader: shader473 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleThickness.vertex.js
var exports_fluidRenderingParticleThickness_vertex = {};
__export(exports_fluidRenderingParticleThickness_vertex, {
  fluidRenderingParticleThicknessVertexShaderWGSL: () => fluidRenderingParticleThicknessVertexShaderWGSL
});
var name475 = "fluidRenderingParticleThicknessVertexShader", shader474 = `attribute position: vec3f;attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;@vertex
fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(
vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,
0.0
);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;}
`, fluidRenderingParticleThicknessVertexShaderWGSL;
var init_fluidRenderingParticleThickness_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name475]) {
    ShaderStore.ShadersStoreWGSL[name475] = shader474;
  }
  fluidRenderingParticleThicknessVertexShaderWGSL = { name: name475, shader: shader474 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleThickness.fragment.js
var exports_fluidRenderingParticleThickness_fragment = {};
__export(exports_fluidRenderingParticleThickness_fragment, {
  fluidRenderingParticleThicknessPixelShaderWGSL: () => fluidRenderingParticleThicknessPixelShaderWGSL
});
var name476 = "fluidRenderingParticleThicknessPixelShader", shader475 = `uniform particleAlpha: f32;varying uv: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}
var thickness: f32=sqrt(1.0-r2);fragmentOutputs.color=vec4f(vec3f(uniforms.particleAlpha*thickness),1.0);}
`, fluidRenderingParticleThicknessPixelShaderWGSL;
var init_fluidRenderingParticleThickness_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name476]) {
    ShaderStore.ShadersStoreWGSL[name476] = shader475;
  }
  fluidRenderingParticleThicknessPixelShaderWGSL = { name: name476, shader: shader475 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.vertex.js
var exports_fluidRenderingParticleThickness_vertex2 = {};
__export(exports_fluidRenderingParticleThickness_vertex2, {
  fluidRenderingParticleThicknessVertexShader: () => fluidRenderingParticleThicknessVertexShader
});
var name477 = "fluidRenderingParticleThicknessVertexShader", shader476 = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}
`, fluidRenderingParticleThicknessVertexShader;
var init_fluidRenderingParticleThickness_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name477]) {
    ShaderStore.ShadersStore[name477] = shader476;
  }
  fluidRenderingParticleThicknessVertexShader = { name: name477, shader: shader476 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.fragment.js
var exports_fluidRenderingParticleThickness_fragment2 = {};
__export(exports_fluidRenderingParticleThickness_fragment2, {
  fluidRenderingParticleThicknessPixelShader: () => fluidRenderingParticleThicknessPixelShader
});
var name478 = "fluidRenderingParticleThicknessPixelShader", shader477 = `uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}
`, fluidRenderingParticleThicknessPixelShader;
var init_fluidRenderingParticleThickness_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name478]) {
    ShaderStore.ShadersStore[name478] = shader477;
  }
  fluidRenderingParticleThicknessPixelShader = { name: name478, shader: shader477 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingStandardBlur.fragment.js
var exports_fluidRenderingStandardBlur_fragment = {};
__export(exports_fluidRenderingStandardBlur_fragment, {
  fluidRenderingStandardBlurPixelShaderWGSL: () => fluidRenderingStandardBlurPixelShaderWGSL
});
var name479 = "fluidRenderingStandardBlurPixelShader", shader478 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform filterSize: i32;uniform blurDir: vec2f;varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var s: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.);if (s.r==0.) {fragmentOutputs.color=vec4f(0.,0.,0.,1.);return fragmentOutputs;}
var sigma: f32=f32(uniforms.filterSize)/3.0;var twoSigma2: f32=2.0*sigma*sigma;var sum: vec4f=vec4f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampl: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.);var w: f32=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}
sum/=wsum;fragmentOutputs.color=vec4f(sum.rgb,1.);}
`, fluidRenderingStandardBlurPixelShaderWGSL;
var init_fluidRenderingStandardBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name479]) {
    ShaderStore.ShadersStoreWGSL[name479] = shader478;
  }
  fluidRenderingStandardBlurPixelShaderWGSL = { name: name479, shader: shader478 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingStandardBlur.fragment.js
var exports_fluidRenderingStandardBlur_fragment2 = {};
__export(exports_fluidRenderingStandardBlur_fragment2, {
  fluidRenderingStandardBlurPixelShader: () => fluidRenderingStandardBlurPixelShader
});
var name480 = "fluidRenderingStandardBlurPixelShader", shader479 = `uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}
float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}
sum/=wsum;glFragColor=vec4(sum.rgb,1.);}
`, fluidRenderingStandardBlurPixelShader;
var init_fluidRenderingStandardBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name480]) {
    ShaderStore.ShadersStore[name480] = shader479;
  }
  fluidRenderingStandardBlurPixelShader = { name: name480, shader: shader479 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingBilateralBlur.fragment.js
var exports_fluidRenderingBilateralBlur_fragment = {};
__export(exports_fluidRenderingBilateralBlur_fragment, {
  fluidRenderingBilateralBlurPixelShaderWGSL: () => fluidRenderingBilateralBlurPixelShaderWGSL
});
var name481 = "fluidRenderingBilateralBlurPixelShader", shader480 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform maxFilterSize: i32;uniform blurDir: vec2f;uniform projectedParticleConstant: f32;uniform depthThreshold: f32;varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color=vec4f(vec3f(depth),1.);return fragmentOutputs;}
var filterSize: i32=min(uniforms.maxFilterSize,i32(ceil(uniforms.projectedParticleConstant/depth)));var sigma: f32=f32(filterSize)/3.0;var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold/3.0;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sum: f32=0.;var wsum: f32=0.;var sumVel: f32=0.;for (var x: i32=-filterSize; x<=filterSize; x++) {var coords: vec2f=vec2f(f32(x));var sampleDepthVel: vec2f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rg;var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepthVel.r-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}
fragmentOutputs.color=vec4f(sum/wsum,sumVel/wsum,0.,1.);}
`, fluidRenderingBilateralBlurPixelShaderWGSL;
var init_fluidRenderingBilateralBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name481]) {
    ShaderStore.ShadersStoreWGSL[name481] = shader480;
  }
  fluidRenderingBilateralBlurPixelShaderWGSL = { name: name481, shader: shader480 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingBilateralBlur.fragment.js
var exports_fluidRenderingBilateralBlur_fragment2 = {};
__export(exports_fluidRenderingBilateralBlur_fragment2, {
  fluidRenderingBilateralBlurPixelShader: () => fluidRenderingBilateralBlurPixelShader
});
var name482 = "fluidRenderingBilateralBlurPixelShader", shader481 = `uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}
int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}
glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}
`, fluidRenderingBilateralBlurPixelShader;
var init_fluidRenderingBilateralBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name482]) {
    ShaderStore.ShadersStore[name482] = shader481;
  }
  fluidRenderingBilateralBlurPixelShader = { name: name482, shader: shader481 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingRender.fragment.js
var exports_fluidRenderingRender_fragment = {};
__export(exports_fluidRenderingRender_fragment, {
  fluidRenderingRenderPixelShaderWGSL: () => fluidRenderingRenderPixelShaderWGSL
});
var name483 = "fluidRenderingRenderPixelShader", shader482 = `#define DISABLE_UNIFORMITY_ANALYSIS
#define IOR 1.333
#define ETA 1.0/IOR
#define F0 0.02
var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d<f32>;
#else
uniform diffuseColor: vec3f;
#endif
#ifdef FLUIDRENDERING_FIXED_THICKNESS
uniform thickness: f32;var bgDepthSamplerSampler: sampler;var bgDepthSampler: texture_2d<f32>;
#else
uniform minimumThickness: f32;var thicknessSamplerSampler: sampler;var thicknessSampler: texture_2d<f32>;
#endif
#ifdef FLUIDRENDERING_ENVIRONMENT
var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube<f32>;
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
var debugSamplerSampler: sampler;var debugSampler: texture_2d<f32>;
#endif
uniform viewMatrix: mat4x4f;uniform projectionMatrix: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform texelSize: vec2f;uniform dirLight: vec3f;uniform cameraFar: f32;uniform density: f32;uniform refractionStrength: f32;uniform fresnelClamp: f32;uniform specularPower: f32;varying vUV: vec2f;fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32)->vec3f {var ndc: vec4f=vec4f(texCoord*2.0-1.0,0.0,1.0);
#ifdef FLUIDRENDERING_RHS
ndc.z=-uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;
#else
ndc.z=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;
#endif
ndc.w=1.0;var eyePos: vec4f=uniforms.invProjectionMatrix*ndc;return eyePos.xyz/eyePos.w;}
fn getViewPosFromTexCoord(texCoord: vec2f)->vec3f {var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var texCoord: vec2f=input.vUV;
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
var color: vec4f=textureSample(debugSampler,debugSamplerSampler,texCoord);
#ifdef FLUIDRENDERING_DEBUG_DEPTH
fragmentOutputs.color=vec4f(color.rgb/vec3f(2.0),1.);if (color.r>0.999 && color.g>0.999) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}
#else
fragmentOutputs.color=vec4f(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,texCoord);}
#endif
return fragmentOutputs;
#endif
var depthVel: vec2f=textureSampleLevel(depthSampler,depthSamplerSampler,texCoord,0.).rg;var depth: f32=depthVel.r;
#ifndef FLUIDRENDERING_FIXED_THICKNESS
var thickness: f32=textureSample(thicknessSampler,thicknessSamplerSampler,texCoord).x;
#else
var thickness: f32=uniforms.thickness;var bgDepth: f32=textureSample(bgDepthSampler,bgDepthSamplerSampler,texCoord).x;var depthNonLinear: f32=uniforms.projectionMatrix[2].z+uniforms.projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;
#endif
var backColor: vec4f=textureSample(textureSampler,textureSamplerSampler,texCoord);
#ifndef FLUIDRENDERING_FIXED_THICKNESS
if (depth>=uniforms.cameraFar || depth<=0. || thickness<=uniforms.minimumThickness) {
#else
if (depth>=uniforms.cameraFar || depth<=0. || bgDepth<=depthNonLinear) {
#endif
#ifdef FLUIDRENDERING_COMPOSITE_MODE
fragmentOutputs.color=vec4f(backColor.rgb*backColor.a,backColor.a);
#else
fragmentOutputs.color=backColor;
#endif
return fragmentOutputs;}
var viewPos: vec3f=computeViewPosFromUVDepth(texCoord,depth);var ddx: vec3f=getViewPosFromTexCoord(texCoord+vec2f(uniforms.texelSize.x,0.))-viewPos;var ddy: vec3f=getViewPosFromTexCoord(texCoord+vec2f(0.,uniforms.texelSize.y))-viewPos;var ddx2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(-uniforms.texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}
var ddy2: vec3f=viewPos-getViewPosFromTexCoord(texCoord+vec2f(0.,-uniforms.texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}
var normal: vec3f=normalize(cross(ddy,ddx));
#ifdef FLUIDRENDERING_RHS
normal=-normal;
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)
fragmentOutputs.color=vec4f(normal*0.5+0.5,1.0);return fragmentOutputs;
#endif
var rayDir: vec3f=normalize(viewPos); 
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
var diffuseColor: vec3f=textureSampleLevel(diffuseSampler,diffuseSamplerSampler,texCoord,0.0).rgb;
#else
var diffuseColor: vec3f=uniforms.diffuseColor;
#endif
var lightDir: vec3f=normalize((uniforms.viewMatrix*vec4f(-uniforms.dirLight,0.)).xyz);var H: vec3f =normalize(lightDir-rayDir);var specular: f32 =pow(max(0.0,dot(H,normal)),uniforms.specularPower);
#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING
var diffuse: f32 =max(0.0,dot(lightDir,normal))*1.0;fragmentOutputs.color=vec4f(vec3f(0.1) /*ambient*/+vec3f(0.42,0.50,1.00)*diffuse+vec3f(0,0,0.2)+specular,1.);return fragmentOutputs;
#endif
var refractionDir: vec3f=refract(rayDir,normal,ETA);var transmitted: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,vec2f(texCoord+refractionDir.xy*thickness*uniforms.refractionStrength),0.0);
#ifdef FLUIDRENDERING_COMPOSITE_MODE
if (transmitted.a==0.) {transmitted.a=thickness;}
#endif
var transmittance: vec3f=exp(-uniforms.density*thickness*(1.0-diffuseColor)); 
var refractionColor: vec3f=transmitted.rgb*transmittance;
#ifdef FLUIDRENDERING_ENVIRONMENT
var reflectionDir: vec3f=reflect(rayDir,normal);var reflectionColor: vec3f=(textureSample(reflectionSampler,reflectionSamplerSampler,reflectionDir).rgb);var fresnel: f32=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,uniforms.fresnelClamp);var finalColor: vec3f=mix(refractionColor,reflectionColor,fresnel)+specular;
#else
var finalColor: vec3f=refractionColor+specular;
#endif
#ifdef FLUIDRENDERING_VELOCITY
var velocity: f32=depthVel.g;finalColor=mix(finalColor,vec3f(1.0),smoothstep(0.3,1.0,velocity/6.0));
#endif
fragmentOutputs.color=vec4f(finalColor,transmitted.a);}
`, fluidRenderingRenderPixelShaderWGSL;
var init_fluidRenderingRender_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name483]) {
    ShaderStore.ShadersStoreWGSL[name483] = shader482;
  }
  fluidRenderingRenderPixelShaderWGSL = { name: name483, shader: shader482 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingRender.fragment.js
var exports_fluidRenderingRender_fragment2 = {};
__export(exports_fluidRenderingRender_fragment2, {
  fluidRenderingRenderPixelShader: () => fluidRenderingRenderPixelShader
});
var name484 = "fluidRenderingRenderPixelShader", shader483 = `#define DISABLE_UNIFORMITY_ANALYSIS
#define IOR 1.333
#define ETA 1.0/IOR
#define F0 0.02
uniform sampler2D textureSampler;uniform sampler2D depthSampler;
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
uniform sampler2D diffuseSampler;
#else
uniform vec3 diffuseColor;
#endif
#ifdef FLUIDRENDERING_FIXED_THICKNESS
uniform float thickness;uniform sampler2D bgDepthSampler;
#else
uniform float minimumThickness;uniform sampler2D thicknessSampler;
#endif
#ifdef FLUIDRENDERING_ENVIRONMENT
uniform samplerCube reflectionSampler;
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
uniform sampler2D debugSampler;
#endif
uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;
#ifdef FLUIDRENDERING_RHS
ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;
#else
ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;
#endif
ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}
vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}
void main(void) {vec2 texCoord=vUV;
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)
vec4 color=texture2D(debugSampler,texCoord);
#ifdef FLUIDRENDERING_DEBUG_DEPTH
glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}
#else
glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}
#endif
return;
#endif
vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;
#ifndef FLUIDRENDERING_FIXED_THICKNESS
float thickness=texture2D(thicknessSampler,texCoord).x;
#else
float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;
#endif
vec4 backColor=texture2D(textureSampler,texCoord);
#ifndef FLUIDRENDERING_FIXED_THICKNESS
if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {
#else
if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {
#endif
#ifdef FLUIDRENDERING_COMPOSITE_MODE
glFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;
#else
glFragColor=backColor;
#endif
return;}
vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}
vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}
vec3 normal=normalize(cross(ddy,ddx));
#ifdef FLUIDRENDERING_RHS
normal=-normal;
#endif
#ifndef WEBGPU
if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}
#endif
#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)
glFragColor=vec4(normal*0.5+0.5,1.0);return;
#endif
vec3 rayDir=normalize(viewPos); 
#ifdef FLUIDRENDERING_DIFFUSETEXTURE
vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;
#endif
vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);
#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING
float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;
#endif
vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);
#ifdef FLUIDRENDERING_COMPOSITE_MODE
if (transmitted.a==0.) transmitted.a=thickness;
#endif
vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); 
vec3 refractionColor=transmitted.rgb*transmittance;
#ifdef FLUIDRENDERING_ENVIRONMENT
vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;
#else
vec3 finalColor=refractionColor+specular;
#endif
#ifdef FLUIDRENDERING_VELOCITY
float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));
#endif
glFragColor=vec4(finalColor,transmitted.a);}
`, fluidRenderingRenderPixelShader;
var init_fluidRenderingRender_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name484]) {
    ShaderStore.ShadersStore[name484] = shader483;
  }
  fluidRenderingRenderPixelShader = { name: name484, shader: shader483 };
});

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleDiffuse.fragment.js
var exports_fluidRenderingParticleDiffuse_fragment = {};
__export(exports_fluidRenderingParticleDiffuse_fragment, {
  fluidRenderingParticleDiffusePixelShaderWGSL: () => fluidRenderingParticleDiffusePixelShaderWGSL
});
var name485 = "fluidRenderingParticleDiffusePixelShader", shader484 = `uniform particleAlpha: f32;varying uv: vec2f;varying diffuseColor: vec3f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var normalxy: vec2f=input.uv*2.0-1.0;var r2: f32=dot(normalxy,normalxy);if (r2>1.0) {discard;}
fragmentOutputs.color=vec4f(input.diffuseColor,1.0);}
`, fluidRenderingParticleDiffusePixelShaderWGSL;
var init_fluidRenderingParticleDiffuse_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name485]) {
    ShaderStore.ShadersStoreWGSL[name485] = shader484;
  }
  fluidRenderingParticleDiffusePixelShaderWGSL = { name: name485, shader: shader484 };
});

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.fragment.js
var exports_fluidRenderingParticleDiffuse_fragment2 = {};
__export(exports_fluidRenderingParticleDiffuse_fragment2, {
  fluidRenderingParticleDiffusePixelShader: () => fluidRenderingParticleDiffusePixelShader
});
var name486 = "fluidRenderingParticleDiffusePixelShader", shader485 = `uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}
`, fluidRenderingParticleDiffusePixelShader;
var init_fluidRenderingParticleDiffuse_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name486]) {
    ShaderStore.ShadersStore[name486] = shader485;
  }
  fluidRenderingParticleDiffusePixelShader = { name: name486, shader: shader485 };
});

// node_modules/@babylonjs/core/ShadersWGSL/bilateralBlur.fragment.js
var exports_bilateralBlur_fragment = {};
__export(exports_bilateralBlur_fragment, {
  bilateralBlurPixelShaderWGSL: () => bilateralBlurPixelShaderWGSL
});
var name489 = "bilateralBlurPixelShader", shader488 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var normalSamplerSampler: sampler;var normalSampler: texture_2d<f32>;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}
var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {var coords=vec2f(f32(x));var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords*uniforms.blurDir,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var depthDelta: f32=abs(sampleDepth-depth);var wd: f32=step(depthDelta,uniforms.depthThreshold);var normalDelta: vec3f=abs(sampleNormal-normal);var wn: f32=step(normalDelta.x+normalDelta.y+normalDelta.z,uniforms.normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}
fragmentOutputs.color= vec4f(sum/wsum,1.);}
`, bilateralBlurPixelShaderWGSL;
var init_bilateralBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name489]) {
    ShaderStore.ShadersStoreWGSL[name489] = shader488;
  }
  bilateralBlurPixelShaderWGSL = { name: name489, shader: shader488 };
});

// node_modules/@babylonjs/core/ShadersWGSL/bilateralBlurQuality.fragment.js
var exports_bilateralBlurQuality_fragment = {};
__export(exports_bilateralBlurQuality_fragment, {
  bilateralBlurQualityPixelShaderWGSL: () => bilateralBlurQualityPixelShaderWGSL
});
var name490 = "bilateralBlurQualityPixelShader", shader489 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var normalSamplerSampler: sampler;var normalSampler: texture_2d<f32>;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;uniform filterSize: i32;uniform blurDir: vec2f;uniform depthThreshold: f32;uniform normalThreshold: f32;varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var color: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.).x;if (depth>=1e6 || depth<=0.) {fragmentOutputs.color= vec4f(color,1.);return fragmentOutputs;}
var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
var sigma: f32= f32(uniforms.filterSize);var two_sigma2: f32=2.0*sigma*sigma;var sigmaDepth: f32=uniforms.depthThreshold;var two_sigmaDepth2: f32=2.0*sigmaDepth*sigmaDepth;var sigmaNormal: f32=uniforms.normalThreshold;var two_sigmaNormal2: f32=2.0*sigmaNormal*sigmaNormal;var sum: vec3f= vec3f(0.);var wsum: f32=0.;for (var x: i32=-uniforms.filterSize; x<=uniforms.filterSize; x++) {for (var y: i32=-uniforms.filterSize; y<=uniforms.filterSize; y++) {var coords: vec2f= vec2f(f32(x),f32(y))*uniforms.blurDir;var sampleColor: vec3f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV+coords,0.).rgb;var sampleDepth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV+coords,0.).r;var sampleNormal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV+coords,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
var r: f32=dot(coords,coords);var w: f32=exp(-r/two_sigma2);var rDepth: f32=sampleDepth-depth;var wd: f32=exp(-rDepth*rDepth/two_sigmaDepth2);var rNormal: f32=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);var wn: f32=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}
fragmentOutputs.color= vec4f(sum/wsum,1.);}
`, bilateralBlurQualityPixelShaderWGSL;
var init_bilateralBlurQuality_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name490]) {
    ShaderStore.ShadersStoreWGSL[name490] = shader489;
  }
  bilateralBlurQualityPixelShaderWGSL = { name: name490, shader: shader489 };
});

// node_modules/@babylonjs/core/ShadersWGSL/rsmGlobalIllumination.fragment.js
var exports_rsmGlobalIllumination_fragment = {};
__export(exports_rsmGlobalIllumination_fragment, {
  rsmGlobalIlluminationPixelShaderWGSL: () => rsmGlobalIlluminationPixelShaderWGSL
});
var name491 = "rsmGlobalIlluminationPixelShader", shader490 = `/**
* The implementation is an application of the formula found in http:
* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).
*/
varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;uniform rsmInfo2: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var normalSamplerSampler: sampler;var normalSampler: texture_2d<f32>;var rsmPositionWSampler: sampler;var rsmPositionW: texture_2d<f32>;var rsmNormalWSampler: sampler;var rsmNormalW: texture_2d<f32>;var rsmFluxSampler: sampler;var rsmFlux: texture_2d<f32>;var rsmSamples: texture_2d<f32>;
#ifdef TRANSFORM_NORMAL
uniform invView: mat4x4f;
#endif
fn mod289(x: f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}
fn mod289Vec4(x: vec4f)->vec4f {return x-floor(x*(1.0/289.0))* 289.0;}
fn perm(x: vec4f)->vec4f {return mod289Vec4(((x*34.0)+1.0)*x) ;}
fn noise(p: vec3f)->f32{var a: vec3f=floor(p);var d: vec3f=p-a;d=d*d*(3.0-2.0*d);var b: vec4f=a.xxyy+ vec4f(0.0,1.0,0.0,1.0);var k1: vec4f=perm(b.xyxy);var k2: vec4f=perm(k1.xyxy+b.zzww);var c: vec4f=k2+a.zzzz;var k3: vec4f=perm(c);var k4: vec4f=perm(c+1.0);var o1: vec4f=fract(k3*(1.0/41.0));var o2: vec4f=fract(k4*(1.0/41.0));var o3: vec4f=o2*d.z+o1*(1.0-d.z);var o4: vec2f=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}
fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var numSamples: i32= i32(uniforms.rsmInfo.x);var radius: f32=uniforms.rsmInfo.y;var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var angle: f32=noise(p*uniforms.rsmInfo2.x);var c: f32=cos(angle);var s: f32=sin(angle);for (var i: i32=0; i<numSamples; i++) {var rsmSample: vec3f=textureLoad(rsmSamples,vec2<i32>(i,0),0).xyz;var weightSquare: f32=rsmSample.z;if (uniforms.rsmInfo2.y==1.0){rsmSample=vec3f(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c,rsmSample.z);}
var uv: vec2f=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) {continue;}
var vplPositionW: vec3f=textureSampleLevel(rsmPositionW,rsmPositionWSampler,uv,0.).xyz;var vplNormalW: vec3f=textureSampleLevel(rsmNormalW,rsmNormalWSampler,uv,0.).xyz*2.0-1.0;var vplFlux: vec3f=textureSampleLevel(rsmFlux,rsmFluxSampler,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}
return clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,input.vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(uniforms.invView* vec4f(normalW,0.)).xyz;
#endif
fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}
`, rsmGlobalIlluminationPixelShaderWGSL;
var init_rsmGlobalIllumination_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name491]) {
    ShaderStore.ShadersStoreWGSL[name491] = shader490;
  }
  rsmGlobalIlluminationPixelShaderWGSL = { name: name491, shader: shader490 };
});

// node_modules/@babylonjs/core/ShadersWGSL/rsmFullGlobalIllumination.fragment.js
var exports_rsmFullGlobalIllumination_fragment = {};
__export(exports_rsmFullGlobalIllumination_fragment, {
  rsmFullGlobalIlluminationPixelShaderWGSL: () => rsmFullGlobalIlluminationPixelShaderWGSL
});
var name492 = "rsmFullGlobalIlluminationPixelShader", shader491 = `/**
* The implementation is a direct application of the formula found in http:
*/
varying vUV: vec2f;uniform rsmLightMatrix: mat4x4f;uniform rsmInfo: vec4f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var normalSamplerSampler: sampler;var normalSampler: texture_2d<f32>;var rsmPositionW: texture_2d<f32>;var rsmNormalW: texture_2d<f32>;var rsmFlux: texture_2d<f32>;
#ifdef TRANSFORM_NORMAL
uniform invView: mat4x4f;
#endif
fn computeIndirect(p: vec3f,n: vec3f)->vec3f {var indirectDiffuse: vec3f= vec3f(0.);var intensity: f32=uniforms.rsmInfo.z;var edgeArtifactCorrection: f32=uniforms.rsmInfo.w;var texRSM: vec4f=uniforms.rsmLightMatrix* vec4f(p,1.);texRSM=vec4f(texRSM.xy/texRSM.w,texRSM.z,texRSM.w);texRSM=vec4f(texRSM.xy*0.5+0.5,texRSM.z,texRSM.w);var width: i32= i32(uniforms.rsmInfo.x);var height: i32= i32(uniforms.rsmInfo.y);for (var j: i32=0; j<height; j++) {for (var i: i32=0; i<width; i++) {var uv=vec2<i32>(i,j);var vplPositionW: vec3f=textureLoad(rsmPositionW,uv,0).xyz;var vplNormalW: vec3f=textureLoad(rsmNormalW,uv,0).xyz*2.0-1.0;var vplFlux: vec3f=textureLoad(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
var dist2: f32=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}
return clamp(indirectDiffuse*intensity,vec3f(0.0),vec3f(1.0));}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var positionW: vec3f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV).xyz;var normalW: vec3f=textureSample(normalSampler,normalSamplerSampler,fragmentInputs.vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(uniforms.invView* vec4f(normalW,0.)).xyz;
#endif
fragmentOutputs.color=vec4f(computeIndirect(positionW,normalW),1.0);}
`, rsmFullGlobalIlluminationPixelShaderWGSL;
var init_rsmFullGlobalIllumination_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name492]) {
    ShaderStore.ShadersStoreWGSL[name492] = shader491;
  }
  rsmFullGlobalIlluminationPixelShaderWGSL = { name: name492, shader: shader491 };
});

// node_modules/@babylonjs/core/Shaders/bilateralBlur.fragment.js
var exports_bilateralBlur_fragment2 = {};
__export(exports_bilateralBlur_fragment2, {
  bilateralBlurPixelShader: () => bilateralBlurPixelShader
});
var name493 = "bilateralBlurPixelShader", shader492 = `uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}
vec3 normal=textureLod(normalSampler,vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
float r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}
glFragColor=vec4(sum/wsum,1.);}
`, bilateralBlurPixelShader;
var init_bilateralBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name493]) {
    ShaderStore.ShadersStore[name493] = shader492;
  }
  bilateralBlurPixelShader = { name: name493, shader: shader492 };
});

// node_modules/@babylonjs/core/Shaders/bilateralBlurQuality.fragment.js
var exports_bilateralBlurQuality_fragment2 = {};
__export(exports_bilateralBlurQuality_fragment2, {
  bilateralBlurQualityPixelShader: () => bilateralBlurQualityPixelShader
});
var name494 = "bilateralBlurQualityPixelShader", shader493 = `uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}
vec3 normal=textureLod(normalSampler,vUV,0.).rgb;
#ifdef DECODE_NORMAL
normal=normal*2.0-1.0;
#endif
float sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;
#ifdef DECODE_NORMAL
sampleNormal=sampleNormal*2.0-1.0;
#endif
float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}
glFragColor=vec4(sum/wsum,1.);}
`, bilateralBlurQualityPixelShader;
var init_bilateralBlurQuality_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name494]) {
    ShaderStore.ShadersStore[name494] = shader493;
  }
  bilateralBlurQualityPixelShader = { name: name494, shader: shader493 };
});

// node_modules/@babylonjs/core/Shaders/rsmGlobalIllumination.fragment.js
var exports_rsmGlobalIllumination_fragment2 = {};
__export(exports_rsmGlobalIllumination_fragment2, {
  rsmGlobalIlluminationPixelShader: () => rsmGlobalIlluminationPixelShader
});
var name495 = "rsmGlobalIlluminationPixelShader", shader494 = `/**
* The implementation is an application of the formula found in http:
* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).
*/
precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;
#ifdef TRANSFORM_NORMAL
uniform mat4 invView;
#endif
float mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}
float noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}
vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i<numSamples; i++) {vec3 rsmSample=texelFetch(rsmSamples,ivec2(i,0),0).xyz;float weightSquare=rsmSample.z;if (rsmInfo2.y==1.0) rsmSample.xy=vec2(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c);vec2 uv=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}
return clamp(indirectDiffuse*intensity,0.0,1.0);}
void main(void) 
{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(invView*vec4(normalW,0.)).xyz;
#endif
gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}
`, rsmGlobalIlluminationPixelShader;
var init_rsmGlobalIllumination_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name495]) {
    ShaderStore.ShadersStore[name495] = shader494;
  }
  rsmGlobalIlluminationPixelShader = { name: name495, shader: shader494 };
});

// node_modules/@babylonjs/core/Shaders/rsmFullGlobalIllumination.fragment.js
var exports_rsmFullGlobalIllumination_fragment2 = {};
__export(exports_rsmFullGlobalIllumination_fragment2, {
  rsmFullGlobalIlluminationPixelShader: () => rsmFullGlobalIlluminationPixelShader
});
var name496 = "rsmFullGlobalIlluminationPixelShader", shader495 = `/**
* The implementation is a direct application of the formula found in http:
*/
precision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;
#ifdef TRANSFORM_NORMAL
uniform mat4 invView;
#endif
vec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j<height; j++) {for (int i=0; i<width; i++) {ivec2 uv=ivec2(i,j);vec3 vplPositionW=texelFetch(rsmPositionW,uv,0).xyz;vec3 vplNormalW=texelFetch(rsmNormalW,uv,0).xyz*2.0-1.0;vec3 vplFlux=texelFetch(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; 
float dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}
return clamp(indirectDiffuse*intensity,0.0,1.0);}
void main(void) 
{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;
#ifdef DECODE_NORMAL
normalW=normalW*2.0-1.0;
#endif
#ifdef TRANSFORM_NORMAL
normalW=(invView*vec4(normalW,0.)).xyz;
#endif
gl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}
`, rsmFullGlobalIlluminationPixelShader;
var init_rsmFullGlobalIllumination_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name496]) {
    ShaderStore.ShadersStore[name496] = shader495;
  }
  rsmFullGlobalIlluminationPixelShader = { name: name496, shader: shader495 };
});

// node_modules/@babylonjs/core/Shaders/copyTexture3DLayerToTexture.fragment.js
var name497 = "copyTexture3DLayerToTexturePixelShader", shader496 = `precision highp sampler3D;uniform sampler3D textureSampler;uniform int layerNum;varying vec2 vUV;void main(void) {vec3 coord=vec3(0.0,0.0,float(layerNum));coord.xy=vec2(vUV.x,vUV.y)*vec2(textureSize(textureSampler,0).xy);vec3 color=texelFetch(textureSampler,ivec3(coord),0).rgb;gl_FragColor=vec4(color,1);}
`;
var init_copyTexture3DLayerToTexture_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name497]) {
    ShaderStore.ShadersStore[name497] = shader496;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/copyTexture3DLayerToTexture.fragment.js
var name498 = "copyTexture3DLayerToTexturePixelShader", shader497 = `var textureSampler: texture_3d<f32>;uniform layerNum: i32;varying vUV: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec3f(vec2f(input.vUV.x,input.vUV.y)*vec2f(textureDimensions(textureSampler,0).xy),f32(uniforms.layerNum));let color=textureLoad(textureSampler,vec3i(coord),0).rgb;fragmentOutputs.color= vec4f(color,1);}`;
var init_copyTexture3DLayerToTexture_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name498]) {
    ShaderStore.ShadersStoreWGSL[name498] = shader497;
  }
});

// node_modules/@babylonjs/core/Shaders/iblShadowVoxelTracing.fragment.js
var name499 = "iblShadowVoxelTracingPixelShader", shader498 = `precision highp sampler2D;precision highp sampler3D;
#define PI 3.1415927
varying vec2 vUV;
#define DISABLE_UNIFORMITY_ANALYSIS
uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D blueNoiseSampler;uniform sampler2D icdfSampler;uniform sampler3D voxelGridSampler;
#ifdef COLOR_SHADOWS
uniform samplerCube iblSampler;
#endif
uniform vec4 shadowParameters;
#define SHADOWdirs shadowParameters.x
#define SHADOWframe shadowParameters.y
#define SHADOWenvRot shadowParameters.w
uniform vec4 voxelBiasParameters;
#define highestMipLevel voxelBiasParameters.z
uniform vec4 sssParameters;
#define SSSsamples sssParameters.x
#define SSSstride sssParameters.y
#define SSSmaxDistance sssParameters.z
#define SSSthickness sssParameters.w
uniform vec4 shadowOpacity;uniform mat4 projMtx;uniform mat4 viewMtx;uniform mat4 invProjMtx;uniform mat4 invViewMtx;uniform mat4 wsNormalizationMtx;uniform mat4 invVPMtx;
#define PI 3.1415927
#define GOLD 0.618034
struct AABB3f {vec3 m_min;vec3 m_max;};struct Ray {vec3 orig;vec3 dir;vec3 dir_rcp;float t_min;float t_max;};Ray make_ray(const vec3 origin,const vec3 direction,const float tmin,
const float tmax) {Ray ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}
bool ray_box_intersection(const in AABB3f aabb,const in Ray ray,
out float distance_near,out float distance_far) {vec3 tbot=ray.dir_rcp*(aabb.m_min-ray.orig);vec3 ttop=ray.dir_rcp*(aabb.m_max-ray.orig);vec3 tmin=min(ttop,tbot);vec3 tmax=max(ttop,tbot);distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return distance_near<=distance_far;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
struct VoxelMarchDiagnosticInfo {float heat;ivec3 voxel_intersect_coords;};
#endif
uint hash(uint i) {i ^= i>>16u;i*=0x7FEB352Du;i ^= i>>15u;i*=0x846CA68Bu;i ^= i>>16u;return i;}
float uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}
vec3 uv_to_normal(vec2 uv) {vec3 N;vec2 uvRange=uv;float theta=uvRange.x*2.0*PI;float phi=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}
vec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u),
uint2float(rstate*2447445414u));}
float goldenSequence(const uint rstate) {return uint2float(rstate*2654435769u);}
float distanceSquared(vec2 a,vec2 b) {vec2 diff=a-b;return dot(diff,diff);}
void genTB(const vec3 N,out vec3 T,out vec3 B) {float s=N.z<0.0 ? -1.0 : 1.0;float a=-1.0/(s+N.z);float b=N.x*N.y*a;T=vec3(1.0+s*N.x*N.x*a,s*b,-s*N.x);B=vec3(b,s+N.y*N.y*a,-N.y);}
int stack[24]; 
#define PUSH(i) stack[stackLevel++]=i; 
#define POP() stack[--stackLevel] 
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
bool anyHitVoxels(const Ray ray_vs,
out VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) {
#else
bool anyHitVoxels(const Ray ray_vs) {
#endif
vec3 invD=ray_vs.dir_rcp;vec3 D=ray_vs.dir;vec3 O=ray_vs.orig;ivec3 negD=ivec3(lessThan(D,vec3(0,0,0)));int voxel0=negD.x | negD.y<<1 | negD.z<<2;vec3 t0=-O*invD,t1=(vec3(1.0)-O)*invD;int maxLod=int(highestMipLevel);int stackLevel=0;
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
uint steps=0u;
#endif
PUSH(maxLod<<24);while (stackLevel>0) {int elem=POP();ivec4 Coords =
ivec4(elem & 0xFF,elem>>8 & 0xFF,elem>>16 & 0xFF,elem>>24);if (Coords.w==0) {
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
voxel_march_diagnostic_info.heat=float(steps)/24.0;
#endif
return true;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
++steps;
#endif
float invRes=exp2(float(Coords.w-maxLod));vec3 bbmin=invRes*vec3(Coords.xyz+negD);vec3 bbmax=invRes*vec3(Coords.xyz-negD+ivec3(1));vec3 mint=mix(t0,t1,bbmin);vec3 maxt=mix(t0,t1,bbmax);vec3 midt=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);int nodeMask=int(
round(texelFetch(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;int voxelBit=voxel0;Coords.xyz=(Coords.xyz<<1)+negD;int packedCoords =
Coords.x | Coords.y<<8 | Coords.z<<16 | Coords.w<<24;if (max(mint.x,max(mint.y,mint.z))<min(midt.x,min(midt.y,midt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(midt.x,max(mint.y,mint.z))<min(maxt.x,min(midt.y,midt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x2;packedCoords ^= 0x00100;if (max(midt.x,max(midt.y,mint.z))<min(maxt.x,min(maxt.y,midt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(mint.x,max(midt.y,mint.z))<min(midt.x,min(maxt.y,midt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x4;packedCoords ^= 0x10000;if (max(mint.x,max(midt.y,midt.z))<min(midt.x,min(maxt.y,maxt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(midt.x,max(midt.y,midt.z))<min(maxt.x,min(maxt.y,maxt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x2;packedCoords ^= 0x00100;if (max(midt.x,max(mint.y,midt.z))<min(maxt.x,min(midt.y,maxt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(mint.x,max(mint.y,midt.z))<min(midt.x,min(midt.y,maxt.z)) &&
(1<<voxelBit & nodeMask) != 0)
PUSH(packedCoords);}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
voxel_march_diagnostic_info.heat=float(steps)/24.0;
#endif
return false;}
float linearizeDepth(float depth,float near,float far) {return (near*far)/(far-depth*(far-near));}
float screenSpaceShadow(vec3 csOrigin,vec3 csDirection,vec2 csZBufferSize,
float nearPlaneZ,float farPlaneZ,float noise) {
#ifdef RIGHT_HANDED
float csZDir=-1.0;
#else 
float csZDir=1.0;
#endif
float ssSamples=SSSsamples;float ssMaxDist=SSSmaxDistance;float ssStride=SSSstride;float ssThickness=SSSthickness;float rayLength =
csZDir*(csOrigin.z+ssMaxDist*csDirection.z)<csZDir*nearPlaneZ
? 
(nearPlaneZ-csOrigin.z)/csDirection.z
: ssMaxDist;vec3 csEndPoint=csOrigin+rayLength*csDirection;vec4 H0=projMtx*vec4(csOrigin,1.0);vec4 H1=projMtx*vec4(csEndPoint,1.0);vec2 Z0=vec2(csOrigin.z ,1.0)/H0.w;vec2 Z1=vec2(csEndPoint.z,1.0)/H1.w;vec2 P0=csZBufferSize*(0.5*H0.xy*Z0.y+0.5);vec2 P1=csZBufferSize*(0.5*H1.xy*Z1.y+0.5);P1+=vec2(distanceSquared(P0,P1)<0.0001 ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) {permute=true;P0=P0.yx;P1=P1.yx;delta=delta.yx;}
float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=ssStride*vec2(stepDirection,invdx*delta.y);vec2 dZ=ssStride*invdx*(Z1-Z0);float opacity=0.0;vec2 P=P0+noise*dP;vec2 Z=Z0+noise*dZ;float end=P1.x*stepDirection;float rayZMax=csZDir*Z.x/Z.y;float sceneDepth=rayZMax;Z+=dZ;for (float stepCount=0.0;opacity<1.0 && P.x*stepDirection<end && sceneDepth>0.0 && stepCount<ssSamples;stepCount++,P+=dP,
Z+=dZ) { 
ivec2 coords=ivec2(permute ? P.yx : P);sceneDepth=texelFetch(depthSampler,coords,0).x;sceneDepth=linearizeDepth(sceneDepth,nearPlaneZ,farPlaneZ);sceneDepth=csZDir*sceneDepth;if (sceneDepth<=0.0) {break;}
float rayZMin=rayZMax;rayZMax=csZDir*Z.x/Z.y;opacity+=max(opacity,step(rayZMax,sceneDepth+ssThickness)*step(sceneDepth,rayZMin));}
return opacity;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
float voxelShadow(vec3 wsOrigin,vec3 wsDirection,vec3 wsNormal,
vec2 DitherNoise,
out VoxelMarchDiagnosticInfo voxel_march_diagnostic_info) {
#else
float voxelShadow(vec3 wsOrigin,vec3 wsDirection,vec3 wsNormal,
vec2 DitherNoise) {
#endif
float vxResolution=float(textureSize(voxelGridSampler,0).x);vec3 T,B;genTB(wsDirection,T,B);vec2 DitherXY=sqrt(DitherNoise.x)*vec2(cos(2.0*PI*DitherNoise.y),
sin(2.0*PI*DitherNoise.y));float sceneScale=wsNormalizationMtx[0][0];vec3 Dithering =
(voxelBiasParameters.x*wsNormal+voxelBiasParameters.y*wsDirection +
DitherXY.x*T+DitherXY.y*B) /
vxResolution;vec3 O=0.5*wsOrigin+0.5+Dithering;Ray ray_vs=make_ray(O,wsDirection,0.0,10.0);AABB3f voxel_aabb;voxel_aabb.m_min=vec3(0);voxel_aabb.m_max=vec3(1);float near,far;if (!ray_box_intersection(voxel_aabb,ray_vs,near,far))
return 0.0;ray_vs.t_min=max(ray_vs.t_min,near);ray_vs.t_max=min(ray_vs.t_max,far);
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
return anyHitVoxels(ray_vs,voxel_march_diagnostic_info) ? 1.0f : 0.0f;
#else
return anyHitVoxels(ray_vs) ? 1.0f : 0.0f;
#endif
}
void main(void) {uint nbDirs=uint(SHADOWdirs);uint frameId=uint(SHADOWframe);float envRot=SHADOWenvRot;vec2 Resolution=vec2(textureSize(depthSampler,0));ivec2 currentPixel=ivec2(vUV*Resolution);uint GlobalIndex=(frameId*uint(Resolution.y)+uint(currentPixel.y)) *
uint(Resolution.x) +
uint(currentPixel.x);vec3 N=texelFetch(worldNormalSampler,currentPixel,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;}
float normalizedRotation=envRot/(2.0*PI);float depth=texelFetch(depthSampler,currentPixel,0).x;
#ifndef IS_NDC_HALF_ZRANGE
depth=depth*2.0-1.0;
#endif
vec2 temp=(vec2(currentPixel)+vec2(0.5))*2.0/Resolution-vec2(1.0);vec4 VP=invProjMtx*vec4(temp.x,-temp.y,depth,1.0);VP/=VP.w;N=normalize(N);vec3 noise=texelFetch(blueNoiseSampler,currentPixel & 0xFF,0).xyz;noise.z=fract(noise.z+goldenSequence(frameId*nbDirs));
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
float heat=0.0f;
#endif
float shadowAccum=0.001;float specShadowAccum=0.001;float sampleWeight=0.001;
#ifdef COLOR_SHADOWS
vec3 totalLight=vec3(0.001);vec3 shadowedLight=vec3(0.0);
#endif
for (uint i=0u; i<nbDirs; i++) {uint dirId=nbDirs*GlobalIndex+i;vec4 L;vec2 T;{vec2 r=plasticSequence(frameId*nbDirs+i);r=fract(r+vec2(2.0)*abs(noise.xy-vec2(0.5)));T.x=textureLod(icdfSampler,vec2(r.x,0.0),0.0).x;T.y=textureLod(icdfSampler,vec2(T.x,r.y),0.0).y;L=vec4(uv_to_normal(vec2(T.x-normalizedRotation,T.y)),0);
#ifndef RIGHT_HANDED
L.z*=-1.0;
#endif
}
#ifdef COLOR_SHADOWS
vec3 lightDir=uv_to_normal(vec2(1.0-fract(T.x+0.25),T.y));vec3 ibl=textureLod(iblSampler,lightDir,0.0).xyz;float pdf=textureLod(icdfSampler,T,0.0).z;
#endif
float cosNL=dot(N,L.xyz);float opacity=0.0;if (cosNL>0.0) {vec4 VP2=VP;VP2.y*=-1.0;vec4 unormWP=invViewMtx*VP2;vec3 WP=(wsNormalizationMtx*unormWP).xyz;vec2 vxNoise=vec2(uint2float(hash(dirId*2u)),uint2float(hash(dirId*2u+1u)));
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
VoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,voxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;
#else
opacity =
max(opacity,shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));
#endif
vec3 VL=(viewMtx*L).xyz;
#ifdef RIGHT_HANDED
float nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0); 
float farPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0);
#else
float nearPlaneZ=-projMtx[3][2]/(projMtx[2][2]+1.0); 
float farPlaneZ=-projMtx[3][2]/(projMtx[2][2]-1.0);
#endif
float ssShadow=shadowOpacity.y *
screenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,
abs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);
#ifdef COLOR_SHADOWS
vec3 light=pdf<1e-6 ? vec3(0.0) : vec3(cosNL)/vec3(pdf)*ibl;shadowedLight+=light*opacity;totalLight+=light;
#else
float rcos=(1.0-cosNL);shadowAccum+=(1.0-opacity*(1.0-pow(rcos,8.0)));sampleWeight+=1.0;vec3 VR=-(viewMtx*vec4(reflect(-L.xyz,N),0.0)).xyz;specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);
#endif
}
noise.z=fract(noise.z+GOLD);}
#ifdef COLOR_SHADOWS
vec3 shadow=(totalLight-shadowedLight)/totalLight;float maxShadow=max(max(shadow.x,max(shadow.y,shadow.z)),1.0);glFragColor=vec4(shadow/maxShadow,1.0);
#else
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
gl_FragColor=vec4(shadowAccum/float(sampleWeight),
specShadowAccum/float(sampleWeight),heat/float(sampleWeight),1.0);
#else
gl_FragColor=vec4(shadowAccum/float(sampleWeight),specShadowAccum/float(sampleWeight),0.0,1.0);
#endif
#endif
}`;
var init_iblShadowVoxelTracing_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name499]) {
    ShaderStore.ShadersStore[name499] = shader498;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblShadowVoxelTracing.fragment.js
var name500 = "iblShadowVoxelTracingPixelShader", shader499 = `#define PI 3.1415927
varying vUV: vec2f;
#define DISABLE_UNIFORMITY_ANALYSIS
var depthSampler: texture_2d<f32>;var worldNormalSampler : texture_2d<f32>;var blueNoiseSampler: texture_2d<f32>;var icdfSamplerSampler: sampler;var icdfSampler: texture_2d<f32>;var voxelGridSamplerSampler: sampler;var voxelGridSampler: texture_3d<f32>;
#ifdef COLOR_SHADOWS
var iblSamplerSampler: sampler;var iblSampler: texture_cube<f32>;
#endif
uniform shadowParameters: vec4f;
#define SHADOWdirs uniforms.shadowParameters.x
#define SHADOWframe uniforms.shadowParameters.y
#define SHADOWenvRot uniforms.shadowParameters.w
uniform voxelBiasParameters : vec4f;
#define highestMipLevel uniforms.voxelBiasParameters.z
uniform sssParameters: vec4f;
#define SSSsamples uniforms.sssParameters.x
#define SSSstride uniforms.sssParameters.y
#define SSSmaxDistance uniforms.sssParameters.z
#define SSSthickness uniforms.sssParameters.w
uniform shadowOpacity: vec4f;uniform projMtx: mat4x4f;uniform viewMtx: mat4x4f;uniform invProjMtx: mat4x4f;uniform invViewMtx: mat4x4f;uniform wsNormalizationMtx: mat4x4f;uniform invVPMtx: mat4x4f;
#define PI 3.1415927
#define GOLD 0.618034
struct AABB3f {m_min: vec3f,
m_max: vec3f,};struct Ray {orig: vec3f,
dir: vec3f,
dir_rcp: vec3f,
t_min: f32,
t_max: f32,};fn make_ray(origin: vec3f,direction: vec3f,tmin: f32,
tmax: f32)->Ray {var ray: Ray;ray.orig=origin;ray.dir=direction;ray.dir_rcp=1.0f/direction;ray.t_min=tmin;ray.t_max=tmax;return ray;}
fn ray_box_intersection(aabb: AABB3f,ray: Ray ,
distance_near: ptr<function,f32>,distance_far: ptr<function,f32>)->bool{var tbot: vec3f=ray.dir_rcp*(aabb.m_min-ray.orig);var ttop: vec3f=ray.dir_rcp*(aabb.m_max-ray.orig);var tmin: vec3f=min(ttop,tbot);var tmax: vec3f=max(ttop,tbot);*distance_near=max(ray.t_min,max(tmin.x,max(tmin.y,tmin.z)));*distance_far=min(ray.t_max,min(tmax.x,min(tmax.y,tmax.z)));return *distance_near<=*distance_far;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
struct VoxelMarchDiagnosticInfo {heat: f32,
voxel_intersect_coords: vec3i,};
#endif
fn hash(i: u32)->u32 {var temp=i ^ (i>>16u);temp*=0x7FEB352Du;temp ^= temp>>15u;temp*=0x846CA68Bu;temp ^= temp>>16u;return temp;}
fn uintBitsToFloat(x: u32)->f32 {return bitcast<f32>(x);}
fn uint2float(i: u32)->f32 {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;}
fn uv_to_normal(uv: vec2f)->vec3f {var N: vec3f;var uvRange: vec2f=uv;var theta: f32=uvRange.x*2.0*PI;var phi: f32=uvRange.y*PI;N.x=cos(theta)*sin(phi);N.z=sin(theta)*sin(phi);N.y=cos(phi);return N;}
fn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u),
uint2float(rstate*2447445414u));}
fn goldenSequence(rstate: u32)->f32 {return uint2float(rstate*2654435769u);}
fn distanceSquared(a: vec2f,b: vec2f)->f32 {var diff: vec2f=a-b;return dot(diff,diff);}
fn genTB(N: vec3f,T: ptr<function,vec3f>,B: ptr<function,vec3f>) {var s: f32=select(1.0,-1.0,N.z<0.0);var a: f32=-1.0/(s+N.z);var b: f32=N.x*N.y*a;*T= vec3f(1.0+s*N.x*N.x*a,s*b,-s*N.x);*B= vec3f(b,s+N.y*N.y*a,-N.y);}
fn lessThan(x: vec3f,y: vec3f)->vec3<bool> {return x<y;}
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
fn anyHitVoxels(ray_vs: Ray,
voxel_march_diagnostic_info: ptr<function,VoxelMarchDiagnosticInfo>)->bool {
#else
fn anyHitVoxels(ray_vs: Ray)->bool {
#endif
var stack=array<i32,24>(); 
var invD: vec3f=ray_vs.dir_rcp;var D: vec3f=ray_vs.dir;var O: vec3f=ray_vs.orig;var negD=vec3i(lessThan(D, vec3f(0,0,0)));var voxel0: i32=negD.x | (negD.y<<1) | (negD.z<<2);var t0: vec3f=-O*invD;var t1=(vec3f(1.0)-O)*invD;var maxLod: i32= i32(highestMipLevel);var stackLevel: i32=0;
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
var steps: u32=0u;
#endif
stack[stackLevel]=maxLod<<24;stackLevel++;while (stackLevel>0) {stackLevel=stackLevel-1;var elem: i32=stack[stackLevel];var Coords: vec4i =
vec4i(elem & 0xFF,(elem>>8) & 0xFF,(elem>>16) & 0xFF,elem>>24);if (Coords.w==0) {
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
*voxel_march_diagnostic_info.heat= f32(steps)/24.0;
#endif
return true;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
++steps;
#endif
var invRes: f32=exp2(f32(Coords.w-maxLod));var bbmin: vec3f=invRes*vec3f(Coords.xyz+negD);var bbmax: vec3f=invRes*vec3f(Coords.xyz-negD+vec3i(1));var mint: vec3f=mix(t0,t1,bbmin);var maxt: vec3f=mix(t0,t1,bbmax);var midt: vec3f=0.5*(mint+maxt);mint.x=max(0.0,mint.x);midt.x=max(0.0,midt.x);var nodeMask: u32= u32(
round(textureLoad(voxelGridSampler,Coords.xyz,Coords.w).x*255.0));Coords.w--;var voxelBit: u32=u32(voxel0);Coords=vec4i((Coords.xyz<<vec3u(1))+negD,Coords.w);var packedCoords: i32 =
Coords.x | (Coords.y<<8) | (Coords.z<<16) | (Coords.w<<24);if (max(mint.x,max(mint.y,mint.z))<min(midt.x,min(midt.y,midt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(midt.x,max(mint.y,mint.z))<min(maxt.x,min(midt.y,midt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x2;packedCoords ^= 0x00100;if (max(midt.x,max(midt.y,mint.z))<min(maxt.x,min(maxt.y,midt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(mint.x,max(midt.y,mint.z))<min(midt.x,min(maxt.y,midt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x4;packedCoords ^= 0x10000;if (max(mint.x,max(midt.y,midt.z))<min(midt.x,min(maxt.y,maxt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(midt.x,max(midt.y,midt.z))<min(maxt.x,min(maxt.y,maxt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x2;packedCoords ^= 0x00100;if (max(midt.x,max(mint.y,midt.z))<min(maxt.x,min(midt.y,maxt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}
voxelBit ^= 0x1;packedCoords ^= 0x00001;if (max(mint.x,max(mint.y,midt.z))<min(midt.x,min(midt.y,maxt.z)) &&
((1u<<voxelBit) & nodeMask) != 0) {stack[stackLevel]=packedCoords;stackLevel++;}}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
*voxel_march_diagnostic_info.heat= f32(steps)/24.0;
#endif
return false;}
fn linearizeDepth(depth: f32,near: f32,far: f32)->f32 {return (near*far)/(far-depth*(far-near));}
fn screenSpaceShadow(csOrigin: vec3f,csDirection: vec3f,csZBufferSize: vec2f,
nearPlaneZ: f32,farPlaneZ: f32,noise: f32)->f32 {
#ifdef RIGHT_HANDED
var csZDir : f32=-1.0;
#else 
var csZDir : f32=1.0;
#endif
var ssSamples: f32=SSSsamples;var ssMaxDist: f32=SSSmaxDistance;var ssStride: f32=SSSstride;var ssThickness: f32=SSSthickness;var rayLength: f32 =
select(ssMaxDist,(nearPlaneZ-csOrigin.z)/csDirection.z,
csZDir*(csOrigin.z+ssMaxDist*csDirection.z)<csZDir*nearPlaneZ);var csEndPoint: vec3f=csOrigin+rayLength*csDirection;var H0: vec4f=uniforms.projMtx*vec4f(csOrigin,1.0);var H1: vec4f=uniforms.projMtx*vec4f(csEndPoint,1.0);var Z0=vec2f(csOrigin.z ,1.0)/H0.w;var Z1=vec2f(csEndPoint.z,1.0)/H1.w;var P0=csZBufferSize*(0.5*H0.xy*Z0.y+0.5);var P1=csZBufferSize*(0.5*H1.xy*Z1.y+0.5);P1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)<abs(delta.y)) {permute=true;P0=P0.yx;P1=P1.yx;delta=delta.yx;}
var stepDirection: f32=sign(delta.x);var invdx: f32=stepDirection/delta.x;var dP: vec2f=ssStride* vec2f(stepDirection,invdx*delta.y);var dZ: vec2f=ssStride*invdx*(Z1-Z0);var opacity: f32=0.0;var P: vec2f=P0+noise*dP;var Z: vec2f=Z0+noise*dZ;var end: f32=P1.x*stepDirection;var rayZMax=csZDir*Z.x/Z.y;var sceneDepth=rayZMax;Z+=dZ;for (var stepCount: f32=0.0; 
opacity<1.0 && P.x*stepDirection<end && sceneDepth>0.0 && stepCount<ssSamples;stepCount+=1) { 
var coords=vec2i(select(P,P.yx,permute));sceneDepth=textureLoad(depthSampler,coords,0).x;sceneDepth=linearizeDepth(sceneDepth,nearPlaneZ,farPlaneZ);sceneDepth=csZDir*sceneDepth;if (sceneDepth<=0.0) {break;}
var rayZMin: f32=rayZMax;rayZMax=csZDir*Z.x/Z.y;opacity+=max(opacity,step(rayZMax,sceneDepth+ssThickness)*step(sceneDepth,rayZMin));P+=dP;Z+=dZ;}
return opacity;}
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
fn voxelShadow(wsOrigin: vec3f,wsDirection: vec3f,wsNormal: vec3f,
DitherNoise: vec2f,
voxel_march_diagnostic_info: ptr<function,VoxelMarchDiagnosticInfo>)->f32 {
#else
fn voxelShadow(wsOrigin: vec3f,wsDirection: vec3f,wsNormal: vec3f,
DitherNoise: vec2f)->f32 {
#endif
var vxResolution: f32=f32(textureDimensions(voxelGridSampler,0).x);var T: vec3f;var B: vec3f;genTB(wsDirection,&T,&B);var DitherXY: vec2f=sqrt(DitherNoise.x)* vec2f(cos(2.0*PI*DitherNoise.y),
sin(2.0*PI*DitherNoise.y));var Dithering : vec3f=(uniforms.voxelBiasParameters.x*wsNormal +
uniforms.voxelBiasParameters.y*wsDirection +
DitherXY.x*T+DitherXY.y*B) /
vxResolution;var O: vec3f=0.5*wsOrigin+0.5+Dithering;var ray_vs=make_ray(O,wsDirection,0.0,10.0);var voxel_aabb: AABB3f;voxel_aabb.m_min=vec3f(0);voxel_aabb.m_max=vec3f(1);var near: f32=0;var far: f32=0;if (!ray_box_intersection(voxel_aabb,ray_vs,&near,&far)) {return 0.0;}
ray_vs.t_min=max(ray_vs.t_min,near);ray_vs.t_max=min(ray_vs.t_max,far);
#if VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
return select(0.0f,1.0f,anyHitVoxels(ray_vs,voxel_march_diagnostic_info));
#else
return select(0.0f,1.0f,anyHitVoxels(ray_vs));
#endif
}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var nbDirs=u32(SHADOWdirs);var frameId=u32(SHADOWframe);var envRot: f32=SHADOWenvRot;var Resolution: vec2f= vec2f(textureDimensions(depthSampler,0));var currentPixel=vec2i(fragmentInputs.vUV*Resolution);var GlobalIndex =
(frameId*u32(Resolution.y)+u32(currentPixel.y))*u32(Resolution.x) +
u32(currentPixel.x);var N : vec3f=textureLoad(worldNormalSampler,currentPixel,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}
var normalizedRotation: f32=envRot/(2.0*PI);var depth : f32=textureLoad(depthSampler,currentPixel,0).x;
#ifndef IS_NDC_HALF_ZRANGE
depth=depth*2.0-1.0;
#endif
var temp : vec2f=(vec2f(currentPixel)+vec2f(0.5))*2.0/Resolution -
vec2f(1.0);var VP : vec4f=uniforms.invProjMtx*vec4f(temp.x,-temp.y,depth,1.0);VP/=VP.w;N=normalize(N);var noise : vec3f=textureLoad(blueNoiseSampler,currentPixel & vec2i(0xFF),0).xyz;noise.z=fract(noise.z+goldenSequence(frameId*nbDirs));
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
var heat: f32=0.0f;
#endif
var shadowAccum: f32=0.001;var specShadowAccum: f32=0.001;var sampleWeight : f32=0.001;
#ifdef COLOR_SHADOWS
var totalLight: vec3f=vec3f(0.001);var shadowedLight: vec3f=vec3f(0.0);
#endif
for (var i: u32=0; i<nbDirs; i++) {var dirId: u32=nbDirs*GlobalIndex+i;var L: vec4f;var T: vec2f;{var r: vec2f=plasticSequence(frameId*nbDirs+i);r=fract(r+ vec2f(2.0)*abs(noise.xy- vec2f(0.5)));T.x=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2f(r.x,0.0),0.0).x;T.y=textureSampleLevel(icdfSampler,icdfSamplerSampler,vec2f(T.x,r.y),0.0).y;L= vec4f(uv_to_normal(vec2f(T.x-normalizedRotation,T.y)),0);
#ifndef RIGHT_HANDED
L.z*=-1.0;
#endif
}
#ifdef COLOR_SHADOWS
var lightDir: vec3f=uv_to_normal(vec2f(1.0-fract(T.x+0.25),T.y));var ibl: vec3f=textureSampleLevel(iblSampler,iblSamplerSampler,lightDir,0.0).xyz;var pdf: f32=textureSampleLevel(icdfSampler,icdfSamplerSampler,T,0.0).z;
#endif
var cosNL: f32=dot(N,L.xyz);var opacity: f32=0.0;if (cosNL>0.0) {var VP2: vec4f=VP;VP2.y*=-1.0;var unormWP : vec4f=uniforms.invViewMtx*VP2;var WP: vec3f=(uniforms.wsNormalizationMtx*unormWP).xyz;var vxNoise: vec2f=vec2f(uint2float(hash(dirId*2)),uint2float(hash(dirId*2+1)));
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
VoxelMarchDiagnosticInfo voxel_march_diagnostic_info;opacity=max(opacity,
uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise,
voxel_march_diagnostic_info));heat+=voxel_march_diagnostic_info.heat;
#else
opacity =
max(opacity,uniforms.shadowOpacity.x*voxelShadow(WP,L.xyz,N,vxNoise));
#endif
var VL : vec3f=(uniforms.viewMtx*L).xyz;
#ifdef RIGHT_HANDED
var nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0); 
var farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0);
#else
var nearPlaneZ: f32=-2.0*uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]+1.0); 
var farPlaneZ: f32=-uniforms.projMtx[3][2]/(uniforms.projMtx[2][2]-1.0);
#endif
var ssShadow: f32=uniforms.shadowOpacity.y *
screenSpaceShadow(VP2.xyz,VL,Resolution,nearPlaneZ,farPlaneZ,
abs(2.0*noise.z-1.0));opacity=max(opacity,ssShadow);
#ifdef COLOR_SHADOWS
var light: vec3f=select(vec3f(0.0),vec3f(cosNL)/vec3f(pdf)*ibl,pdf>1e-6);shadowedLight+=light*opacity;totalLight+=light;
#else
var rcos: f32=1.0-cosNL;shadowAccum+=(1.0-opacity*(1.0-pow(rcos,8.0)));sampleWeight+=1.0;var VR : vec3f=abs((uniforms.viewMtx*vec4f(reflect(-L.xyz,N),0.0)).xyz);specShadowAccum+=max(1.0-(opacity*pow(VR.z,8.0)),0.0);
#endif
}
noise.z=fract(noise.z+GOLD);}
#ifdef COLOR_SHADOWS
var shadow: vec3f=(totalLight-shadowedLight)/totalLight;var maxShadow: f32=max(max(shadow.x,max(shadow.y,shadow.z)),1.0);fragmentOutputs.color=vec4f(shadow/maxShadow,1.0);
#else
#ifdef VOXEL_MARCH_DIAGNOSTIC_INFO_OPTION
fragmentOutputs.color =
vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,heat/sampleWeight,1.0);
#else
fragmentOutputs.color=vec4f(shadowAccum/sampleWeight,specShadowAccum/sampleWeight,0.0,1.0);
#endif
#endif
}`;
var init_iblShadowVoxelTracing_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name500]) {
    ShaderStore.ShadersStoreWGSL[name500] = shader499;
  }
});

// node_modules/@babylonjs/core/Shaders/iblShadowDebug.fragment.js
var name501 = "iblShadowDebugPixelShader", shader500 = `#ifdef GL_ES
precision mediump float;
#endif
varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D debugSampler;uniform vec4 sizeParams;
#define offsetX sizeParams.x
#define offsetY sizeParams.y
#define widthScale sizeParams.z
#define heightScale sizeParams.w
void main(void) {vec2 uv =
vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 debugColour=texture2D(debugSampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {gl_FragColor.rgb=mix(debugColour.rgb,background.rgb,0.0);gl_FragColor.a=1.0;}}`;
var init_iblShadowDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name501]) {
    ShaderStore.ShadersStore[name501] = shader500;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblShadowDebug.fragment.js
var name502 = "iblShadowDebugPixelShader", shader501 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var debugSamplerSampler: sampler;var debugSampler: texture_2d<f32>;uniform sizeParams: vec4f;
#define offsetX uniforms.sizeParams.x
#define offsetY uniforms.sizeParams.y
#define widthScale uniforms.sizeParams.z
#define heightScale uniforms.sizeParams.w
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =
vec2f((offsetX+fragmentInputs.vUV.x)*widthScale,(offsetY+fragmentInputs.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);var debugColour: vec4f=textureSample(debugSampler,debugSamplerSampler,fragmentInputs.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {fragmentOutputs.color=vec4f(mix(debugColour.rgb,background.rgb,0.0),1.0);}}`;
var init_iblShadowDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name502]) {
    ShaderStore.ShadersStoreWGSL[name502] = shader501;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblShadowSpatialBlur.fragment.js
var name503 = "iblShadowSpatialBlurPixelShader", shader502 = `#define PI 3.1415927
varying vUV: vec2f;var depthSampler: texture_2d<f32>;var worldNormalSampler: texture_2d<f32>;var voxelTracingSampler : texture_2d<f32>;uniform blurParameters: vec4f;
#define stridef uniforms.blurParameters.x
#define worldScale uniforms.blurParameters.y
const weights=array<f32,5>(0.0625,0.25,0.375,0.25,0.0625);const nbWeights: i32=5;fn max2(v: vec2f,w: vec2f)->vec2f {return vec2f(max(v.x,w.x),max(v.y,w.y));}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var gbufferRes=vec2f(textureDimensions(depthSampler,0));var gbufferPixelCoord= vec2i(fragmentInputs.vUV*gbufferRes);var shadowRes=vec2f(textureDimensions(voxelTracingSampler,0));var shadowPixelCoord= vec2i(fragmentInputs.vUV*shadowRes);var N: vec3f=textureLoad(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {fragmentOutputs.color=vec4f(1.0,1.0,0.0,1.0);return fragmentOutputs;}
var depth: f32=-textureLoad(depthSampler,gbufferPixelCoord,0).x;var X: vec4f= vec4f(0.0);for(var y: i32=0; y<nbWeights; y++) {for(var x: i32=0; x<nbWeights; x++) {var gBufferCoords: vec2i=gbufferPixelCoord+i32(stridef)*vec2i(x-(nbWeights>>1),y-(nbWeights>>1));var shadowCoords: vec2i=shadowPixelCoord+i32(stridef)*vec2i(x-(nbWeights>>1),y-(nbWeights>>1));var T : vec3f=textureLoad(voxelTracingSampler,shadowCoords,0).xyz;var ddepth: f32=-textureLoad(depthSampler,gBufferCoords,0).x-depth;var dN: vec3f=textureLoad(worldNormalSampler,gBufferCoords,0).xyz-N;var w: f32=weights[x]*weights[y] *
exp2(max(-1000.0/(worldScale*worldScale),-0.5) *
(ddepth*ddepth) -
1e1*dot(dN,dN));X+= vec4f(w*T.x,w*T.y,w*T.z,w);}}
fragmentOutputs.color= vec4f(X.x/X.w,X.y/X.w,X.z/X.w,1.0);}`;
var init_iblShadowSpatialBlur_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name503]) {
    ShaderStore.ShadersStoreWGSL[name503] = shader502;
  }
});

// node_modules/@babylonjs/core/Shaders/iblShadowSpatialBlur.fragment.js
var name504 = "iblShadowSpatialBlurPixelShader", shader503 = `precision highp sampler2D;
#define PI 3.1415927
varying vec2 vUV;uniform sampler2D depthSampler;uniform sampler2D worldNormalSampler;uniform sampler2D voxelTracingSampler;uniform vec4 blurParameters;
#define stridef blurParameters.x
#define worldScale blurParameters.y
const float weights[5]=float[5](0.0625,0.25,0.375,0.25,0.0625);const int nbWeights=5;vec2 max2(vec2 v,vec2 w) {return vec2(max(v.x,w.x),max(v.y,w.y));}
void main(void)
{vec2 gbufferRes=vec2(textureSize(depthSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(voxelTracingSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec3 N=texelFetch(worldNormalSampler,gbufferPixelCoord,0).xyz;if (length(N)<0.01) {glFragColor=vec4(1.0,1.0,0.0,1.0);return;}
float depth=-texelFetch(depthSampler,gbufferPixelCoord,0).x;vec4 X=vec4(0.0);for(int y=0; y<nbWeights; ++y) {for(int x=0; x<nbWeights; ++x) {ivec2 gBufferCoords=gbufferPixelCoord+int(stridef)*ivec2(x-(nbWeights>>1),y-(nbWeights>>1));ivec2 shadowCoords=shadowPixelCoord+int(stridef)*ivec2(x-(nbWeights>>1),y-(nbWeights>>1));vec4 T=texelFetch(voxelTracingSampler,shadowCoords,0);float ddepth=-texelFetch(depthSampler,gBufferCoords,0).x-depth;vec3 dN=texelFetch(worldNormalSampler,gBufferCoords,0).xyz-N;float w=weights[x]*weights[y] *
exp2(max(-1000.0/(worldScale*worldScale),-0.5) *
(ddepth*ddepth) -
1e1*dot(dN,dN));X+=vec4(w*T.x,w*T.y,w*T.z,w);}}
gl_FragColor=vec4(X.x/X.w,X.y/X.w,X.z/X.w,1.0);}`;
var init_iblShadowSpatialBlur_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name504]) {
    ShaderStore.ShadersStore[name504] = shader503;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblShadowAccumulation.fragment.js
var name505 = "iblShadowAccumulationPixelShader", shader504 = `varying vUV: vec2f;uniform accumulationParameters: vec4f;
#define remanence uniforms.accumulationParameters.x
#define resetb uniforms.accumulationParameters.y
#define sceneSize uniforms.accumulationParameters.z
var motionSampler: texture_2d<f32>;var positionSampler: texture_2d<f32>;var spatialBlurSampler : texture_2d<f32>;var oldAccumulationSamplerSampler: sampler;var oldAccumulationSampler: texture_2d<f32>;var prevPositionSamplerSampler: sampler;var prevPositionSampler: texture_2d<f32>;fn max2(v: vec2f,w: vec2f)->vec2f { 
return vec2f(max(v.x,w.x),max(v.y,w.y)); }
fn lessThan(x: vec2f,y: vec2f)->vec2<bool> {return x<y;}
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var reset: bool= bool(resetb);var gbufferRes : vec2f=vec2f(textureDimensions(positionSampler,0));var gbufferPixelCoord: vec2i= vec2i(input.vUV*gbufferRes);var shadowRes : vec2f=vec2f(textureDimensions(spatialBlurSampler,0));var shadowPixelCoord: vec2i= vec2i(input.vUV*shadowRes);var LP: vec4f=textureLoad(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {fragmentOutputs.color=vec4f(1.0,0.0,0.0,1.0);return fragmentOutputs;}
var velocityColor: vec2f=textureLoad(motionSampler,gbufferPixelCoord,0).xy;var prevCoord: vec2f=input.vUV+velocityColor;var PrevLP: vec3f=textureSampleLevel(prevPositionSampler,prevPositionSamplerSampler,prevCoord,0.0).xyz;var PrevShadows: vec4f=textureSampleLevel(oldAccumulationSampler,oldAccumulationSamplerSampler,prevCoord,0.0);var newShadows : vec3f=textureLoad(spatialBlurSampler,shadowPixelCoord,0).xyz;PrevShadows.a=select(1.0,max(PrevShadows.a/(1.0+PrevShadows.a),1.0-remanence),!reset && all(lessThan(abs(prevCoord- vec2f(0.5)), vec2f(0.5))) &&
distance(LP.xyz,PrevLP)<5e-2*sceneSize);PrevShadows=max( vec4f(0.0),PrevShadows);fragmentOutputs.color= vec4f(mix(PrevShadows.x,newShadows.x,PrevShadows.a),
mix(PrevShadows.y,newShadows.y,PrevShadows.a),
mix(PrevShadows.z,newShadows.z,PrevShadows.a),PrevShadows.a);}`;
var init_iblShadowAccumulation_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name505]) {
    ShaderStore.ShadersStoreWGSL[name505] = shader504;
  }
});

// node_modules/@babylonjs/core/Shaders/iblShadowAccumulation.fragment.js
var name506 = "iblShadowAccumulationPixelShader", shader505 = `#ifdef GL_ES
precision mediump float;
#endif
varying vec2 vUV;uniform vec4 accumulationParameters;
#define remanence accumulationParameters.x
#define resetb accumulationParameters.y
#define sceneSize accumulationParameters.z
uniform sampler2D motionSampler;uniform sampler2D positionSampler;uniform sampler2D spatialBlurSampler;uniform sampler2D oldAccumulationSampler;uniform sampler2D prevPositionSampler;vec2 max2(vec2 v,vec2 w) { return vec2(max(v.x,w.x),max(v.y,w.y)); }
void main(void) {bool reset=bool(resetb);vec2 gbufferRes=vec2(textureSize(motionSampler,0));ivec2 gbufferPixelCoord=ivec2(vUV*gbufferRes);vec2 shadowRes=vec2(textureSize(spatialBlurSampler,0));ivec2 shadowPixelCoord=ivec2(vUV*shadowRes);vec4 LP=texelFetch(positionSampler,gbufferPixelCoord,0);if (0.0==LP.w) {gl_FragColor=vec4(1.0,0.0,0.0,1.0);return;}
vec2 velocityColor=texelFetch(motionSampler,gbufferPixelCoord,0).xy;vec2 prevCoord=vUV+velocityColor;vec3 PrevLP=texture(prevPositionSampler,prevCoord).xyz;vec4 PrevShadows=texture(oldAccumulationSampler,prevCoord);vec3 newShadows=texelFetch(spatialBlurSampler,shadowPixelCoord,0).xyz;PrevShadows.a =
!reset && all(lessThan(abs(prevCoord-vec2(0.5)),vec2(0.5))) &&
distance(LP.xyz,PrevLP)<5e-2*sceneSize
? max(PrevShadows.a/(1.0+PrevShadows.a),1.0-remanence)
: 1.0;PrevShadows=max(vec4(0.0),PrevShadows);gl_FragColor =
vec4(mix(PrevShadows.x,newShadows.x,PrevShadows.a),
mix(PrevShadows.y,newShadows.y,PrevShadows.a),
mix(PrevShadows.z,newShadows.z,PrevShadows.a),PrevShadows.a);}`;
var init_iblShadowAccumulation_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name506]) {
    ShaderStore.ShadersStore[name506] = shader505;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblCombineVoxelGrids.fragment.js
var name509 = "iblCombineVoxelGridsPixelShader", shader508 = `varying vUV: vec2f;var voxelXaxisSamplerSampler: sampler;var voxelXaxisSampler: texture_3d<f32>;var voxelYaxisSamplerSampler: sampler;var voxelYaxisSampler: texture_3d<f32>;var voxelZaxisSamplerSampler: sampler;var voxelZaxisSampler: texture_3d<f32>;uniform layer: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var coordZ: vec3f= vec3f(fragmentInputs.vUV.x,fragmentInputs.vUV.y,uniforms.layer);var voxelZ: f32=textureSample(voxelZaxisSampler,voxelZaxisSamplerSampler,coordZ).r;var coordX: vec3f= vec3f(1.0-uniforms.layer,fragmentInputs.vUV.y,fragmentInputs.vUV.x);var voxelX: f32=textureSample(voxelXaxisSampler,voxelXaxisSamplerSampler,coordX).r;var coordY: vec3f= vec3f(uniforms.layer,fragmentInputs.vUV.x,fragmentInputs.vUV.y);var voxelY: f32=textureSample(voxelYaxisSampler,voxelYaxisSamplerSampler,coordY).r;var voxel=select(0.0,1.0,(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0));fragmentOutputs.color= vec4f( vec3f(voxel),1.0);}`;
var init_iblCombineVoxelGrids_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name509]) {
    ShaderStore.ShadersStoreWGSL[name509] = shader508;
  }
});

// node_modules/@babylonjs/core/Shaders/iblCombineVoxelGrids.fragment.js
var name510 = "iblCombineVoxelGridsPixelShader", shader509 = `precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelXaxisSampler;uniform sampler3D voxelYaxisSampler;uniform sampler3D voxelZaxisSampler;uniform float layer;void main(void) {vec3 coordZ=vec3(vUV.x,vUV.y,layer);float voxelZ=texture(voxelZaxisSampler,coordZ).r;vec3 coordX=vec3(1.0-layer,vUV.y,vUV.x);float voxelX=texture(voxelXaxisSampler,coordX).r;vec3 coordY=vec3(layer,vUV.x,vUV.y);float voxelY=texture(voxelYaxisSampler,coordY).r;float voxel=(voxelX>0.0 || voxelY>0.0 || voxelZ>0.0) ? 1.0 : 0.0;glFragColor=vec4(vec3(voxel),1.0);}`;
var init_iblCombineVoxelGrids_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name510]) {
    ShaderStore.ShadersStore[name510] = shader509;
  }
});

// node_modules/@babylonjs/core/Shaders/iblGenerateVoxelMip.fragment.js
var name511 = "iblGenerateVoxelMipPixelShader", shader510 = `precision highp float;precision highp sampler3D;varying vec2 vUV;uniform sampler3D srcMip;uniform int layerNum;void main(void) {ivec3 Coords=ivec3(2)*ivec3(gl_FragCoord.x,gl_FragCoord.y,layerNum);uint tex =
uint(texelFetch(srcMip,Coords+ivec3(0,0,0),0).x>0.0f ? 1u : 0u)
<< 0u |
uint(texelFetch(srcMip,Coords+ivec3(1,0,0),0).x>0.0f ? 1u : 0u)
<< 1u |
uint(texelFetch(srcMip,Coords+ivec3(0,1,0),0).x>0.0f ? 1u : 0u)
<< 2u |
uint(texelFetch(srcMip,Coords+ivec3(1,1,0),0).x>0.0f ? 1u : 0u)
<< 3u |
uint(texelFetch(srcMip,Coords+ivec3(0,0,1),0).x>0.0f ? 1u : 0u)
<< 4u |
uint(texelFetch(srcMip,Coords+ivec3(1,0,1),0).x>0.0f ? 1u : 0u)
<< 5u |
uint(texelFetch(srcMip,Coords+ivec3(0,1,1),0).x>0.0f ? 1u : 0u)
<< 6u |
uint(texelFetch(srcMip,Coords+ivec3(1,1,1),0).x>0.0f ? 1u : 0u)
<< 7u;glFragColor.rgb=vec3(float(tex)/255.0f,0.0f,0.0f);glFragColor.a=1.0;}`;
var init_iblGenerateVoxelMip_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name511]) {
    ShaderStore.ShadersStore[name511] = shader510;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblGenerateVoxelMip.fragment.js
var name512 = "iblGenerateVoxelMipPixelShader", shader511 = `varying vUV: vec2f;var srcMip: texture_3d<f32>;uniform layerNum: i32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var Coords=vec3i(2)*vec3i(vec2i(fragmentInputs.position.xy),uniforms.layerNum);var tex =
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,0),0).x>0.0f))
<< 0u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,0),0).x>0.0f))
<< 1u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,0),0).x>0.0f))
<< 2u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,0),0).x>0.0f))
<< 3u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,0,1),0).x>0.0f))
<< 4u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,0,1),0).x>0.0f))
<< 5u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(0,1,1),0).x>0.0f))
<< 6u) |
(u32(select(0u,1u,textureLoad(srcMip,Coords+vec3i(1,1,1),0).x>0.0f))
<< 7u);fragmentOutputs.color=vec4f( f32(tex)/255.0f,0.0f,0.0f,1.0);}`;
var init_iblGenerateVoxelMip_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name512]) {
    ShaderStore.ShadersStoreWGSL[name512] = shader511;
  }
});

// node_modules/@babylonjs/core/Shaders/iblShadowGBufferDebug.fragment.js
var name513 = "iblShadowGBufferDebugPixelShader", shader512 = `#ifdef GL_ES
precision mediump float;
#endif
varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;uniform sampler2D velocitySampler;uniform vec4 sizeParams;uniform float maxDepth;
#define offsetX sizeParams.x
#define offsetY sizeParams.y
#define widthScale sizeParams.z
#define heightScale sizeParams.w
void main(void) {vec2 uv =
vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 backgroundColour=texture2D(textureSampler,vUV).rgba;vec4 depth=texture2D(depthSampler,vUV);vec4 worldNormal=texture2D(normalSampler,vUV);vec4 worldPosition=texture2D(positionSampler,vUV);vec4 velocityLinear=texture2D(velocitySampler,vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=backgroundColour;} else {gl_FragColor.a=1.0;if (uv.x<=0.25) {gl_FragColor.rgb=depth.rgb;gl_FragColor.a=1.0;} else if (uv.x<=0.5) {velocityLinear.rg=velocityLinear.rg*0.5+0.5;gl_FragColor.rgb=velocityLinear.rgb;} else if (uv.x<=0.75) {gl_FragColor.rgb=worldPosition.rgb;} else {gl_FragColor.rgb=worldNormal.rgb;}}}`;
var init_iblShadowGBufferDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name513]) {
    ShaderStore.ShadersStore[name513] = shader512;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblShadowGBufferDebug.fragment.js
var name514 = "iblShadowGBufferDebugPixelShader", shader513 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var depthSampler: sampler;var depthTexture: texture_2d<f32>;var normalSampler: sampler;var normalTexture: texture_2d<f32>;var positionSampler: sampler;var positionTexture: texture_2d<f32>;var velocitySampler: sampler;var velocityTexture: texture_2d<f32>;uniform sizeParams: vec4f;uniform maxDepth: f32;
#define offsetX uniforms.sizeParams.x
#define offsetY uniforms.sizeParams.y
#define widthScale uniforms.sizeParams.z
#define heightScale uniforms.sizeParams.w
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =
vec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var backgroundColour: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgba;var depth: vec4f=textureSample(depthTexture,depthSampler,input.vUV);var worldNormal: vec4f=textureSample(normalTexture,normalSampler,input.vUV);var worldPosition: vec4f=textureSample(positionTexture,positionSampler,input.vUV);var velocityLinear: vec4f=textureSample(velocityTexture,velocitySampler,input.vUV);if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=backgroundColour;} else {if (uv.x<=0.25) {fragmentOutputs.color=vec4f(depth.rgb,1.0);} else if (uv.x<=0.5) {velocityLinear=vec4f(velocityLinear.r*0.5+0.5,velocityLinear.g*0.5+0.5,velocityLinear.b,velocityLinear.a);fragmentOutputs.color=vec4f(velocityLinear.rgb,1.0);} else if (uv.x<=0.75) {fragmentOutputs.color=vec4f(worldPosition.rgb,1.0);} else {fragmentOutputs.color=vec4f(worldNormal.rgb,1.0);}}}`;
var init_iblShadowGBufferDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name514]) {
    ShaderStore.ShadersStoreWGSL[name514] = shader513;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelGrid2dArrayDebug.fragment.js
var name515 = "iblVoxelGrid2dArrayDebugPixelShader", shader514 = `precision highp sampler2DArray;varying vec2 vUV;uniform sampler2DArray voxelTexture;uniform sampler2D textureSampler;uniform int slice;void main(void) {ivec3 size=textureSize(voxelTexture,0);float dimension=sqrt(float(size.z));vec2 samplePos=fract(vUV.xy*vec2(dimension));int sampleIndex=int(floor(vUV.x*float(dimension))+floor(vUV.y*float(dimension))*dimension);glFragColor.rgb=texture(voxelTexture,vec3(samplePos.xy,sampleIndex)).rrr;glFragColor.a=1.0;glFragColor.rgb+=texture(textureSampler,vUV.xy).rgb;}`;
var init_iblVoxelGrid2dArrayDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name515]) {
    ShaderStore.ShadersStore[name515] = shader514;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelGrid2dArrayDebug.fragment.js
var name516 = "iblVoxelGrid2dArrayDebugPixelShader", shader515 = `varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d<f32>;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform slice: i32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var size: vec3u=textureDimensions(voxelTexture,0);var dimension: f32=sqrt( f32(size.z));var samplePos: vec2f=fract(input.vUV.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(input.vUV.x* f32(dimension))+floor(input.vUV.y* f32(dimension))*dimension);var color=textureSample(voxelTexture,voxelTextureSampler, vec3f(samplePos.xy,sampleIndex)).rrr;color+=textureSample(textureSampler,textureSamplerSampler,input.vUV.xy).rgb;fragmentOutputs.color=vec4f(color,1.0);}`;
var init_iblVoxelGrid2dArrayDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name516]) {
    ShaderStore.ShadersStoreWGSL[name516] = shader515;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelGrid.fragment.js
var name517 = "iblVoxelGridPixelShader", shader516 = `precision highp float;layout(location=0) out highp float glFragData[MAX_DRAW_BUFFERS];varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;if (normPos.z<nearPlane || normPos.z>farPlane) {discard;}
glFragData[0]=normPos.z<nearPlane+stepSize ? 1.0 : 0.0;glFragData[1]=normPos.z>=nearPlane+stepSize && normPos.z<nearPlane+2.0*stepSize ? 1.0 : 0.0;glFragData[2]=normPos.z>=nearPlane+2.0*stepSize && normPos.z<nearPlane+3.0*stepSize ? 1.0 : 0.0;glFragData[3]=normPos.z>=nearPlane+3.0*stepSize && normPos.z<nearPlane+4.0*stepSize ? 1.0 : 0.0;
#if MAX_DRAW_BUFFERS>4
glFragData[4]=normPos.z>=nearPlane+4.0*stepSize && normPos.z<nearPlane+5.0*stepSize ? 1.0 : 0.0;glFragData[5]=normPos.z>=nearPlane+5.0*stepSize && normPos.z<nearPlane+6.0*stepSize ? 1.0 : 0.0;glFragData[6]=normPos.z>=nearPlane+6.0*stepSize && normPos.z<nearPlane+7.0*stepSize ? 1.0 : 0.0;glFragData[7]=normPos.z>=nearPlane+7.0*stepSize && normPos.z<nearPlane+8.0*stepSize ? 1.0 : 0.0;
#endif
}`;
var init_iblVoxelGrid_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name517]) {
    ShaderStore.ShadersStore[name517] = shader516;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelGrid.vertex.js
var name518 = "iblVoxelGridVertexShader", shader517 = `attribute vec3 position;attribute vec3 normal;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 viewMatrix;void main(void) {gl_Position=viewMatrix*invWorldScale*world*vec4(position,1.);vNormalizedPosition.xyz=gl_Position.xyz*0.5+0.5;
#ifdef IS_NDC_HALF_ZRANGE
gl_Position.z=gl_Position.z*0.5+0.5;
#endif
}`;
var init_iblVoxelGrid_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name518]) {
    ShaderStore.ShadersStore[name518] = shader517;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelGrid.fragment.js
var name519 = "iblVoxelGridPixelShader", shader518 = `varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;if (normPos.z<uniforms.nearPlane || normPos.z>uniforms.farPlane) {discard;}
fragmentOutputs.fragData0=select(vec4f(0.0),vec4f(1.0),normPos.z<uniforms.nearPlane+uniforms.stepSize);fragmentOutputs.fragData1=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+uniforms.stepSize && normPos.z<uniforms.nearPlane+2.0*uniforms.stepSize);fragmentOutputs.fragData2=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+2.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+3.0*uniforms.stepSize);fragmentOutputs.fragData3=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+3.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+4.0*uniforms.stepSize);
#if MAX_DRAW_BUFFERS>4
fragmentOutputs.fragData4=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+4.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+5.0*uniforms.stepSize);fragmentOutputs.fragData5=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+5.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+6.0*uniforms.stepSize);fragmentOutputs.fragData6=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+6.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+7.0*uniforms.stepSize);fragmentOutputs.fragData7=select(vec4f(0.0),vec4f(1.0),normPos.z>=uniforms.nearPlane+7.0*uniforms.stepSize && normPos.z<uniforms.nearPlane+8.0*uniforms.stepSize);
#endif
}`;
var init_iblVoxelGrid_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name519]) {
    ShaderStore.ShadersStoreWGSL[name519] = shader518;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelGrid.vertex.js
var name520 = "iblVoxelGridVertexShader", shader519 = `attribute position: vec3f;attribute normal: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform viewMatrix: mat4x4f;@vertex
fn main(input : VertexInputs)->FragmentInputs {vertexOutputs.position=uniforms.viewMatrix*uniforms.invWorldScale*uniforms.world* vec4f(input.position,1.);vertexOutputs.vNormalizedPosition=vertexOutputs.position.xyz*0.5+0.5;
#ifdef IS_NDC_HALF_ZRANGE
vertexOutputs.position=vec4f(vertexOutputs.position.x,vertexOutputs.position.y,vertexOutputs.position.z*0.5+0.5,vertexOutputs.position.w);
#endif
}`;
var init_iblVoxelGrid_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name520]) {
    ShaderStore.ShadersStoreWGSL[name520] = shader519;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelGrid3dDebug.fragment.js
var name521 = "iblVoxelGrid3dDebugPixelShader", shader520 = `precision highp sampler3D;varying vec2 vUV;uniform sampler3D voxelTexture;uniform sampler2D voxelSlabTexture;uniform sampler2D textureSampler;uniform vec4 sizeParams;
#define offsetX sizeParams.x
#define offsetY sizeParams.y
#define widthScale sizeParams.z
#define heightScale sizeParams.w
uniform float mipNumber;void main(void) {vec2 uv =
vec2((offsetX+vUV.x)*widthScale,(offsetY+vUV.y)*heightScale);vec4 background=texture2D(textureSampler,vUV);vec4 voxelSlab=texture2D(voxelSlabTexture,vUV);ivec3 size=textureSize(voxelTexture,int(mipNumber));float dimension=ceil(sqrt(float(size.z)));vec2 samplePos=fract(uv.xy*vec2(dimension));int sampleIndex=int(floor(uv.x*float(dimension)) +
floor(uv.y*float(dimension))*dimension);float mip_separator=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}
bool outBounds=sampleIndex>size.z-1 ? true : false;sampleIndex=clamp(sampleIndex,0,size.z-1);ivec2 samplePosInt=ivec2(samplePos.xy*vec2(size.xy));vec3 voxel=texelFetch(voxelTexture,
ivec3(samplePosInt.x,samplePosInt.y,sampleIndex),
int(mipNumber))
.rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {gl_FragColor.rgba=background;} else {if (outBounds) {voxel=vec3(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}
voxel.r+=mip_separator;}
glFragColor.rgb=mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel;glFragColor.a=1.0;}}`;
var init_iblVoxelGrid3dDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name521]) {
    ShaderStore.ShadersStore[name521] = shader520;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelGrid3dDebug.fragment.js
var name522 = "iblVoxelGrid3dDebugPixelShader", shader521 = `varying vUV: vec2f;var voxelTextureSampler: sampler;var voxelTexture: texture_3d<f32>;var voxelSlabTextureSampler: sampler;var voxelSlabTexture: texture_2d<f32>;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform sizeParams: vec4f;
#define offsetX uniforms.sizeParams.x
#define offsetY uniforms.sizeParams.y
#define widthScale uniforms.sizeParams.z
#define heightScale uniforms.sizeParams.w
uniform mipNumber: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f =
vec2f((offsetX+input.vUV.x)*widthScale,(offsetY+input.vUV.y)*heightScale);var background: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var voxelSlab: vec4f=textureSample(voxelSlabTexture,voxelSlabTextureSampler,input.vUV);var size: vec3u=textureDimensions(voxelTexture, i32(uniforms.mipNumber));var dimension: f32=ceil(sqrt( f32(size.z)));var samplePos: vec2f=fract(uv.xy* vec2f(dimension));var sampleIndex: u32= u32(floor(uv.x* f32(dimension)) +
floor(uv.y* f32(dimension))*dimension);var mip_separator: f32=0.0;if (samplePos.x<0.01 || samplePos.y<0.01) {mip_separator=1.0;}
var outBounds: bool=select(false,true,sampleIndex>size.z-1);sampleIndex=clamp(sampleIndex,0,size.z-1);var samplePosInt: vec2i= vec2i(samplePos.xy* vec2f(size.xy));var voxel: vec3f=textureLoad(voxelTexture,
vec3i(i32(samplePosInt.x),i32(samplePosInt.y),i32(sampleIndex)),
i32(uniforms.mipNumber)).rgb;if (uv.x<0.0 || uv.x>1.0 || uv.y<0.0 || uv.y>1.0) {fragmentOutputs.color=background;} else {if (outBounds) {voxel= vec3f(0.15,0.0,0.0);} else {if (voxel.r>0.001) {voxel.g=1.0;}
voxel.r+=mip_separator;}
fragmentOutputs.color=vec4f(mix(background.rgb,voxelSlab.rgb,voxelSlab.a)+voxel,1.0);}}`;
var init_iblVoxelGrid3dDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name522]) {
    ShaderStore.ShadersStoreWGSL[name522] = shader521;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelSlabDebug.vertex.js
var name523 = "iblVoxelSlabDebugVertexShader", shader522 = `attribute vec3 position;varying vec3 vNormalizedPosition;uniform mat4 world;uniform mat4 invWorldScale;uniform mat4 cameraViewMatrix;uniform mat4 projection;uniform mat4 viewMatrix;void main(void) {vec4 worldPosition=(world*vec4(position,1.));gl_Position=projection*cameraViewMatrix*worldPosition;vNormalizedPosition=(viewMatrix*invWorldScale*worldPosition).rgb;vNormalizedPosition.xyz=vNormalizedPosition.xyz*vec3(0.5)+vec3(0.5);}`;
var init_iblVoxelSlabDebug_vertex = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name523]) {
    ShaderStore.ShadersStore[name523] = shader522;
  }
});

// node_modules/@babylonjs/core/Shaders/iblVoxelSlabDebug.fragment.js
var name524 = "iblVoxelSlabDebugPixelShader", shader523 = `precision highp float;varying vec3 vNormalizedPosition;uniform float nearPlane;uniform float farPlane;uniform float stepSize;void main(void) {vec3 normPos=vNormalizedPosition.xyz;float chunkSize=stepSize*float(MAX_DRAW_BUFFERS);float numChunks=1.0/chunkSize;float positionInChunk=fract(normPos.z/chunkSize);float slab=floor(positionInChunk*float(MAX_DRAW_BUFFERS)) /
float(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||
normPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {gl_FragColor=vec4(0.0,0.0,0.0,0.0);} else {gl_FragColor=vec4(slab,0.0,0.0,0.75);}}`;
var init_iblVoxelSlabDebug_fragment = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStore[name524]) {
    ShaderStore.ShadersStore[name524] = shader523;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelSlabDebug.vertex.js
var name525 = "iblVoxelSlabDebugVertexShader", shader524 = `attribute position: vec3f;varying vNormalizedPosition: vec3f;uniform world: mat4x4f;uniform invWorldScale: mat4x4f;uniform cameraViewMatrix: mat4x4f;uniform projection: mat4x4f;uniform viewMatrix: mat4x4f;@vertex
fn main(input : VertexInputs)->FragmentInputs {var worldPosition: vec4f=(uniforms.world* vec4f(input.position,1.));vertexOutputs.position=uniforms.projection*uniforms.cameraViewMatrix*worldPosition;vertexOutputs.vNormalizedPosition=(uniforms.viewMatrix*uniforms.invWorldScale*worldPosition).rgb;vertexOutputs.vNormalizedPosition=vertexOutputs.vNormalizedPosition* vec3f(0.5)+ vec3f(0.5);}`;
var init_iblVoxelSlabDebug_vertex2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name525]) {
    ShaderStore.ShadersStoreWGSL[name525] = shader524;
  }
});

// node_modules/@babylonjs/core/ShadersWGSL/iblVoxelSlabDebug.fragment.js
var name526 = "iblVoxelSlabDebugPixelShader", shader525 = `varying vNormalizedPosition: vec3f;uniform nearPlane: f32;uniform farPlane: f32;uniform stepSize: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var normPos: vec3f=input.vNormalizedPosition.xyz;var chunkSize: f32=uniforms.stepSize* f32(MAX_DRAW_BUFFERS);var numChunks: f32=1.0/chunkSize;var positionInChunk: f32=fract(normPos.z/chunkSize);var slab: f32=floor(positionInChunk* f32(MAX_DRAW_BUFFERS)) /
f32(MAX_DRAW_BUFFERS);if (normPos.x<0.0 || normPos.y<0.0 || normPos.z<0.0 ||
normPos.x>1.0 || normPos.y>1.0 || normPos.z>1.0) {fragmentOutputs.color= vec4f(0.0,0.0,0.0,0.0);} else {fragmentOutputs.color= vec4f(slab,0.0,0.0,0.75);}}`;
var init_iblVoxelSlabDebug_fragment2 = __esm(() => {
  init_shaderStore();
  if (!ShaderStore.ShadersStoreWGSL[name526]) {
    ShaderStore.ShadersStoreWGSL[name526] = shader525;
  }
});

// node_modules/electrobun/dist/api/bun/index.ts
init_eventEmitter();
await __promiseAll([
  init_BrowserWindow(),
  init_BrowserView(),
  init_GpuWindow(),
  init_WGPUView(),
  init_Tray()
]);

// node_modules/electrobun/dist/api/bun/core/ApplicationMenu.ts
init_eventEmitter();
await init_native();

// node_modules/electrobun/dist/api/bun/core/ContextMenu.ts
init_eventEmitter();
await init_native();

// node_modules/electrobun/dist/api/bun/index.ts
init_Paths();
await __promiseAll([
  init_Updater(),
  init_Utils(),
  init_Socket()
]);

// node_modules/electrobun/dist/api/bun/webGPU.ts
import { existsSync } from "fs";
import { join as join5, dirname as dirname2 } from "path";
import { dlopen as dlopen2, suffix as suffix2, FFIType as FFIType2 } from "bun:ffi";
var WGPU_SYMBOLS = {
  wgpuCreateInstance: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuGetInstanceFeatures: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuGetInstanceLimits: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuHasInstanceFeature: { args: [FFIType2.u32], returns: FFIType2.u32 },
  wgpuGetProcAddress: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuAdapterCreateDevice: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuAdapterGetFeatures: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuAdapterGetFormatCapabilities: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuAdapterGetInfo: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuAdapterGetInstance: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuAdapterGetLimits: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuAdapterHasFeature: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.u32 },
  wgpuAdapterRequestDevice: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuAdapterAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuAdapterRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuAdapterInfoFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuAdapterPropertiesMemoryHeapsFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuAdapterPropertiesSubgroupMatrixConfigsFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupLayoutSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupLayoutAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBindGroupLayoutRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBufferCreateTexelView: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuBufferDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBufferGetConstMappedRange: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.ptr },
  wgpuBufferGetMappedRange: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.ptr },
  wgpuBufferGetMapState: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuBufferGetSize: { args: [FFIType2.ptr], returns: FFIType2.u64 },
  wgpuBufferGetUsage: { args: [FFIType2.ptr], returns: FFIType2.u64 },
  wgpuBufferMapAsync: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.u64, FFIType2.u64, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuBufferReadMappedRange: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64], returns: FFIType2.u32 },
  wgpuBufferSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuBufferUnmap: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBufferWriteMappedRange: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64], returns: FFIType2.u32 },
  wgpuBufferAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuBufferRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandBufferSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandBufferAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandBufferRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderBeginComputePass: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuCommandEncoderBeginRenderPass: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuCommandEncoderClearBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuCommandEncoderCopyBufferToBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuCommandEncoderCopyBufferToTexture: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderCopyTextureToBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderCopyTextureToTexture: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderFinish: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuCommandEncoderInjectValidationError: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderInsertDebugMarker: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderPopDebugGroup: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderPushDebugGroup: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderResolveQuerySet: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuCommandEncoderSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderWriteBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuCommandEncoderWriteTimestamp: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuCommandEncoderAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuCommandEncoderRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderDispatchWorkgroups: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32], returns: FFIType2.void },
  wgpuComputePassEncoderDispatchWorkgroupsIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuComputePassEncoderEnd: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderInsertDebugMarker: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderPopDebugGroup: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderPushDebugGroup: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderSetBindGroup: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderSetImmediates: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuComputePassEncoderSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderSetPipeline: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderSetResourceTable: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderWriteTimestamp: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuComputePassEncoderAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePassEncoderRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePipelineGetBindGroupLayout: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.ptr },
  wgpuComputePipelineSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePipelineAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuComputePipelineRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuDawnDrmFormatCapabilitiesFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceCreateBindGroup: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateBindGroupLayout: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateBuffer: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateCommandEncoder: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateComputePipeline: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateComputePipelineAsync: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuDeviceCreateErrorBuffer: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateErrorExternalTexture: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateErrorShaderModule: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateErrorTexture: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateExternalTexture: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreatePipelineLayout: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateQuerySet: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateRenderBundleEncoder: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateRenderPipeline: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateRenderPipelineAsync: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuDeviceCreateResourceTable: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateSampler: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateShaderModule: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceCreateTexture: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceForceLoss: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceGetAdapter: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceGetAdapterInfo: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuDeviceGetAHardwareBufferProperties: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuDeviceGetFeatures: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceGetLimits: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuDeviceGetLostFuture: { args: [FFIType2.ptr], returns: FFIType2.u64 },
  wgpuDeviceGetQueue: { args: [FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceHasFeature: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.u32 },
  wgpuDeviceImportSharedBufferMemory: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceImportSharedFence: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceImportSharedTextureMemory: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuDeviceInjectError: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr], returns: FFIType2.void },
  wgpuDevicePopErrorScope: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuDevicePushErrorScope: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuDeviceSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceSetLoggingCallback: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceTick: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceValidateTextureDescriptor: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuDeviceRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureExpire: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureRefresh: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuExternalTextureRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuInstanceCreateSurface: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuInstanceGetWGSLLanguageFeatures: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuInstanceHasWGSLLanguageFeature: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.u32 },
  wgpuInstanceProcessEvents: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuInstanceRequestAdapter: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuInstanceWaitAny: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64], returns: FFIType2.u32 },
  wgpuInstanceAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuInstanceRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuPipelineLayoutSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuPipelineLayoutAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuPipelineLayoutRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuQuerySetDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuQuerySetGetCount: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuQuerySetGetType: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuQuerySetSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuQuerySetAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuQuerySetRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueCopyExternalTextureForBrowser: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueCopyTextureForBrowser: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueOnSubmittedWorkDone: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuQueueSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueSubmit: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueWriteBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuQueueWriteTexture: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuQueueRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderDraw: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderBundleEncoderDrawIndexed: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32, FFIType2.i32, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderBundleEncoderDrawIndexedIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderBundleEncoderDrawIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderBundleEncoderFinish: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuRenderBundleEncoderInsertDebugMarker: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderPopDebugGroup: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderPushDebugGroup: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetBindGroup: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetImmediates: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetIndexBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetPipeline: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetResourceTable: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderSetVertexBuffer: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderBundleEncoderAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderBundleEncoderRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderBeginOcclusionQuery: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderDraw: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderDrawIndexed: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32, FFIType2.i32, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderDrawIndexedIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderDrawIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderEnd: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderEndOcclusionQuery: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderExecuteBundles: { args: [FFIType2.ptr, FFIType2.u64, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderInsertDebugMarker: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderMultiDrawIndexedIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderMultiDrawIndirect: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u64, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderPixelLocalStorageBarrier: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderPopDebugGroup: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderPushDebugGroup: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetBindGroup: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetBlendConstant: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetImmediates: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderSetIndexBuffer: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetPipeline: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetResourceTable: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderSetScissorRect: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.u32, FFIType2.u32, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderSetStencilReference: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderSetVertexBuffer: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr, FFIType2.u64, FFIType2.u64], returns: FFIType2.void },
  wgpuRenderPassEncoderSetViewport: { args: [FFIType2.ptr, FFIType2.f32, FFIType2.f32, FFIType2.f32, FFIType2.f32, FFIType2.f32, FFIType2.f32], returns: FFIType2.void },
  wgpuRenderPassEncoderWriteTimestamp: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.u32], returns: FFIType2.void },
  wgpuRenderPassEncoderAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPassEncoderRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPipelineGetBindGroupLayout: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.ptr },
  wgpuRenderPipelineSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPipelineAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuRenderPipelineRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuResourceTableDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuResourceTableGetSize: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuResourceTableInsertBinding: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuResourceTableRemoveBinding: { args: [FFIType2.ptr, FFIType2.u32], returns: FFIType2.u32 },
  wgpuResourceTableUpdate: { args: [FFIType2.ptr, FFIType2.u32, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuResourceTableAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuResourceTableRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSamplerSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSamplerAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSamplerRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuShaderModuleGetCompilationInfo: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u64 },
  wgpuShaderModuleSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuShaderModuleAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuShaderModuleRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedBufferMemoryBeginAccess: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedBufferMemoryCreateBuffer: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuSharedBufferMemoryEndAccess: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedBufferMemoryGetProperties: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedBufferMemoryIsDeviceLost: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedBufferMemorySetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedBufferMemoryAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedBufferMemoryRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedBufferMemoryEndAccessStateFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedFenceExportInfo: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedFenceAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedFenceRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedTextureMemoryBeginAccess: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedTextureMemoryCreateTexture: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuSharedTextureMemoryEndAccess: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedTextureMemoryGetProperties: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedTextureMemoryIsDeviceLost: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSharedTextureMemorySetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedTextureMemoryAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedTextureMemoryRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSharedTextureMemoryEndAccessStateFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSupportedFeaturesFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSupportedInstanceFeaturesFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSupportedWGSLLanguageFeaturesFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceConfigure: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceGetCapabilities: { args: [FFIType2.ptr, FFIType2.ptr, FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSurfaceGetCurrentTexture: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfacePresent: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuSurfaceSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceUnconfigure: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuSurfaceCapabilitiesFreeMembers: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTexelBufferViewSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuTexelBufferViewAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTexelBufferViewRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureCreateErrorView: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuTextureCreateView: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.ptr },
  wgpuTextureDestroy: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureGetDepthOrArrayLayers: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetDimension: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetFormat: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetHeight: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetMipLevelCount: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetSampleCount: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetTextureBindingViewDimension: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTextureGetUsage: { args: [FFIType2.ptr], returns: FFIType2.u64 },
  wgpuTextureGetWidth: { args: [FFIType2.ptr], returns: FFIType2.u32 },
  wgpuTexturePin: { args: [FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuTextureSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureSetOwnershipForMemoryDump: { args: [FFIType2.ptr, FFIType2.u64], returns: FFIType2.void },
  wgpuTextureUnpin: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureRelease: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureViewSetLabel: { args: [FFIType2.ptr, FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureViewAddRef: { args: [FFIType2.ptr], returns: FFIType2.void },
  wgpuTextureViewRelease: { args: [FFIType2.ptr], returns: FFIType2.void }
};
var WGPU_LIB_NAMES = {
  darwin: ["libwebgpu_dawn.dylib"],
  win32: ["webgpu_dawn.dll", "libwebgpu_dawn.dll"],
  linux: ["libwebgpu_dawn.so"]
};
function findWgpuLibraryPath() {
  const debug = process.env["ELECTROBUN_WGPU_DEBUG"] === "1";
  const envPath = process.env["ELECTROBUN_WGPU_PATH"];
  if (envPath && existsSync(envPath)) {
    if (debug)
      console.log("[WGPU] using ELECTROBUN_WGPU_PATH:", envPath);
    return envPath;
  } else if (envPath && debug) {
    console.warn("[WGPU] ELECTROBUN_WGPU_PATH not found:", envPath);
  }
  const names = WGPU_LIB_NAMES[process.platform] ?? ["libwebgpu_dawn." + suffix2];
  for (const name2 of names) {
    const cwdCandidate = join5(process.cwd(), name2);
    if (existsSync(cwdCandidate)) {
      if (debug)
        console.log("[WGPU] found in cwd:", cwdCandidate);
      return cwdCandidate;
    }
    const execDir = dirname2(process.execPath);
    const macCandidate = join5(execDir, "..", "MacOS", name2);
    if (existsSync(macCandidate)) {
      if (debug)
        console.log("[WGPU] found in bundle MacOS:", macCandidate);
      return macCandidate;
    }
    const resCandidate = join5(execDir, "..", "Resources", name2);
    if (existsSync(resCandidate)) {
      if (debug)
        console.log("[WGPU] found in bundle Resources:", resCandidate);
      return resCandidate;
    }
    const execCandidate = join5(execDir, name2);
    if (existsSync(execCandidate)) {
      if (debug)
        console.log("[WGPU] found next to exec:", execCandidate);
      return execCandidate;
    }
  }
  if (debug) {
    console.warn("[WGPU] not found. platform:", process.platform, "execPath:", process.execPath, "cwd:", process.cwd());
    console.warn("[WGPU] names:", names);
  }
  return null;
}
var native2 = (() => {
  const libPath = findWgpuLibraryPath();
  if (!libPath) {
    return {
      available: false,
      path: null,
      symbols: {},
      close: () => {}
    };
  }
  try {
    const lib = dlopen2(libPath, WGPU_SYMBOLS);
    return {
      available: true,
      path: libPath,
      symbols: lib.symbols,
      close: lib.close
    };
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.warn("[WGPU] dlopen failed:", libPath, message);
    return {
      available: false,
      path: libPath,
      symbols: {},
      close: () => {}
    };
  }
})();
var WGPU = {
  native: native2
};
var webGPU_default = WGPU;

// node_modules/electrobun/dist/api/bun/webgpuAdapter.ts
await init_GpuWindow();
await init_native();
import { ptr as ptr2, CString as CString2, toArrayBuffer as toArrayBuffer2, JSCallback as JSCallback2 } from "bun:ffi";
var WGPUNative = webGPU_default.native;
var WGPUTextureFormat_BGRA8Unorm = 27;
var WGPUTextureFormat_BGRA8UnormSrgb = 28;
var WGPUTextureFormat_RGBA8Unorm = 22;
var WGPUTextureFormat_RGBA8UnormSrgb = 23;
var WGPUTextureFormat_Depth24Plus = 46;
var WGPUTextureFormat_Depth24PlusStencil8 = 47;
var WGPUTextureFormat_Depth32Float = 48;
var WGPUTextureFormat_Depth16Unorm = 45;
var WGPUTextureFormat_Depth32FloatStencil8 = 49;
var WGPUTextureFormat_RGBA32Sint = 43;
var WGPUTextureFormat_RGBA32Uint = 42;
var WGPUTextureFormat_RGBA16Sint = 39;
var WGPUTextureFormat_RGBA16Uint = 38;
var WGPUTextureFormat_RGBA16Float = 40;
var WGPUTextureFormat_RG32Sint = 35;
var WGPUTextureFormat_RG32Uint = 34;
var WGPUTextureFormat_RG32Float = 33;
var WGPUTextureFormat_R32Sint = 16;
var WGPUTextureFormat_R32Uint = 15;
var WGPUTextureFormat_R32Float = 14;
var WGPUTextureFormat_RGBA8Snorm = 24;
var WGPUTextureFormat_RGBA8Uint = 25;
var WGPUTextureFormat_RGBA8Sint = 26;
var WGPUTextureFormat_RG8Unorm = 10;
var WGPUTextureFormat_RG8Snorm = 11;
var WGPUTextureFormat_RG8Uint = 12;
var WGPUTextureFormat_RG8Sint = 13;
var WGPUTextureFormat_R8Unorm = 1;
var WGPUTextureFormat_R8Snorm = 2;
var WGPUTextureFormat_R8Uint = 3;
var WGPUTextureFormat_R8Sint = 4;
var WGPUTextureUsage_RenderAttachment = 0x0000000000000010n;
var WGPUPresentMode_Fifo = 1;
var WGPUCompositeAlphaMode_Opaque = 1;
var WGPUCompositeAlphaMode_Premultiplied = 2;
var WGPUCompositeAlphaMode_Unpremultiplied = 3;
var WGPUVertexFormat_Float32 = 28;
var WGPUVertexFormat_Float32x2 = 29;
var WGPUVertexFormat_Float32x3 = 30;
var WGPUVertexFormat_Float32x4 = 31;
var WGPUVertexFormat_Uint32 = 32;
var WGPUVertexFormat_Uint32x2 = 33;
var WGPUVertexFormat_Uint32x3 = 34;
var WGPUVertexFormat_Uint32x4 = 35;
var WGPUVertexFormat_Sint32 = 36;
var WGPUVertexFormat_Sint32x2 = 37;
var WGPUVertexFormat_Sint32x3 = 38;
var WGPUVertexFormat_Sint32x4 = 39;
var WGPUVertexStepMode_Vertex = 1;
var WGPUVertexStepMode_Instance = 2;
var WGPUPrimitiveTopology_PointList = 1;
var WGPUPrimitiveTopology_LineList = 2;
var WGPUPrimitiveTopology_LineStrip = 3;
var WGPUPrimitiveTopology_TriangleList = 4;
var WGPUPrimitiveTopology_TriangleStrip = 5;
var WGPUFrontFace_CCW = 1;
var WGPUFrontFace_CW = 2;
var WGPUCullMode_None = 1;
var WGPUCullMode_Front = 2;
var WGPUCullMode_Back = 3;
var WGPULoadOp_Load = 1;
var WGPULoadOp_Clear = 2;
var WGPUStoreOp_Store = 1;
var WGPUStoreOp_Discard = 2;
var WGPUTextureDimension_2D = 2;
var WGPUTextureViewDimension_2D = 2;
var WGPUTextureViewDimension_2DArray = 3;
var WGPUTextureViewDimension_3D = 6;
var WGPUTextureViewDimension_Cube = 4;
var WGPUTextureViewDimension_CubeArray = 5;
var WGPUTextureAspect_All = 1;
var WGPUTextureAspect_StencilOnly = 2;
var WGPUTextureAspect_DepthOnly = 3;
var WGPUCompareFunction_Never = 1;
var WGPUCompareFunction_Less = 2;
var WGPUCompareFunction_Equal = 3;
var WGPUCompareFunction_LessEqual = 4;
var WGPUCompareFunction_Greater = 5;
var WGPUCompareFunction_NotEqual = 6;
var WGPUCompareFunction_GreaterEqual = 7;
var WGPUCompareFunction_Always = 8;
var WGPUAddressMode_ClampToEdge = 1;
var WGPUAddressMode_Repeat = 2;
var WGPUAddressMode_MirrorRepeat = 3;
var WGPUFilterMode_Nearest = 1;
var WGPUFilterMode_Linear = 2;
var WGPUMipmapFilterMode_Nearest = 1;
var WGPUMipmapFilterMode_Linear = 2;
var WGPUBufferUsage_MapRead = 0x0000000000000001n;
var WGPUMapMode_Read = 0x0000000000000001n;
var WGPUMapMode_Write = 0x0000000000000002n;
var WGPUCallbackMode_AllowSpontaneous = 3;
var WGPUBufferMapState_Mapped = 3;
var WGPUMapAsyncStatus_Success = 1;
var WGPUQueueWorkDoneStatus_Success = 1;
var WGPUColorWriteMask_All = 15;
var WGPUBlendOperation_Add = 1;
var WGPUBlendFactor_One = 2;
var WGPUBlendFactor_Zero = 1;
var WGPUBlendFactor_SrcAlpha = 5;
var WGPUBlendFactor_OneMinusSrcAlpha = 6;
var WGPUShaderStage_Vertex = 1;
var WGPUShaderStage_Fragment = 2;
var WGPUShaderStage_Compute = 4;
var WGPUBufferBindingType_Uniform = 2;
var WGPUBufferBindingType_Storage = 3;
var WGPUBufferBindingType_ReadOnlyStorage = 4;
var WGPUSamplerBindingType_Filtering = 2;
var WGPUSamplerBindingType_NonFiltering = 3;
var WGPUSamplerBindingType_Comparison = 4;
var WGPUTextureSampleType_Float = 2;
var WGPUTextureSampleType_UnfilterableFloat = 3;
var WGPUTextureSampleType_Depth = 4;
var WGPUTextureSampleType_Sint = 5;
var WGPUTextureSampleType_Uint = 6;
var WGPUStorageTextureAccess_WriteOnly = 2;
var WGPUStorageTextureAccess_ReadOnly = 3;
var WGPUStorageTextureAccess_ReadWrite = 4;
var WGPU_STRLEN = 0xffffffffffffffffn;
var WGPU_DEPTH_SLICE_UNDEFINED = 4294967295;
var WGPU_KEEPALIVE = [];
var LAST_SURFACE_PTR = null;
var LAST_SURFACE_HAS_TEXTURE = false;
var VIEW_CONTEXTS = new Map;
var MAP_ASYNC_RESOLVERS = new Map;
var WORK_DONE_RESOLVERS = new Map;
var bufferMapCallback = new JSCallback2((status, _message, userdata1, _userdata2) => {
  const key = Number(userdata1);
  const resolve3 = MAP_ASYNC_RESOLVERS.get(key);
  if (resolve3) {
    MAP_ASYNC_RESOLVERS.delete(key);
    resolve3(status === WGPUMapAsyncStatus_Success);
  }
}, {
  args: ["u32", "ptr", "ptr", "ptr"],
  returns: "void",
  threadsafe: true
});
WGPU_KEEPALIVE.push(bufferMapCallback);
var queueWorkDoneCallback = new JSCallback2((status, _message, userdata1, _userdata2) => {
  const key = Number(userdata1);
  const resolve3 = WORK_DONE_RESOLVERS.get(key);
  if (resolve3) {
    WORK_DONE_RESOLVERS.delete(key);
    resolve3(status === WGPUQueueWorkDoneStatus_Success);
  }
}, {
  args: ["u32", "ptr", "ptr", "ptr"],
  returns: "void",
  threadsafe: true
});
WGPU_KEEPALIVE.push(queueWorkDoneCallback);
function toBigInt(value, fallback = 0n) {
  if (typeof value === "bigint")
    return value;
  if (typeof value === "number" && Number.isFinite(value)) {
    return BigInt(Math.trunc(value));
  }
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (/^(0x[0-9a-fA-F]+|\d+)$/.test(trimmed)) {
      return BigInt(trimmed);
    }
  }
  return fallback;
}
function writePtr(view, offset, value) {
  view.setBigUint64(offset, toBigInt(value ?? 0), true);
}
function writeU32(view, offset, value) {
  view.setUint32(offset, Number(value) >>> 0, true);
}
function writeU64(view, offset, value) {
  view.setBigUint64(offset, toBigInt(value), true);
}
function writeF32(view, offset, value) {
  view.setFloat32(offset, value, true);
}
function writeF64(view, offset, value) {
  view.setFloat64(offset, value, true);
}
function makeStringView(str) {
  if (!str) {
    return { ptr: 0, len: 0n, cstr: null };
  }
  const cstr = new CString2(str);
  WGPU_KEEPALIVE.push(cstr);
  return { ptr: cstr.ptr, len: WGPU_STRLEN, cstr };
}
function makeSurfaceConfiguration(devicePtr, width, height, format, alphaMode, usage = WGPUTextureUsage_RenderAttachment) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, devicePtr);
  writeU32(view, 16, format);
  writeU32(view, 20, 0);
  writeU64(view, 24, usage);
  writeU32(view, 32, width);
  writeU32(view, 36, height);
  writeU64(view, 40, 0n);
  writePtr(view, 48, 0);
  writeU32(view, 56, alphaMode);
  writeU32(view, 60, WGPUPresentMode_Fifo);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBufferDescriptor(size, usage, mappedAtCreation) {
  const buffer = new ArrayBuffer(48);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU64(view, 24, usage);
  writeU64(view, 32, BigInt(size));
  writeU32(view, 40, mappedAtCreation ? 1 : 0);
  writeU32(view, 44, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeTextureDescriptor(width, height, depthOrArrayLayers, format, usage, mipLevelCount = 1, sampleCount = 1, viewFormatsPtr = null, viewFormatCount = 0) {
  const buffer = new ArrayBuffer(80);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU64(view, 24, usage);
  writeU32(view, 32, WGPUTextureDimension_2D);
  writeU32(view, 36, width);
  writeU32(view, 40, height);
  writeU32(view, 44, depthOrArrayLayers);
  writeU32(view, 48, format);
  writeU32(view, 52, mipLevelCount);
  writeU32(view, 56, sampleCount);
  writeU32(view, 60, 0);
  writeU64(view, 64, BigInt(viewFormatCount));
  writePtr(view, 72, viewFormatsPtr ?? 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeTextureViewDescriptor(options) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU32(view, 24, options?.format ?? 0);
  writeU32(view, 28, options?.dimension ?? 0);
  writeU32(view, 32, options?.baseMipLevel ?? 0);
  writeU32(view, 36, options?.mipLevelCount ?? 4294967295);
  writeU32(view, 40, options?.baseArrayLayer ?? 0);
  writeU32(view, 44, options?.arrayLayerCount ?? 4294967295);
  writeU32(view, 48, options?.aspect ?? 0);
  writeU32(view, 52, 0);
  writeU64(view, 56, options?.usage ?? 0n);
  return { buffer, ptr: ptr2(buffer) };
}
function makeSamplerDescriptor(options) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU32(view, 24, options?.addressModeU ?? WGPUAddressMode_ClampToEdge);
  writeU32(view, 28, options?.addressModeV ?? WGPUAddressMode_ClampToEdge);
  writeU32(view, 32, options?.addressModeW ?? WGPUAddressMode_ClampToEdge);
  writeU32(view, 36, options?.magFilter ?? WGPUFilterMode_Linear);
  writeU32(view, 40, options?.minFilter ?? WGPUFilterMode_Linear);
  writeU32(view, 44, options?.mipmapFilter ?? WGPUMipmapFilterMode_Linear);
  writeF32(view, 48, options?.lodMinClamp ?? 0);
  writeF32(view, 52, options?.lodMaxClamp ?? 32);
  writeU32(view, 56, options?.compare ?? 0);
  view.setUint16(60, options?.maxAnisotropy ?? 1, true);
  view.setUint16(62, 0, true);
  return { buffer, ptr: ptr2(buffer) };
}
function makeVertexAttribute(offset, shaderLocation, format) {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, format);
  writeU32(view, 12, 0);
  writeU64(view, 16, BigInt(offset));
  writeU32(view, 24, shaderLocation);
  writeU32(view, 28, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeVertexBufferLayout(attributePtr, attributeCount, arrayStride, stepMode) {
  const buffer = new ArrayBuffer(40);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, stepMode);
  writeU32(view, 12, 0);
  writeU64(view, 16, arrayStride);
  writeU64(view, 24, BigInt(attributeCount));
  writePtr(view, 32, attributePtr);
  return { buffer, ptr: ptr2(buffer) };
}
function makeVertexState(modulePtr, entryPoint, bufferLayoutPtr, bufferLayoutCount) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, modulePtr);
  writePtr(view, 16, entryPoint.ptr);
  writeU64(view, 24, entryPoint.len);
  writeU64(view, 32, 0n);
  writePtr(view, 40, 0);
  writeU64(view, 48, BigInt(bufferLayoutCount));
  writePtr(view, 56, bufferLayoutPtr);
  return { buffer, ptr: ptr2(buffer) };
}
function makeFragmentState(modulePtr, entryPoint, targetPtr, targetCount) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, modulePtr);
  writePtr(view, 16, entryPoint.ptr);
  writeU64(view, 24, entryPoint.len);
  writeU64(view, 32, 0n);
  writePtr(view, 40, 0);
  writeU64(view, 48, BigInt(targetCount));
  writePtr(view, 56, targetPtr);
  return { buffer, ptr: ptr2(buffer) };
}
function makeColorTargetState(format, blendPtr, writeMask = WGPUColorWriteMask_All) {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, format);
  writeU32(view, 12, 0);
  writePtr(view, 16, blendPtr ?? 0);
  writeU64(view, 24, BigInt(writeMask));
  return { buffer, ptr: ptr2(buffer) };
}
function makeBlendComponent(operation, srcFactor, dstFactor) {
  const buffer = new ArrayBuffer(12);
  const view = new DataView(buffer);
  writeU32(view, 0, operation);
  writeU32(view, 4, srcFactor);
  writeU32(view, 8, dstFactor);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBlendState(color, alpha) {
  const buffer = new ArrayBuffer(24);
  new Uint8Array(buffer, 0, 12).set(new Uint8Array(color, 0, 12));
  new Uint8Array(buffer, 12, 12).set(new Uint8Array(alpha, 0, 12));
  return { buffer, ptr: ptr2(buffer) };
}
function makePrimitiveState(options) {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, options?.topology ?? WGPUPrimitiveTopology_TriangleList);
  writeU32(view, 12, options?.stripIndexFormat ?? 0);
  writeU32(view, 16, options?.frontFace ?? WGPUFrontFace_CCW);
  writeU32(view, 20, options?.cullMode ?? WGPUCullMode_None);
  writeU32(view, 24, options?.unclippedDepth ?? 0);
  writeU32(view, 28, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeMultisampleState(options) {
  const buffer = new ArrayBuffer(24);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, options?.count ?? 1);
  writeU32(view, 12, options?.mask ?? 4294967295);
  writeU32(view, 16, options?.alphaToCoverageEnabled ? 1 : 0);
  writeU32(view, 20, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeDepthStencilState(options) {
  const buffer = new ArrayBuffer(72);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, options?.format ?? 0);
  writeU32(view, 12, options?.depthWriteEnabled ? 1 : 0);
  writeU32(view, 16, options?.depthCompare ?? 0);
  writeU32(view, 20, 0);
  writeU32(view, 24, 0);
  writeU32(view, 28, 0);
  writeU32(view, 32, 0);
  writeU32(view, 36, 0);
  writeU32(view, 40, 0);
  writeU32(view, 44, 0);
  writeU32(view, 48, 0);
  writeU32(view, 52, options?.stencilReadMask ?? 4294967295);
  writeU32(view, 56, options?.stencilWriteMask ?? 4294967295);
  view.setInt32(60, options?.depthBias ?? 0, true);
  writeF32(view, 64, options?.depthBiasSlopeScale ?? 0);
  writeF32(view, 68, options?.depthBiasClamp ?? 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeRenderPipelineDescriptor(layoutPtr, vertexStateBuffer, primitiveStateBuffer, depthStencilPtr, multisampleBuffer, fragmentStatePtr) {
  const buffer = new ArrayBuffer(168);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writePtr(view, 24, layoutPtr ?? 0);
  new Uint8Array(buffer, 32, 64).set(new Uint8Array(vertexStateBuffer, 0, 64));
  new Uint8Array(buffer, 96, 32).set(new Uint8Array(primitiveStateBuffer, 0, 32));
  writePtr(view, 128, depthStencilPtr ?? 0);
  new Uint8Array(buffer, 136, 24).set(new Uint8Array(multisampleBuffer, 0, 24));
  writePtr(view, 160, fragmentStatePtr ?? 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeProgrammableStageDescriptor(modulePtr, entryPoint) {
  const buffer = new ArrayBuffer(48);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, modulePtr);
  writePtr(view, 16, entryPoint.ptr);
  writeU64(view, 24, entryPoint.len);
  writeU64(view, 32, 0n);
  writePtr(view, 40, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeComputePipelineDescriptor(layoutPtr, stageBuffer) {
  const buffer = new ArrayBuffer(80);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writePtr(view, 24, layoutPtr ?? 0);
  new Uint8Array(buffer, 32, 48).set(new Uint8Array(stageBuffer, 0, 48));
  return { buffer, ptr: ptr2(buffer) };
}
function makeComputePassDescriptor() {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writePtr(view, 24, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBufferMapCallbackInfo(callbackPtr, userdata1, userdata2) {
  const buffer = new ArrayBuffer(40);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, WGPUCallbackMode_AllowSpontaneous);
  writeU32(view, 12, 0);
  writePtr(view, 16, callbackPtr);
  writePtr(view, 24, userdata1);
  writePtr(view, 32, userdata2);
  return { buffer, ptr: ptr2(buffer) };
}
function makeQueueWorkDoneCallbackInfo(callbackPtr, userdata1, userdata2) {
  const buffer = new ArrayBuffer(40);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, WGPUCallbackMode_AllowSpontaneous);
  writeU32(view, 12, 0);
  writePtr(view, 16, callbackPtr);
  writePtr(view, 24, userdata1);
  writePtr(view, 32, userdata2);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBindGroupLayoutEntry(entry) {
  const buffer = new ArrayBuffer(120);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, entry.binding);
  writeU32(view, 16, entry.visibility);
  writeU32(view, 24, entry.bindingArraySize ?? 0);
  writePtr(view, 32, 0);
  writeU32(view, 40, entry.buffer?.type ?? 0);
  writeU32(view, 44, entry.buffer?.hasDynamicOffset ? 1 : 0);
  writeU64(view, 48, entry.buffer?.minBindingSize ?? 0);
  writePtr(view, 56, 0);
  writeU32(view, 64, entry.sampler?.type ?? 0);
  writePtr(view, 72, 0);
  writeU32(view, 80, entry.texture?.sampleType ?? 0);
  writeU32(view, 84, entry.texture?.viewDimension ?? 0);
  writeU32(view, 88, entry.texture?.multisampled ? 1 : 0);
  writePtr(view, 96, 0);
  writeU32(view, 104, entry.storageTexture?.access ?? 0);
  writeU32(view, 108, entry.storageTexture?.format ?? 0);
  writeU32(view, 112, entry.storageTexture?.viewDimension ?? 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBindGroupLayoutDescriptor(entriesPtr, count) {
  const buffer = new ArrayBuffer(40);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU64(view, 24, BigInt(count));
  writePtr(view, 32, entriesPtr);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBindGroupEntry(entry) {
  const buffer = new ArrayBuffer(56);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, entry.binding);
  writeU32(view, 12, 0);
  writePtr(view, 16, entry.buffer ? entry.buffer.buffer.ptr : 0);
  writeU64(view, 24, BigInt(entry.buffer?.offset ?? 0));
  const sizeValue = entry.buffer?.size ?? 0xffffffffffffffffn;
  writeU64(view, 32, toBigInt(sizeValue, 0xffffffffffffffffn));
  writePtr(view, 40, entry.sampler ? entry.sampler.ptr : 0);
  writePtr(view, 48, entry.textureView ? entry.textureView.ptr : 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeBindGroupDescriptor(layoutPtr, entriesPtr, count) {
  const buffer = new ArrayBuffer(48);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writePtr(view, 24, layoutPtr);
  writeU64(view, 32, BigInt(count));
  writePtr(view, 40, entriesPtr);
  return { buffer, ptr: ptr2(buffer) };
}
function makePipelineLayoutDescriptor(layoutsPtr, count) {
  const buffer = new ArrayBuffer(48);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU64(view, 24, BigInt(count));
  writePtr(view, 32, layoutsPtr);
  writeU32(view, 40, 0);
  writeU32(view, 44, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeCommandEncoderDescriptor() {
  const buffer = new ArrayBuffer(24);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  return { buffer, ptr: ptr2(buffer) };
}
function makeRenderPassColorAttachment(viewPtr, resolveTargetPtr, clear = { r: 0, g: 0, b: 0, a: 1 }, loadOp = WGPULoadOp_Clear, storeOp = WGPUStoreOp_Store) {
  const buffer = new ArrayBuffer(72);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, viewPtr);
  writeU32(view, 16, WGPU_DEPTH_SLICE_UNDEFINED);
  writeU32(view, 20, 0);
  writePtr(view, 24, resolveTargetPtr ?? 0);
  writeU32(view, 32, loadOp);
  writeU32(view, 36, storeOp);
  writeF64(view, 40, clear.r);
  writeF64(view, 48, clear.g);
  writeF64(view, 56, clear.b);
  writeF64(view, 64, clear.a);
  return { buffer, ptr: ptr2(buffer) };
}
function makeRenderPassDepthStencilAttachment(options) {
  const buffer = new ArrayBuffer(48);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, options.view);
  writeU32(view, 16, options.depthLoadOp);
  writeU32(view, 20, options.depthStoreOp);
  writeF32(view, 24, options.depthClearValue);
  writeU32(view, 28, options.depthReadOnly ? 1 : 0);
  writeU32(view, 32, options.stencilLoadOp);
  writeU32(view, 36, options.stencilStoreOp);
  writeU32(view, 40, options.stencilClearValue);
  writeU32(view, 44, options.stencilReadOnly ? 1 : 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeRenderPassDescriptor(colorAttachmentsPtr, colorAttachmentCount, depthStencilPtr) {
  const buffer = new ArrayBuffer(64);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  writeU64(view, 24, BigInt(colorAttachmentCount));
  writePtr(view, 32, colorAttachmentsPtr);
  writePtr(view, 40, depthStencilPtr ?? 0);
  writePtr(view, 48, 0);
  writePtr(view, 56, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeSurfaceTexture() {
  const buffer = new ArrayBuffer(24);
  return { buffer, view: new DataView(buffer), ptr: ptr2(buffer) };
}
class GPUTexture {
  ptr;
  format;
  constructor(ptr3, format) {
    this.ptr = ptr3;
    this.format = format;
  }
  createView(descriptor) {
    let descPtr = 0;
    if (descriptor) {
      let format = mapTextureFormat(descriptor.format) ?? 0;
      const baseFormat = this.format ?? WGPUNative.symbols.wgpuTextureGetFormat(this.ptr);
      if (isDepthFormat(baseFormat) && !isDepthFormat(format)) {
        format = 0;
      }
      const desc = makeTextureViewDescriptor({
        format,
        dimension: mapTextureViewDimension(descriptor.dimension) ?? 0,
        baseMipLevel: descriptor.baseMipLevel ?? 0,
        mipLevelCount: descriptor.mipLevelCount ?? 4294967295,
        baseArrayLayer: descriptor.baseArrayLayer ?? 0,
        arrayLayerCount: descriptor.arrayLayerCount ?? 4294967295,
        aspect: mapTextureAspect(descriptor.aspect) ?? 0,
        usage: toBigInt(descriptor.usage ?? 0)
      });
      WGPU_KEEPALIVE.push(desc.buffer);
      descPtr = desc.ptr;
    }
    const view = WGPUNative.symbols.wgpuTextureCreateView(this.ptr, descPtr);
    return new GPUTextureView(view, this.format);
  }
  destroy() {
    WGPUNative.symbols.wgpuTextureDestroy(this.ptr);
  }
}

class GPUTextureView {
  ptr;
  format;
  constructor(ptr3, format) {
    this.ptr = ptr3;
    this.format = format;
  }
}

class GPUQueue {
  ptr;
  _device;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
  submit(commandBuffers) {
    const buffer = new BigUint64Array(commandBuffers.length);
    for (let i = 0;i < commandBuffers.length; i += 1) {
      buffer[i] = BigInt(commandBuffers[i].ptr);
    }
    WGPU_KEEPALIVE.push(buffer);
    WGPUNative.symbols.wgpuQueueSubmit(this.ptr, BigInt(commandBuffers.length), ptr2(buffer));
    if (LAST_SURFACE_PTR && LAST_SURFACE_HAS_TEXTURE) {
      LAST_SURFACE_HAS_TEXTURE = false;
      WGPUBridge.surfacePresent(LAST_SURFACE_PTR);
    }
  }
  writeBuffer(buffer, offset, data) {
    WGPUNative.symbols.wgpuQueueWriteBuffer(this.ptr, buffer.ptr, BigInt(offset), ptr2(data), data.byteLength);
  }
  writeTexture(destination, data, dataLayout, size) {
    if (!data || data.byteLength === 0)
      return;
    let bytesPerPixel = bytesPerPixelForFormat(destination.texture.format);
    let width = Number.isFinite(size.width) && size.width > 0 ? size.width : Math.max(1, Math.floor((dataLayout.bytesPerRow ?? data.byteLength) / bytesPerPixel));
    let height = Number.isFinite(size.height) && size.height > 0 ? size.height : Math.max(1, dataLayout.rowsPerImage ?? 1);
    const layers = size.depthOrArrayLayers ?? 1;
    if (width <= 0 || height <= 0 || layers <= 0)
      return;
    const inferredBpp = Math.floor(data.byteLength / Math.max(1, width * height * layers));
    if (inferredBpp > bytesPerPixel) {
      bytesPerPixel = inferredBpp;
    }
    const exactRGBABytes = width * height * layers * 4;
    if (data.byteLength === exactRGBABytes) {
      bytesPerPixel = 4;
    }
    let minBytesPerRow = Math.max(1, width * bytesPerPixel);
    const minExpectedSize = minBytesPerRow * height * layers;
    if (data.byteLength > minExpectedSize && height > 0) {
      const widthFromData = Math.floor(data.byteLength / Math.max(1, height * layers * bytesPerPixel));
      if (widthFromData > width) {
        width = widthFromData;
        minBytesPerRow = Math.max(1, width * bytesPerPixel);
      }
    }
    let bytesPerRow = dataLayout.bytesPerRow ?? minBytesPerRow;
    if (bytesPerRow < minBytesPerRow)
      bytesPerRow = minBytesPerRow;
    const derivedRowBytes = Math.ceil(data.byteLength / Math.max(1, height * layers));
    if (bytesPerRow < derivedRowBytes) {
      bytesPerRow = derivedRowBytes;
    }
    let rowsPerImage = dataLayout.rowsPerImage ?? height;
    if (rowsPerImage === 0)
      rowsPerImage = height;
    let writeData = data;
    const needsPadding = bytesPerRow % 256 !== 0;
    if (needsPadding) {
      const aligned = alignTo(bytesPerRow, 256);
      const srcStride = Math.max(minBytesPerRow, dataLayout.bytesPerRow ?? minBytesPerRow);
      writeData = repackTextureData(data, srcStride, aligned, minBytesPerRow, height, rowsPerImage, layers);
      bytesPerRow = aligned;
    }
    const texInfo = makeTexelCopyTextureInfo(destination.texture.ptr, destination.mipLevel ?? 0, destination.origin ?? {});
    const layout = makeTexelCopyBufferLayout(dataLayout.offset ?? 0, bytesPerRow, rowsPerImage);
    const extent = makeExtent3D(width, height, layers);
    WGPU_KEEPALIVE.push(texInfo.buffer, layout.buffer, extent.buffer);
    WGPUNative.symbols.wgpuQueueWriteTexture(this.ptr, texInfo.ptr, ptr2(writeData), writeData.byteLength, layout.ptr, extent.ptr);
  }
  onSubmittedWorkDone() {
    const callbackPtr = queueWorkDoneCallback.ptr ?? queueWorkDoneCallback;
    const info = makeQueueWorkDoneCallbackInfo(Number(callbackPtr), this.ptr, 0);
    WGPU_KEEPALIVE.push(info.buffer);
    WGPUBridge.queueOnSubmittedWorkDone(this.ptr, info.ptr);
    return new Promise((resolve3) => {
      let done = false;
      const resolveOnce = () => {
        if (done)
          return;
        done = true;
        resolve3(true);
      };
      WORK_DONE_RESOLVERS.set(this.ptr, () => resolveOnce());
      const start = Date.now();
      const poll = () => {
        if (done)
          return;
        try {
          if (this._device?.instancePtr) {
            WGPUNative.symbols.wgpuInstanceProcessEvents(this._device.instancePtr);
          }
          WGPUNative.symbols.wgpuDeviceTick(this._device?.ptr ?? 0);
        } catch {}
        if (Date.now() - start > 5000) {
          resolve3(false);
          return;
        }
        setTimeout(poll, 5);
      };
      setTimeout(poll, 5);
    });
  }
}

class GPUDevice {
  ptr;
  queue;
  features = new Set;
  limits = {};
  _uncapturedErrorListeners = [];
  instancePtr = null;
  constructor(ptr3, instancePtr) {
    if (!ptr3) {
      throw new Error("Failed to create WGPU device");
    }
    this.ptr = ptr3;
    this.instancePtr = instancePtr ?? null;
    this.queue = new GPUQueue(WGPUNative.symbols.wgpuDeviceGetQueue(ptr3));
    this.queue._device = this;
  }
  destroy() {
    if (!this.ptr)
      return;
    try {
      WGPUNative.symbols.wgpuDeviceDestroy(this.ptr);
    } catch {}
    try {
      WGPUNative.symbols.wgpuDeviceRelease(this.ptr);
    } catch {}
  }
  createBuffer(descriptor) {
    let usage = toBigInt(descriptor.usage ?? 0);
    const desc = makeBufferDescriptor(descriptor.size, usage, !!descriptor.mappedAtCreation);
    WGPU_KEEPALIVE.push(desc.buffer);
    const bufferPtr = WGPUNative.symbols.wgpuDeviceCreateBuffer(this.ptr, desc.ptr);
    return new GPUBuffer(bufferPtr, descriptor.size, usage, this, !!descriptor.mappedAtCreation);
  }
  createTexture(descriptor) {
    const mappedFormat = mapTextureFormat(descriptor.format) ?? WGPUTextureFormat_BGRA8Unorm;
    const rawSample = Number(descriptor.sampleCount ?? 1);
    let sampleCount = Number.isFinite(rawSample) ? rawSample : 1;
    if (sampleCount > 1 && isIntegerFormat(mappedFormat)) {
      sampleCount = 1;
    }
    let viewFormatsPtr = null;
    let viewFormatCount = 0;
    if (descriptor.viewFormats && descriptor.viewFormats.length) {
      const arr = new Uint32Array(descriptor.viewFormats.length);
      descriptor.viewFormats.forEach((f, i) => {
        arr[i] = mapTextureFormat(f) ?? 0;
      });
      WGPU_KEEPALIVE.push(arr);
      viewFormatsPtr = ptr2(arr);
      viewFormatCount = descriptor.viewFormats.length;
    }
    const desc = makeTextureDescriptor(descriptor.size.width, descriptor.size.height, descriptor.size.depthOrArrayLayers ?? 1, mappedFormat, toBigInt(descriptor.usage ?? 0), descriptor.mipLevelCount ?? 1, sampleCount, viewFormatsPtr, viewFormatCount);
    WGPU_KEEPALIVE.push(desc.buffer);
    const texPtr = WGPUNative.symbols.wgpuDeviceCreateTexture(this.ptr, desc.ptr);
    return new GPUTexture(texPtr, mappedFormat);
  }
  createSampler(descriptor) {
    const desc = makeSamplerDescriptor({
      addressModeU: mapAddressMode(descriptor?.addressModeU),
      addressModeV: mapAddressMode(descriptor?.addressModeV),
      addressModeW: mapAddressMode(descriptor?.addressModeW),
      magFilter: mapFilterMode(descriptor?.magFilter),
      minFilter: mapFilterMode(descriptor?.minFilter),
      mipmapFilter: mapMipmapFilterMode(descriptor?.mipmapFilter),
      lodMinClamp: descriptor?.lodMinClamp,
      lodMaxClamp: descriptor?.lodMaxClamp,
      compare: mapCompareFunction(descriptor?.compare),
      maxAnisotropy: descriptor?.maxAnisotropy
    });
    WGPU_KEEPALIVE.push(desc.buffer);
    const samplerPtr = WGPUNative.symbols.wgpuDeviceCreateSampler(this.ptr, desc.ptr);
    return new GPUSampler(samplerPtr);
  }
  createBindGroupLayout(descriptor) {
    const entries = descriptor.entries.map((entry) => {
      const hasBindingKind = !!entry.buffer || !!entry.sampler || !!entry.texture || !!entry.storageTexture;
      const normalized = hasBindingKind ? entry : {
        ...entry,
        buffer: { type: "uniform" }
      };
      const bindingEntry = makeBindGroupLayoutEntry({
        binding: normalized.binding ?? 0,
        visibility: mapShaderStage(normalized.visibility) ?? 0,
        bindingArraySize: normalized.bindingArraySize ?? 0,
        buffer: normalized.buffer ? {
          type: mapBufferBindingType(normalized.buffer.type),
          hasDynamicOffset: !!normalized.buffer.hasDynamicOffset,
          minBindingSize: normalized.buffer.minBindingSize ?? 0
        } : undefined,
        sampler: normalized.sampler ? { type: mapSamplerBindingType(normalized.sampler.type) } : undefined,
        texture: normalized.texture ? {
          sampleType: mapTextureSampleType(normalized.texture.sampleType),
          viewDimension: mapTextureViewDimension(normalized.texture.viewDimension),
          multisampled: !!normalized.texture.multisampled
        } : undefined,
        storageTexture: normalized.storageTexture ? {
          access: mapStorageTextureAccess(normalized.storageTexture.access),
          format: mapTextureFormat(normalized.storageTexture.format),
          viewDimension: mapTextureViewDimension(normalized.storageTexture.viewDimension)
        } : undefined
      });
      WGPU_KEEPALIVE.push(bindingEntry.buffer);
      return bindingEntry;
    });
    const entryBuf = new ArrayBuffer(entries.length * 120);
    entries.forEach((entry, i) => {
      new Uint8Array(entryBuf, i * 120, 120).set(new Uint8Array(entry.buffer));
    });
    const entryPtr = ptr2(entryBuf);
    WGPU_KEEPALIVE.push(entryBuf);
    const desc = makeBindGroupLayoutDescriptor(entryPtr, entries.length);
    WGPU_KEEPALIVE.push(desc.buffer);
    const layoutPtr = WGPUNative.symbols.wgpuDeviceCreateBindGroupLayout(this.ptr, desc.ptr);
    return new GPUBindGroupLayout(layoutPtr);
  }
  createBindGroup(descriptor) {
    const entries = descriptor.entries.map((entry) => {
      if (entry.resource?.buffer || entry.resource instanceof GPUBuffer) {
        const buffer = entry.resource.buffer ?? entry.resource;
        return makeBindGroupEntry({
          binding: entry.binding ?? 0,
          buffer: {
            buffer,
            offset: entry.resource.offset ?? 0,
            size: entry.resource.size ?? 0xffffffffffffffffn
          }
        });
      }
      if (entry.resource instanceof GPUSampler) {
        return makeBindGroupEntry({
          binding: entry.binding ?? 0,
          sampler: entry.resource
        });
      }
      if (entry.resource instanceof GPUTextureView) {
        return makeBindGroupEntry({
          binding: entry.binding ?? 0,
          textureView: entry.resource
        });
      }
      if (entry.resource?.sampler) {
        return makeBindGroupEntry({
          binding: entry.binding ?? 0,
          sampler: entry.resource.sampler
        });
      }
      if (entry.resource?.textureView) {
        return makeBindGroupEntry({
          binding: entry.binding ?? 0,
          textureView: entry.resource.textureView
        });
      }
      return makeBindGroupEntry({ binding: entry.binding ?? 0 });
    });
    const entryBuf = new ArrayBuffer(entries.length * 56);
    entries.forEach((entry, i) => {
      new Uint8Array(entryBuf, i * 56, 56).set(new Uint8Array(entry.buffer));
    });
    const entryPtr = ptr2(entryBuf);
    WGPU_KEEPALIVE.push(entryBuf);
    const desc = makeBindGroupDescriptor(descriptor.layout.ptr, entryPtr, entries.length);
    WGPU_KEEPALIVE.push(desc.buffer);
    const bindGroupPtr = WGPUNative.symbols.wgpuDeviceCreateBindGroup(this.ptr, desc.ptr);
    return new GPUBindGroup(bindGroupPtr);
  }
  createPipelineLayout(descriptor) {
    const layouts = new BigUint64Array(descriptor.bindGroupLayouts.length);
    for (let i = 0;i < layouts.length; i += 1) {
      layouts[i] = BigInt(descriptor.bindGroupLayouts[i].ptr);
    }
    WGPU_KEEPALIVE.push(layouts);
    const desc = makePipelineLayoutDescriptor(ptr2(layouts), layouts.length);
    WGPU_KEEPALIVE.push(desc.buffer);
    const layoutPtr = WGPUNative.symbols.wgpuDeviceCreatePipelineLayout(this.ptr, desc.ptr);
    return new GPUPipelineLayout(layoutPtr);
  }
  createShaderModule(descriptor) {
    const code = new TextEncoder().encode(descriptor.code + "\x00");
    const codeBuf = new Uint8Array(code);
    WGPU_KEEPALIVE.push(codeBuf);
    const codePtr = ptr2(codeBuf);
    const source = makeShaderSourceWGSL(codePtr, WGPU_STRLEN);
    const desc = makeShaderModuleDescriptor(source.ptr);
    WGPU_KEEPALIVE.push(source.buffer, desc.buffer);
    const modulePtr = WGPUNative.symbols.wgpuDeviceCreateShaderModule(this.ptr, desc.ptr);
    return new GPUShaderModule(modulePtr);
  }
  createRenderPipeline(descriptor) {
    const vertexModule = descriptor.vertex.module;
    const vertexEntry = makeStringView(descriptor.vertex.entryPoint ?? "main");
    const vertexBuffers = descriptor.vertex.buffers ?? [];
    const vertexLayouts = [];
    const vertexLayoutPtrs = [];
    for (const buf of vertexBuffers) {
      const attrs = buf.attributes ?? [];
      const attrBuf = new ArrayBuffer(attrs.length * 32);
      attrs.forEach((attr, idx) => {
        const format = mapVertexFormat(attr.format);
        const attrStruct = makeVertexAttribute(attr.offset ?? 0, attr.shaderLocation ?? 0, format);
        new Uint8Array(attrBuf, idx * 32, 32).set(new Uint8Array(attrStruct.buffer));
      });
      const attrPtr = ptr2(attrBuf);
      WGPU_KEEPALIVE.push(attrBuf);
      const layout = makeVertexBufferLayout(attrPtr, attrs.length, BigInt(buf.arrayStride ?? 0), mapVertexStepMode(buf.stepMode));
      WGPU_KEEPALIVE.push(layout.buffer);
      vertexLayouts.push(layout.buffer);
      vertexLayoutPtrs.push(layout.ptr);
    }
    const vertexLayoutsBuf = new ArrayBuffer(vertexLayouts.length * 40);
    vertexLayouts.forEach((layoutBuf, i) => {
      new Uint8Array(vertexLayoutsBuf, i * 40, 40).set(new Uint8Array(layoutBuf));
    });
    const vertexLayoutsPtr = ptr2(vertexLayoutsBuf);
    WGPU_KEEPALIVE.push(vertexLayoutsBuf);
    const vertexState = makeVertexState(vertexModule.ptr, { ptr: vertexEntry.ptr, len: vertexEntry.len }, vertexLayoutsPtr, vertexLayouts.length);
    WGPU_KEEPALIVE.push(vertexState.buffer);
    let fragmentStatePtr = null;
    if (descriptor.fragment) {
      const fragModule = descriptor.fragment.module;
      const fragEntry = makeStringView(descriptor.fragment.entryPoint ?? "main");
      const targets = descriptor.fragment.targets ?? [];
      const targetBuf = new ArrayBuffer(targets.length * 32);
      targets.forEach((t, i) => {
        let blendPtr = null;
        if (t.blend) {
          const colorComp = makeBlendComponent(mapBlendOperation(t.blend.color?.operation), mapBlendFactor(t.blend.color?.srcFactor), mapBlendFactor(t.blend.color?.dstFactor));
          const alphaComp = makeBlendComponent(mapBlendOperation(t.blend.alpha?.operation), mapBlendFactor(t.blend.alpha?.srcFactor), mapBlendFactor(t.blend.alpha?.dstFactor));
          const blend = makeBlendState(colorComp.buffer, alphaComp.buffer);
          WGPU_KEEPALIVE.push(colorComp.buffer, alphaComp.buffer, blend.buffer);
          blendPtr = blend.ptr;
        }
        const target = makeColorTargetState(mapTextureFormat(t.format) ?? WGPUTextureFormat_BGRA8Unorm, blendPtr, t.writeMask ?? WGPUColorWriteMask_All);
        new Uint8Array(targetBuf, i * 32, 32).set(new Uint8Array(target.buffer));
      });
      const targetPtr = ptr2(targetBuf);
      WGPU_KEEPALIVE.push(targetBuf);
      const fragState = makeFragmentState(fragModule.ptr, { ptr: fragEntry.ptr, len: fragEntry.len }, targetPtr, targets.length);
      WGPU_KEEPALIVE.push(fragState.buffer);
      fragmentStatePtr = fragState.ptr;
    }
    const primitive = makePrimitiveState({
      topology: mapPrimitiveTopology(descriptor.primitive?.topology),
      stripIndexFormat: mapIndexFormat(descriptor.primitive?.stripIndexFormat),
      frontFace: mapFrontFace(descriptor.primitive?.frontFace),
      cullMode: mapCullMode(descriptor.primitive?.cullMode),
      unclippedDepth: descriptor.primitive?.unclippedDepth ? 1 : 0
    });
    WGPU_KEEPALIVE.push(primitive.buffer);
    let depthStencilPtr = null;
    if (descriptor.depthStencil) {
      const depth = makeDepthStencilState({
        format: mapTextureFormat(descriptor.depthStencil.format) ?? WGPUTextureFormat_Depth24Plus,
        depthWriteEnabled: !!descriptor.depthStencil.depthWriteEnabled,
        depthCompare: mapCompareFunction(descriptor.depthStencil.depthCompare),
        stencilReadMask: descriptor.depthStencil.stencilReadMask ?? 4294967295,
        stencilWriteMask: descriptor.depthStencil.stencilWriteMask ?? 4294967295,
        depthBias: descriptor.depthStencil.depthBias ?? 0,
        depthBiasSlopeScale: descriptor.depthStencil.depthBiasSlopeScale ?? 0,
        depthBiasClamp: descriptor.depthStencil.depthBiasClamp ?? 0
      });
      WGPU_KEEPALIVE.push(depth.buffer);
      depthStencilPtr = depth.ptr;
    }
    const multisample = makeMultisampleState({
      count: descriptor.multisample?.count ?? 1,
      mask: descriptor.multisample?.mask ?? 4294967295,
      alphaToCoverageEnabled: !!descriptor.multisample?.alphaToCoverageEnabled
    });
    WGPU_KEEPALIVE.push(multisample.buffer);
    const pipelineDesc = makeRenderPipelineDescriptor(descriptor.layout && descriptor.layout !== "auto" ? descriptor.layout.ptr : null, vertexState.buffer, primitive.buffer, depthStencilPtr, multisample.buffer, fragmentStatePtr);
    WGPU_KEEPALIVE.push(pipelineDesc.buffer);
    const pipelinePtr = WGPUNative.symbols.wgpuDeviceCreateRenderPipeline(this.ptr, pipelineDesc.ptr);
    return new GPURenderPipeline(pipelinePtr);
  }
  createComputePipeline(descriptor) {
    const module = descriptor.compute.module;
    const entry = makeStringView(descriptor.compute.entryPoint ?? "main");
    const stage = makeProgrammableStageDescriptor(module.ptr, { ptr: entry.ptr, len: entry.len });
    WGPU_KEEPALIVE.push(stage.buffer);
    const pipelineDesc = makeComputePipelineDescriptor(descriptor.layout && descriptor.layout !== "auto" ? descriptor.layout.ptr : null, stage.buffer);
    WGPU_KEEPALIVE.push(pipelineDesc.buffer);
    const pipelinePtr = WGPUNative.symbols.wgpuDeviceCreateComputePipeline(this.ptr, pipelineDesc.ptr);
    return new GPUComputePipeline(pipelinePtr);
  }
  createCommandEncoder() {
    const desc = makeCommandEncoderDescriptor();
    WGPU_KEEPALIVE.push(desc.buffer);
    const encoderPtr = WGPUNative.symbols.wgpuDeviceCreateCommandEncoder(this.ptr, desc.ptr);
    return new GPUCommandEncoder(encoderPtr, this);
  }
  addEventListener(type, handler) {
    if (type !== "uncapturederror")
      return;
    this._uncapturedErrorListeners.push(handler);
  }
  pushErrorScope(_filter) {
    return;
  }
  popErrorScope() {
    return Promise.resolve(null);
  }
}

class GPUBuffer {
  ptr;
  size;
  usage;
  _device;
  _mapped;
  constructor(ptr3, size, usage, device, mapped = false) {
    this.ptr = ptr3;
    this.size = size;
    this.usage = usage;
    this._device = device;
    this._mapped = mapped;
  }
  getMappedRange(_offset = 0, _size) {
    if (!this._mapped) {
      return new ArrayBuffer(0);
    }
    const size = Math.max(0, _size ?? this.size - _offset);
    const mapped = WGPUNative.symbols.wgpuBufferGetMappedRange(this.ptr, BigInt(_offset), BigInt(size));
    if (!mapped) {
      return new ArrayBuffer(0);
    }
    return toArrayBuffer2(mapped, 0, size);
  }
  mapAsync(mode, offset = 0, size) {
    const mapMode = mode ?? ((this.usage & WGPUBufferUsage_MapRead) !== 0n ? Number(WGPUMapMode_Read) : Number(WGPUMapMode_Write));
    const mapSize = size ?? this.size - offset;
    const callbackPtr = bufferMapCallback.ptr ?? bufferMapCallback;
    const info = makeBufferMapCallbackInfo(Number(callbackPtr), this.ptr, 0);
    WGPU_KEEPALIVE.push(info.buffer);
    WGPUBridge.bufferMapAsync(this.ptr, BigInt(mapMode), BigInt(offset), BigInt(mapSize), info.ptr);
    return new Promise((resolve3) => {
      let done = false;
      const resolveOnce = () => {
        if (done)
          return;
        done = true;
        resolve3(true);
      };
      MAP_ASYNC_RESOLVERS.set(this.ptr, (mapped) => {
        if (mapped) {
          this._mapped = true;
          resolveOnce();
        } else {
          resolve3(false);
        }
      });
      const start = Date.now();
      const poll = () => {
        if (done)
          return;
        try {
          if (this._device.instancePtr) {
            WGPUNative.symbols.wgpuInstanceProcessEvents(this._device.instancePtr);
          }
          WGPUNative.symbols.wgpuDeviceTick(this._device.ptr);
        } catch {}
        const state = WGPUNative.symbols.wgpuBufferGetMapState(this.ptr);
        if (state === WGPUBufferMapState_Mapped) {
          this._mapped = true;
          resolveOnce();
          return;
        }
        if (Date.now() - start > 2000) {
          resolve3(false);
          return;
        }
        setTimeout(poll, 5);
      };
      setTimeout(poll, 5);
    });
  }
  unmap() {
    WGPUNative.symbols.wgpuBufferUnmap(this.ptr);
    this._mapped = false;
  }
  readSync(offset = 0, size, timeoutNs = 2000000000) {
    if (!this._device.instancePtr)
      return null;
    const readSize = Math.max(0, size ?? this.size - offset);
    const out = new ArrayBuffer(readSize);
    const ok = WGPUBridge.bufferReadSyncInto(this._device.instancePtr, this.ptr, BigInt(offset), BigInt(readSize), BigInt(timeoutNs), ptr2(out));
    if (!ok)
      return null;
    return out;
  }
  readbackAsync(dst, offset = 0, size, timeoutMs = 2000) {
    const readSize = Math.max(0, size ?? dst.byteLength);
    const jobPtr = WGPUBridge.bufferReadbackBegin(this.ptr, BigInt(offset), BigInt(readSize), ptr2(dst));
    if (!jobPtr)
      return Promise.resolve(0);
    return new Promise((resolve3) => {
      const start = Date.now();
      const poll = () => {
        try {
          if (this._device.instancePtr) {
            WGPUNative.symbols.wgpuInstanceProcessEvents(this._device.instancePtr);
          }
          WGPUNative.symbols.wgpuDeviceTick(this._device.ptr);
        } catch {}
        const status = WGPUBridge.bufferReadbackStatus(jobPtr);
        if (status === 1) {
          WGPUBridge.bufferReadbackFree(jobPtr);
          resolve3(1);
          return;
        }
        if (status === 2 || status === 3 || Date.now() - start > timeoutMs) {
          WGPUBridge.bufferReadbackFree(jobPtr);
          resolve3(status === 0 ? 2 : status);
          return;
        }
        setTimeout(poll, 5);
      };
      setTimeout(poll, 5);
    });
  }
  destroy() {
    WGPUNative.symbols.wgpuBufferDestroy(this.ptr);
  }
}

class GPUSampler {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPUBindGroupLayout {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPUBindGroup {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPUPipelineLayout {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPUShaderModule {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPURenderPipeline {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
  getBindGroupLayout(index) {
    const layoutPtr = WGPUNative.symbols.wgpuRenderPipelineGetBindGroupLayout(this.ptr, index);
    return new GPUBindGroupLayout(layoutPtr);
  }
}

class GPUComputePipeline {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
  getBindGroupLayout(index) {
    const layoutPtr = WGPUNative.symbols.wgpuComputePipelineGetBindGroupLayout(this.ptr, index);
    return new GPUBindGroupLayout(layoutPtr);
  }
}

class GPUCommandBuffer {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
}

class GPUCommandEncoder {
  ptr;
  _device;
  constructor(ptr3, device) {
    this.ptr = ptr3;
    this._device = device;
  }
  beginRenderPass(descriptor) {
    const colorAttachments = descriptor.colorAttachments.map((c) => makeRenderPassColorAttachment(c.view.ptr, c.resolveTarget ? c.resolveTarget.ptr : null, c.clearValue ?? { r: 0, g: 0, b: 0, a: 1 }, mapLoadOp(c.loadOp), mapStoreOp(c.storeOp)));
    const colorBuf = new ArrayBuffer(colorAttachments.length * 72);
    colorAttachments.forEach((c, i) => {
      new Uint8Array(colorBuf, i * 72, 72).set(new Uint8Array(c.buffer));
    });
    const colorPtr = ptr2(colorBuf);
    WGPU_KEEPALIVE.push(colorBuf);
    let depthPtr = null;
    if (descriptor.depthStencilAttachment) {
      const d = descriptor.depthStencilAttachment;
      const viewFormat = d.view.format ?? 0;
      if (viewFormat && !isDepthFormat(viewFormat)) {} else {
        const depth = makeRenderPassDepthStencilAttachment({
          view: d.view.ptr,
          depthLoadOp: mapLoadOp(d.depthLoadOp),
          depthStoreOp: mapStoreOp(d.depthStoreOp),
          depthClearValue: d.depthClearValue ?? 1,
          depthReadOnly: !!d.depthReadOnly,
          stencilLoadOp: mapLoadOp(d.stencilLoadOp),
          stencilStoreOp: mapStoreOp(d.stencilStoreOp),
          stencilClearValue: d.stencilClearValue ?? 0,
          stencilReadOnly: !!d.stencilReadOnly
        });
        WGPU_KEEPALIVE.push(depth.buffer);
        depthPtr = depth.ptr;
      }
    }
    const passDesc = makeRenderPassDescriptor(colorPtr, colorAttachments.length, depthPtr);
    WGPU_KEEPALIVE.push(passDesc.buffer);
    const passPtr = WGPUNative.symbols.wgpuCommandEncoderBeginRenderPass(this.ptr, passDesc.ptr);
    return new GPURenderPassEncoder(passPtr);
  }
  beginComputePass() {
    const desc = makeComputePassDescriptor();
    WGPU_KEEPALIVE.push(desc.buffer);
    const passPtr = WGPUNative.symbols.wgpuCommandEncoderBeginComputePass(this.ptr, desc.ptr);
    return new GPUComputePassEncoder(passPtr);
  }
  copyBufferToTexture(source, destination, size) {
    const offset = source.offset ?? 0;
    const mapped = source.buffer.getMappedRange(0, source.buffer.size);
    const data = offset > 0 ? new Uint8Array(mapped, offset) : new Uint8Array(mapped);
    this._device.queue.writeTexture(destination, data, {
      bytesPerRow: source.bytesPerRow ?? 0,
      rowsPerImage: source.rowsPerImage ?? 0
    }, size);
  }
  copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) {
    WGPUNative.symbols.wgpuCommandEncoderCopyBufferToBuffer(this.ptr, source.ptr, BigInt(sourceOffset), destination.ptr, BigInt(destinationOffset), BigInt(size));
  }
  finish() {
    const cmdPtr = WGPUNative.symbols.wgpuCommandEncoderFinish(this.ptr, 0);
    return new GPUCommandBuffer(cmdPtr);
  }
}

class GPURenderPassEncoder {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
  setPipeline(pipeline) {
    WGPUNative.symbols.wgpuRenderPassEncoderSetPipeline(this.ptr, pipeline.ptr);
  }
  setBindGroup(index, bindGroup, offsets) {
    let offsetsPtr = 0;
    let count = 0n;
    if (offsets && offsets.length) {
      const arr = new BigUint64Array(offsets.length);
      offsets.forEach((o, i) => {
        arr[i] = BigInt(o);
      });
      WGPU_KEEPALIVE.push(arr);
      offsetsPtr = ptr2(arr);
      count = BigInt(offsets.length);
    }
    WGPUNative.symbols.wgpuRenderPassEncoderSetBindGroup(this.ptr, index, bindGroup.ptr, count, offsetsPtr);
  }
  setVertexBuffer(slot, buffer, offset = 0, size) {
    WGPUNative.symbols.wgpuRenderPassEncoderSetVertexBuffer(this.ptr, slot, buffer.ptr, BigInt(offset), BigInt(size ?? buffer.size));
  }
  setIndexBuffer(buffer, indexFormat, offset = 0, size) {
    const format = mapIndexFormat(indexFormat);
    WGPUNative.symbols.wgpuRenderPassEncoderSetIndexBuffer(this.ptr, buffer.ptr, format ?? 0, BigInt(offset), BigInt(size ?? buffer.size));
  }
  setViewport(x, y, width, height, minDepth = 0, maxDepth = 1) {
    WGPUNative.symbols.wgpuRenderPassEncoderSetViewport(this.ptr, x, y, width, height, minDepth, maxDepth);
  }
  setScissorRect(x, y, width, height) {
    WGPUNative.symbols.wgpuRenderPassEncoderSetScissorRect(this.ptr, x, y, width, height);
  }
  draw(vertexCount, instanceCount = 1, firstVertex = 0, firstInstance = 0) {
    WGPUNative.symbols.wgpuRenderPassEncoderDraw(this.ptr, vertexCount, instanceCount, firstVertex, firstInstance);
  }
  drawIndexed(indexCount, instanceCount = 1, firstIndex = 0, baseVertex = 0, firstInstance = 0) {
    WGPUNative.symbols.wgpuRenderPassEncoderDrawIndexed(this.ptr, indexCount, instanceCount, firstIndex, baseVertex, firstInstance);
  }
  end() {
    WGPUNative.symbols.wgpuRenderPassEncoderEnd(this.ptr);
  }
}

class GPUComputePassEncoder {
  ptr;
  constructor(ptr3) {
    this.ptr = ptr3;
  }
  setPipeline(pipeline) {
    WGPUNative.symbols.wgpuComputePassEncoderSetPipeline(this.ptr, pipeline.ptr);
  }
  setBindGroup(index, bindGroup, offsets) {
    let offsetsPtr = 0;
    let count = 0n;
    if (offsets && offsets.length) {
      const arr = new BigUint64Array(offsets.length);
      offsets.forEach((o, i) => {
        arr[i] = BigInt(o);
      });
      WGPU_KEEPALIVE.push(arr);
      offsetsPtr = ptr2(arr);
      count = BigInt(offsets.length);
    }
    WGPUNative.symbols.wgpuComputePassEncoderSetBindGroup(this.ptr, index, bindGroup.ptr, count, offsetsPtr);
  }
  dispatchWorkgroups(x, y = 1, z = 1) {
    WGPUNative.symbols.wgpuComputePassEncoderDispatchWorkgroups(this.ptr, x, y, z);
  }
  end() {
    WGPUNative.symbols.wgpuComputePassEncoderEnd(this.ptr);
  }
}

class GPUAdapter {
  instancePtr;
  surfacePtr;
  features = new Set;
  limits = {};
  info = {};
  constructor(instancePtr, surfacePtr) {
    this.instancePtr = instancePtr;
    this.surfacePtr = surfacePtr;
  }
  async requestDevice() {
    const adapterDevice = new BigUint64Array(2);
    WGPUBridge.createAdapterDeviceMainThread(this.instancePtr, this.surfacePtr, ptr2(adapterDevice));
    const devicePtr = adapterDevice[1];
    if (devicePtr === 0n) {
      throw new Error("Failed to create WGPU device");
    }
    const device = Number(devicePtr);
    return new GPUDevice(device, this.instancePtr);
  }
}

class GPUCanvasContext {
  surfacePtr;
  instancePtr = null;
  devicePtr = null;
  format = WGPUTextureFormat_BGRA8UnormSrgb;
  alphaMode = WGPUCompositeAlphaMode_Opaque;
  supportedAlphaModes = new Set([WGPUCompositeAlphaMode_Opaque]);
  width = 1;
  height = 1;
  _hasCurrentTexture = false;
  _fallbackSize;
  constructor(surfacePtr, instancePtr) {
    this.surfacePtr = surfacePtr;
    this.instancePtr = instancePtr ?? null;
  }
  configure(options) {
    if (!options.size && this._fallbackSize) {
      this.width = this._fallbackSize.width;
      this.height = this._fallbackSize.height;
    }
    this.devicePtr = options.device.ptr;
    if (options.format) {
      this.format = typeof options.format === "string" ? mapTextureFormat(options.format) ?? this.format : options.format;
    }
    if (options.alphaMode) {
      const requestedAlphaMode = typeof options.alphaMode === "string" ? mapAlphaMode(options.alphaMode) : options.alphaMode;
      if (typeof requestedAlphaMode === "number" && this.supportedAlphaModes.has(requestedAlphaMode)) {
        this.alphaMode = requestedAlphaMode;
      } else if (typeof requestedAlphaMode === "number" && !this.supportedAlphaModes.has(requestedAlphaMode)) {
        this.alphaMode = this.supportedAlphaModes.values().next().value ?? WGPUCompositeAlphaMode_Opaque;
      }
    }
    if (options.size) {
      this.width = options.size.width;
      this.height = options.size.height;
    }
    const config = makeSurfaceConfiguration(this.devicePtr, this.width, this.height, this.format, this.alphaMode, toBigInt(options.usage ?? WGPUTextureUsage_RenderAttachment));
    WGPUBridge.surfaceConfigure(this.surfacePtr, config.ptr);
    this._hasCurrentTexture = false;
  }
  getCurrentTexture() {
    const surfaceTexture = makeSurfaceTexture();
    WGPUBridge.surfaceGetCurrentTexture(this.surfacePtr, surfaceTexture.ptr);
    const status = surfaceTexture.view.getUint32(16, true);
    if (status !== 1 && status !== 2) {
      throw new Error(`Surface status ${status}`);
    }
    const texPtr = Number(surfaceTexture.view.getBigUint64(8, true));
    LAST_SURFACE_PTR = this.surfacePtr;
    this._hasCurrentTexture = true;
    LAST_SURFACE_HAS_TEXTURE = true;
    return new GPUTexture(texPtr, this.format);
  }
  present() {
    if (!this._hasCurrentTexture)
      return;
    this._hasCurrentTexture = false;
    LAST_SURFACE_HAS_TEXTURE = false;
    return WGPUBridge.surfacePresent(this.surfacePtr);
  }
  unconfigure() {
    this._hasCurrentTexture = false;
    LAST_SURFACE_HAS_TEXTURE = false;
    return WGPUNative.symbols.wgpuSurfaceUnconfigure(this.surfacePtr);
  }
}
function mapTextureFormat(format) {
  if (typeof format === "number")
    return format;
  switch (format) {
    case "r8unorm":
      return WGPUTextureFormat_R8Unorm;
    case "r8snorm":
      return WGPUTextureFormat_R8Snorm;
    case "r8uint":
      return WGPUTextureFormat_R8Uint;
    case "r8sint":
      return WGPUTextureFormat_R8Sint;
    case "rg8unorm":
      return WGPUTextureFormat_RG8Unorm;
    case "rg8snorm":
      return WGPUTextureFormat_RG8Snorm;
    case "rg8uint":
      return WGPUTextureFormat_RG8Uint;
    case "rg8sint":
      return WGPUTextureFormat_RG8Sint;
    case "bgra8unorm":
      return WGPUTextureFormat_BGRA8Unorm;
    case "bgra8unorm-srgb":
      return WGPUTextureFormat_BGRA8UnormSrgb;
    case "rgba8unorm":
      return WGPUTextureFormat_RGBA8Unorm;
    case "rgba8unorm-srgb":
      return WGPUTextureFormat_RGBA8UnormSrgb;
    case "rgba8snorm":
      return WGPUTextureFormat_RGBA8Snorm;
    case "rgba8uint":
      return WGPUTextureFormat_RGBA8Uint;
    case "rgba8sint":
      return WGPUTextureFormat_RGBA8Sint;
    case "r32float":
      return WGPUTextureFormat_R32Float;
    case "r32uint":
      return WGPUTextureFormat_R32Uint;
    case "r32sint":
      return WGPUTextureFormat_R32Sint;
    case "rg32float":
      return WGPUTextureFormat_RG32Float;
    case "rg32uint":
      return WGPUTextureFormat_RG32Uint;
    case "rg32sint":
      return WGPUTextureFormat_RG32Sint;
    case "rgba16float":
      return WGPUTextureFormat_RGBA16Float;
    case "rgba16uint":
      return WGPUTextureFormat_RGBA16Uint;
    case "rgba16sint":
      return WGPUTextureFormat_RGBA16Sint;
    case "rgba32uint":
      return WGPUTextureFormat_RGBA32Uint;
    case "rgba32sint":
      return WGPUTextureFormat_RGBA32Sint;
    case "depth24plus":
      return WGPUTextureFormat_Depth24Plus;
    case "depth24plus-stencil8":
      return WGPUTextureFormat_Depth24PlusStencil8;
    case "depth32float":
      return WGPUTextureFormat_Depth32Float;
    case "depth16unorm":
      return WGPUTextureFormat_Depth16Unorm;
    case "depth32float-stencil8":
      return WGPUTextureFormat_Depth32FloatStencil8;
    default:
      return;
  }
}
function isIntegerFormat(format) {
  return format === WGPUTextureFormat_R8Uint || format === WGPUTextureFormat_R8Sint || format === WGPUTextureFormat_RG8Uint || format === WGPUTextureFormat_RG8Sint || format === WGPUTextureFormat_RGBA8Uint || format === WGPUTextureFormat_RGBA8Sint || format === WGPUTextureFormat_R32Uint || format === WGPUTextureFormat_R32Sint || format === WGPUTextureFormat_RG32Uint || format === WGPUTextureFormat_RG32Sint || format === WGPUTextureFormat_RGBA16Uint || format === WGPUTextureFormat_RGBA16Sint || format === WGPUTextureFormat_RGBA32Uint || format === WGPUTextureFormat_RGBA32Sint;
}
function isDepthFormat(format) {
  return format === WGPUTextureFormat_Depth24Plus || format === WGPUTextureFormat_Depth24PlusStencil8 || format === WGPUTextureFormat_Depth32Float || format === WGPUTextureFormat_Depth16Unorm || format === WGPUTextureFormat_Depth32FloatStencil8;
}
function mapTextureViewDimension(dim) {
  if (typeof dim === "number")
    return dim;
  switch (dim) {
    case "2d":
      return WGPUTextureViewDimension_2D;
    case "2d-array":
      return WGPUTextureViewDimension_2DArray;
    case "3d":
      return WGPUTextureViewDimension_3D;
    case "cube":
      return WGPUTextureViewDimension_Cube;
    case "cube-array":
      return WGPUTextureViewDimension_CubeArray;
    default:
      return;
  }
}
function mapTextureAspect(aspect) {
  if (typeof aspect === "number")
    return aspect;
  switch (aspect) {
    case "all":
      return WGPUTextureAspect_All;
    case "depth-only":
      return WGPUTextureAspect_DepthOnly;
    case "stencil-only":
      return WGPUTextureAspect_StencilOnly;
    default:
      return;
  }
}
function mapVertexFormat(format) {
  if (typeof format === "number")
    return format;
  switch (format) {
    case "float32":
      return WGPUVertexFormat_Float32;
    case "float32x2":
      return WGPUVertexFormat_Float32x2;
    case "float32x3":
      return WGPUVertexFormat_Float32x3;
    case "float32x4":
      return WGPUVertexFormat_Float32x4;
    case "uint32":
      return WGPUVertexFormat_Uint32;
    case "uint32x2":
      return WGPUVertexFormat_Uint32x2;
    case "uint32x3":
      return WGPUVertexFormat_Uint32x3;
    case "uint32x4":
      return WGPUVertexFormat_Uint32x4;
    case "sint32":
      return WGPUVertexFormat_Sint32;
    case "sint32x2":
      return WGPUVertexFormat_Sint32x2;
    case "sint32x3":
      return WGPUVertexFormat_Sint32x3;
    case "sint32x4":
      return WGPUVertexFormat_Sint32x4;
    default:
      return WGPUVertexFormat_Float32x3;
  }
}
function mapVertexStepMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "instance":
      return WGPUVertexStepMode_Instance;
    case "vertex":
    default:
      return WGPUVertexStepMode_Vertex;
  }
}
function mapPrimitiveTopology(topology) {
  if (typeof topology === "number")
    return topology;
  switch (topology) {
    case "point-list":
      return WGPUPrimitiveTopology_PointList;
    case "line-list":
      return WGPUPrimitiveTopology_LineList;
    case "line-strip":
      return WGPUPrimitiveTopology_LineStrip;
    case "triangle-strip":
      return WGPUPrimitiveTopology_TriangleStrip;
    case "triangle-list":
    default:
      return WGPUPrimitiveTopology_TriangleList;
  }
}
function mapFrontFace(face) {
  if (typeof face === "number")
    return face;
  switch (face) {
    case "cw":
      return WGPUFrontFace_CW;
    case "ccw":
    default:
      return WGPUFrontFace_CCW;
  }
}
function mapCullMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "front":
      return WGPUCullMode_Front;
    case "back":
      return WGPUCullMode_Back;
    case "none":
    default:
      return WGPUCullMode_None;
  }
}
function mapCompareFunction(fn) {
  if (fn == null)
    return 0;
  if (typeof fn === "number")
    return fn;
  switch (fn) {
    case "never":
      return WGPUCompareFunction_Never;
    case "less":
      return WGPUCompareFunction_Less;
    case "equal":
      return WGPUCompareFunction_Equal;
    case "less-equal":
      return WGPUCompareFunction_LessEqual;
    case "greater":
      return WGPUCompareFunction_Greater;
    case "not-equal":
      return WGPUCompareFunction_NotEqual;
    case "greater-equal":
      return WGPUCompareFunction_GreaterEqual;
    case "always":
    default:
      return WGPUCompareFunction_Always;
  }
}
function mapAddressMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "repeat":
      return WGPUAddressMode_Repeat;
    case "mirror-repeat":
      return WGPUAddressMode_MirrorRepeat;
    case "clamp-to-edge":
    default:
      return WGPUAddressMode_ClampToEdge;
  }
}
function mapFilterMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "nearest":
      return WGPUFilterMode_Nearest;
    case "linear":
    default:
      return WGPUFilterMode_Linear;
  }
}
function mapMipmapFilterMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "nearest":
      return WGPUMipmapFilterMode_Nearest;
    case "linear":
    default:
      return WGPUMipmapFilterMode_Linear;
  }
}
function mapShaderStage(stage) {
  if (typeof stage === "number")
    return stage;
  switch (stage) {
    case "vertex":
      return WGPUShaderStage_Vertex;
    case "fragment":
      return WGPUShaderStage_Fragment;
    case "compute":
      return WGPUShaderStage_Compute;
    default:
      return 0;
  }
}
function mapBufferBindingType(type) {
  if (typeof type === "number")
    return type;
  switch (type) {
    case "uniform":
      return WGPUBufferBindingType_Uniform;
    case "storage":
      return WGPUBufferBindingType_Storage;
    case "read-only-storage":
      return WGPUBufferBindingType_ReadOnlyStorage;
    default:
      return WGPUBufferBindingType_Uniform;
  }
}
function mapSamplerBindingType(type) {
  if (typeof type === "number")
    return type;
  switch (type) {
    case "comparison":
      return WGPUSamplerBindingType_Comparison;
    case "non-filtering":
      return WGPUSamplerBindingType_NonFiltering;
    case "filtering":
    default:
      return WGPUSamplerBindingType_Filtering;
  }
}
function mapTextureSampleType(type) {
  if (typeof type === "number")
    return type;
  switch (type) {
    case "unfilterable-float":
      return WGPUTextureSampleType_UnfilterableFloat;
    case "depth":
      return WGPUTextureSampleType_Depth;
    case "sint":
      return WGPUTextureSampleType_Sint;
    case "uint":
      return WGPUTextureSampleType_Uint;
    case "float":
    default:
      return WGPUTextureSampleType_Float;
  }
}
function mapStorageTextureAccess(access) {
  if (typeof access === "number")
    return access;
  switch (access) {
    case "read-only":
      return WGPUStorageTextureAccess_ReadOnly;
    case "read-write":
      return WGPUStorageTextureAccess_ReadWrite;
    case "write-only":
    default:
      return WGPUStorageTextureAccess_WriteOnly;
  }
}
function mapBlendOperation(op) {
  if (typeof op === "number")
    return op;
  switch (op) {
    case "add":
    default:
      return WGPUBlendOperation_Add;
  }
}
function mapBlendFactor(factor) {
  if (typeof factor === "number")
    return factor;
  switch (factor) {
    case "one":
      return WGPUBlendFactor_One;
    case "zero":
      return WGPUBlendFactor_Zero;
    case "src-alpha":
      return WGPUBlendFactor_SrcAlpha;
    case "one-minus-src-alpha":
      return WGPUBlendFactor_OneMinusSrcAlpha;
    default:
      return WGPUBlendFactor_One;
  }
}
function mapLoadOp(op) {
  if (typeof op === "number")
    return op;
  switch (op) {
    case "load":
      return WGPULoadOp_Load;
    case "clear":
    default:
      return WGPULoadOp_Clear;
  }
}
function mapStoreOp(op) {
  if (typeof op === "number")
    return op;
  switch (op) {
    case "discard":
      return WGPUStoreOp_Discard;
    case "store":
    default:
      return WGPUStoreOp_Store;
  }
}
function mapIndexFormat(format) {
  if (typeof format === "number")
    return format;
  switch (format) {
    case "uint32":
      return 2;
    case "uint16":
      return 1;
    default:
      return 0;
  }
}
function mapAlphaMode(mode) {
  if (typeof mode === "number")
    return mode;
  switch (mode) {
    case "premultiplied":
      return WGPUCompositeAlphaMode_Premultiplied;
    case "unpremultiplied":
      return WGPUCompositeAlphaMode_Unpremultiplied;
    case "opaque":
    default:
      return WGPUCompositeAlphaMode_Opaque;
  }
}
function makeShaderSourceWGSL(codePtr, codeLen) {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, 0);
  writeU32(view, 8, 2);
  writeU32(view, 12, 0);
  writePtr(view, 16, codePtr);
  writeU64(view, 24, codeLen);
  return { buffer, ptr: ptr2(buffer) };
}
function makeShaderModuleDescriptor(nextInChainPtr) {
  const buffer = new ArrayBuffer(24);
  const view = new DataView(buffer);
  writePtr(view, 0, nextInChainPtr);
  writePtr(view, 8, 0);
  writeU64(view, 16, 0n);
  return { buffer, ptr: ptr2(buffer) };
}
function makeTexelCopyTextureInfo(texturePtr, mipLevel = 0, origin) {
  const buffer = new ArrayBuffer(32);
  const view = new DataView(buffer);
  writePtr(view, 0, texturePtr);
  writeU32(view, 8, mipLevel);
  writeU32(view, 12, origin?.x ?? 0);
  writeU32(view, 16, origin?.y ?? 0);
  writeU32(view, 20, origin?.z ?? 0);
  writeU32(view, 24, 0);
  writeU32(view, 28, 0);
  return { buffer, ptr: ptr2(buffer) };
}
function makeTexelCopyBufferLayout(offset, bytesPerRow, rowsPerImage) {
  const buffer = new ArrayBuffer(16);
  const view = new DataView(buffer);
  writeU64(view, 0, BigInt(offset));
  writeU32(view, 8, bytesPerRow);
  writeU32(view, 12, rowsPerImage);
  return { buffer, ptr: ptr2(buffer) };
}
function makeExtent3D(width, height, depth) {
  const buffer = new ArrayBuffer(12);
  const view = new DataView(buffer);
  writeU32(view, 0, width);
  writeU32(view, 4, height);
  writeU32(view, 8, depth);
  return { buffer, ptr: ptr2(buffer) };
}
function alignTo(value, alignment) {
  return Math.ceil(value / alignment) * alignment;
}
function bytesPerPixelForFormat(format) {
  switch (format) {
    case WGPUTextureFormat_R8Unorm:
    case WGPUTextureFormat_R8Snorm:
    case WGPUTextureFormat_R8Uint:
    case WGPUTextureFormat_R8Sint:
      return 1;
    case WGPUTextureFormat_RG8Unorm:
    case WGPUTextureFormat_RG8Snorm:
    case WGPUTextureFormat_RG8Uint:
    case WGPUTextureFormat_RG8Sint:
      return 2;
    case WGPUTextureFormat_BGRA8Unorm:
    case WGPUTextureFormat_BGRA8UnormSrgb:
    case WGPUTextureFormat_RGBA8Unorm:
    case WGPUTextureFormat_RGBA8UnormSrgb:
    case WGPUTextureFormat_Depth24Plus:
    case WGPUTextureFormat_Depth24PlusStencil8:
    case WGPUTextureFormat_Depth32Float:
      return 4;
    case WGPUTextureFormat_Depth32FloatStencil8:
      return 8;
    case WGPUTextureFormat_RG32Float:
    case WGPUTextureFormat_RG32Uint:
    case WGPUTextureFormat_RG32Sint:
    case WGPUTextureFormat_RGBA16Float:
    case WGPUTextureFormat_RGBA16Uint:
    case WGPUTextureFormat_RGBA16Sint:
      return 8;
    case WGPUTextureFormat_RGBA32Uint:
    case WGPUTextureFormat_RGBA32Sint:
      return 16;
    default:
      return 4;
  }
}
function repackTextureData(data, srcStride, dstStride, minRowBytes, height, rowsPerImage, layers) {
  const src = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  const totalRows = rowsPerImage * layers;
  const dst = new Uint8Array(dstStride * totalRows);
  let srcOffset = 0;
  let dstOffset = 0;
  for (let layer = 0;layer < layers; layer += 1) {
    for (let row = 0;row < rowsPerImage; row += 1) {
      if (row < height) {
        dst.set(src.subarray(srcOffset, srcOffset + minRowBytes), dstOffset);
      }
      srcOffset += srcStride;
      dstOffset += dstStride;
    }
  }
  return dst;
}

// node_modules/@babylonjs/core/Actions/index.js
init_abstractActionManager();

// node_modules/@babylonjs/core/Actions/action.js
init_observable();
init_math_vector();
init_math_color();
init_typeStore();

class Action {
  constructor(triggerOptions, condition) {
    this.triggerOptions = triggerOptions;
    this.onBeforeExecuteObservable = new Observable;
    if (triggerOptions.parameter) {
      this.trigger = triggerOptions.trigger;
      this._triggerParameter = triggerOptions.parameter;
    } else if (triggerOptions.trigger) {
      this.trigger = triggerOptions.trigger;
    } else {
      this.trigger = triggerOptions;
    }
    this._nextActiveAction = this;
    this._condition = condition;
  }
  _prepare() {}
  getTriggerParameter() {
    return this._triggerParameter;
  }
  setTriggerParameter(value) {
    this._triggerParameter = value;
  }
  _evaluateConditionForCurrentFrame() {
    const condition = this._condition;
    if (!condition) {
      return true;
    }
    const currentRenderId = this._actionManager.getScene().getRenderId();
    if (condition._evaluationId !== currentRenderId) {
      condition._evaluationId = currentRenderId;
      condition._currentResult = condition.isValid();
    }
    return condition._currentResult;
  }
  _executeCurrent(evt) {
    const isConditionValid = this._evaluateConditionForCurrentFrame();
    if (!isConditionValid) {
      return;
    }
    this.onBeforeExecuteObservable.notifyObservers(this);
    this._nextActiveAction.execute(evt);
    this.skipToNextActiveAction();
  }
  execute(evt) {}
  skipToNextActiveAction() {
    if (this._nextActiveAction._child) {
      if (!this._nextActiveAction._child._actionManager) {
        this._nextActiveAction._child._actionManager = this._actionManager;
      }
      this._nextActiveAction = this._nextActiveAction._child;
    } else {
      this._nextActiveAction = this;
    }
  }
  then(action) {
    this._child = action;
    action._actionManager = this._actionManager;
    action._prepare();
    return action;
  }
  _getProperty(propertyPath) {
    return this._actionManager._getProperty(propertyPath);
  }
  _getEffectiveTarget(target, propertyPath) {
    return this._actionManager._getEffectiveTarget(target, propertyPath);
  }
  serialize(parent) {
    return null;
  }
  _serialize(serializedAction, parent) {
    const serializationObject = {
      type: 1,
      children: [],
      name: serializedAction.name,
      properties: serializedAction.properties || []
    };
    if (this._child) {
      this._child.serialize(serializationObject);
    }
    if (this._condition) {
      const serializedCondition = this._condition.serialize();
      serializedCondition.children.push(serializationObject);
      if (parent) {
        parent.children.push(serializedCondition);
      }
      return serializedCondition;
    }
    if (parent) {
      parent.children.push(serializationObject);
    }
    return serializationObject;
  }
}
Action._SerializeValueAsString = (value) => {
  if (typeof value === "number") {
    return value.toString();
  }
  if (typeof value === "boolean") {
    return value ? "true" : "false";
  }
  if (value instanceof Vector2) {
    return value.x + ", " + value.y;
  }
  if (value instanceof Vector3) {
    return value.x + ", " + value.y + ", " + value.z;
  }
  if (value instanceof Color3) {
    return value.r + ", " + value.g + ", " + value.b;
  }
  if (value instanceof Color4) {
    return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  }
  return value;
};
Action._GetTargetProperty = (target) => {
  return {
    name: "target",
    targetType: target._isMesh ? "MeshProperties" : target._isLight ? "LightProperties" : target._isCamera ? "CameraProperties" : target._isMaterial ? "MaterialProperties" : "SceneProperties",
    value: target._isScene ? "Scene" : target.name
  };
};
RegisterClass("BABYLON.Action", Action);
// node_modules/@babylonjs/core/Actions/actionManager.js
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Actions/condition.js
init_typeStore();

class Condition {
  constructor(actionManager) {
    this._actionManager = actionManager;
  }
  isValid() {
    return true;
  }
  _getProperty(propertyPath) {
    return this._actionManager._getProperty(propertyPath);
  }
  _getEffectiveTarget(target, propertyPath) {
    return this._actionManager._getEffectiveTarget(target, propertyPath);
  }
  serialize() {}
  _serialize(serializedCondition) {
    return {
      type: 2,
      children: [],
      name: serializedCondition.name,
      properties: serializedCondition.properties
    };
  }
}

class ValueCondition extends Condition {
  static get IsEqual() {
    return ValueCondition._IsEqual;
  }
  static get IsDifferent() {
    return ValueCondition._IsDifferent;
  }
  static get IsGreater() {
    return ValueCondition._IsGreater;
  }
  static get IsLesser() {
    return ValueCondition._IsLesser;
  }
  constructor(actionManager, target, propertyPath, value, operator = ValueCondition.IsEqual) {
    super(actionManager);
    this.propertyPath = propertyPath;
    this.value = value;
    this.operator = operator;
    this._target = target;
    this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
    this._property = this._getProperty(this.propertyPath);
  }
  isValid() {
    switch (this.operator) {
      case ValueCondition.IsGreater:
        return this._effectiveTarget[this._property] > this.value;
      case ValueCondition.IsLesser:
        return this._effectiveTarget[this._property] < this.value;
      case ValueCondition.IsEqual:
      case ValueCondition.IsDifferent: {
        let check;
        if (this.value.equals) {
          check = this.value.equals(this._effectiveTarget[this._property]);
        } else {
          check = this.value === this._effectiveTarget[this._property];
        }
        return this.operator === ValueCondition.IsEqual ? check : !check;
      }
    }
    return false;
  }
  serialize() {
    return this._serialize({
      name: "ValueCondition",
      properties: [
        Action._GetTargetProperty(this._target),
        { name: "propertyPath", value: this.propertyPath },
        { name: "value", value: Action._SerializeValueAsString(this.value) },
        { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
      ]
    });
  }
  static GetOperatorName(operator) {
    switch (operator) {
      case ValueCondition._IsEqual:
        return "IsEqual";
      case ValueCondition._IsDifferent:
        return "IsDifferent";
      case ValueCondition._IsGreater:
        return "IsGreater";
      case ValueCondition._IsLesser:
        return "IsLesser";
      default:
        return "";
    }
  }
}
ValueCondition._IsEqual = 0;
ValueCondition._IsDifferent = 1;
ValueCondition._IsGreater = 2;
ValueCondition._IsLesser = 3;

class PredicateCondition extends Condition {
  constructor(actionManager, predicate) {
    super(actionManager);
    this.predicate = predicate;
  }
  isValid() {
    return this.predicate();
  }
}

class StateCondition extends Condition {
  constructor(actionManager, target, value) {
    super(actionManager);
    this.value = value;
    this._target = target;
  }
  isValid() {
    return this._target.state === this.value;
  }
  serialize() {
    return this._serialize({
      name: "StateCondition",
      properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }]
    });
  }
}
RegisterClass("BABYLON.ValueCondition", ValueCondition);
RegisterClass("BABYLON.PredicateCondition", PredicateCondition);
RegisterClass("BABYLON.StateCondition", StateCondition);

// node_modules/@babylonjs/core/Actions/directActions.js
init_logger();
init_math_vector();
init_typeStore();

class SwitchBooleanAction extends Action {
  constructor(triggerOptions, target, propertyPath, condition) {
    super(triggerOptions, condition);
    this.propertyPath = propertyPath;
    this._target = this._effectiveTarget = target;
  }
  _prepare() {
    this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
    this._property = this._getProperty(this.propertyPath);
  }
  execute() {
    this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  }
  serialize(parent) {
    return super._serialize({
      name: "SwitchBooleanAction",
      properties: [Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }]
    }, parent);
  }
}

class SetStateAction extends Action {
  constructor(triggerOptions, target, value, condition) {
    super(triggerOptions, condition);
    this.value = value;
    this._target = target;
  }
  execute() {
    this._target.state = this.value;
  }
  serialize(parent) {
    return super._serialize({
      name: "SetStateAction",
      properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }]
    }, parent);
  }
}

class SetValueAction extends Action {
  constructor(triggerOptions, target, propertyPath, value, condition) {
    super(triggerOptions, condition);
    this.propertyPath = propertyPath;
    this.value = value;
    this._target = this._effectiveTarget = target;
  }
  _prepare() {
    this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
    this._property = this._getProperty(this.propertyPath);
  }
  execute() {
    this._effectiveTarget[this._property] = this.value;
    if (this._target.markAsDirty) {
      this._target.markAsDirty(this._property);
    }
  }
  serialize(parent) {
    return super._serialize({
      name: "SetValueAction",
      properties: [
        Action._GetTargetProperty(this._target),
        { name: "propertyPath", value: this.propertyPath },
        { name: "value", value: Action._SerializeValueAsString(this.value) }
      ]
    }, parent);
  }
}

class IncrementValueAction extends Action {
  constructor(triggerOptions, target, propertyPath, value, condition) {
    super(triggerOptions, condition);
    this.propertyPath = propertyPath;
    this.value = value;
    this._target = this._effectiveTarget = target;
  }
  _prepare() {
    this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
    this._property = this._getProperty(this.propertyPath);
    if (typeof this._effectiveTarget[this._property] !== "number") {
      Logger.Warn("Warning: IncrementValueAction can only be used with number values");
    }
  }
  execute() {
    this._effectiveTarget[this._property] += this.value;
    if (this._target.markAsDirty) {
      this._target.markAsDirty(this._property);
    }
  }
  serialize(parent) {
    return super._serialize({
      name: "IncrementValueAction",
      properties: [
        Action._GetTargetProperty(this._target),
        { name: "propertyPath", value: this.propertyPath },
        { name: "value", value: Action._SerializeValueAsString(this.value) }
      ]
    }, parent);
  }
}

class PlayAnimationAction extends Action {
  constructor(triggerOptions, target, from, to, loop, condition) {
    super(triggerOptions, condition);
    this.from = from;
    this.to = to;
    this.loop = loop;
    this._target = target;
  }
  _prepare() {}
  execute() {
    const scene = this._actionManager.getScene();
    scene.beginAnimation(this._target, this.from, this.to, this.loop);
  }
  serialize(parent) {
    return super._serialize({
      name: "PlayAnimationAction",
      properties: [
        Action._GetTargetProperty(this._target),
        { name: "from", value: String(this.from) },
        { name: "to", value: String(this.to) },
        { name: "loop", value: Action._SerializeValueAsString(this.loop) || false }
      ]
    }, parent);
  }
}

class StopAnimationAction extends Action {
  constructor(triggerOptions, target, condition) {
    super(triggerOptions, condition);
    this._target = target;
  }
  _prepare() {}
  execute() {
    const scene = this._actionManager.getScene();
    scene.stopAnimation(this._target);
  }
  serialize(parent) {
    return super._serialize({
      name: "StopAnimationAction",
      properties: [Action._GetTargetProperty(this._target)]
    }, parent);
  }
}

class DoNothingAction extends Action {
  constructor(triggerOptions = 0, condition) {
    super(triggerOptions, condition);
  }
  execute() {}
  serialize(parent) {
    return super._serialize({
      name: "DoNothingAction",
      properties: []
    }, parent);
  }
}

class CombineAction extends Action {
  constructor(triggerOptions, children, condition, enableChildrenConditions = true) {
    super(triggerOptions, condition);
    this.children = children;
    this.enableChildrenConditions = enableChildrenConditions;
  }
  _prepare() {
    for (let index = 0;index < this.children.length; index++) {
      this.children[index]._actionManager = this._actionManager;
      this.children[index]._prepare();
    }
  }
  execute(evt) {
    for (const action of this.children) {
      if (!this.enableChildrenConditions || action._evaluateConditionForCurrentFrame()) {
        action.execute(evt);
      }
    }
  }
  serialize(parent) {
    const serializationObject = super._serialize({
      name: "CombineAction",
      properties: [],
      combine: []
    }, parent);
    for (let i = 0;i < this.children.length; i++) {
      serializationObject.combine.push(this.children[i].serialize(null));
    }
    return serializationObject;
  }
}

class ExecuteCodeAction extends Action {
  constructor(triggerOptions, func, condition) {
    super(triggerOptions, condition);
    this.func = func;
  }
  execute(evt) {
    this.func(evt);
  }
}

class SetParentAction extends Action {
  constructor(triggerOptions, target, parent, condition) {
    super(triggerOptions, condition);
    this._target = target;
    this._parent = parent;
  }
  _prepare() {}
  execute() {
    if (this._target.parent === this._parent) {
      return;
    }
    const invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
    invertParentWorldMatrix.invert();
    this._target.position = Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
    this._target.parent = this._parent;
  }
  serialize(parent) {
    return super._serialize({
      name: "SetParentAction",
      properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)]
    }, parent);
  }
}
RegisterClass("BABYLON.SetParentAction", SetParentAction);
RegisterClass("BABYLON.ExecuteCodeAction", ExecuteCodeAction);
RegisterClass("BABYLON.DoNothingAction", DoNothingAction);
RegisterClass("BABYLON.StopAnimationAction", StopAnimationAction);
RegisterClass("BABYLON.PlayAnimationAction", PlayAnimationAction);
RegisterClass("BABYLON.IncrementValueAction", IncrementValueAction);
RegisterClass("BABYLON.SetValueAction", SetValueAction);
RegisterClass("BABYLON.SetStateAction", SetStateAction);
RegisterClass("BABYLON.SetParentAction", SetParentAction);
RegisterClass("BABYLON.SwitchBooleanAction", SwitchBooleanAction);
RegisterClass("BABYLON.CombineAction", CombineAction);

// node_modules/@babylonjs/core/Actions/actionManager.js
init_engineStore();
init_logger();
init_deepCopier();
init_typeStore();
init_abstractActionManager();

class ActionManager extends AbstractActionManager {
  constructor(scene) {
    super();
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this._scene = scene;
    scene.actionManagers.push(this);
  }
  dispose() {
    const sceneIndex = this._scene.actionManagers.indexOf(this);
    for (let i = 0;i < this.actions.length; i++) {
      const action = this.actions[i];
      ActionManager.Triggers[action.trigger]--;
      if (ActionManager.Triggers[action.trigger] === 0) {
        delete ActionManager.Triggers[action.trigger];
      }
    }
    this.actions.length = 0;
    if (sceneIndex > -1) {
      this._scene.actionManagers.splice(sceneIndex, 1);
    }
    const ownerMeshes = this._scene.meshes.filter((m) => m.actionManager === this);
    for (const ownerMesh of ownerMeshes) {
      ownerMesh.actionManager = null;
    }
  }
  getScene() {
    return this._scene;
  }
  hasSpecificTriggers(triggers) {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (triggers.indexOf(action.trigger) > -1) {
        return true;
      }
    }
    return false;
  }
  hasSpecificTriggers2(triggerA, triggerB) {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (triggerA == action.trigger || triggerB == action.trigger) {
        return true;
      }
    }
    return false;
  }
  hasSpecificTrigger(trigger, parameterPredicate) {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (action.trigger === trigger) {
        if (parameterPredicate) {
          if (parameterPredicate(action.getTriggerParameter())) {
            return true;
          }
        } else {
          return true;
        }
      }
    }
    return false;
  }
  get hasPointerTriggers() {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
        return true;
      }
    }
    return false;
  }
  get hasPickTriggers() {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
        return true;
      }
    }
    return false;
  }
  registerAction(action) {
    if (action.trigger === ActionManager.OnEveryFrameTrigger) {
      if (this.getScene().actionManager !== this) {
        Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
        return null;
      }
    }
    this.actions.push(action);
    this.getScene()._registeredActions++;
    if (ActionManager.Triggers[action.trigger]) {
      ActionManager.Triggers[action.trigger]++;
    } else {
      ActionManager.Triggers[action.trigger] = 1;
    }
    action._actionManager = this;
    action._prepare();
    return action;
  }
  unregisterAction(action) {
    const index = this.actions.indexOf(action);
    if (index !== -1) {
      this.actions.splice(index, 1);
      ActionManager.Triggers[action.trigger] -= 1;
      if (ActionManager.Triggers[action.trigger] === 0) {
        delete ActionManager.Triggers[action.trigger];
      }
      action._actionManager = null;
      this.getScene()._registeredActions--;
      return true;
    }
    return false;
  }
  processTrigger(trigger, evt) {
    for (let index = 0;index < this.actions.length; index++) {
      const action = this.actions[index];
      if (action.trigger === trigger) {
        if (evt) {
          if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
            const parameter = action.getTriggerParameter();
            if (typeof parameter === "function") {
              if (!parameter(evt)) {
                continue;
              }
            } else if (parameter && parameter !== evt.sourceEvent.keyCode) {
              if (!parameter.toLowerCase) {
                continue;
              }
              const lowerCase = parameter.toLowerCase();
              if (lowerCase !== evt.sourceEvent.key) {
                const unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
                const actualkey = String.fromCharCode(unicode).toLowerCase();
                if (actualkey !== lowerCase) {
                  continue;
                }
              }
            }
          }
        }
        action._executeCurrent(evt);
      }
    }
  }
  _getEffectiveTarget(target, propertyPath) {
    const properties = propertyPath.split(".");
    for (let index = 0;index < properties.length - 1; index++) {
      target = target[properties[index]];
    }
    return target;
  }
  _getProperty(propertyPath) {
    const properties = propertyPath.split(".");
    return properties[properties.length - 1];
  }
  serialize(name2) {
    const root = {
      children: new Array,
      name: name2,
      type: 3,
      properties: new Array
    };
    for (let i = 0;i < this.actions.length; i++) {
      const triggerObject = {
        type: 0,
        children: new Array,
        name: ActionManager.GetTriggerName(this.actions[i].trigger),
        properties: new Array
      };
      const triggerOptions = this.actions[i].triggerOptions;
      if (triggerOptions && typeof triggerOptions !== "number") {
        if (triggerOptions.parameter instanceof Node) {
          triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter));
        } else if (typeof triggerOptions.parameter === "object") {
          const parameter = {};
          DeepCopier.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
          if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
            parameter._meshId = triggerOptions.parameter.mesh.id;
          }
          triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
        } else {
          triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
        }
      }
      this.actions[i].serialize(triggerObject);
      root.children.push(triggerObject);
    }
    return root;
  }
  static Parse(parsedActions, object, scene) {
    const actionManager = new ActionManager(scene);
    if (object === null) {
      scene.actionManager = actionManager;
    } else {
      object.actionManager = actionManager;
    }
    const instantiate = (name2, params) => {
      const internalClassType = GetClass("BABYLON." + name2);
      return internalClassType && new internalClassType(...params);
    };
    const parseParameter = (name2, value, target, propertyPath) => {
      if (propertyPath === null) {
        const floatValue = parseFloat(value);
        if (value === "true" || value === "false") {
          return value === "true";
        } else {
          return isNaN(floatValue) ? value : floatValue;
        }
      }
      const effectiveTarget = propertyPath.split(".");
      const values = value.split(",");
      for (let i = 0;i < effectiveTarget.length; i++) {
        target = target[effectiveTarget[i]];
      }
      if (typeof target === "boolean") {
        return values[0] === "true";
      }
      if (typeof target === "string") {
        return values[0];
      }
      const split = [];
      for (let i = 0;i < values.length; i++) {
        split.push(parseFloat(values[i]));
      }
      if (target instanceof Vector3) {
        return Vector3.FromArray(split);
      }
      if (target instanceof Vector4) {
        return Vector4.FromArray(split);
      }
      if (target instanceof Color3) {
        return Color3.FromArray(split);
      }
      if (target instanceof Color4) {
        return Color4.FromArray(split);
      }
      return parseFloat(values[0]);
    };
    const traverse = (parsedAction, trigger, condition, action, combineArray = null) => {
      if (parsedAction.detached) {
        return;
      }
      const parameters = [];
      let target = null;
      let propertyPath = null;
      const combine = parsedAction.combine && parsedAction.combine.length > 0;
      if (parsedAction.type === 2) {
        parameters.push(actionManager);
      } else {
        parameters.push(trigger);
      }
      if (combine) {
        const actions = [];
        for (let j = 0;j < parsedAction.combine.length; j++) {
          traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
        }
        parameters.push(actions);
      } else {
        for (let i = 0;i < parsedAction.properties.length; i++) {
          let value = parsedAction.properties[i].value;
          const name2 = parsedAction.properties[i].name;
          const targetType = parsedAction.properties[i].targetType;
          if (name2 === "target") {
            if (targetType === "SceneProperties") {
              value = target = scene;
            } else if (targetType === "MaterialProperties") {
              value = target = scene.getMaterialByName(value);
            } else {
              value = target = scene.getNodeByName(value);
            }
          } else if (name2 === "parent") {
            value = scene.getNodeByName(value);
          } else if (name2 === "sound") {
            if (scene.getSoundByName) {
              value = scene.getSoundByName(value);
            }
          } else if (name2 !== "propertyPath") {
            if (parsedAction.type === 2 && name2 === "operator") {
              value = ValueCondition[value];
            } else {
              value = parseParameter(name2, value, target, name2 === "value" ? propertyPath : null);
            }
          } else {
            propertyPath = value;
          }
          parameters.push(value);
        }
      }
      if (combineArray === null) {
        parameters.push(condition);
      } else {
        parameters.push(null);
      }
      if (parsedAction.name === "InterpolateValueAction") {
        const param = parameters[parameters.length - 2];
        parameters[parameters.length - 1] = param;
        parameters[parameters.length - 2] = condition;
      }
      let newAction = instantiate(parsedAction.name, parameters);
      if (newAction instanceof Condition && condition !== null) {
        const nothing = new DoNothingAction(trigger, condition);
        if (action) {
          action.then(nothing);
        } else {
          actionManager.registerAction(nothing);
        }
        action = nothing;
      }
      if (combineArray === null) {
        if (newAction instanceof Condition) {
          condition = newAction;
          newAction = action;
        } else {
          condition = null;
          if (action) {
            action.then(newAction);
          } else {
            actionManager.registerAction(newAction);
          }
        }
      } else {
        combineArray.push(newAction);
      }
      for (let i = 0;i < parsedAction.children.length; i++) {
        traverse(parsedAction.children[i], trigger, condition, newAction, null);
      }
    };
    for (let i = 0;i < parsedActions.children.length; i++) {
      let triggerParams;
      const trigger = parsedActions.children[i];
      if (trigger.properties.length > 0) {
        const param = trigger.properties[0].value;
        const value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
        if (value._meshId) {
          value.mesh = scene.getMeshById(value._meshId);
        }
        triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
      } else {
        triggerParams = ActionManager[trigger.name];
      }
      for (let j = 0;j < trigger.children.length; j++) {
        if (!trigger.detached) {
          traverse(trigger.children[j], triggerParams, null, null);
        }
      }
    }
  }
  static GetTriggerName(trigger) {
    switch (trigger) {
      case 0:
        return "NothingTrigger";
      case 1:
        return "OnPickTrigger";
      case 2:
        return "OnLeftPickTrigger";
      case 3:
        return "OnRightPickTrigger";
      case 4:
        return "OnCenterPickTrigger";
      case 5:
        return "OnPickDownTrigger";
      case 6:
        return "OnDoublePickTrigger";
      case 7:
        return "OnPickUpTrigger";
      case 8:
        return "OnLongPressTrigger";
      case 9:
        return "OnPointerOverTrigger";
      case 10:
        return "OnPointerOutTrigger";
      case 11:
        return "OnEveryFrameTrigger";
      case 12:
        return "OnIntersectionEnterTrigger";
      case 13:
        return "OnIntersectionExitTrigger";
      case 14:
        return "OnKeyDownTrigger";
      case 15:
        return "OnKeyUpTrigger";
      case 16:
        return "OnPickOutTrigger";
      default:
        return "";
    }
  }
}
ActionManager.NothingTrigger = 0;
ActionManager.OnPickTrigger = 1;
ActionManager.OnLeftPickTrigger = 2;
ActionManager.OnRightPickTrigger = 3;
ActionManager.OnCenterPickTrigger = 4;
ActionManager.OnPickDownTrigger = 5;
ActionManager.OnDoublePickTrigger = 6;
ActionManager.OnPickUpTrigger = 7;
ActionManager.OnPickOutTrigger = 16;
ActionManager.OnLongPressTrigger = 8;
ActionManager.OnPointerOverTrigger = 9;
ActionManager.OnPointerOutTrigger = 10;
ActionManager.OnEveryFrameTrigger = 11;
ActionManager.OnIntersectionEnterTrigger = 12;
ActionManager.OnIntersectionExitTrigger = 13;
ActionManager.OnKeyDownTrigger = 14;
ActionManager.OnKeyUpTrigger = 15;
// node_modules/@babylonjs/core/Actions/directAudioActions.js
init_typeStore();

class PlaySoundAction extends Action {
  constructor(triggerOptions, sound, condition) {
    super(triggerOptions, condition);
    this._sound = sound;
  }
  _prepare() {}
  execute() {
    if (this._sound !== undefined) {
      this._sound.play();
    }
  }
  serialize(parent) {
    return super._serialize({
      name: "PlaySoundAction",
      properties: [{ name: "sound", value: this._sound.name }]
    }, parent);
  }
}

class StopSoundAction extends Action {
  constructor(triggerOptions, sound, condition) {
    super(triggerOptions, condition);
    this._sound = sound;
  }
  _prepare() {}
  execute() {
    if (this._sound !== undefined) {
      this._sound.stop();
    }
  }
  serialize(parent) {
    return super._serialize({
      name: "StopSoundAction",
      properties: [{ name: "sound", value: this._sound.name }]
    }, parent);
  }
}
RegisterClass("BABYLON.PlaySoundAction", PlaySoundAction);
RegisterClass("BABYLON.StopSoundAction", StopSoundAction);
// node_modules/@babylonjs/core/Actions/interpolateValueAction.js
init_logger();
init_observable();
init_math_color();
init_math_vector();
init_animation();
init_typeStore();

class InterpolateValueAction extends Action {
  constructor(triggerOptions, target, propertyPath, value, duration = 1000, condition, stopOtherAnimations, onInterpolationDone) {
    super(triggerOptions, condition);
    this.duration = 1000;
    this.onInterpolationDoneObservable = new Observable;
    this.propertyPath = propertyPath;
    this.value = value;
    this.duration = duration;
    this.stopOtherAnimations = stopOtherAnimations;
    this.onInterpolationDone = onInterpolationDone;
    this._target = this._effectiveTarget = target;
  }
  _prepare() {
    this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
    this._property = this._getProperty(this.propertyPath);
  }
  execute() {
    const scene = this._actionManager.getScene();
    const keys = [
      {
        frame: 0,
        value: this._effectiveTarget[this._property]
      },
      {
        frame: 100,
        value: this.value
      }
    ];
    let dataType;
    if (typeof this.value === "number") {
      dataType = Animation.ANIMATIONTYPE_FLOAT;
    } else if (this.value instanceof Color3) {
      dataType = Animation.ANIMATIONTYPE_COLOR3;
    } else if (this.value instanceof Vector3) {
      dataType = Animation.ANIMATIONTYPE_VECTOR3;
    } else if (this.value instanceof Matrix) {
      dataType = Animation.ANIMATIONTYPE_MATRIX;
    } else if (this.value instanceof Quaternion) {
      dataType = Animation.ANIMATIONTYPE_QUATERNION;
    } else {
      Logger.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
      return;
    }
    const animation = new Animation("InterpolateValueAction", this._property, 100 * (1000 / this.duration), dataType, Animation.ANIMATIONLOOPMODE_CONSTANT);
    animation.setKeys(keys);
    if (this.stopOtherAnimations) {
      scene.stopAnimation(this._effectiveTarget);
    }
    const wrapper = () => {
      this.onInterpolationDoneObservable.notifyObservers(this);
      if (this.onInterpolationDone) {
        this.onInterpolationDone();
      }
    };
    scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  }
  serialize(parent) {
    return super._serialize({
      name: "InterpolateValueAction",
      properties: [
        Action._GetTargetProperty(this._target),
        { name: "propertyPath", value: this.propertyPath },
        { name: "value", value: Action._SerializeValueAsString(this.value) },
        { name: "duration", value: Action._SerializeValueAsString(this.duration) },
        { name: "stopOtherAnimations", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false }
      ]
    }, parent);
  }
}
RegisterClass("BABYLON.InterpolateValueAction", InterpolateValueAction);
// node_modules/@babylonjs/core/Animations/index.js
init_animatable();
init_animation();

// node_modules/@babylonjs/core/Animations/animationPropertiesOverride.js
init_animation();

// node_modules/@babylonjs/core/Animations/index.js
init_easing();
init_runtimeAnimation();
init_animationGroup();

// node_modules/@babylonjs/core/Animations/animationKey.js
var AnimationKeyInterpolation;
(function(AnimationKeyInterpolation2) {
  AnimationKeyInterpolation2[AnimationKeyInterpolation2["NONE"] = 0] = "NONE";
  AnimationKeyInterpolation2[AnimationKeyInterpolation2["STEP"] = 1] = "STEP";
})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {}));
// node_modules/@babylonjs/core/Animations/pathCursor.js
init_math_vector();
// node_modules/@babylonjs/core/Animations/animationGroupMask.js
var AnimationGroupMaskMode;
(function(AnimationGroupMaskMode2) {
  AnimationGroupMaskMode2[AnimationGroupMaskMode2["Include"] = 0] = "Include";
  AnimationGroupMaskMode2[AnimationGroupMaskMode2["Exclude"] = 1] = "Exclude";
})(AnimationGroupMaskMode || (AnimationGroupMaskMode = {}));
// node_modules/@babylonjs/core/Meshes/mesh.js
init_observable();
init_tools();
init_deepCopier();
init_tags();

// node_modules/@babylonjs/core/Misc/coroutine.js
function inlineScheduler(coroutine, onStep, onError) {
  try {
    const step = coroutine.next();
    if (step.done) {
      onStep(step);
    } else if (!step.value) {
      onStep(step);
    } else {
      step.value.then(() => {
        step.value = undefined;
        onStep(step);
      }, onError);
    }
  } catch (error) {
    onError(error);
  }
}
function createYieldingScheduler(yieldAfterMS = 25) {
  let startTime;
  return (coroutine, onStep, onError) => {
    const currentTime = performance.now();
    if (startTime === undefined || currentTime - startTime > yieldAfterMS) {
      startTime = currentTime;
      setTimeout(() => {
        inlineScheduler(coroutine, onStep, onError);
      }, 0);
    } else {
      inlineScheduler(coroutine, onStep, onError);
    }
  };
}
function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) {
  const resume = () => {
    let reschedule;
    const onStep = (stepResult) => {
      if (stepResult.done) {
        onSuccess(stepResult.value);
      } else {
        if (reschedule === undefined) {
          reschedule = true;
        } else {
          resume();
        }
      }
    };
    do {
      reschedule = undefined;
      if (!abortSignal || !abortSignal.aborted) {
        scheduler(coroutine, onStep, onError);
      } else {
        onError(new Error("Aborted"));
      }
      if (reschedule === undefined) {
        reschedule = false;
      }
    } while (reschedule);
  };
  resume();
}
function runCoroutineSync(coroutine, abortSignal) {
  let result;
  runCoroutine(coroutine, inlineScheduler, (r) => result = r, (e) => {
    throw e;
  }, abortSignal);
  return result;
}
function runCoroutineAsync(coroutine, scheduler, abortSignal) {
  return new Promise((resolve3, reject) => {
    runCoroutine(coroutine, scheduler, resolve3, reject, abortSignal);
  });
}
function makeSyncFunction(coroutineFactory, abortSignal) {
  return (...params) => {
    return runCoroutineSync(coroutineFactory(...params), abortSignal);
  };
}

// node_modules/@babylonjs/core/Cameras/camera.js
init_tslib_es6();
init_decorators();
init_smartArray();
init_tools();
init_observable();
init_math_vector();
init_node();
init_logger();
init_typeStore();
init_devTools();
init_math_frustum();
init_decorators_serialization();

class Camera extends Node2 {
  get position() {
    return this._position;
  }
  set position(newPosition) {
    this._position = newPosition;
  }
  set upVector(vec) {
    this._upVector = vec;
  }
  get upVector() {
    return this._upVector;
  }
  get screenArea() {
    let x = 0;
    let y = 0;
    if (this.mode === Camera.PERSPECTIVE_CAMERA) {
      if (this.fovMode === Camera.FOVMODE_VERTICAL_FIXED) {
        y = this.minZ * 2 * Math.tan(this.fov / 2);
        x = this.getEngine().getAspectRatio(this) * y;
      } else {
        x = this.minZ * 2 * Math.tan(this.fov / 2);
        y = x / this.getEngine().getAspectRatio(this);
      }
    } else {
      const halfWidth = this.getEngine().getRenderWidth() / 2;
      const halfHeight = this.getEngine().getRenderHeight() / 2;
      x = (this.orthoRight ?? halfWidth) - (this.orthoLeft ?? -halfWidth);
      y = (this.orthoTop ?? halfHeight) - (this.orthoBottom ?? -halfHeight);
    }
    return x * y;
  }
  set orthoLeft(value) {
    this._orthoLeft = value;
    for (const rigCamera of this._rigCameras) {
      rigCamera.orthoLeft = value;
    }
  }
  get orthoLeft() {
    return this._orthoLeft;
  }
  set orthoRight(value) {
    this._orthoRight = value;
    for (const rigCamera of this._rigCameras) {
      rigCamera.orthoRight = value;
    }
  }
  get orthoRight() {
    return this._orthoRight;
  }
  set orthoBottom(value) {
    this._orthoBottom = value;
    for (const rigCamera of this._rigCameras) {
      rigCamera.orthoBottom = value;
    }
  }
  get orthoBottom() {
    return this._orthoBottom;
  }
  set orthoTop(value) {
    this._orthoTop = value;
    for (const rigCamera of this._rigCameras) {
      rigCamera.orthoTop = value;
    }
  }
  get orthoTop() {
    return this._orthoTop;
  }
  set mode(mode) {
    this._mode = mode;
    for (const rigCamera of this._rigCameras) {
      rigCamera.mode = mode;
    }
  }
  get mode() {
    return this._mode;
  }
  get hasMoved() {
    return this._hasMoved;
  }
  constructor(name18, position, scene, setActiveOnSceneIfNoneActive = true) {
    super(name18, scene, false);
    this._position = Vector3.Zero();
    this._upVector = Vector3.Up();
    this.oblique = null;
    this._orthoLeft = null;
    this._orthoRight = null;
    this._orthoBottom = null;
    this._orthoTop = null;
    this.fov = 0.8;
    this.projectionPlaneTilt = 0;
    this.minZ = 1;
    this.maxZ = 1e4;
    this.inertia = 0.9;
    this._mode = Camera.PERSPECTIVE_CAMERA;
    this.isIntermediate = false;
    this.viewport = new Viewport(0, 0, 1, 1);
    this.layerMask = 268435455;
    this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
    this.cameraRigMode = Camera.RIG_MODE_NONE;
    this.customRenderTargets = [];
    this.outputRenderTarget = null;
    this.onViewMatrixChangedObservable = new Observable;
    this.onProjectionMatrixChangedObservable = new Observable;
    this.onAfterCheckInputsObservable = new Observable;
    this.onRestoreStateObservable = new Observable;
    this.isRigCamera = false;
    this._hasMoved = false;
    this._rigCameras = new Array;
    this._skipRendering = false;
    this._projectionMatrix = new Matrix;
    this._postProcesses = new Array;
    this._activeMeshes = new SmartArray(256);
    this._globalPosition = Vector3.Zero();
    this._computedViewMatrix = Matrix.Identity();
    this._doNotComputeProjectionMatrix = false;
    this._transformMatrix = Matrix.Zero();
    this._refreshFrustumPlanes = true;
    this._absoluteRotation = Quaternion.Identity();
    this._isCamera = true;
    this._isLeftCamera = false;
    this._isRightCamera = false;
    this.getScene().addCamera(this);
    if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {
      this.getScene().activeCamera = this;
    }
    this.position = position;
    this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name18}`);
  }
  storeState() {
    this._stateStored = true;
    this._storedFov = this.fov;
    return this;
  }
  hasStateStored() {
    return !!this._stateStored;
  }
  _restoreStateValues() {
    if (!this._stateStored) {
      return false;
    }
    this.fov = this._storedFov;
    return true;
  }
  restoreState() {
    if (this._restoreStateValues()) {
      this.onRestoreStateObservable.notifyObservers(this);
      return true;
    }
    return false;
  }
  getClassName() {
    return "Camera";
  }
  toString(fullDetails) {
    let ret = "Name: " + this.name;
    ret += ", type: " + this.getClassName();
    if (this.animations) {
      for (let i = 0;i < this.animations.length; i++) {
        ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
      }
    }
    return ret;
  }
  applyVerticalCorrection() {
    const rot = this.absoluteRotation.toEulerAngles();
    this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x;
  }
  get globalPosition() {
    return this._globalPosition;
  }
  getActiveMeshes() {
    return this._activeMeshes;
  }
  isActiveMesh(mesh) {
    return this._activeMeshes.indexOf(mesh) !== -1;
  }
  isReady(completeCheck = false) {
    if (completeCheck) {
      for (const pp of this._postProcesses) {
        if (pp && !pp.isReady()) {
          return false;
        }
      }
    }
    return super.isReady(completeCheck);
  }
  _initCache() {
    super._initCache();
    this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cache.mode = undefined;
    this._cache.minZ = undefined;
    this._cache.maxZ = undefined;
    this._cache.fov = undefined;
    this._cache.fovMode = undefined;
    this._cache.aspectRatio = undefined;
    this._cache.orthoLeft = undefined;
    this._cache.orthoRight = undefined;
    this._cache.orthoBottom = undefined;
    this._cache.orthoTop = undefined;
    this._cache.obliqueAngle = undefined;
    this._cache.obliqueLength = undefined;
    this._cache.obliqueOffset = undefined;
    this._cache.renderWidth = undefined;
    this._cache.renderHeight = undefined;
  }
  _updateCache(ignoreParentClass) {
    if (!ignoreParentClass) {
      super._updateCache();
    }
    this._cache.position.copyFrom(this.position);
    this._cache.upVector.copyFrom(this.upVector);
  }
  _isSynchronized() {
    return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  }
  _isSynchronizedViewMatrix() {
    if (!super._isSynchronized()) {
      return false;
    }
    return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  }
  _isSynchronizedProjectionMatrix() {
    let isSynchronized = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
    if (!isSynchronized) {
      return false;
    }
    const engine = this.getEngine();
    if (this.mode === Camera.PERSPECTIVE_CAMERA) {
      isSynchronized = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === engine.getAspectRatio(this) && this._cache.projectionPlaneTilt === this.projectionPlaneTilt;
    } else {
      isSynchronized = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
      if (this.oblique) {
        isSynchronized = isSynchronized && this._cache.obliqueAngle === this.oblique.angle && this._cache.obliqueLength === this.oblique.length && this._cache.obliqueOffset === this.oblique.offset;
      }
    }
    return isSynchronized;
  }
  attachControl(_ignored, _noPreventDefault) {}
  detachControl(_ignored) {}
  update() {
    this._hasMoved = false;
    this._checkInputs();
    if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
      this._updateRigCameras();
    }
    this.getViewMatrix();
    this.getProjectionMatrix();
  }
  _checkInputs() {
    this.onAfterCheckInputsObservable.notifyObservers(this);
  }
  get rigCameras() {
    return this._rigCameras;
  }
  get rigPostProcess() {
    return this._rigPostProcess;
  }
  _getFirstPostProcess() {
    for (let ppIndex = 0;ppIndex < this._postProcesses.length; ppIndex++) {
      if (this._postProcesses[ppIndex] !== null) {
        return this._postProcesses[ppIndex];
      }
    }
    return null;
  }
  _cascadePostProcessesToRigCams() {
    const firstPostProcess = this._getFirstPostProcess();
    if (firstPostProcess) {
      firstPostProcess.markTextureDirty();
    }
    for (let i = 0, len = this._rigCameras.length;i < len; i++) {
      const cam = this._rigCameras[i];
      const rigPostProcess = cam._rigPostProcess;
      if (rigPostProcess) {
        const isPass = rigPostProcess.getEffectName() === "pass";
        if (isPass) {
          cam.isIntermediate = this._postProcesses.length === 0;
        }
        cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
        rigPostProcess.markTextureDirty();
      } else {
        cam._postProcesses = this._postProcesses.slice(0);
      }
    }
  }
  attachPostProcess(postProcess, insertAt = null) {
    if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
      Logger.Error("You're trying to reuse a post process not defined as reusable.");
      return 0;
    }
    if (insertAt == null || insertAt < 0) {
      this._postProcesses.push(postProcess);
    } else if (this._postProcesses[insertAt] === null) {
      this._postProcesses[insertAt] = postProcess;
    } else {
      this._postProcesses.splice(insertAt, 0, postProcess);
    }
    this._cascadePostProcessesToRigCams();
    if (this._scene.prePassRenderer) {
      this._scene.prePassRenderer.markAsDirty();
    }
    return this._postProcesses.indexOf(postProcess);
  }
  detachPostProcess(postProcess) {
    const idx = this._postProcesses.indexOf(postProcess);
    if (idx !== -1) {
      this._postProcesses[idx] = null;
    }
    if (this._scene.prePassRenderer) {
      this._scene.prePassRenderer.markAsDirty();
    }
    this._cascadePostProcessesToRigCams();
  }
  getWorldMatrix() {
    if (this._isSynchronizedViewMatrix()) {
      return this._worldMatrix;
    }
    this.getViewMatrix();
    return this._worldMatrix;
  }
  _getViewMatrix() {
    return Matrix.Identity();
  }
  getViewMatrix(force) {
    if (!force && this._isSynchronizedViewMatrix()) {
      return this._computedViewMatrix;
    }
    this._hasMoved = true;
    this.updateCache();
    this._computedViewMatrix = this._getViewMatrix();
    this._currentRenderId = this.getScene().getRenderId();
    this._childUpdateId++;
    this._refreshFrustumPlanes = true;
    if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
      this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
    }
    if (this.parent && this.parent.onViewMatrixChangedObservable) {
      this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent);
    }
    this.onViewMatrixChangedObservable.notifyObservers(this);
    this._computedViewMatrix.invertToRef(this._worldMatrix);
    return this._computedViewMatrix;
  }
  freezeProjectionMatrix(projection) {
    this._doNotComputeProjectionMatrix = true;
    if (projection !== undefined) {
      this._projectionMatrix = projection;
    }
  }
  unfreezeProjectionMatrix() {
    this._doNotComputeProjectionMatrix = false;
  }
  getProjectionMatrix(force) {
    if (this._doNotComputeProjectionMatrix || !force && this._isSynchronizedProjectionMatrix()) {
      return this._projectionMatrix;
    }
    this._cache.mode = this.mode;
    this._cache.minZ = this.minZ;
    this._cache.maxZ = this.maxZ;
    this._refreshFrustumPlanes = true;
    const engine = this.getEngine();
    const scene = this.getScene();
    const reverseDepth = engine.useReverseDepthBuffer;
    if (this.mode === Camera.PERSPECTIVE_CAMERA) {
      this._cache.fov = this.fov;
      this._cache.fovMode = this.fovMode;
      this._cache.aspectRatio = engine.getAspectRatio(this);
      this._cache.projectionPlaneTilt = this.projectionPlaneTilt;
      if (this.minZ <= 0) {
        this.minZ = 0.1;
      }
      let getProjectionMatrix;
      if (scene.useRightHandedSystem) {
        getProjectionMatrix = Matrix.PerspectiveFovRHToRef;
      } else {
        getProjectionMatrix = Matrix.PerspectiveFovLHToRef;
      }
      getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth);
    } else {
      const halfWidth = engine.getRenderWidth() / 2;
      const halfHeight = engine.getRenderHeight() / 2;
      if (scene.useRightHandedSystem) {
        if (this.oblique) {
          Matrix.ObliqueOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange);
        } else {
          Matrix.OrthoOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);
        }
      } else {
        if (this.oblique) {
          Matrix.ObliqueOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange);
        } else {
          Matrix.OrthoOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);
        }
      }
      this._cache.orthoLeft = this.orthoLeft;
      this._cache.orthoRight = this.orthoRight;
      this._cache.orthoBottom = this.orthoBottom;
      this._cache.orthoTop = this.orthoTop;
      this._cache.obliqueAngle = this.oblique?.angle;
      this._cache.obliqueLength = this.oblique?.length;
      this._cache.obliqueOffset = this.oblique?.offset;
      this._cache.renderWidth = engine.getRenderWidth();
      this._cache.renderHeight = engine.getRenderHeight();
    }
    this.onProjectionMatrixChangedObservable.notifyObservers(this);
    return this._projectionMatrix;
  }
  getTransformationMatrix() {
    this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
    return this._transformMatrix;
  }
  _computeObliqueDistance(offset) {
    const arcRotateCamera = this;
    const targetCamera = this;
    return (arcRotateCamera.radius || (targetCamera.target ? Vector3.Distance(this.position, targetCamera.target) : this.position.length())) + offset;
  }
  _updateFrustumPlanes() {
    if (!this._refreshFrustumPlanes) {
      return;
    }
    this.getTransformationMatrix();
    if (!this._frustumPlanes) {
      this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
    } else {
      Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
    }
    this._refreshFrustumPlanes = false;
  }
  isInFrustum(target, checkRigCameras = false) {
    this._updateFrustumPlanes();
    if (checkRigCameras && this.rigCameras.length > 0) {
      let result = false;
      this.rigCameras.forEach((cam) => {
        cam._updateFrustumPlanes();
        result = result || target.isInFrustum(cam._frustumPlanes);
      });
      return result;
    } else {
      return target.isInFrustum(this._frustumPlanes);
    }
  }
  isCompletelyInFrustum(target) {
    this._updateFrustumPlanes();
    return target.isCompletelyInFrustum(this._frustumPlanes);
  }
  getForwardRay(length = 100, transform, origin) {
    throw _WarnImport("Ray");
  }
  getForwardRayToRef(refRay, length = 100, transform, origin) {
    throw _WarnImport("Ray");
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this.onViewMatrixChangedObservable.clear();
    this.onProjectionMatrixChangedObservable.clear();
    this.onAfterCheckInputsObservable.clear();
    this.onRestoreStateObservable.clear();
    if (this.inputs) {
      this.inputs.clear();
    }
    this.getScene().stopAnimation(this);
    this.getScene().removeCamera(this);
    while (this._rigCameras.length > 0) {
      const camera = this._rigCameras.pop();
      if (camera) {
        camera.dispose();
      }
    }
    if (this._parentContainer) {
      const index = this._parentContainer.cameras.indexOf(this);
      if (index > -1) {
        this._parentContainer.cameras.splice(index, 1);
      }
      this._parentContainer = null;
    }
    if (this._rigPostProcess) {
      this._rigPostProcess.dispose(this);
      this._rigPostProcess = null;
      this._postProcesses.length = 0;
    } else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
      this._rigPostProcess = null;
      this._postProcesses.length = 0;
    } else {
      let i2 = this._postProcesses.length;
      while (--i2 >= 0) {
        const postProcess = this._postProcesses[i2];
        if (postProcess) {
          postProcess.dispose(this);
        }
      }
    }
    let i = this.customRenderTargets.length;
    while (--i >= 0) {
      this.customRenderTargets[i].dispose();
    }
    this.customRenderTargets.length = 0;
    this._activeMeshes.dispose();
    this.getScene().getEngine().releaseRenderPassId(this.renderPassId);
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  get isLeftCamera() {
    return this._isLeftCamera;
  }
  get isRightCamera() {
    return this._isRightCamera;
  }
  get leftCamera() {
    if (this._rigCameras.length < 1) {
      return null;
    }
    return this._rigCameras[0];
  }
  get rightCamera() {
    if (this._rigCameras.length < 2) {
      return null;
    }
    return this._rigCameras[1];
  }
  getLeftTarget() {
    if (this._rigCameras.length < 1) {
      return null;
    }
    return this._rigCameras[0].getTarget();
  }
  getRightTarget() {
    if (this._rigCameras.length < 2) {
      return null;
    }
    return this._rigCameras[1].getTarget();
  }
  setCameraRigMode(mode, rigParams) {
    if (this.cameraRigMode === mode) {
      return;
    }
    while (this._rigCameras.length > 0) {
      const camera = this._rigCameras.pop();
      if (camera) {
        camera.dispose();
      }
    }
    this.cameraRigMode = mode;
    this._cameraRigParams = {};
    this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
    this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
    if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
      const leftCamera = this.createRigCamera(this.name + "_L", 0);
      if (leftCamera) {
        leftCamera._isLeftCamera = true;
      }
      const rightCamera = this.createRigCamera(this.name + "_R", 1);
      if (rightCamera) {
        rightCamera._isRightCamera = true;
      }
      if (leftCamera && rightCamera) {
        this._rigCameras.push(leftCamera);
        this._rigCameras.push(rightCamera);
      }
    }
    this._setRigMode(rigParams);
    this._cascadePostProcessesToRigCams();
    this.update();
  }
  _setRigMode(rigParams) {}
  _getVRProjectionMatrix() {
    Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange);
    this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
    return this._projectionMatrix;
  }
  setCameraRigParameter(name18, value) {
    if (!this._cameraRigParams) {
      this._cameraRigParams = {};
    }
    this._cameraRigParams[name18] = value;
    if (name18 === "interaxialDistance") {
      this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);
    }
  }
  createRigCamera(name18, cameraIndex) {
    return null;
  }
  _updateRigCameras() {
    for (let i = 0;i < this._rigCameras.length; i++) {
      this._rigCameras[i].minZ = this.minZ;
      this._rigCameras[i].maxZ = this.maxZ;
      this._rigCameras[i].fov = this.fov;
      this._rigCameras[i].upVector.copyFrom(this.upVector);
    }
    if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
      this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
    }
  }
  _setupInputs() {}
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.type = this.getClassName();
    if (this.parent) {
      this.parent._serializeAsParent(serializationObject);
    }
    if (this.inputs) {
      this.inputs.serialize(serializationObject);
    }
    SerializationHelper.AppendSerializedAnimations(this, serializationObject);
    serializationObject.ranges = this.serializeAnimationRanges();
    serializationObject.isEnabled = this.isEnabled();
    return serializationObject;
  }
  clone(name18, newParent = null) {
    const camera = SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name18, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
    camera.name = name18;
    camera.parent = newParent;
    this.onClonedObservable.notifyObservers(camera);
    return camera;
  }
  getDirection(localAxis) {
    const result = Vector3.Zero();
    this.getDirectionToRef(localAxis, result);
    return result;
  }
  get absoluteRotation() {
    this.getWorldMatrix().decompose(undefined, this._absoluteRotation);
    return this._absoluteRotation;
  }
  getDirectionToRef(localAxis, result) {
    Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  }
  static GetConstructorFromName(type, name18, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) {
    const constructorFunc = Node2.Construct(type, name18, scene, {
      interaxial_distance,
      isStereoscopicSideBySide
    });
    if (constructorFunc) {
      return constructorFunc;
    }
    return () => Camera._CreateDefaultParsedCamera(name18, scene);
  }
  computeWorldMatrix() {
    return this.getWorldMatrix();
  }
  static Parse(parsedCamera, scene) {
    const type = parsedCamera.type;
    const construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
    const camera = SerializationHelper.Parse(construct, parsedCamera, scene);
    if (parsedCamera.parentId !== undefined) {
      camera._waitingParentId = parsedCamera.parentId;
    }
    if (parsedCamera.parentInstanceIndex !== undefined) {
      camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex;
    }
    if (camera.inputs) {
      camera.inputs.parse(parsedCamera);
      camera._setupInputs();
    }
    if (parsedCamera.upVector) {
      camera.upVector = Vector3.FromArray(parsedCamera.upVector);
    }
    if (camera.setPosition) {
      camera.position.copyFromFloats(0, 0, 0);
      camera.setPosition(Vector3.FromArray(parsedCamera.position));
    }
    if (parsedCamera.target) {
      if (camera.setTarget) {
        camera.setTarget(Vector3.FromArray(parsedCamera.target));
      }
    }
    if (parsedCamera.cameraRigMode) {
      const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
      camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
    }
    if (parsedCamera.animations) {
      for (let animationIndex = 0;animationIndex < parsedCamera.animations.length; animationIndex++) {
        const parsedAnimation = parsedCamera.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          camera.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
      Node2.ParseAnimationRanges(camera, parsedCamera, scene);
    }
    if (parsedCamera.autoAnimate) {
      scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1);
    }
    if (parsedCamera.isEnabled !== undefined) {
      camera.setEnabled(parsedCamera.isEnabled);
    }
    return camera;
  }
  _calculateHandednessMultiplier() {
    let handednessMultiplier = this.getScene().useRightHandedSystem ? -1 : 1;
    if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
      handednessMultiplier *= -1;
    }
    return handednessMultiplier;
  }
}
Camera._CreateDefaultParsedCamera = (name18, scene) => {
  throw _WarnImport("UniversalCamera");
};
Camera.PERSPECTIVE_CAMERA = 0;
Camera.ORTHOGRAPHIC_CAMERA = 1;
Camera.FOVMODE_VERTICAL_FIXED = 0;
Camera.FOVMODE_HORIZONTAL_FIXED = 1;
Camera.RIG_MODE_NONE = 0;
Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
Camera.RIG_MODE_VR = 20;
Camera.RIG_MODE_CUSTOM = 22;
Camera.ForceAttachControlToAlwaysPreventDefault = false;
__decorate([
  serializeAsVector3("position")
], Camera.prototype, "_position", undefined);
__decorate([
  serializeAsVector3("upVector")
], Camera.prototype, "_upVector", undefined);
__decorate([
  serialize()
], Camera.prototype, "orthoLeft", null);
__decorate([
  serialize()
], Camera.prototype, "orthoRight", null);
__decorate([
  serialize()
], Camera.prototype, "orthoBottom", null);
__decorate([
  serialize()
], Camera.prototype, "orthoTop", null);
__decorate([
  serialize()
], Camera.prototype, "fov", undefined);
__decorate([
  serialize()
], Camera.prototype, "projectionPlaneTilt", undefined);
__decorate([
  serialize()
], Camera.prototype, "minZ", undefined);
__decorate([
  serialize()
], Camera.prototype, "maxZ", undefined);
__decorate([
  serialize()
], Camera.prototype, "inertia", undefined);
__decorate([
  serialize()
], Camera.prototype, "mode", null);
__decorate([
  serialize()
], Camera.prototype, "layerMask", undefined);
__decorate([
  serialize()
], Camera.prototype, "fovMode", undefined);
__decorate([
  serialize()
], Camera.prototype, "cameraRigMode", undefined);
__decorate([
  serialize()
], Camera.prototype, "interaxialDistance", undefined);
__decorate([
  serialize()
], Camera.prototype, "isStereoscopicSideBySide", undefined);

// node_modules/@babylonjs/core/Meshes/mesh.js
init_math_vector();
init_math_color();
init_node();
init_buffer();

// node_modules/@babylonjs/core/Meshes/mesh.vertexData.js
init_tslib_es6();
init_math_vector();
init_buffer();
init_devTools();
init_math_color();
init_logger();
init_decorators();
init_error();

// node_modules/@babylonjs/core/Meshes/subMesh.js
init_buffer();

// node_modules/@babylonjs/core/Collisions/intersectionInfo.js
class IntersectionInfo {
  constructor(bu, bv, distance) {
    this.bu = bu;
    this.bv = bv;
    this.distance = distance;
    this.faceId = 0;
    this.subMeshId = 0;
  }
}

// node_modules/@babylonjs/core/Culling/boundingInfo.js
init_arrayTools();
init_math_vector();
init_math_vector();

// node_modules/@babylonjs/core/Culling/boundingBox.js
init_arrayTools();
init_math_vector();
init_math_constants();

class BoundingBox {
  constructor(min, max, worldMatrix) {
    this.vectors = BuildArray(8, Vector3.Zero);
    this.center = Vector3.Zero();
    this.centerWorld = Vector3.Zero();
    this.extendSize = Vector3.Zero();
    this.extendSizeWorld = Vector3.Zero();
    this.directions = BuildArray(3, Vector3.Zero);
    this.vectorsWorld = BuildArray(8, Vector3.Zero);
    this.minimumWorld = Vector3.Zero();
    this.maximumWorld = Vector3.Zero();
    this.minimum = Vector3.Zero();
    this.maximum = Vector3.Zero();
    this._drawWrapperFront = null;
    this._drawWrapperBack = null;
    this.reConstruct(min, max, worldMatrix);
  }
  reConstruct(min, max, worldMatrix) {
    const { x: minX, y: minY, z: minZ } = min, maxX = max.x, maxY = max.y, maxZ = max.z;
    const vectors = this.vectors;
    this.minimum.copyFromFloats(minX, minY, minZ);
    this.maximum.copyFromFloats(maxX, maxY, maxZ);
    vectors[0].copyFromFloats(minX, minY, minZ);
    vectors[1].copyFromFloats(maxX, maxY, maxZ);
    vectors[2].copyFromFloats(maxX, minY, minZ);
    vectors[3].copyFromFloats(minX, maxY, minZ);
    vectors[4].copyFromFloats(minX, minY, maxZ);
    vectors[5].copyFromFloats(maxX, maxY, minZ);
    vectors[6].copyFromFloats(minX, maxY, maxZ);
    vectors[7].copyFromFloats(maxX, minY, maxZ);
    max.addToRef(min, this.center).scaleInPlace(0.5);
    max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
    this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly;
    this._update(this._worldMatrix);
  }
  scale(factor) {
    const tmpVectors = BoundingBox._TmpVector3;
    const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
    const len = diff.length();
    diff.normalizeFromLength(len);
    const distance = len * factor;
    const newRadius = diff.scaleInPlace(distance * 0.5);
    const min = this.center.subtractToRef(newRadius, tmpVectors[1]);
    const max = this.center.addToRef(newRadius, tmpVectors[2]);
    this.reConstruct(min, max, this._worldMatrix);
    return this;
  }
  getWorldMatrix() {
    return this._worldMatrix;
  }
  _update(world) {
    const minWorld = this.minimumWorld;
    const maxWorld = this.maximumWorld;
    const directions = this.directions;
    const vectorsWorld = this.vectorsWorld;
    const vectors = this.vectors;
    if (!world.isIdentity()) {
      minWorld.setAll(Number.MAX_VALUE);
      maxWorld.setAll(-Number.MAX_VALUE);
      for (let index = 0;index < 8; ++index) {
        const v = vectorsWorld[index];
        Vector3.TransformCoordinatesToRef(vectors[index], world, v);
        minWorld.minimizeInPlace(v);
        maxWorld.maximizeInPlace(v);
      }
      maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
      maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
    } else {
      minWorld.copyFrom(this.minimum);
      maxWorld.copyFrom(this.maximum);
      for (let index = 0;index < 8; ++index) {
        vectorsWorld[index].copyFrom(vectors[index]);
      }
      this.extendSizeWorld.copyFrom(this.extendSize);
      this.centerWorld.copyFrom(this.center);
    }
    Vector3.FromArrayToRef(world.m, 0, directions[0]);
    Vector3.FromArrayToRef(world.m, 4, directions[1]);
    Vector3.FromArrayToRef(world.m, 8, directions[2]);
    this._worldMatrix = world;
  }
  isInFrustum(frustumPlanes) {
    return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  }
  isCompletelyInFrustum(frustumPlanes) {
    return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  }
  intersectsPoint(point) {
    const min = this.minimumWorld;
    const max = this.maximumWorld;
    const { x: minX, y: minY, z: minZ } = min, maxX = max.x, maxY = max.y, maxZ = max.z;
    const { x: pointX, y: pointY, z: pointZ } = point;
    const delta = -Epsilon;
    if (maxX - pointX < delta || delta > pointX - minX) {
      return false;
    }
    if (maxY - pointY < delta || delta > pointY - minY) {
      return false;
    }
    if (maxZ - pointZ < delta || delta > pointZ - minZ) {
      return false;
    }
    return true;
  }
  intersectsSphere(sphere) {
    return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  }
  intersectsMinMax(min, max) {
    const myMin = this.minimumWorld;
    const myMax = this.maximumWorld;
    const { x: myMinX, y: myMinY, z: myMinZ } = myMin, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
    const { x: minX, y: minY, z: minZ } = min, maxX = max.x, maxY = max.y, maxZ = max.z;
    if (myMaxX < minX || myMinX > maxX) {
      return false;
    }
    if (myMaxY < minY || myMinY > maxY) {
      return false;
    }
    if (myMaxZ < minZ || myMinZ > maxZ) {
      return false;
    }
    return true;
  }
  dispose() {
    this._drawWrapperFront?.dispose();
    this._drawWrapperBack?.dispose();
  }
  static Intersects(box0, box1) {
    return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  }
  static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) {
    const vector = BoundingBox._TmpVector3[0];
    Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
    const num = Vector3.DistanceSquared(sphereCenter, vector);
    return num <= sphereRadius * sphereRadius;
  }
  static IsCompletelyInFrustum(boundingVectors, frustumPlanes) {
    for (let p = 0;p < 6; ++p) {
      const frustumPlane = frustumPlanes[p];
      for (let i = 0;i < 8; ++i) {
        if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
          return false;
        }
      }
    }
    return true;
  }
  static IsInFrustum(boundingVectors, frustumPlanes) {
    for (let p = 0;p < 6; ++p) {
      let canReturnFalse = true;
      const frustumPlane = frustumPlanes[p];
      for (let i = 0;i < 8; ++i) {
        if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
          canReturnFalse = false;
          break;
        }
      }
      if (canReturnFalse) {
        return false;
      }
    }
    return true;
  }
}
BoundingBox._TmpVector3 = BuildArray(3, Vector3.Zero);

// node_modules/@babylonjs/core/Culling/boundingSphere.js
init_arrayTools();
init_math_vector();

class BoundingSphere {
  constructor(min, max, worldMatrix) {
    this.center = Vector3.Zero();
    this.centerWorld = Vector3.Zero();
    this.minimum = Vector3.Zero();
    this.maximum = Vector3.Zero();
    this.reConstruct(min, max, worldMatrix);
  }
  reConstruct(min, max, worldMatrix) {
    this.minimum.copyFrom(min);
    this.maximum.copyFrom(max);
    const distance = Vector3.Distance(min, max);
    max.addToRef(min, this.center).scaleInPlace(0.5);
    this.radius = distance * 0.5;
    this._update(worldMatrix || Matrix.IdentityReadOnly);
  }
  scale(factor) {
    const newRadius = this.radius * factor;
    const tmpVectors = BoundingSphere._TmpVector3;
    const tempRadiusVector = tmpVectors[0].setAll(newRadius);
    const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
    const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
    this.reConstruct(min, max, this._worldMatrix);
    return this;
  }
  getWorldMatrix() {
    return this._worldMatrix;
  }
  _update(worldMatrix) {
    if (!worldMatrix.isIdentity()) {
      Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
      const tempVector = BoundingSphere._TmpVector3[0];
      Vector3.TransformNormalFromFloatsToRef(1, 1, 1, worldMatrix, tempVector);
      this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
    } else {
      this.centerWorld.copyFrom(this.center);
      this.radiusWorld = this.radius;
    }
  }
  isInFrustum(frustumPlanes) {
    const center = this.centerWorld;
    const radius = this.radiusWorld;
    for (let i = 0;i < 6; i++) {
      if (frustumPlanes[i].dotCoordinate(center) <= -radius) {
        return false;
      }
    }
    return true;
  }
  isCenterInFrustum(frustumPlanes) {
    const center = this.centerWorld;
    for (let i = 0;i < 6; i++) {
      if (frustumPlanes[i].dotCoordinate(center) < 0) {
        return false;
      }
    }
    return true;
  }
  intersectsPoint(point) {
    const squareDistance = Vector3.DistanceSquared(this.centerWorld, point);
    if (this.radiusWorld * this.radiusWorld < squareDistance) {
      return false;
    }
    return true;
  }
  static Intersects(sphere0, sphere1) {
    const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
    const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
    if (radiusSum * radiusSum < squareDistance) {
      return false;
    }
    return true;
  }
  static CreateFromCenterAndRadius(center, radius, matrix) {
    this._TmpVector3[0].copyFrom(center);
    this._TmpVector3[1].copyFromFloats(0, 0, radius);
    this._TmpVector3[2].copyFrom(center);
    this._TmpVector3[0].addInPlace(this._TmpVector3[1]);
    this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);
    const sphere = new BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]);
    if (matrix) {
      sphere._worldMatrix = matrix;
    } else {
      sphere._worldMatrix = Matrix.Identity();
    }
    return sphere;
  }
}
BoundingSphere._TmpVector3 = BuildArray(3, Vector3.Zero);

// node_modules/@babylonjs/core/Culling/boundingInfo.js
var _result0 = { min: 0, max: 0 };
var _result1 = { min: 0, max: 0 };
var computeBoxExtents = (axis, box, result) => {
  const p = Vector3.Dot(box.centerWorld, axis);
  const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  const r = r0 + r1 + r2;
  result.min = p - r;
  result.max = p + r;
};
var axisOverlap = (axis, box0, box1) => {
  computeBoxExtents(axis, box0, _result0);
  computeBoxExtents(axis, box1, _result1);
  return !(_result0.min > _result1.max || _result1.min > _result0.max);
};

class BoundingInfo {
  constructor(minimum, maximum, worldMatrix) {
    this._isLocked = false;
    this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix);
    this.boundingSphere = new BoundingSphere(minimum, maximum, worldMatrix);
  }
  reConstruct(min, max, worldMatrix) {
    this.boundingBox.reConstruct(min, max, worldMatrix);
    this.boundingSphere.reConstruct(min, max, worldMatrix);
  }
  get minimum() {
    return this.boundingBox.minimum;
  }
  get maximum() {
    return this.boundingBox.maximum;
  }
  get isLocked() {
    return this._isLocked;
  }
  set isLocked(value) {
    this._isLocked = value;
  }
  update(world) {
    if (this._isLocked) {
      return;
    }
    this.boundingBox._update(world);
    this.boundingSphere._update(world);
  }
  centerOn(center, extend) {
    const minimum = BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend);
    const maximum = BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend);
    this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
    this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
    return this;
  }
  encapsulate(point) {
    const minimum = Vector3.Minimize(this.minimum, point);
    const maximum = Vector3.Maximize(this.maximum, point);
    this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
    return this;
  }
  encapsulateBoundingInfo(toEncapsulate) {
    const invw = TmpVectors.Matrix[0];
    this.boundingBox.getWorldMatrix().invertToRef(invw);
    const v = TmpVectors.Vector3[0];
    Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v);
    this.encapsulate(v);
    Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v);
    this.encapsulate(v);
    return this;
  }
  scale(factor) {
    this.boundingBox.scale(factor);
    this.boundingSphere.scale(factor);
    return this;
  }
  isInFrustum(frustumPlanes, strategy = 0) {
    const inclusionTest = strategy === 2 || strategy === 3;
    if (inclusionTest) {
      if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {
        return true;
      }
    }
    if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
      return false;
    }
    const bSphereOnlyTest = strategy === 1 || strategy === 3;
    if (bSphereOnlyTest) {
      return true;
    }
    return this.boundingBox.isInFrustum(frustumPlanes);
  }
  get diagonalLength() {
    const boundingBox = this.boundingBox;
    const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo._TmpVector3[0]);
    return diag.length();
  }
  isCompletelyInFrustum(frustumPlanes) {
    return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  }
  _checkCollision(collider) {
    return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  }
  intersectsPoint(point) {
    if (!this.boundingSphere.centerWorld) {
      return false;
    }
    if (!this.boundingSphere.intersectsPoint(point)) {
      return false;
    }
    if (!this.boundingBox.intersectsPoint(point)) {
      return false;
    }
    return true;
  }
  intersects(boundingInfo, precise) {
    if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
      return false;
    }
    if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
      return false;
    }
    if (!precise) {
      return true;
    }
    const box0 = this.boundingBox;
    const box1 = boundingInfo.boundingBox;
    if (!axisOverlap(box0.directions[0], box0, box1)) {
      return false;
    }
    if (!axisOverlap(box0.directions[1], box0, box1)) {
      return false;
    }
    if (!axisOverlap(box0.directions[2], box0, box1)) {
      return false;
    }
    if (!axisOverlap(box1.directions[0], box0, box1)) {
      return false;
    }
    if (!axisOverlap(box1.directions[1], box0, box1)) {
      return false;
    }
    if (!axisOverlap(box1.directions[2], box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
      return false;
    }
    if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
      return false;
    }
    return true;
  }
}
BoundingInfo._TmpVector3 = BuildArray(2, Vector3.Zero);

// node_modules/@babylonjs/core/Meshes/subMesh.js
init_math_functions();
init_drawWrapper();

class SubMesh {
  get materialDefines() {
    return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : this._getDrawWrapper()?.defines;
  }
  set materialDefines(defines) {
    const drawWrapper = this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true);
    drawWrapper.defines = defines;
  }
  _getDrawWrapper(passId, createIfNotExisting = false) {
    passId = passId ?? this._engine.currentRenderPassId;
    let drawWrapper = this._drawWrappers[passId];
    if (!drawWrapper && createIfNotExisting) {
      this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine());
    }
    return drawWrapper;
  }
  _removeDrawWrapper(passId, disposeWrapper = true, immediate = false) {
    if (disposeWrapper) {
      this._drawWrappers[passId]?.dispose(immediate);
    }
    this._drawWrappers[passId] = undefined;
  }
  get effect() {
    return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : this._getDrawWrapper()?.effect ?? null;
  }
  get _drawWrapper() {
    return this._mainDrawWrapperOverride ?? this._getDrawWrapper(undefined, true);
  }
  get _drawWrapperOverride() {
    return this._mainDrawWrapperOverride;
  }
  _setMainDrawWrapperOverride(wrapper) {
    this._mainDrawWrapperOverride = wrapper;
  }
  setEffect(effect, defines = null, materialContext, resetContext = true) {
    const drawWrapper = this._drawWrapper;
    drawWrapper.setEffect(effect, defines, resetContext);
    if (materialContext !== undefined) {
      drawWrapper.materialContext = materialContext;
    }
    if (!effect) {
      drawWrapper.defines = null;
      drawWrapper.materialContext = undefined;
    }
  }
  resetDrawCache(passId, immediate = false) {
    if (this._drawWrappers) {
      if (passId !== undefined) {
        this._removeDrawWrapper(passId, true, immediate);
        return;
      } else {
        for (const drawWrapper of this._drawWrappers) {
          drawWrapper?.dispose(immediate);
        }
      }
    }
    this._drawWrappers = [];
  }
  static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) {
    return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  }
  constructor(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) {
    this.materialIndex = materialIndex;
    this.verticesStart = verticesStart;
    this.verticesCount = verticesCount;
    this.indexStart = indexStart;
    this.indexCount = indexCount;
    this._mainDrawWrapperOverride = null;
    this._linesIndexCount = 0;
    this._linesIndexBuffer = null;
    this._lastColliderWorldVertices = null;
    this._lastColliderTransformMatrix = null;
    this._wasDispatched = false;
    this._renderId = 0;
    this._alphaIndex = 0;
    this._distanceToCamera = 0;
    this._currentMaterial = null;
    this._mesh = mesh;
    this._renderingMesh = renderingMesh || mesh;
    if (addToMesh) {
      mesh.subMeshes.push(this);
    }
    this._engine = this._mesh.getScene().getEngine();
    this.resetDrawCache();
    this._trianglePlanes = [];
    this._id = mesh.subMeshes.length - 1;
    if (createBoundingBox) {
      this.refreshBoundingInfo();
      mesh.computeWorldMatrix(true);
    }
  }
  get IsGlobal() {
    return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices();
  }
  getBoundingInfo() {
    if (this.IsGlobal || this._mesh.hasThinInstances) {
      return this._mesh.getBoundingInfo();
    }
    return this._boundingInfo;
  }
  setBoundingInfo(boundingInfo) {
    this._boundingInfo = boundingInfo;
    return this;
  }
  getMesh() {
    return this._mesh;
  }
  getRenderingMesh() {
    return this._renderingMesh;
  }
  getReplacementMesh() {
    return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
  }
  getEffectiveMesh() {
    const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;
    return replacementMesh ? replacementMesh : this._renderingMesh;
  }
  getMaterial(getDefaultMaterial = true) {
    const rootMaterial = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId) ?? this._renderingMesh.material;
    if (!rootMaterial) {
      return getDefaultMaterial && this._mesh.getScene()._hasDefaultMaterial ? this._mesh.getScene().defaultMaterial : null;
    } else if (this._isMultiMaterial(rootMaterial)) {
      const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex);
      if (this._currentMaterial !== effectiveMaterial) {
        this._currentMaterial = effectiveMaterial;
        this.resetDrawCache();
      }
      return effectiveMaterial;
    }
    return rootMaterial;
  }
  _isMultiMaterial(material) {
    return material.getSubMaterial !== undefined;
  }
  refreshBoundingInfo(data = null) {
    this._lastColliderWorldVertices = null;
    if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
      return this;
    }
    if (!data) {
      data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);
    }
    if (!data) {
      this._boundingInfo = this._mesh.getBoundingInfo();
      return this;
    }
    const indices = this._renderingMesh.getIndices();
    let extend;
    if (this.indexStart === 0 && this.indexCount === indices.length) {
      const boundingInfo = this._renderingMesh.getBoundingInfo();
      extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
    } else {
      extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
    }
    if (this._boundingInfo) {
      this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
    } else {
      this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
    }
    return this;
  }
  _checkCollision(collider) {
    const boundingInfo = this.getBoundingInfo();
    return boundingInfo._checkCollision(collider);
  }
  updateBoundingInfo(world) {
    let boundingInfo = this.getBoundingInfo();
    if (!boundingInfo) {
      this.refreshBoundingInfo();
      boundingInfo = this.getBoundingInfo();
    }
    if (boundingInfo) {
      boundingInfo.update(world);
    }
    return this;
  }
  isInFrustum(frustumPlanes) {
    const boundingInfo = this.getBoundingInfo();
    if (!boundingInfo) {
      return false;
    }
    return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  }
  isCompletelyInFrustum(frustumPlanes) {
    const boundingInfo = this.getBoundingInfo();
    if (!boundingInfo) {
      return false;
    }
    return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  }
  render(enableAlphaMode) {
    this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined);
    return this;
  }
  _getLinesIndexBuffer(indices, engine) {
    if (!this._linesIndexBuffer) {
      const adjustedIndexCount = Math.floor(this.indexCount / 3) * 6;
      const shouldUseUint32 = this.verticesStart + this.verticesCount > 65535;
      const linesIndices = shouldUseUint32 ? new Uint32Array(adjustedIndexCount) : new Uint16Array(adjustedIndexCount);
      let offset = 0;
      if (indices.length === 0) {
        for (let index = this.indexStart;index < this.indexStart + this.indexCount; index += 3) {
          linesIndices[offset++] = index;
          linesIndices[offset++] = index + 1;
          linesIndices[offset++] = index + 1;
          linesIndices[offset++] = index + 2;
          linesIndices[offset++] = index + 2;
          linesIndices[offset++] = index;
        }
      } else {
        for (let index = this.indexStart;index < this.indexStart + this.indexCount; index += 3) {
          linesIndices[offset++] = indices[index];
          linesIndices[offset++] = indices[index + 1];
          linesIndices[offset++] = indices[index + 1];
          linesIndices[offset++] = indices[index + 2];
          linesIndices[offset++] = indices[index + 2];
          linesIndices[offset++] = indices[index];
        }
      }
      this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
      this._linesIndexCount = linesIndices.length;
    }
    return this._linesIndexBuffer;
  }
  canIntersects(ray) {
    const boundingInfo = this.getBoundingInfo();
    if (!boundingInfo) {
      return false;
    }
    return ray.intersectsBox(boundingInfo.boundingBox);
  }
  intersects(ray, positions, indices, fastCheck, trianglePredicate) {
    const material = this.getMaterial();
    if (!material) {
      return null;
    }
    let step = 3;
    let checkStopper = false;
    switch (material.fillMode) {
      case 3:
      case 5:
      case 6:
      case 8:
        return null;
      case 7:
        step = 1;
        checkStopper = true;
        break;
      default:
        break;
    }
    if (material.fillMode === 4) {
      if (!indices.length) {
        return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
      }
      return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
    } else {
      if (!indices.length && this._mesh._unIndexed) {
        return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate);
      }
      return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate);
    }
  }
  _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) {
    let intersectInfo = null;
    for (let index = this.indexStart;index < this.indexStart + this.indexCount; index += 2) {
      const p0 = positions[indices[index]];
      const p1 = positions[indices[index + 1]];
      const length = ray.intersectionSegment(p0, p1, intersectionThreshold);
      if (length < 0) {
        continue;
      }
      if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
        intersectInfo = new IntersectionInfo(null, null, length);
        intersectInfo.faceId = index / 2;
        if (fastCheck) {
          break;
        }
      }
    }
    return intersectInfo;
  }
  _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) {
    let intersectInfo = null;
    for (let index = this.verticesStart;index < this.verticesStart + this.verticesCount; index += 2) {
      const p0 = positions[index];
      const p1 = positions[index + 1];
      const length = ray.intersectionSegment(p0, p1, intersectionThreshold);
      if (length < 0) {
        continue;
      }
      if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
        intersectInfo = new IntersectionInfo(null, null, length);
        intersectInfo.faceId = index / 2;
        if (fastCheck) {
          break;
        }
      }
    }
    return intersectInfo;
  }
  _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) {
    let intersectInfo = null;
    let faceId = -1;
    for (let index = this.indexStart;index < this.indexStart + this.indexCount - (3 - step); index += step) {
      faceId++;
      const indexA = indices[index];
      const indexB = indices[index + 1];
      const indexC = indices[index + 2];
      if (checkStopper && indexC === 4294967295) {
        index += 2;
        continue;
      }
      const p0 = positions[indexA];
      const p1 = positions[indexB];
      const p2 = positions[indexC];
      if (!p0 || !p1 || !p2) {
        continue;
      }
      if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) {
        continue;
      }
      const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
      if (currentIntersectInfo) {
        if (currentIntersectInfo.distance < 0) {
          continue;
        }
        if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
          intersectInfo = currentIntersectInfo;
          intersectInfo.faceId = faceId;
          if (fastCheck) {
            break;
          }
        }
      }
    }
    return intersectInfo;
  }
  _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) {
    let intersectInfo = null;
    for (let index = this.verticesStart;index < this.verticesStart + this.verticesCount; index += 3) {
      const p0 = positions[index];
      const p1 = positions[index + 1];
      const p2 = positions[index + 2];
      if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) {
        continue;
      }
      const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
      if (currentIntersectInfo) {
        if (currentIntersectInfo.distance < 0) {
          continue;
        }
        if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
          intersectInfo = currentIntersectInfo;
          intersectInfo.faceId = index / 3;
          if (fastCheck) {
            break;
          }
        }
      }
    }
    return intersectInfo;
  }
  _rebuild() {
    if (this._linesIndexBuffer) {
      this._linesIndexBuffer = null;
    }
  }
  clone(newMesh, newRenderingMesh) {
    const result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
    if (!this.IsGlobal) {
      const boundingInfo = this.getBoundingInfo();
      if (!boundingInfo) {
        return result;
      }
      result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
    }
    return result;
  }
  dispose(immediate = false) {
    if (this._linesIndexBuffer) {
      this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
      this._linesIndexBuffer = null;
    }
    const index = this._mesh.subMeshes.indexOf(this);
    this._mesh.subMeshes.splice(index, 1);
    this.resetDrawCache(undefined, immediate);
  }
  getClassName() {
    return "SubMesh";
  }
  static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) {
    let minVertexIndex = Number.MAX_VALUE;
    let maxVertexIndex = -Number.MAX_VALUE;
    const whatWillRender = renderingMesh || mesh;
    const indices = whatWillRender.getIndices();
    for (let index = startIndex;index < startIndex + indexCount; index++) {
      const vertexIndex = indices[index];
      if (vertexIndex < minVertexIndex) {
        minVertexIndex = vertexIndex;
      }
      if (vertexIndex > maxVertexIndex) {
        maxVertexIndex = vertexIndex;
      }
    }
    return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox);
  }
}

// node_modules/@babylonjs/core/Meshes/mesh.vertexData.js
class VertexDataMaterialInfo {
}

class VertexData {
  constructor() {
    this.uniqueId = 0;
    this.metadata = {};
    this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this));
    this.uniqueId = VertexData._UniqueIDGenerator;
    VertexData._UniqueIDGenerator++;
  }
  set(data, kind) {
    if (!data.length) {
      Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`);
    }
    switch (kind) {
      case VertexBuffer.PositionKind:
        this.positions = data;
        break;
      case VertexBuffer.NormalKind:
        this.normals = data;
        break;
      case VertexBuffer.TangentKind:
        this.tangents = data;
        break;
      case VertexBuffer.UVKind:
        this.uvs = data;
        break;
      case VertexBuffer.UV2Kind:
        this.uvs2 = data;
        break;
      case VertexBuffer.UV3Kind:
        this.uvs3 = data;
        break;
      case VertexBuffer.UV4Kind:
        this.uvs4 = data;
        break;
      case VertexBuffer.UV5Kind:
        this.uvs5 = data;
        break;
      case VertexBuffer.UV6Kind:
        this.uvs6 = data;
        break;
      case VertexBuffer.ColorKind:
        this.colors = data;
        break;
      case VertexBuffer.MatricesIndicesKind:
        this.matricesIndices = data;
        break;
      case VertexBuffer.MatricesWeightsKind:
        this.matricesWeights = data;
        break;
      case VertexBuffer.MatricesIndicesExtraKind:
        this.matricesIndicesExtra = data;
        break;
      case VertexBuffer.MatricesWeightsExtraKind:
        this.matricesWeightsExtra = data;
        break;
    }
  }
  applyToMesh(mesh, updatable) {
    this._applyTo(mesh, updatable, false);
    return this;
  }
  applyToGeometry(geometry, updatable) {
    this._applyTo(geometry, updatable, false);
    return this;
  }
  updateMesh(mesh) {
    this._update(mesh);
    return this;
  }
  updateGeometry(geometry) {
    this._update(geometry);
    return this;
  }
  *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) {
    if (this.positions) {
      meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.normals) {
      meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.tangents) {
      meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs) {
      meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs2) {
      meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs3) {
      meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs4) {
      meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs5) {
      meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.uvs6) {
      meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.colors) {
      const stride = this.positions && this.colors.length === this.positions.length ? 3 : 4;
      meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable, stride);
      if (this.hasVertexAlpha && meshOrGeometry.hasVertexAlpha !== undefined) {
        meshOrGeometry.hasVertexAlpha = true;
      }
      if (isAsync) {
        yield;
      }
    }
    if (this.matricesIndices) {
      meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.matricesWeights) {
      meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.matricesIndicesExtra) {
      meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.matricesWeightsExtra) {
      meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
      if (isAsync) {
        yield;
      }
    }
    if (this.indices) {
      meshOrGeometry.setIndices(this.indices, null, updatable);
      if (isAsync) {
        yield;
      }
    } else {
      meshOrGeometry.setIndices([], null);
    }
    if (meshOrGeometry.subMeshes && this.materialInfos && this.materialInfos.length > 1) {
      const mesh = meshOrGeometry;
      mesh.subMeshes = [];
      for (const matInfo of this.materialInfos) {
        new SubMesh(matInfo.materialIndex, matInfo.verticesStart, matInfo.verticesCount, matInfo.indexStart, matInfo.indexCount, mesh);
      }
    }
    return this;
  }
  _update(meshOrGeometry, updateExtends, makeItUnique) {
    if (this.positions) {
      meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
    }
    if (this.normals) {
      meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
    }
    if (this.tangents) {
      meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
    }
    if (this.uvs) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
    }
    if (this.uvs2) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
    }
    if (this.uvs3) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
    }
    if (this.uvs4) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
    }
    if (this.uvs5) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
    }
    if (this.uvs6) {
      meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
    }
    if (this.colors) {
      meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
    }
    if (this.matricesIndices) {
      meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
    }
    if (this.matricesWeights) {
      meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
    }
    if (this.matricesIndicesExtra) {
      meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
    }
    if (this.matricesWeightsExtra) {
      meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
    }
    if (this.indices) {
      meshOrGeometry.setIndices(this.indices, null);
    }
    return this;
  }
  static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) {
    const coordinate = TmpVectors.Vector3[0];
    const transformedCoordinate = TmpVectors.Vector3[1];
    for (let index = offset;index < offset + length; index += 3) {
      Vector3.FromArrayToRef(coordinates, index, coordinate);
      Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate);
      coordinates[index] = transformedCoordinate.x;
      coordinates[index + 1] = transformedCoordinate.y;
      coordinates[index + 2] = transformedCoordinate.z;
    }
  }
  static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) {
    const normal = TmpVectors.Vector3[0];
    const transformedNormal = TmpVectors.Vector3[1];
    for (let index = offset;index < offset + length; index += 3) {
      Vector3.FromArrayToRef(normals, index, normal);
      Vector3.TransformNormalToRef(normal, transformation, transformedNormal);
      normals[index] = transformedNormal.x;
      normals[index + 1] = transformedNormal.y;
      normals[index + 2] = transformedNormal.z;
    }
  }
  static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) {
    const normal = TmpVectors.Vector4[0];
    const transformedNormal = TmpVectors.Vector4[1];
    for (let index = offset;index < offset + length; index += 4) {
      Vector4.FromArrayToRef(normals, index, normal);
      Vector4.TransformNormalToRef(normal, transformation, transformedNormal);
      normals[index] = transformedNormal.x;
      normals[index + 1] = transformedNormal.y;
      normals[index + 2] = transformedNormal.z;
      normals[index + 3] = transformedNormal.w;
    }
  }
  static _FlipFaces(indices, offset = 0, length = indices.length) {
    for (let index = offset;index < offset + length; index += 3) {
      const tmp = indices[index + 1];
      indices[index + 1] = indices[index + 2];
      indices[index + 2] = tmp;
    }
  }
  transform(matrix) {
    const flip = matrix.determinant() < 0;
    if (this.positions) {
      VertexData._TransformVector3Coordinates(this.positions, matrix);
    }
    if (this.normals) {
      VertexData._TransformVector3Normals(this.normals, matrix);
    }
    if (this.tangents) {
      VertexData._TransformVector4Normals(this.tangents, matrix);
    }
    if (flip && this.indices) {
      VertexData._FlipFaces(this.indices);
    }
    return this;
  }
  splitBasedOnMaterialID() {
    if (!this.materialInfos || this.materialInfos.length < 2) {
      return [this];
    }
    const result = [];
    for (const materialInfo of this.materialInfos) {
      const vertexData = new VertexData;
      if (this.positions) {
        vertexData.positions = this.positions.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3);
      }
      if (this.normals) {
        vertexData.normals = this.normals.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3);
      }
      if (this.tangents) {
        vertexData.tangents = this.tangents.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.colors) {
        vertexData.colors = this.colors.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.uvs) {
        vertexData.uvs = this.uvs.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.uvs2) {
        vertexData.uvs2 = this.uvs2.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.uvs3) {
        vertexData.uvs3 = this.uvs3.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.uvs4) {
        vertexData.uvs4 = this.uvs4.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.uvs5) {
        vertexData.uvs5 = this.uvs5.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.uvs6) {
        vertexData.uvs6 = this.uvs6.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2);
      }
      if (this.matricesIndices) {
        vertexData.matricesIndices = this.matricesIndices.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.matricesIndicesExtra) {
        vertexData.matricesIndicesExtra = this.matricesIndicesExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.matricesWeights) {
        vertexData.matricesWeights = this.matricesWeights.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.matricesWeightsExtra) {
        vertexData.matricesWeightsExtra = this.matricesWeightsExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4);
      }
      if (this.indices) {
        vertexData.indices = [];
        for (let index = materialInfo.indexStart;index < materialInfo.indexStart + materialInfo.indexCount; index++) {
          vertexData.indices.push(this.indices[index] - materialInfo.verticesStart);
        }
      }
      const newMaterialInfo = new VertexDataMaterialInfo;
      newMaterialInfo.indexStart = 0;
      newMaterialInfo.indexCount = vertexData.indices ? vertexData.indices.length : 0;
      newMaterialInfo.materialIndex = materialInfo.materialIndex;
      newMaterialInfo.verticesStart = 0;
      newMaterialInfo.verticesCount = (vertexData.positions ? vertexData.positions.length : 0) / 3;
      vertexData.materialInfos = [newMaterialInfo];
      result.push(vertexData);
    }
    return result;
  }
  merge(others, use32BitsIndices = false, forceCloneIndices = false, mergeMaterialIds = false, enableCompletion = false) {
    const vertexDatas = Array.isArray(others) ? others.map((other) => {
      return { vertexData: other };
    }) : [{ vertexData: others }];
    return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices, mergeMaterialIds, enableCompletion));
  }
  *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices, mergeMaterialIds = false, enableCompletion = false) {
    this._validate();
    let others = vertexDatas.map((vertexData) => vertexData.vertexData);
    let root = this;
    if (enableCompletion) {
      for (const other of others) {
        if (!other) {
          continue;
        }
        other._validate();
        if (!this.normals && other.normals) {
          this.normals = new Float32Array(this.positions.length);
        }
        if (!this.tangents && other.tangents) {
          this.tangents = new Float32Array(this.positions.length / 3 * 4);
        }
        if (!this.uvs && other.uvs) {
          this.uvs = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.uvs2 && other.uvs2) {
          this.uvs2 = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.uvs3 && other.uvs3) {
          this.uvs3 = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.uvs4 && other.uvs4) {
          this.uvs4 = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.uvs5 && other.uvs5) {
          this.uvs5 = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.uvs6 && other.uvs6) {
          this.uvs6 = new Float32Array(this.positions.length / 3 * 2);
        }
        if (!this.colors && other.colors) {
          this.colors = new Float32Array(this.positions.length / 3 * 4);
          this.colors.fill(1);
        }
        if (!this.matricesIndices && other.matricesIndices) {
          this.matricesIndices = new Float32Array(this.positions.length / 3 * 4);
        }
        if (!this.matricesWeights && other.matricesWeights) {
          this.matricesWeights = new Float32Array(this.positions.length / 3 * 4);
        }
        if (!this.matricesIndicesExtra && other.matricesIndicesExtra) {
          this.matricesIndicesExtra = new Float32Array(this.positions.length / 3 * 4);
        }
        if (!this.matricesWeightsExtra && other.matricesWeightsExtra) {
          this.matricesWeightsExtra = new Float32Array(this.positions.length / 3 * 4);
        }
      }
    }
    for (const other of others) {
      if (!other) {
        continue;
      }
      if (!enableCompletion) {
        other._validate();
        if (!this.normals !== !other.normals || !this.tangents !== !other.tangents || !this.uvs !== !other.uvs || !this.uvs2 !== !other.uvs2 || !this.uvs3 !== !other.uvs3 || !this.uvs4 !== !other.uvs4 || !this.uvs5 !== !other.uvs5 || !this.uvs6 !== !other.uvs6 || !this.colors !== !other.colors || !this.matricesIndices !== !other.matricesIndices || !this.matricesWeights !== !other.matricesWeights || !this.matricesIndicesExtra !== !other.matricesIndicesExtra || !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
          throw new Error("Cannot merge vertex data that do not have the same set of attributes");
        }
      } else {
        if (this.normals && !other.normals) {
          other.normals = new Float32Array(other.positions.length);
        }
        if (this.tangents && !other.tangents) {
          other.tangents = new Float32Array(other.positions.length / 3 * 4);
        }
        if (this.uvs && !other.uvs) {
          other.uvs = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.uvs2 && !other.uvs2) {
          other.uvs2 = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.uvs3 && !other.uvs3) {
          other.uvs3 = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.uvs4 && !other.uvs4) {
          other.uvs4 = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.uvs5 && !other.uvs5) {
          other.uvs5 = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.uvs6 && !other.uvs6) {
          other.uvs6 = new Float32Array(other.positions.length / 3 * 2);
        }
        if (this.colors && !other.colors) {
          other.colors = new Float32Array(other.positions.length / 3 * 4);
          other.colors.fill(1);
        }
        if (this.matricesIndices && !other.matricesIndices) {
          other.matricesIndices = new Float32Array(other.positions.length / 3 * 4);
        }
        if (this.matricesWeights && !other.matricesWeights) {
          other.matricesWeights = new Float32Array(other.positions.length / 3 * 4);
        }
        if (this.matricesIndicesExtra && !other.matricesIndicesExtra) {
          other.matricesIndicesExtra = new Float32Array(other.positions.length / 3 * 4);
        }
        if (this.matricesWeightsExtra && !other.matricesWeightsExtra) {
          other.matricesWeightsExtra = new Float32Array(other.positions.length / 3 * 4);
        }
      }
    }
    if (mergeMaterialIds) {
      let materialIndex = 0;
      let indexOffset = 0;
      let vertexOffset = 0;
      const materialInfos = [];
      let currentMaterialInfo = null;
      const vertexDataList = [];
      for (const split of this.splitBasedOnMaterialID()) {
        vertexDataList.push({ vertexData: split, transform });
      }
      for (const data of vertexDatas) {
        if (!data.vertexData) {
          continue;
        }
        for (const split of data.vertexData.splitBasedOnMaterialID()) {
          vertexDataList.push({ vertexData: split, transform: data.transform });
        }
      }
      vertexDataList.sort((a, b) => {
        const matInfoA = a.vertexData.materialInfos ? a.vertexData.materialInfos[0].materialIndex : 0;
        const matInfoB = b.vertexData.materialInfos ? b.vertexData.materialInfos[0].materialIndex : 0;
        if (matInfoA > matInfoB) {
          return 1;
        }
        if (matInfoA === matInfoB) {
          return 0;
        }
        return -1;
      });
      for (const vertexDataSource of vertexDataList) {
        const vertexData = vertexDataSource.vertexData;
        if (vertexData.materialInfos) {
          materialIndex = vertexData.materialInfos[0].materialIndex;
        } else {
          materialIndex = 0;
        }
        if (currentMaterialInfo && currentMaterialInfo.materialIndex === materialIndex) {
          currentMaterialInfo.indexCount += vertexData.indices.length;
          currentMaterialInfo.verticesCount += vertexData.positions.length / 3;
        } else {
          const materialInfo = new VertexDataMaterialInfo;
          materialInfo.materialIndex = materialIndex;
          materialInfo.indexStart = indexOffset;
          materialInfo.indexCount = vertexData.indices.length;
          materialInfo.verticesStart = vertexOffset;
          materialInfo.verticesCount = vertexData.positions.length / 3;
          materialInfos.push(materialInfo);
          currentMaterialInfo = materialInfo;
        }
        indexOffset += vertexData.indices.length;
        vertexOffset += vertexData.positions.length / 3;
      }
      const first = vertexDataList.splice(0, 1)[0];
      root = first.vertexData;
      transform = first.transform;
      others = vertexDataList.map((v) => v.vertexData);
      vertexDatas = vertexDataList;
      this.materialInfos = materialInfos;
    }
    const totalIndices = others.reduce((indexSum, vertexData) => indexSum + (vertexData.indices?.length ?? 0), root.indices?.length ?? 0);
    const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === root.indices);
    let indices = sliceIndices ? root.indices?.slice() : root.indices;
    if (totalIndices > 0) {
      let indicesOffset = indices?.length ?? 0;
      if (!indices) {
        indices = new Array(totalIndices);
      }
      if (indices.length !== totalIndices) {
        if (Array.isArray(indices)) {
          indices.length = totalIndices;
        } else {
          const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices);
          temp.set(indices);
          indices = temp;
        }
        if (transform && transform.determinant() < 0) {
          VertexData._FlipFaces(indices, 0, indicesOffset);
        }
      }
      let positionsOffset = root.positions ? root.positions.length / 3 : 0;
      for (const { vertexData: other, transform: transform2 } of vertexDatas) {
        if (other.indices) {
          for (let index = 0;index < other.indices.length; index++) {
            indices[indicesOffset + index] = other.indices[index] + positionsOffset;
          }
          if (transform2 && transform2.determinant() < 0) {
            VertexData._FlipFaces(indices, indicesOffset, other.indices.length);
          }
          positionsOffset += other.positions.length / 3;
          indicesOffset += other.indices.length;
          if (isAsync) {
            yield;
          }
        }
      }
    }
    this.indices = indices;
    this.positions = VertexData._MergeElement(VertexBuffer.PositionKind, root.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform]));
    if (isAsync) {
      yield;
    }
    if (root.normals) {
      this.normals = VertexData._MergeElement(VertexBuffer.NormalKind, root.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.tangents) {
      this.tangents = VertexData._MergeElement(VertexBuffer.TangentKind, root.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs) {
      this.uvs = VertexData._MergeElement(VertexBuffer.UVKind, root.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs2) {
      this.uvs2 = VertexData._MergeElement(VertexBuffer.UV2Kind, root.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs3) {
      this.uvs3 = VertexData._MergeElement(VertexBuffer.UV3Kind, root.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs4) {
      this.uvs4 = VertexData._MergeElement(VertexBuffer.UV4Kind, root.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs5) {
      this.uvs5 = VertexData._MergeElement(VertexBuffer.UV5Kind, root.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.uvs6) {
      this.uvs6 = VertexData._MergeElement(VertexBuffer.UV6Kind, root.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.colors) {
      this.colors = VertexData._MergeElement(VertexBuffer.ColorKind, root.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform]));
      if (root.hasVertexAlpha !== undefined || vertexDatas.some((other) => other.vertexData.hasVertexAlpha !== undefined)) {
        this.hasVertexAlpha = root.hasVertexAlpha || vertexDatas.some((other) => other.vertexData.hasVertexAlpha);
      }
      if (isAsync) {
        yield;
      }
    }
    if (root.matricesIndices) {
      this.matricesIndices = VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, root.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.matricesWeights) {
      this.matricesWeights = VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, root.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.matricesIndicesExtra) {
      this.matricesIndicesExtra = VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, root.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform]));
      if (isAsync) {
        yield;
      }
    }
    if (root.matricesWeightsExtra) {
      this.matricesWeightsExtra = VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, root.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform]));
    }
    return this;
  }
  static _MergeElement(kind, source, transform, others) {
    const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined);
    if (!source && nonNullOthers.length == 0) {
      return source;
    }
    if (!source) {
      return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1));
    }
    const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length);
    const transformRange = kind === VertexBuffer.PositionKind ? VertexData._TransformVector3Coordinates : kind === VertexBuffer.NormalKind ? VertexData._TransformVector3Normals : kind === VertexBuffer.TangentKind ? VertexData._TransformVector4Normals : () => {};
    if (source instanceof Float32Array) {
      const ret32 = new Float32Array(len);
      ret32.set(source);
      transform && transformRange(ret32, transform, 0, source.length);
      let offset = source.length;
      for (const [vertexData, transform2] of nonNullOthers) {
        ret32.set(vertexData, offset);
        transform2 && transformRange(ret32, transform2, offset, vertexData.length);
        offset += vertexData.length;
      }
      return ret32;
    } else {
      const ret = new Array(len);
      for (let i = 0;i < source.length; i++) {
        ret[i] = source[i];
      }
      transform && transformRange(ret, transform, 0, source.length);
      let offset = source.length;
      for (const [vertexData, transform2] of nonNullOthers) {
        for (let i = 0;i < vertexData.length; i++) {
          ret[offset + i] = vertexData[i];
        }
        transform2 && transformRange(ret, transform2, offset, vertexData.length);
        offset += vertexData.length;
      }
      return ret;
    }
  }
  _validate() {
    if (!this.positions) {
      throw new RuntimeError("Positions are required", ErrorCodes.MeshInvalidPositionsError);
    }
    const getElementCount = (kind, values) => {
      const stride = VertexBuffer.DeduceStride(kind);
      if (values.length % stride !== 0) {
        throw new Error("The " + kind + "s array count must be a multiple of " + stride);
      }
      return values.length / stride;
    };
    const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions);
    const validateElementCount = (kind, values) => {
      const elementCount = getElementCount(kind, values);
      if (elementCount !== positionsElementCount) {
        throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
      }
    };
    if (this.normals) {
      validateElementCount(VertexBuffer.NormalKind, this.normals);
    }
    if (this.tangents) {
      validateElementCount(VertexBuffer.TangentKind, this.tangents);
    }
    if (this.uvs) {
      validateElementCount(VertexBuffer.UVKind, this.uvs);
    }
    if (this.uvs2) {
      validateElementCount(VertexBuffer.UV2Kind, this.uvs2);
    }
    if (this.uvs3) {
      validateElementCount(VertexBuffer.UV3Kind, this.uvs3);
    }
    if (this.uvs4) {
      validateElementCount(VertexBuffer.UV4Kind, this.uvs4);
    }
    if (this.uvs5) {
      validateElementCount(VertexBuffer.UV5Kind, this.uvs5);
    }
    if (this.uvs6) {
      validateElementCount(VertexBuffer.UV6Kind, this.uvs6);
    }
    if (this.colors) {
      validateElementCount(VertexBuffer.ColorKind, this.colors);
    }
    if (this.matricesIndices) {
      validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices);
    }
    if (this.matricesWeights) {
      validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights);
    }
    if (this.matricesIndicesExtra) {
      validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
    }
    if (this.matricesWeightsExtra) {
      validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
    }
  }
  clone() {
    const serializationObject = this.serialize();
    return VertexData.Parse(serializationObject);
  }
  serialize() {
    const serializationObject = {};
    if (this.positions) {
      serializationObject.positions = Array.from(this.positions);
    }
    if (this.normals) {
      serializationObject.normals = Array.from(this.normals);
    }
    if (this.tangents) {
      serializationObject.tangents = Array.from(this.tangents);
    }
    if (this.uvs) {
      serializationObject.uvs = Array.from(this.uvs);
    }
    if (this.uvs2) {
      serializationObject.uvs2 = Array.from(this.uvs2);
    }
    if (this.uvs3) {
      serializationObject.uvs3 = Array.from(this.uvs3);
    }
    if (this.uvs4) {
      serializationObject.uvs4 = Array.from(this.uvs4);
    }
    if (this.uvs5) {
      serializationObject.uvs5 = Array.from(this.uvs5);
    }
    if (this.uvs6) {
      serializationObject.uvs6 = Array.from(this.uvs6);
    }
    if (this.colors) {
      serializationObject.colors = Array.from(this.colors);
      serializationObject.hasVertexAlpha = this.hasVertexAlpha;
    }
    if (this.matricesIndices) {
      serializationObject.matricesIndices = Array.from(this.matricesIndices);
      serializationObject.matricesIndices._isExpanded = true;
    }
    if (this.matricesWeights) {
      serializationObject.matricesWeights = Array.from(this.matricesWeights);
    }
    if (this.matricesIndicesExtra) {
      serializationObject.matricesIndicesExtra = Array.from(this.matricesIndicesExtra);
      serializationObject.matricesIndicesExtra._isExpanded = true;
    }
    if (this.matricesWeightsExtra) {
      serializationObject.matricesWeightsExtra = Array.from(this.matricesWeightsExtra);
    }
    serializationObject.indices = this.indices ? Array.from(this.indices) : [];
    if (this.materialInfos) {
      serializationObject.materialInfos = [];
      for (const materialInfo of this.materialInfos) {
        const materialInfoSerializationObject = {
          indexStart: materialInfo.indexStart,
          indexCount: materialInfo.indexCount,
          materialIndex: materialInfo.materialIndex,
          verticesStart: materialInfo.verticesStart,
          verticesCount: materialInfo.verticesCount
        };
        serializationObject.materialInfos.push(materialInfoSerializationObject);
      }
    }
    return serializationObject;
  }
  static ExtractFromMesh(mesh, copyWhenShared, forceCopy) {
    return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  }
  static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) {
    return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  }
  static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) {
    const result = new VertexData;
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) {
      result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) {
      result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) {
      result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
      result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
      result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
      result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
      result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
      result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) {
      const geometry = meshOrGeometry.geometry || meshOrGeometry;
      const vertexBuffer = geometry.getVertexBuffer(VertexBuffer.ColorKind);
      const colors = geometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy);
      if (vertexBuffer.getSize() === 3) {
        const newColors = new Float32Array(colors.length * 4 / 3);
        for (let i = 0, j = 0;i < colors.length; i += 3, j += 4) {
          newColors[j] = colors[i];
          newColors[j + 1] = colors[i + 1];
          newColors[j + 2] = colors[i + 2];
          newColors[j + 3] = 1;
        }
        result.colors = newColors;
      } else if (vertexBuffer.getSize() === 4) {
        result.colors = colors;
      } else {
        throw new Error(`Unexpected number of color components: ${vertexBuffer.getSize()}`);
      }
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
      result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
      result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) {
      result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
    }
    if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
      result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
    }
    result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
    return result;
  }
  static CreateRibbon(options) {
    throw _WarnImport("ribbonBuilder");
  }
  static CreateBox(options) {
    throw _WarnImport("boxBuilder");
  }
  static CreateTiledBox(options) {
    throw _WarnImport("tiledBoxBuilder");
  }
  static CreateTiledPlane(options) {
    throw _WarnImport("tiledPlaneBuilder");
  }
  static CreateSphere(options) {
    throw _WarnImport("sphereBuilder");
  }
  static CreateCylinder(options) {
    throw _WarnImport("cylinderBuilder");
  }
  static CreateTorus(options) {
    throw _WarnImport("torusBuilder");
  }
  static CreateLineSystem(options) {
    throw _WarnImport("linesBuilder");
  }
  static CreateDashedLines(options) {
    throw _WarnImport("linesBuilder");
  }
  static CreateGround(options) {
    throw _WarnImport("groundBuilder");
  }
  static CreateTiledGround(options) {
    throw _WarnImport("groundBuilder");
  }
  static CreateGroundFromHeightMap(options) {
    throw _WarnImport("groundBuilder");
  }
  static CreatePlane(options) {
    throw _WarnImport("planeBuilder");
  }
  static CreateDisc(options) {
    throw _WarnImport("discBuilder");
  }
  static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) {
    throw _WarnImport("polygonBuilder");
  }
  static CreateIcoSphere(options) {
    throw _WarnImport("icoSphereBuilder");
  }
  static CreatePolyhedron(options) {
    throw _WarnImport("polyhedronBuilder");
  }
  static CreateCapsule(options = {
    orientation: Vector3.Up(),
    subdivisions: 2,
    tessellation: 16,
    height: 1,
    radius: 0.25,
    capSubdivisions: 6
  }) {
    throw _WarnImport("capsuleBuilder");
  }
  static CreateTorusKnot(options) {
    throw _WarnImport("torusKnotBuilder");
  }
  static ComputeNormals(positions, indices, normals, options) {
    let index = 0;
    let p1p2x = 0;
    let p1p2y = 0;
    let p1p2z = 0;
    let p3p2x = 0;
    let p3p2y = 0;
    let p3p2z = 0;
    let faceNormalx = 0;
    let faceNormaly = 0;
    let faceNormalz = 0;
    let length = 0;
    let v1x = 0;
    let v1y = 0;
    let v1z = 0;
    let v2x = 0;
    let v2y = 0;
    let v2z = 0;
    let v3x = 0;
    let v3y = 0;
    let v3z = 0;
    let computeFacetNormals = false;
    let computeFacetPositions = false;
    let computeFacetPartitioning = false;
    let computeDepthSort = false;
    let faceNormalSign = 1;
    let ratio = 0;
    let distanceTo = null;
    if (options) {
      computeFacetNormals = options.facetNormals ? true : false;
      computeFacetPositions = options.facetPositions ? true : false;
      computeFacetPartitioning = options.facetPartitioning ? true : false;
      faceNormalSign = options.useRightHandedSystem === true ? -1 : 1;
      ratio = options.ratio || 0;
      computeDepthSort = options.depthSort ? true : false;
      distanceTo = options.distanceTo;
      if (computeDepthSort) {
        if (distanceTo === undefined) {
          distanceTo = Vector3.Zero();
        }
      }
    }
    let xSubRatio = 0;
    let ySubRatio = 0;
    let zSubRatio = 0;
    let subSq = 0;
    if (computeFacetPartitioning && options && options.bbSize) {
      xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
      ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
      zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
      subSq = options.subDiv.max * options.subDiv.max;
      options.facetPartitioning.length = 0;
    }
    for (index = 0;index < positions.length; index++) {
      normals[index] = 0;
    }
    const nbFaces = indices.length / 3 | 0;
    for (index = 0;index < nbFaces; index++) {
      v1x = indices[index * 3] * 3;
      v1y = v1x + 1;
      v1z = v1x + 2;
      v2x = indices[index * 3 + 1] * 3;
      v2y = v2x + 1;
      v2z = v2x + 2;
      v3x = indices[index * 3 + 2] * 3;
      v3y = v3x + 1;
      v3z = v3x + 2;
      p1p2x = positions[v1x] - positions[v2x];
      p1p2y = positions[v1y] - positions[v2y];
      p1p2z = positions[v1z] - positions[v2z];
      p3p2x = positions[v3x] - positions[v2x];
      p3p2y = positions[v3y] - positions[v2y];
      p3p2z = positions[v3z] - positions[v2z];
      faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
      faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
      faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
      length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
      length = length === 0 ? 1 : length;
      faceNormalx /= length;
      faceNormaly /= length;
      faceNormalz /= length;
      if (computeFacetNormals && options) {
        options.facetNormals[index].x = faceNormalx;
        options.facetNormals[index].y = faceNormaly;
        options.facetNormals[index].z = faceNormalz;
      }
      if (computeFacetPositions && options) {
        options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3;
        options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3;
        options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3;
      }
      if (computeFacetPartitioning && options) {
        const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
        const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
        const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
        const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
        const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
        const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
        const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
        const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
        const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
        const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
        const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
        const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
        const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
        const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
        const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
        const block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
        options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array;
        options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array;
        options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array;
        options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array;
        options.facetPartitioning[block_idx_v1].push(index);
        if (block_idx_v2 != block_idx_v1) {
          options.facetPartitioning[block_idx_v2].push(index);
        }
        if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
          options.facetPartitioning[block_idx_v3].push(index);
        }
        if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
          options.facetPartitioning[block_idx_o].push(index);
        }
      }
      if (computeDepthSort && options && options.facetPositions) {
        const dsf = options.depthSortedFacets[index];
        dsf.ind = index * 3;
        dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
      }
      normals[v1x] += faceNormalx;
      normals[v1y] += faceNormaly;
      normals[v1z] += faceNormalz;
      normals[v2x] += faceNormalx;
      normals[v2y] += faceNormaly;
      normals[v2z] += faceNormalz;
      normals[v3x] += faceNormalx;
      normals[v3y] += faceNormaly;
      normals[v3z] += faceNormalz;
    }
    for (index = 0;index < normals.length / 3; index++) {
      faceNormalx = normals[index * 3];
      faceNormaly = normals[index * 3 + 1];
      faceNormalz = normals[index * 3 + 2];
      length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
      length = length === 0 ? 1 : length;
      faceNormalx /= length;
      faceNormaly /= length;
      faceNormalz /= length;
      normals[index * 3] = faceNormalx;
      normals[index * 3 + 1] = faceNormaly;
      normals[index * 3 + 2] = faceNormalz;
    }
  }
  static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
    const li = indices.length;
    const ln = normals.length;
    let i;
    let n;
    sideOrientation = sideOrientation || VertexData.DEFAULTSIDE;
    switch (sideOrientation) {
      case VertexData.FRONTSIDE:
        break;
      case VertexData.BACKSIDE:
        for (i = 0;i < li; i += 3) {
          const tmp = indices[i];
          indices[i] = indices[i + 2];
          indices[i + 2] = tmp;
        }
        for (n = 0;n < ln; n++) {
          normals[n] = -normals[n];
        }
        break;
      case VertexData.DOUBLESIDE: {
        const lp = positions.length;
        const l = lp / 3;
        for (let p = 0;p < lp; p++) {
          positions[lp + p] = positions[p];
        }
        for (i = 0;i < li; i += 3) {
          indices[i + li] = indices[i + 2] + l;
          indices[i + 1 + li] = indices[i + 1] + l;
          indices[i + 2 + li] = indices[i] + l;
        }
        for (n = 0;n < ln; n++) {
          normals[ln + n] = -normals[n];
        }
        const lu = uvs.length;
        let u = 0;
        for (u = 0;u < lu; u++) {
          uvs[u + lu] = uvs[u];
        }
        frontUVs = frontUVs ? frontUVs : new Vector4(0, 0, 1, 1);
        backUVs = backUVs ? backUVs : new Vector4(0, 0, 1, 1);
        u = 0;
        for (i = 0;i < lu / 2; i++) {
          uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
          uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
          uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
          uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
          u += 2;
        }
        break;
      }
    }
  }
  static Parse(parsedVertexData) {
    const vertexData = new VertexData;
    const positions = parsedVertexData.positions;
    if (positions) {
      vertexData.set(positions, VertexBuffer.PositionKind);
    }
    const normals = parsedVertexData.normals;
    if (normals) {
      vertexData.set(normals, VertexBuffer.NormalKind);
    }
    const tangents = parsedVertexData.tangents;
    if (tangents) {
      vertexData.set(tangents, VertexBuffer.TangentKind);
    }
    const uvs = parsedVertexData.uvs;
    if (uvs) {
      vertexData.set(uvs, VertexBuffer.UVKind);
    }
    const uvs2 = parsedVertexData.uvs2;
    if (uvs2) {
      vertexData.set(uvs2, VertexBuffer.UV2Kind);
    }
    const uvs3 = parsedVertexData.uvs3;
    if (uvs3) {
      vertexData.set(uvs3, VertexBuffer.UV3Kind);
    }
    const uvs4 = parsedVertexData.uvs4;
    if (uvs4) {
      vertexData.set(uvs4, VertexBuffer.UV4Kind);
    }
    const uvs5 = parsedVertexData.uvs5;
    if (uvs5) {
      vertexData.set(uvs5, VertexBuffer.UV5Kind);
    }
    const uvs6 = parsedVertexData.uvs6;
    if (uvs6) {
      vertexData.set(uvs6, VertexBuffer.UV6Kind);
    }
    const colors = parsedVertexData.colors;
    if (colors) {
      vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind);
      if (parsedVertexData.hasVertexAlpha !== undefined) {
        vertexData.hasVertexAlpha = parsedVertexData.hasVertexAlpha;
      }
    }
    const matricesIndices = parsedVertexData.matricesIndices;
    if (matricesIndices) {
      vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind);
    }
    const matricesWeights = parsedVertexData.matricesWeights;
    if (matricesWeights) {
      vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind);
    }
    const indices = parsedVertexData.indices;
    if (indices) {
      vertexData.indices = indices;
    }
    const materialInfos = parsedVertexData.materialInfos;
    if (materialInfos) {
      vertexData.materialInfos = [];
      for (const materialInfoFromJSON of materialInfos) {
        const materialInfo = new VertexDataMaterialInfo;
        materialInfo.indexCount = materialInfoFromJSON.indexCount;
        materialInfo.indexStart = materialInfoFromJSON.indexStart;
        materialInfo.verticesCount = materialInfoFromJSON.verticesCount;
        materialInfo.verticesStart = materialInfoFromJSON.verticesStart;
        materialInfo.materialIndex = materialInfoFromJSON.materialIndex;
        vertexData.materialInfos.push(materialInfo);
      }
    }
    return vertexData;
  }
  static ImportVertexData(parsedVertexData, geometry) {
    const vertexData = VertexData.Parse(parsedVertexData);
    geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  }
}
VertexData.FRONTSIDE = 0;
VertexData.BACKSIDE = 1;
VertexData.DOUBLESIDE = 2;
VertexData.DEFAULTSIDE = 0;
VertexData._UniqueIDGenerator = 0;
__decorate([
  nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates))
], VertexData, "_TransformVector3Coordinates", null);
__decorate([
  nativeOverride.filter((...[normals]) => !Array.isArray(normals))
], VertexData, "_TransformVector3Normals", null);
__decorate([
  nativeOverride.filter((...[normals]) => !Array.isArray(normals))
], VertexData, "_TransformVector4Normals", null);
__decorate([
  nativeOverride.filter((...[indices]) => !Array.isArray(indices))
], VertexData, "_FlipFaces", null);

// node_modules/@babylonjs/core/Meshes/geometry.js
init_math_vector();
init_math_color();
init_buffer();

// node_modules/@babylonjs/core/Loading/sceneLoaderFlags.js
class SceneLoaderFlags {
  static get ForceFullSceneLoadingForIncremental() {
    return SceneLoaderFlags._ForceFullSceneLoadingForIncremental;
  }
  static set ForceFullSceneLoadingForIncremental(value) {
    SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value;
  }
  static get ShowLoadingScreen() {
    return SceneLoaderFlags._ShowLoadingScreen;
  }
  static set ShowLoadingScreen(value) {
    SceneLoaderFlags._ShowLoadingScreen = value;
  }
  static get loggingLevel() {
    return SceneLoaderFlags._LoggingLevel;
  }
  static set loggingLevel(value) {
    SceneLoaderFlags._LoggingLevel = value;
  }
  static get CleanBoneMatrixWeights() {
    return SceneLoaderFlags._CleanBoneMatrixWeights;
  }
  static set CleanBoneMatrixWeights(value) {
    SceneLoaderFlags._CleanBoneMatrixWeights = value;
  }
}
SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false;
SceneLoaderFlags._ShowLoadingScreen = true;
SceneLoaderFlags._CleanBoneMatrixWeights = false;
SceneLoaderFlags._LoggingLevel = 0;

// node_modules/@babylonjs/core/Meshes/geometry.js
init_tools();
init_tags();
init_math_functions();
init_engineStore();
init_compatibilityOptions();
init_bufferUtils();

class Geometry {
  get boundingBias() {
    return this._boundingBias;
  }
  set boundingBias(value) {
    if (this._boundingBias) {
      this._boundingBias.copyFrom(value);
    } else {
      this._boundingBias = value.clone();
    }
    this._updateBoundingInfo(true, null);
  }
  static CreateGeometryForMesh(mesh) {
    const geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
    geometry.applyToMesh(mesh);
    return geometry;
  }
  get meshes() {
    return this._meshes;
  }
  constructor(id, scene, vertexData, updatable = false, mesh = null) {
    this.delayLoadState = 0;
    this._totalVertices = 0;
    this._isDisposed = false;
    this._extend = {
      minimum: new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE),
      maximum: new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE)
    };
    this._indexBufferIsUpdatable = false;
    this._positionsCache = [];
    this._parentContainer = null;
    this.useBoundingInfoFromGeometry = false;
    this._scene = scene || EngineStore.LastCreatedScene;
    if (!this._scene) {
      return;
    }
    this.id = id;
    this.uniqueId = this._scene.getUniqueId();
    this._engine = this._scene.getEngine();
    this._meshes = [];
    this._vertexBuffers = {};
    this._indices = [];
    this._updatable = updatable;
    if (vertexData) {
      this.setAllVerticesData(vertexData, updatable);
    } else {
      this._totalVertices = 0;
    }
    if (this._engine.getCaps().vertexArrayObject) {
      this._vertexArrayObjects = {};
    }
    if (mesh) {
      this.applyToMesh(mesh);
      mesh.computeWorldMatrix(true);
    }
  }
  get extend() {
    return this._extend;
  }
  getScene() {
    return this._scene;
  }
  getEngine() {
    return this._engine;
  }
  isReady() {
    return this.delayLoadState === 1 || this.delayLoadState === 0;
  }
  get doNotSerialize() {
    for (let index = 0;index < this._meshes.length; index++) {
      if (!this._meshes[index].doNotSerialize) {
        return false;
      }
    }
    return true;
  }
  _rebuild() {
    if (this._vertexArrayObjects) {
      this._vertexArrayObjects = {};
    }
    if (this._meshes.length !== 0 && this._indices) {
      this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer");
    }
    const buffers = new Set;
    for (const key in this._vertexBuffers) {
      buffers.add(this._vertexBuffers[key].getWrapperBuffer());
    }
    buffers.forEach((buffer) => {
      buffer._rebuild();
    });
  }
  setAllVerticesData(vertexData, updatable) {
    vertexData.applyToGeometry(this, updatable);
    this._notifyUpdate();
  }
  setVerticesData(kind, data, updatable = false, stride) {
    if (updatable && Array.isArray(data)) {
      data = new Float32Array(data);
    }
    const buffer = new VertexBuffer(this._engine, data, kind, {
      updatable,
      postponeInternalCreation: this._meshes.length === 0,
      stride,
      label: "Geometry_" + this.id + "_" + kind
    });
    this.setVerticesBuffer(buffer);
  }
  removeVerticesData(kind) {
    if (this._vertexBuffers[kind]) {
      this._vertexBuffers[kind].dispose();
      delete this._vertexBuffers[kind];
    }
    if (this._vertexArrayObjects) {
      this._disposeVertexArrayObjects();
    }
  }
  setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) {
    const kind = buffer.getKind();
    if (this._vertexBuffers[kind] && disposeExistingBuffer) {
      this._vertexBuffers[kind].dispose();
    }
    if (buffer._buffer) {
      buffer._buffer._increaseReferences();
    }
    this._vertexBuffers[kind] = buffer;
    const meshes = this._meshes;
    const numOfMeshes = meshes.length;
    if (kind === VertexBuffer.PositionKind) {
      this._totalVertices = totalVertices ?? buffer._maxVerticesCount;
      this._updateExtend(buffer.getFloatData(this._totalVertices));
      this._resetPointsArrayCache();
      const minimum = this._extend && this._extend.minimum || new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
      const maximum = this._extend && this._extend.maximum || new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
      for (let index = 0;index < numOfMeshes; index++) {
        const mesh = meshes[index];
        mesh.buildBoundingInfo(minimum, maximum);
        mesh._createGlobalSubMesh(mesh.isUnIndexed);
        mesh.computeWorldMatrix(true);
        mesh.synchronizeInstances();
      }
    }
    this._notifyUpdate(kind);
  }
  updateVerticesDataDirectly(kind, data, offset, useBytes = false) {
    const vertexBuffer = this.getVertexBuffer(kind);
    if (!vertexBuffer) {
      return;
    }
    vertexBuffer.updateDirectly(data, offset, useBytes);
    this._notifyUpdate(kind);
  }
  updateVerticesData(kind, data, updateExtends = false) {
    const vertexBuffer = this.getVertexBuffer(kind);
    if (!vertexBuffer) {
      return;
    }
    vertexBuffer.update(data);
    if (kind === VertexBuffer.PositionKind) {
      this._updateBoundingInfo(updateExtends, data);
    }
    this._notifyUpdate(kind);
  }
  _updateBoundingInfo(updateExtends, data) {
    if (updateExtends) {
      this._updateExtend(data);
    }
    this._resetPointsArrayCache();
    if (updateExtends) {
      const meshes = this._meshes;
      for (const mesh of meshes) {
        if (mesh.hasBoundingInfo) {
          mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum);
        } else {
          mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
        }
        const subMeshes = mesh.subMeshes;
        for (const subMesh of subMeshes) {
          subMesh.refreshBoundingInfo();
        }
      }
    }
  }
  _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) {
    if (!effect) {
      return;
    }
    if (indexToBind === undefined) {
      indexToBind = this._indexBuffer;
    }
    const vbs = this.getVertexBuffers();
    if (!vbs) {
      return;
    }
    if (indexToBind != this._indexBuffer || !this._vertexArrayObjects && !overrideVertexArrayObjects) {
      this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers);
      return;
    }
    const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects;
    const engine = this._engine;
    if (!vaos[effect.key]) {
      vaos[effect.key] = engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers);
    }
    engine.bindVertexArrayObject(vaos[effect.key], indexToBind);
  }
  getTotalVertices() {
    if (!this.isReady()) {
      return 0;
    }
    return this._totalVertices;
  }
  getVerticesData(kind, copyWhenShared, forceCopy) {
    const vertexBuffer = this.getVertexBuffer(kind);
    if (!vertexBuffer) {
      return null;
    }
    return vertexBuffer.getFloatData(this._totalVertices, forceCopy || copyWhenShared && this._meshes.length !== 1);
  }
  copyVerticesData(kind, vertexData) {
    const vertexBuffer = this.getVertexBuffer(kind);
    if (!vertexBuffer) {
      return;
    }
    vertexData[kind] || (vertexData[kind] = new Float32Array(this._totalVertices * vertexBuffer.getSize()));
    const data = vertexBuffer.getData();
    if (data) {
      CopyFloatData(data, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, this._totalVertices, vertexData[kind]);
    }
  }
  isVertexBufferUpdatable(kind) {
    const vb = this._vertexBuffers[kind];
    if (!vb) {
      return false;
    }
    return vb.isUpdatable();
  }
  getVertexBuffer(kind) {
    if (!this.isReady()) {
      return null;
    }
    return this._vertexBuffers[kind];
  }
  getVertexBuffers() {
    if (!this.isReady()) {
      return null;
    }
    return this._vertexBuffers;
  }
  isVerticesDataPresent(kind) {
    if (!this._vertexBuffers) {
      if (this._delayInfo) {
        return this._delayInfo.indexOf(kind) !== -1;
      }
      return false;
    }
    return this._vertexBuffers[kind] !== undefined;
  }
  getVerticesDataKinds() {
    const result = [];
    let kind;
    if (!this._vertexBuffers && this._delayInfo) {
      for (kind in this._delayInfo) {
        result.push(kind);
      }
    } else {
      for (kind in this._vertexBuffers) {
        result.push(kind);
      }
    }
    return result;
  }
  updateIndices(indices, offset, gpuMemoryOnly = false) {
    if (!this._indexBuffer) {
      return;
    }
    if (!this._indexBufferIsUpdatable) {
      this.setIndices(indices, null, true);
    } else {
      const needToUpdateSubMeshes = indices.length !== this._indices.length;
      if (!gpuMemoryOnly) {
        this._indices = indices.slice();
      }
      this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
      if (needToUpdateSubMeshes) {
        for (const mesh of this._meshes) {
          mesh._createGlobalSubMesh(true);
        }
      }
    }
  }
  setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) {
    this._indices = [];
    this._indexBufferIsUpdatable = false;
    this._indexBuffer = indexBuffer;
    this._totalVertices = totalVertices;
    this._totalIndices = totalIndices;
    if (is32Bits === null) {
      indexBuffer.is32Bits = totalVertices > 65535;
    } else {
      indexBuffer.is32Bits = is32Bits;
    }
    for (const mesh of this._meshes) {
      mesh._createGlobalSubMesh(true);
      mesh.synchronizeInstances();
    }
    this._notifyUpdate();
  }
  setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) {
    if (this._indexBuffer) {
      this._engine._releaseBuffer(this._indexBuffer);
    }
    this._indices = indices;
    this._indexBufferIsUpdatable = updatable;
    if (this._meshes.length !== 0 && this._indices) {
      this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable, "Geometry_" + this.id + "_IndexBuffer");
    }
    if (totalVertices != null) {
      this._totalVertices = totalVertices;
    }
    for (const mesh of this._meshes) {
      mesh._createGlobalSubMesh(!dontForceSubMeshRecreation);
      mesh.synchronizeInstances();
    }
    this._notifyUpdate();
  }
  getTotalIndices() {
    if (!this.isReady()) {
      return 0;
    }
    return this._totalIndices !== undefined ? this._totalIndices : this._indices.length;
  }
  getIndices(copyWhenShared, forceCopy) {
    if (!this.isReady()) {
      return null;
    }
    const orig = this._indices;
    if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
      return orig;
    } else {
      return orig.slice();
    }
  }
  getIndexBuffer() {
    if (!this.isReady()) {
      return null;
    }
    return this._indexBuffer;
  }
  _releaseVertexArrayObject(effect = null) {
    if (!effect || !this._vertexArrayObjects) {
      return;
    }
    if (this._vertexArrayObjects[effect.key]) {
      this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
      delete this._vertexArrayObjects[effect.key];
    }
  }
  releaseForMesh(mesh, shouldDispose) {
    const meshes = this._meshes;
    const index = meshes.indexOf(mesh);
    if (index === -1) {
      return;
    }
    meshes.splice(index, 1);
    if (this._vertexArrayObjects) {
      mesh._invalidateInstanceVertexArrayObject();
    }
    mesh._geometry = null;
    if (meshes.length === 0 && shouldDispose) {
      this.dispose();
    }
  }
  applyToMesh(mesh) {
    if (mesh._geometry === this) {
      return;
    }
    const previousGeometry = mesh._geometry;
    if (previousGeometry) {
      previousGeometry.releaseForMesh(mesh);
    }
    if (this._vertexArrayObjects) {
      mesh._invalidateInstanceVertexArrayObject();
    }
    const meshes = this._meshes;
    mesh._geometry = this;
    mesh._internalAbstractMeshDataInfo._positions = null;
    this._scene.pushGeometry(this);
    meshes.push(mesh);
    if (this.isReady()) {
      this._applyToMesh(mesh);
    } else if (this._boundingInfo) {
      mesh.setBoundingInfo(this._boundingInfo);
    }
  }
  _updateExtend(data = null) {
    if (this.useBoundingInfoFromGeometry && this._boundingInfo) {
      this._extend = {
        minimum: this._boundingInfo.minimum.clone(),
        maximum: this._boundingInfo.maximum.clone()
      };
    } else {
      if (!data) {
        data = this.getVerticesData(VertexBuffer.PositionKind);
        if (!data) {
          return;
        }
      }
      this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
    }
  }
  _applyToMesh(mesh) {
    const numOfMeshes = this._meshes.length;
    for (const kind in this._vertexBuffers) {
      if (numOfMeshes === 1) {
        this._vertexBuffers[kind].create();
      }
      if (kind === VertexBuffer.PositionKind) {
        if (!this._extend) {
          this._updateExtend();
        }
        mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);
        mesh._createGlobalSubMesh(mesh.isUnIndexed);
        mesh._updateBoundingInfo();
      }
    }
    if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
      this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer");
    }
    mesh._syncGeometryWithMorphTargetManager();
    mesh.synchronizeInstances();
  }
  _notifyUpdate(kind) {
    if (this.onGeometryUpdated) {
      this.onGeometryUpdated(this, kind);
    }
    if (this._vertexArrayObjects) {
      this._disposeVertexArrayObjects();
    }
    for (const mesh of this._meshes) {
      mesh._markSubMeshesAsAttributesDirty();
    }
  }
  load(scene, onLoaded) {
    if (this.delayLoadState === 2) {
      return;
    }
    if (this.isReady()) {
      if (onLoaded) {
        onLoaded();
      }
      return;
    }
    this.delayLoadState = 2;
    this._queueLoad(scene, onLoaded);
  }
  _queueLoad(scene, onLoaded) {
    if (!this.delayLoadingFile) {
      return;
    }
    scene.addPendingData(this);
    scene._loadFile(this.delayLoadingFile, (data) => {
      if (!this._delayLoadingFunction) {
        return;
      }
      this._delayLoadingFunction(JSON.parse(data), this);
      this.delayLoadState = 1;
      this._delayInfo = [];
      scene.removePendingData(this);
      const meshes = this._meshes;
      const numOfMeshes = meshes.length;
      for (let index = 0;index < numOfMeshes; index++) {
        this._applyToMesh(meshes[index]);
      }
      if (onLoaded) {
        onLoaded();
      }
    }, undefined, true);
  }
  toLeftHanded() {
    const tIndices = this.getIndices(false);
    if (tIndices != null && tIndices.length > 0) {
      for (let i = 0;i < tIndices.length; i += 3) {
        const tTemp = tIndices[i + 0];
        tIndices[i + 0] = tIndices[i + 2];
        tIndices[i + 2] = tTemp;
      }
      this.setIndices(tIndices);
    }
    const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
    if (tPositions != null && tPositions.length > 0) {
      for (let i = 0;i < tPositions.length; i += 3) {
        tPositions[i + 2] = -tPositions[i + 2];
      }
      this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
    }
    const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
    if (tNormals != null && tNormals.length > 0) {
      for (let i = 0;i < tNormals.length; i += 3) {
        tNormals[i + 2] = -tNormals[i + 2];
      }
      this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
    }
  }
  _resetPointsArrayCache() {
    this._positions = null;
  }
  _generatePointsArray() {
    if (this._positions) {
      return true;
    }
    const data = this.getVerticesData(VertexBuffer.PositionKind);
    if (!data || data.length === 0) {
      return false;
    }
    for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length;index < data.length; index += 3, ++arrayIdx) {
      this._positionsCache[arrayIdx] = Vector3.FromArray(data, index);
    }
    for (let index = 0, arrayIdx = 0;index < data.length; index += 3, ++arrayIdx) {
      this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]);
    }
    this._positionsCache.length = data.length / 3;
    this._positions = this._positionsCache;
    return true;
  }
  isDisposed() {
    return this._isDisposed;
  }
  _disposeVertexArrayObjects() {
    if (this._vertexArrayObjects) {
      for (const kind in this._vertexArrayObjects) {
        this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
      }
      this._vertexArrayObjects = {};
      const meshes = this._meshes;
      const numOfMeshes = meshes.length;
      for (let index = 0;index < numOfMeshes; index++) {
        meshes[index]._invalidateInstanceVertexArrayObject();
      }
    }
  }
  dispose() {
    const meshes = this._meshes;
    const numOfMeshes = meshes.length;
    let index;
    for (index = 0;index < numOfMeshes; index++) {
      this.releaseForMesh(meshes[index]);
    }
    this._meshes.length = 0;
    this._disposeVertexArrayObjects();
    for (const kind in this._vertexBuffers) {
      this._vertexBuffers[kind].dispose();
    }
    this._vertexBuffers = {};
    this._totalVertices = 0;
    if (this._indexBuffer) {
      this._engine._releaseBuffer(this._indexBuffer);
    }
    this._indexBuffer = null;
    this._indices = [];
    this.delayLoadState = 0;
    this.delayLoadingFile = null;
    this._delayLoadingFunction = null;
    this._delayInfo = [];
    this._boundingInfo = null;
    this._scene.removeGeometry(this);
    if (this._parentContainer) {
      const index2 = this._parentContainer.geometries.indexOf(this);
      if (index2 > -1) {
        this._parentContainer.geometries.splice(index2, 1);
      }
      this._parentContainer = null;
    }
    this._isDisposed = true;
  }
  copy(id) {
    const vertexData = new VertexData;
    vertexData.indices = [];
    const indices = this.getIndices();
    if (indices) {
      for (let index = 0;index < indices.length; index++) {
        vertexData.indices.push(indices[index]);
      }
    }
    let updatable = false;
    let stopChecking = false;
    let kind;
    for (kind in this._vertexBuffers) {
      const data = this.getVerticesData(kind);
      if (data) {
        if (data instanceof Float32Array) {
          vertexData.set(new Float32Array(data), kind);
        } else {
          vertexData.set(data.slice(0), kind);
        }
        if (!stopChecking) {
          const vb = this.getVertexBuffer(kind);
          if (vb) {
            updatable = vb.isUpdatable();
            stopChecking = !updatable;
          }
        }
      }
    }
    const geometry = new Geometry(id, this._scene, vertexData, updatable);
    geometry.delayLoadState = this.delayLoadState;
    geometry.delayLoadingFile = this.delayLoadingFile;
    geometry._delayLoadingFunction = this._delayLoadingFunction;
    for (kind in this._delayInfo) {
      geometry._delayInfo = geometry._delayInfo || [];
      geometry._delayInfo.push(kind);
    }
    geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
    return geometry;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.id = this.id;
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.updatable = this._updatable;
    if (Tags && Tags.HasTags(this)) {
      serializationObject.tags = Tags.GetTags(this);
    }
    return serializationObject;
  }
  _toNumberArray(origin) {
    if (Array.isArray(origin)) {
      return origin;
    } else {
      return Array.prototype.slice.call(origin);
    }
  }
  clearCachedData() {
    this._indices = [];
    this._resetPointsArrayCache();
    for (const vbName in this._vertexBuffers) {
      if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) {
        continue;
      }
      this._vertexBuffers[vbName]._buffer._data = null;
    }
  }
  serializeVerticeData() {
    const serializationObject = this.serialize();
    if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
      serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
        serializationObject.positions._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
        serializationObject.normals._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
      serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {
        serializationObject.tangents._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {
      serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {
        serializationObject.uvs._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
      serializationObject.uvs2 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {
        serializationObject.uvs2._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
      serializationObject.uvs3 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {
        serializationObject.uvs3._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
      serializationObject.uvs4 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {
        serializationObject.uvs4._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
      serializationObject.uvs5 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {
        serializationObject.uvs5._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
      serializationObject.uvs6 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));
      if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {
        serializationObject.uvs6._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {
      serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {
        serializationObject.colors._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
      serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));
      serializationObject.matricesIndices._isExpanded = true;
      if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {
        serializationObject.matricesIndices._updatable = true;
      }
    }
    if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
      serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));
      if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {
        serializationObject.matricesWeights._updatable = true;
      }
    }
    serializationObject.indices = this._toNumberArray(this.getIndices());
    return serializationObject;
  }
  static ExtractFromMesh(mesh, id) {
    const geometry = mesh._geometry;
    if (!geometry) {
      return null;
    }
    return geometry.copy(id);
  }
  static RandomId() {
    return Tools.RandomId();
  }
  static _GetGeometryByLoadedUniqueId(uniqueId, scene) {
    for (let index = 0;index < scene.geometries.length; index++) {
      if (scene.geometries[index]._loadedUniqueId === uniqueId) {
        return scene.geometries[index];
      }
    }
    return null;
  }
  static _ImportGeometry(parsedGeometry, mesh) {
    const scene = mesh.getScene();
    const geometryUniqueId = parsedGeometry.geometryUniqueId;
    const geometryId = parsedGeometry.geometryId;
    if (geometryUniqueId || geometryId) {
      const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId);
      if (geometry) {
        geometry.applyToMesh(mesh);
      }
    } else if (parsedGeometry instanceof ArrayBuffer) {
      const binaryInfo = mesh._binaryInfo;
      if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
        const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
        mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);
      }
      if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
        const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
        mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);
      }
      if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
        const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
        mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);
      }
      if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
        const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvsData.length; index += 2) {
            uvsData[index] = 1 - uvsData[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);
      }
      if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
        const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvs2Data.length; index += 2) {
            uvs2Data[index] = 1 - uvs2Data[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);
      }
      if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
        const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvs3Data.length; index += 2) {
            uvs3Data[index] = 1 - uvs3Data[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);
      }
      if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
        const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvs4Data.length; index += 2) {
            uvs4Data[index] = 1 - uvs4Data[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);
      }
      if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
        const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvs5Data.length; index += 2) {
            uvs5Data[index] = 1 - uvs5Data[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);
      }
      if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
        const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
        if (useOpenGLOrientationForUV) {
          for (let index = 1;index < uvs6Data.length; index += 2) {
            uvs6Data[index] = 1 - uvs6Data[index];
          }
        }
        mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);
      }
      if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
        const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
        mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
      }
      if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
        const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
        const floatIndices = [];
        for (let i = 0;i < matricesIndicesData.length; i++) {
          const index = matricesIndicesData[i];
          floatIndices.push(index & 255);
          floatIndices.push((index & 65280) >> 8);
          floatIndices.push((index & 16711680) >> 16);
          floatIndices.push(index >> 24 & 255);
        }
        mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);
      }
      if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) {
        const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count);
        const floatIndices = [];
        for (let i = 0;i < matricesIndicesData.length; i++) {
          const index = matricesIndicesData[i];
          floatIndices.push(index & 255);
          floatIndices.push((index & 65280) >> 8);
          floatIndices.push((index & 16711680) >> 16);
          floatIndices.push(index >> 24 & 255);
        }
        mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
      }
      if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
        const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
        mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
      }
      if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
        const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
        mesh.setIndices(indicesData, null);
      }
      if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
        const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
        mesh.subMeshes = [];
        for (let i = 0;i < binaryInfo.subMeshesAttrDesc.count; i++) {
          const materialIndex = subMeshesData[i * 5 + 0];
          const verticesStart = subMeshesData[i * 5 + 1];
          const verticesCount = subMeshesData[i * 5 + 2];
          const indexStart = subMeshesData[i * 5 + 3];
          const indexCount = subMeshesData[i * 5 + 4];
          SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
        }
      }
    } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
      mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
      mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
      if (parsedGeometry.tangents) {
        mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
      }
      if (parsedGeometry.uvs) {
        mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
      }
      if (parsedGeometry.uvs2) {
        mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
      }
      if (parsedGeometry.uvs3) {
        mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
      }
      if (parsedGeometry.uvs4) {
        mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
      }
      if (parsedGeometry.uvs5) {
        mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
      }
      if (parsedGeometry.uvs6) {
        mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
      }
      if (parsedGeometry.colors) {
        mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
      }
      if (parsedGeometry.matricesIndices) {
        if (!parsedGeometry.matricesIndices._isExpanded) {
          const floatIndices = [];
          for (let i = 0;i < parsedGeometry.matricesIndices.length; i++) {
            const matricesIndex = parsedGeometry.matricesIndices[i];
            floatIndices.push(matricesIndex & 255);
            floatIndices.push((matricesIndex & 65280) >> 8);
            floatIndices.push((matricesIndex & 16711680) >> 16);
            floatIndices.push(matricesIndex >> 24 & 255);
          }
          mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
        } else {
          delete parsedGeometry.matricesIndices._isExpanded;
          mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
        }
      }
      if (parsedGeometry.matricesIndicesExtra) {
        if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
          const floatIndices = [];
          for (let i = 0;i < parsedGeometry.matricesIndicesExtra.length; i++) {
            const matricesIndex = parsedGeometry.matricesIndicesExtra[i];
            floatIndices.push(matricesIndex & 255);
            floatIndices.push((matricesIndex & 65280) >> 8);
            floatIndices.push((matricesIndex & 16711680) >> 16);
            floatIndices.push(matricesIndex >> 24 & 255);
          }
          mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
        } else {
          delete parsedGeometry.matricesIndices._isExpanded;
          mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
        }
      }
      if (parsedGeometry.matricesWeights) {
        Geometry._CleanMatricesWeights(parsedGeometry, mesh);
        mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
      }
      if (parsedGeometry.matricesWeightsExtra) {
        mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
      }
      mesh.setIndices(parsedGeometry.indices, null);
    }
    if (parsedGeometry.subMeshes) {
      mesh.subMeshes = [];
      for (let subIndex = 0;subIndex < parsedGeometry.subMeshes.length; subIndex++) {
        const parsedSubMesh = parsedGeometry.subMeshes[subIndex];
        SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
      }
    }
    if (mesh._shouldGenerateFlatShading) {
      mesh.convertToFlatShadedMesh();
      mesh._shouldGenerateFlatShading = false;
    }
    mesh.computeWorldMatrix(true);
    scene.onMeshImportedObservable.notifyObservers(mesh);
  }
  static _CleanMatricesWeights(parsedGeometry, mesh) {
    const epsilon = 0.001;
    if (!SceneLoaderFlags.CleanBoneMatrixWeights) {
      return;
    }
    let noInfluenceBoneIndex = 0;
    if (parsedGeometry.skeletonId > -1) {
      const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId);
      if (!skeleton) {
        return;
      }
      noInfluenceBoneIndex = skeleton.bones.length;
    } else {
      return;
    }
    const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);
    const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);
    const matricesWeights = parsedGeometry.matricesWeights;
    const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
    const influencers = parsedGeometry.numBoneInfluencer;
    const size = matricesWeights.length;
    for (let i = 0;i < size; i += 4) {
      let weight = 0;
      let firstZeroWeight = -1;
      for (let j = 0;j < 4; j++) {
        const w = matricesWeights[i + j];
        weight += w;
        if (w < epsilon && firstZeroWeight < 0) {
          firstZeroWeight = j;
        }
      }
      if (matricesWeightsExtra) {
        for (let j = 0;j < 4; j++) {
          const w = matricesWeightsExtra[i + j];
          weight += w;
          if (w < epsilon && firstZeroWeight < 0) {
            firstZeroWeight = j + 4;
          }
        }
      }
      if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) {
        firstZeroWeight = influencers - 1;
      }
      if (weight > epsilon) {
        const mweight = 1 / weight;
        for (let j = 0;j < 4; j++) {
          matricesWeights[i + j] *= mweight;
        }
        if (matricesWeightsExtra) {
          for (let j = 0;j < 4; j++) {
            matricesWeightsExtra[i + j] *= mweight;
          }
        }
      } else {
        if (firstZeroWeight >= 4) {
          matricesWeightsExtra[i + firstZeroWeight - 4] = 1 - weight;
          matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
        } else {
          matricesWeights[i + firstZeroWeight] = 1 - weight;
          matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
        }
      }
    }
    mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
    if (parsedGeometry.matricesWeightsExtra) {
      mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
    }
  }
  static Parse(parsedVertexData, scene, rootUrl) {
    const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
    geometry._loadedUniqueId = parsedVertexData.uniqueId;
    if (Tags) {
      Tags.AddTagsTo(geometry, parsedVertexData.tags);
    }
    if (parsedVertexData.delayLoadingFile) {
      geometry.delayLoadState = 4;
      geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
      geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
      geometry._delayInfo = [];
      if (parsedVertexData.hasUVs) {
        geometry._delayInfo.push(VertexBuffer.UVKind);
      }
      if (parsedVertexData.hasUVs2) {
        geometry._delayInfo.push(VertexBuffer.UV2Kind);
      }
      if (parsedVertexData.hasUVs3) {
        geometry._delayInfo.push(VertexBuffer.UV3Kind);
      }
      if (parsedVertexData.hasUVs4) {
        geometry._delayInfo.push(VertexBuffer.UV4Kind);
      }
      if (parsedVertexData.hasUVs5) {
        geometry._delayInfo.push(VertexBuffer.UV5Kind);
      }
      if (parsedVertexData.hasUVs6) {
        geometry._delayInfo.push(VertexBuffer.UV6Kind);
      }
      if (parsedVertexData.hasColors) {
        geometry._delayInfo.push(VertexBuffer.ColorKind);
      }
      if (parsedVertexData.hasMatricesIndices) {
        geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);
      }
      if (parsedVertexData.hasMatricesWeights) {
        geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);
      }
      geometry._delayLoadingFunction = VertexData.ImportVertexData;
    } else {
      VertexData.ImportVertexData(parsedVertexData, geometry);
    }
    scene.pushGeometry(geometry, true);
    return geometry;
  }
}

// node_modules/@babylonjs/core/Meshes/abstractMesh.js
init_tslib_es6();
init_observable();
init_math_vector();
init_buffer();

// node_modules/@babylonjs/core/Meshes/transformNode.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_observable();
init_math_vector();
init_node();
init_typeStore();
var convertRHSToLHS = Matrix.Compose(Vector3.One(), Quaternion.FromEulerAngles(0, Math.PI, 0), Vector3.Zero());

class TransformNode extends Node2 {
  get billboardMode() {
    return this._billboardMode;
  }
  set billboardMode(value) {
    if (this._billboardMode === value) {
      return;
    }
    this._billboardMode = value;
    this._cache.useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0;
    this._computeUseBillboardPath();
  }
  get preserveParentRotationForBillboard() {
    return this._preserveParentRotationForBillboard;
  }
  set preserveParentRotationForBillboard(value) {
    if (value === this._preserveParentRotationForBillboard) {
      return;
    }
    this._preserveParentRotationForBillboard = value;
    this._computeUseBillboardPath();
  }
  _computeUseBillboardPath() {
    this._cache.useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
  }
  get infiniteDistance() {
    return this._infiniteDistance;
  }
  set infiniteDistance(value) {
    if (this._infiniteDistance === value) {
      return;
    }
    this._infiniteDistance = value;
  }
  constructor(name18, scene = null, isPure = true) {
    super(name18, scene, false);
    this._forward = new Vector3(0, 0, 1);
    this._up = new Vector3(0, 1, 0);
    this._right = new Vector3(1, 0, 0);
    this._position = Vector3.Zero();
    this._rotation = Vector3.Zero();
    this._rotationQuaternion = null;
    this._scaling = Vector3.One();
    this._transformToBoneReferal = null;
    this._isAbsoluteSynced = false;
    this._billboardMode = TransformNode.BILLBOARDMODE_NONE;
    this._preserveParentRotationForBillboard = false;
    this.scalingDeterminant = 1;
    this._infiniteDistance = false;
    this.ignoreNonUniformScaling = false;
    this.reIntegrateRotationIntoRotationQuaternion = false;
    this._poseMatrix = null;
    this._localMatrix = Matrix.Zero();
    this._usePivotMatrix = false;
    this._absolutePosition = Vector3.Zero();
    this._absoluteScaling = Vector3.Zero();
    this._absoluteRotationQuaternion = Quaternion.Identity();
    this._pivotMatrix = Matrix.Identity();
    this._postMultiplyPivotMatrix = false;
    this._isWorldMatrixFrozen = false;
    this._indexInSceneTransformNodesArray = -1;
    this.onAfterWorldMatrixUpdateObservable = new Observable;
    this._nonUniformScaling = false;
    if (isPure) {
      this.getScene().addTransformNode(this);
    }
  }
  getClassName() {
    return "TransformNode";
  }
  get position() {
    return this._position;
  }
  set position(newPosition) {
    this._position = newPosition;
    this._markAsDirtyInternal();
  }
  isUsingPivotMatrix() {
    return this._usePivotMatrix;
  }
  isUsingPostMultiplyPivotMatrix() {
    return this._postMultiplyPivotMatrix;
  }
  get rotation() {
    return this._rotation;
  }
  set rotation(newRotation) {
    this._rotation = newRotation;
    this._rotationQuaternion = null;
    this._markAsDirtyInternal();
  }
  get scaling() {
    return this._scaling;
  }
  set scaling(newScaling) {
    this._scaling = newScaling;
    this._markAsDirtyInternal();
  }
  get rotationQuaternion() {
    return this._rotationQuaternion;
  }
  set rotationQuaternion(quaternion) {
    this._rotationQuaternion = quaternion;
    if (quaternion) {
      this._rotation.setAll(0);
    }
    this._markAsDirtyInternal();
  }
  _markAsDirtyInternal() {
    if (this._isDirty) {
      return;
    }
    this._isDirty = true;
    if (this.customMarkAsDirty) {
      this.customMarkAsDirty();
    }
  }
  get forward() {
    Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1 : 1, this.getWorldMatrix(), this._forward);
    return this._forward.normalize();
  }
  get up() {
    Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up);
    return this._up.normalize();
  }
  get right() {
    Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1 : 1, 0, 0, this.getWorldMatrix(), this._right);
    return this._right.normalize();
  }
  updatePoseMatrix(matrix) {
    if (!this._poseMatrix) {
      this._poseMatrix = matrix.clone();
      return this;
    }
    this._poseMatrix.copyFrom(matrix);
    return this;
  }
  getPoseMatrix() {
    if (!this._poseMatrix) {
      this._poseMatrix = Matrix.Identity();
    }
    return this._poseMatrix;
  }
  _isSynchronized() {
    const cache = this._cache;
    if (this._billboardMode !== cache.billboardMode || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
      return false;
    }
    if (cache.pivotMatrixUpdated) {
      return false;
    }
    if (this._infiniteDistance) {
      return false;
    }
    if (this._position._isDirty) {
      return false;
    }
    if (this._scaling._isDirty) {
      return false;
    }
    if (this._rotationQuaternion && this._rotationQuaternion._isDirty || this._rotation._isDirty) {
      return false;
    }
    return true;
  }
  _initCache() {
    super._initCache();
    const cache = this._cache;
    cache.localMatrixUpdated = false;
    cache.billboardMode = -1;
    cache.infiniteDistance = false;
    cache.useBillboardPosition = false;
    cache.useBillboardPath = false;
  }
  get absolutePosition() {
    return this.getAbsolutePosition();
  }
  get absoluteScaling() {
    this._syncAbsoluteScalingAndRotation();
    return this._absoluteScaling;
  }
  get absoluteRotationQuaternion() {
    this._syncAbsoluteScalingAndRotation();
    return this._absoluteRotationQuaternion;
  }
  setPreTransformMatrix(matrix) {
    return this.setPivotMatrix(matrix, false);
  }
  setPivotMatrix(matrix, postMultiplyPivotMatrix = true) {
    this._pivotMatrix.copyFrom(matrix);
    this._usePivotMatrix = !this._pivotMatrix.isIdentity();
    this._cache.pivotMatrixUpdated = true;
    this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
    if (this._postMultiplyPivotMatrix) {
      if (!this._pivotMatrixInverse) {
        this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix);
      } else {
        this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
      }
    }
    return this;
  }
  getPivotMatrix() {
    return this._pivotMatrix;
  }
  instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
    const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true);
    if (clone) {
      if (onNewNodeCreated) {
        onNewNodeCreated(this, clone);
      }
    }
    for (const child of this.getChildTransformNodes(true)) {
      child.instantiateHierarchy(clone, options, onNewNodeCreated);
    }
    return clone;
  }
  freezeWorldMatrix(newWorldMatrix = null, decompose = false) {
    if (newWorldMatrix) {
      if (decompose) {
        this._rotation.setAll(0);
        this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity();
        newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position);
        this.computeWorldMatrix(true);
      } else {
        this._worldMatrix = newWorldMatrix;
        this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
        this._afterComputeWorldMatrix();
      }
    } else {
      this._isWorldMatrixFrozen = false;
      this.computeWorldMatrix(true);
    }
    this._isDirty = false;
    this._isWorldMatrixFrozen = true;
    return this;
  }
  unfreezeWorldMatrix() {
    this._isWorldMatrixFrozen = false;
    this.computeWorldMatrix(true);
    return this;
  }
  get isWorldMatrixFrozen() {
    return this._isWorldMatrixFrozen;
  }
  getAbsolutePosition() {
    this.computeWorldMatrix();
    return this._absolutePosition;
  }
  setAbsolutePosition(absolutePosition) {
    if (!absolutePosition) {
      return this;
    }
    let absolutePositionX;
    let absolutePositionY;
    let absolutePositionZ;
    if (absolutePosition.x === undefined) {
      if (arguments.length < 3) {
        return this;
      }
      absolutePositionX = arguments[0];
      absolutePositionY = arguments[1];
      absolutePositionZ = arguments[2];
    } else {
      absolutePositionX = absolutePosition.x;
      absolutePositionY = absolutePosition.y;
      absolutePositionZ = absolutePosition.z;
    }
    if (this.parent) {
      const invertParentWorldMatrix = TmpVectors.Matrix[0];
      this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
      Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
    } else {
      this.position.x = absolutePositionX;
      this.position.y = absolutePositionY;
      this.position.z = absolutePositionZ;
    }
    this._absolutePosition.copyFrom(absolutePosition);
    return this;
  }
  setPositionWithLocalVector(vector3) {
    this.computeWorldMatrix();
    this.position = Vector3.TransformNormal(vector3, this._localMatrix);
    return this;
  }
  getPositionExpressedInLocalSpace() {
    this.computeWorldMatrix();
    const invLocalWorldMatrix = TmpVectors.Matrix[0];
    this._localMatrix.invertToRef(invLocalWorldMatrix);
    return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  }
  locallyTranslate(vector3) {
    this.computeWorldMatrix(true);
    this.position = Vector3.TransformCoordinates(vector3, this._localMatrix);
    return this;
  }
  lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = 0) {
    const dv = TransformNode._LookAtVectorCache;
    const pos = space === 0 ? this.position : this.getAbsolutePosition();
    targetPoint.subtractToRef(pos, dv);
    this.setDirection(dv, yawCor, pitchCor, rollCor);
    if (space === 1 && this.parent) {
      if (this.rotationQuaternion) {
        const rotationMatrix = TmpVectors.Matrix[0];
        this.rotationQuaternion.toRotationMatrix(rotationMatrix);
        const parentRotationMatrix = TmpVectors.Matrix[1];
        this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
        parentRotationMatrix.invert();
        rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
        this.rotationQuaternion.fromRotationMatrix(rotationMatrix);
      } else {
        const quaternionRotation = TmpVectors.Quaternion[0];
        Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);
        const rotationMatrix = TmpVectors.Matrix[0];
        quaternionRotation.toRotationMatrix(rotationMatrix);
        const parentRotationMatrix = TmpVectors.Matrix[1];
        this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
        parentRotationMatrix.invert();
        rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
        quaternionRotation.fromRotationMatrix(rotationMatrix);
        quaternionRotation.toEulerAnglesToRef(this.rotation);
      }
    }
    return this;
  }
  getDirection(localAxis) {
    const result = Vector3.Zero();
    this.getDirectionToRef(localAxis, result);
    return result;
  }
  getDirectionToRef(localAxis, result) {
    Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
    return this;
  }
  setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) {
    const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;
    const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
    const pitch = -Math.atan2(localAxis.y, len);
    if (this.rotationQuaternion) {
      Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
    } else {
      this.rotation.x = pitch + pitchCor;
      this.rotation.y = yaw + yawCor;
      this.rotation.z = rollCor;
    }
    return this;
  }
  setPivotPoint(point, space = 0) {
    if (this.getScene().getRenderId() == 0) {
      this.computeWorldMatrix(true);
    }
    const wm = this.getWorldMatrix();
    if (space == 1) {
      const tmat = TmpVectors.Matrix[0];
      wm.invertToRef(tmat);
      point = Vector3.TransformCoordinates(point, tmat);
    }
    return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);
  }
  getPivotPoint() {
    const point = Vector3.Zero();
    this.getPivotPointToRef(point);
    return point;
  }
  getPivotPointToRef(result) {
    result.x = -this._pivotMatrix.m[12];
    result.y = -this._pivotMatrix.m[13];
    result.z = -this._pivotMatrix.m[14];
    return this;
  }
  getAbsolutePivotPoint() {
    const point = Vector3.Zero();
    this.getAbsolutePivotPointToRef(point);
    return point;
  }
  getAbsolutePivotPointToRef(result) {
    this.getPivotPointToRef(result);
    Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
    return this;
  }
  markAsDirty(property) {
    if (this._isDirty) {
      return this;
    }
    if (this._children) {
      for (const child of this._children) {
        child.markAsDirty(property);
      }
    }
    return super.markAsDirty(property);
  }
  setParent(node, preserveScalingSign = false, updatePivot = false) {
    if (!node && !this.parent) {
      return this;
    }
    const quatRotation = TmpVectors.Quaternion[0];
    const position = TmpVectors.Vector3[0];
    const scale = TmpVectors.Vector3[1];
    const invParentMatrix = TmpVectors.Matrix[1];
    Matrix.IdentityToRef(invParentMatrix);
    const composedMatrix = TmpVectors.Matrix[0];
    this.computeWorldMatrix(true);
    let currentRotation = this.rotationQuaternion;
    if (!currentRotation) {
      currentRotation = TransformNode._TmpRotation;
      Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation);
    }
    Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix);
    if (this.parent) {
      composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix);
    }
    if (node) {
      node.computeWorldMatrix(true).invertToRef(invParentMatrix);
      composedMatrix.multiplyToRef(invParentMatrix, composedMatrix);
    }
    composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined);
    if (this.rotationQuaternion) {
      this.rotationQuaternion.copyFrom(quatRotation);
    } else {
      quatRotation.toEulerAnglesToRef(this.rotation);
    }
    this.scaling.copyFrom(scale);
    this.position.copyFrom(position);
    this.parent = node;
    if (updatePivot) {
      this.setPivotMatrix(Matrix.Identity());
    }
    return this;
  }
  addChild(mesh, preserveScalingSign = false) {
    mesh.setParent(this, preserveScalingSign);
    return this;
  }
  removeChild(mesh, preserveScalingSign = false) {
    if (mesh.parent !== this)
      return this;
    mesh.setParent(null, preserveScalingSign);
    return this;
  }
  get nonUniformScaling() {
    return this._nonUniformScaling;
  }
  _updateNonUniformScalingState(value) {
    if (this._nonUniformScaling === value) {
      return false;
    }
    this._nonUniformScaling = value;
    return true;
  }
  attachToBone(bone, affectedTransformNode) {
    this._currentParentWhenAttachingToBone = this.parent;
    this._transformToBoneReferal = affectedTransformNode;
    this.parent = bone;
    bone.getSkeleton().prepare(true);
    if (bone.getFinalMatrix().determinant() < 0) {
      this.scalingDeterminant *= -1;
    }
    return this;
  }
  detachFromBone(resetToPreviousParent = false) {
    if (!this.parent) {
      if (resetToPreviousParent) {
        this.parent = this._currentParentWhenAttachingToBone;
      }
      return this;
    }
    if (this.parent.getWorldMatrix().determinant() < 0) {
      this.scalingDeterminant *= -1;
    }
    this._transformToBoneReferal = null;
    if (resetToPreviousParent) {
      this.parent = this._currentParentWhenAttachingToBone;
    } else {
      this.parent = null;
    }
    return this;
  }
  rotate(axis, amount, space) {
    axis.normalize();
    if (!this.rotationQuaternion) {
      this.rotationQuaternion = this.rotation.toQuaternion();
      this.rotation.setAll(0);
    }
    let rotationQuaternion;
    if (!space || space === 0) {
      rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);
      this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
    } else {
      if (this.parent) {
        const parentWorldMatrix = this.parent.getWorldMatrix();
        const invertParentWorldMatrix = TmpVectors.Matrix[0];
        parentWorldMatrix.invertToRef(invertParentWorldMatrix);
        axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
        if (parentWorldMatrix.determinant() < 0) {
          amount *= -1;
        }
      }
      rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);
      rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
    }
    return this;
  }
  rotateAround(point, axis, amount) {
    axis.normalize();
    if (!this.rotationQuaternion) {
      this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
      this.rotation.setAll(0);
    }
    const tmpVector = TmpVectors.Vector3[0];
    const finalScale = TmpVectors.Vector3[1];
    const finalTranslation = TmpVectors.Vector3[2];
    const finalRotation = TmpVectors.Quaternion[0];
    const translationMatrix = TmpVectors.Matrix[0];
    const translationMatrixInv = TmpVectors.Matrix[1];
    const rotationMatrix = TmpVectors.Matrix[2];
    const finalMatrix = TmpVectors.Matrix[3];
    point.subtractToRef(this.position, tmpVector);
    Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix);
    Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv);
    Matrix.RotationAxisToRef(axis, amount, rotationMatrix);
    translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix);
    finalMatrix.multiplyToRef(translationMatrix, finalMatrix);
    finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
    this.position.addInPlace(finalTranslation);
    finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
    return this;
  }
  translate(axis, distance, space) {
    const displacementVector = axis.scale(distance);
    if (!space || space === 0) {
      const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
      this.setPositionWithLocalVector(tempV3);
    } else {
      this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
    }
    return this;
  }
  addRotation(x, y, z) {
    let rotationQuaternion;
    if (this.rotationQuaternion) {
      rotationQuaternion = this.rotationQuaternion;
    } else {
      rotationQuaternion = TmpVectors.Quaternion[1];
      Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
    }
    const accumulation = TmpVectors.Quaternion[0];
    Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
    rotationQuaternion.multiplyInPlace(accumulation);
    if (!this.rotationQuaternion) {
      rotationQuaternion.toEulerAnglesToRef(this.rotation);
    }
    return this;
  }
  _getEffectiveParent() {
    return this.parent;
  }
  isWorldMatrixCameraDependent() {
    return this._infiniteDistance && !this.parent || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
  }
  computeWorldMatrix(force = false, camera = null) {
    if (this._isWorldMatrixFrozen && !this._isDirty) {
      return this._worldMatrix;
    }
    const currentRenderId = this.getScene().getRenderId();
    if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) {
      this._currentRenderId = currentRenderId;
      return this._worldMatrix;
    }
    camera = camera || this.getScene().activeCamera;
    this._updateCache();
    const cache = this._cache;
    cache.pivotMatrixUpdated = false;
    cache.billboardMode = this.billboardMode;
    cache.infiniteDistance = this.infiniteDistance;
    cache.parent = this._parentNode;
    this._currentRenderId = currentRenderId;
    this._childUpdateId += 1;
    this._isDirty = false;
    this._position._isDirty = false;
    this._rotation._isDirty = false;
    this._scaling._isDirty = false;
    const parent = this._getEffectiveParent();
    const scaling = TransformNode._TmpScaling;
    let translation = this._position;
    if (this._infiniteDistance) {
      if (!this.parent && camera) {
        const cameraWorldMatrix = camera.getWorldMatrix();
        const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
        translation = TransformNode._TmpTranslation;
        translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z);
      }
    }
    scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
    let rotation;
    if (this._rotationQuaternion) {
      this._rotationQuaternion._isDirty = false;
      rotation = this._rotationQuaternion;
      if (this.reIntegrateRotationIntoRotationQuaternion) {
        const len = this.rotation.lengthSquared();
        if (len) {
          this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z));
          this._rotation.copyFromFloats(0, 0, 0);
        }
      }
    } else {
      rotation = TransformNode._TmpRotation;
      Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation);
    }
    if (this._usePivotMatrix) {
      const scaleMatrix = TmpVectors.Matrix[1];
      Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix);
      const rotationMatrix = TmpVectors.Matrix[0];
      rotation.toRotationMatrix(rotationMatrix);
      this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);
      TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix);
      if (this._postMultiplyPivotMatrix) {
        this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix);
      }
      this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z);
    } else {
      Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix);
    }
    if (parent && parent.getWorldMatrix) {
      if (force) {
        parent.computeWorldMatrix(force);
      }
      if (cache.useBillboardPath) {
        if (this._transformToBoneReferal) {
          const bone = this.parent;
          bone.getSkeleton().prepare();
          bone.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]);
        } else {
          TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix());
        }
        const translation2 = TmpVectors.Vector3[5];
        const scale = TmpVectors.Vector3[6];
        const orientation = TmpVectors.Quaternion[0];
        TmpVectors.Matrix[7].decompose(scale, orientation, translation2);
        Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]);
        TmpVectors.Matrix[7].setTranslation(translation2);
        if (TransformNode.BillboardUseParentOrientation) {
          this._position.applyRotationQuaternionToRef(orientation, translation2);
          this._localMatrix.setTranslation(translation2);
        }
        this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix);
      } else {
        if (this._transformToBoneReferal) {
          const bone = this.parent;
          bone.getSkeleton().prepare();
          this._localMatrix.multiplyToRef(bone.getFinalMatrix(), TmpVectors.Matrix[6]);
          TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
        } else {
          this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix);
        }
      }
      this._markSyncedWithParent();
    } else {
      this._worldMatrix.copyFrom(this._localMatrix);
    }
    if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) {
      const storedTranslation = TmpVectors.Vector3[0];
      this._worldMatrix.getTranslationToRef(storedTranslation);
      TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix());
      if (this._scene.useRightHandedSystem) {
        TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, TmpVectors.Matrix[1]);
      }
      TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0);
      TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]);
      if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
        TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined);
        const eulerAngles = TmpVectors.Vector3[1];
        TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
          eulerAngles.x = 0;
        }
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
          eulerAngles.y = 0;
        }
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
          eulerAngles.z = 0;
        }
        Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);
      }
      this._worldMatrix.setTranslationFromFloats(0, 0, 0);
      this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);
      this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);
    } else if (cache.useBillboardPath && camera && cache.useBillboardPosition) {
      const storedTranslation = TmpVectors.Vector3[0];
      this._worldMatrix.getTranslationToRef(storedTranslation);
      const cameraPosition = camera.globalPosition;
      this._worldMatrix.invertToRef(TmpVectors.Matrix[1]);
      const camInObjSpace = TmpVectors.Vector3[1];
      Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace);
      camInObjSpace.normalize();
      const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2;
      const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z);
      const pitch = -Math.atan2(camInObjSpace.y, len);
      Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]);
      if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
        const eulerAngles = TmpVectors.Vector3[1];
        TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
          eulerAngles.x = 0;
        }
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
          eulerAngles.y = 0;
        }
        if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
          eulerAngles.z = 0;
        }
        Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);
      } else {
        Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]);
      }
      this._worldMatrix.setTranslationFromFloats(0, 0, 0);
      this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);
      this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);
    }
    if (!this.ignoreNonUniformScaling) {
      if (this._scaling.isNonUniformWithinEpsilon(0.000001)) {
        this._updateNonUniformScalingState(true);
      } else if (parent && parent._nonUniformScaling) {
        this._updateNonUniformScalingState(parent._nonUniformScaling);
      } else {
        this._updateNonUniformScalingState(false);
      }
    } else {
      this._updateNonUniformScalingState(false);
    }
    this._afterComputeWorldMatrix();
    this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
    this._isAbsoluteSynced = false;
    this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
    if (!this._poseMatrix) {
      this._poseMatrix = Matrix.Invert(this._worldMatrix);
    }
    this._worldMatrixDeterminantIsDirty = true;
    return this._worldMatrix;
  }
  resetLocalMatrix(independentOfChildren = true) {
    this.computeWorldMatrix();
    if (independentOfChildren) {
      const children = this.getChildren();
      for (let i = 0;i < children.length; ++i) {
        const child = children[i];
        if (child) {
          child.computeWorldMatrix();
          const bakedMatrix = TmpVectors.Matrix[0];
          child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix);
          const tmpRotationQuaternion = TmpVectors.Quaternion[0];
          bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position);
          if (child.rotationQuaternion) {
            child.rotationQuaternion.copyFrom(tmpRotationQuaternion);
          } else {
            tmpRotationQuaternion.toEulerAnglesToRef(child.rotation);
          }
        }
      }
    }
    this.scaling.copyFromFloats(1, 1, 1);
    this.position.copyFromFloats(0, 0, 0);
    this.rotation.copyFromFloats(0, 0, 0);
    if (this.rotationQuaternion) {
      this.rotationQuaternion = Quaternion.Identity();
    }
    this._worldMatrix = Matrix.Identity();
  }
  _afterComputeWorldMatrix() {}
  registerAfterWorldMatrixUpdate(func) {
    this.onAfterWorldMatrixUpdateObservable.add(func);
    return this;
  }
  unregisterAfterWorldMatrixUpdate(func) {
    this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
    return this;
  }
  getPositionInCameraSpace(camera = null) {
    if (!camera) {
      camera = this.getScene().activeCamera;
    }
    return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix());
  }
  getDistanceToCamera(camera = null) {
    if (!camera) {
      camera = this.getScene().activeCamera;
    }
    return this.getAbsolutePosition().subtract(camera.globalPosition).length();
  }
  clone(name18, newParent, doNotCloneChildren) {
    const result = SerializationHelper.Clone(() => new TransformNode(name18, this.getScene()), this);
    result.name = name18;
    result.id = name18;
    if (newParent) {
      result.parent = newParent;
    }
    if (!doNotCloneChildren) {
      const directDescendants = this.getDescendants(true);
      for (let index = 0;index < directDescendants.length; index++) {
        const child = directDescendants[index];
        if (child.clone) {
          child.clone(name18 + "." + child.name, result);
        }
      }
    }
    return result;
  }
  serialize(currentSerializationObject) {
    const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
    serializationObject.type = this.getClassName();
    serializationObject.uniqueId = this.uniqueId;
    if (this.parent) {
      this.parent._serializeAsParent(serializationObject);
    }
    serializationObject.localMatrix = this.getPivotMatrix().asArray();
    serializationObject.isEnabled = this.isEnabled();
    SerializationHelper.AppendSerializedAnimations(this, serializationObject);
    serializationObject.ranges = this.serializeAnimationRanges();
    return serializationObject;
  }
  static Parse(parsedTransformNode, scene, rootUrl) {
    const transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
    if (parsedTransformNode.localMatrix) {
      transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
    } else if (parsedTransformNode.pivotMatrix) {
      transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
    }
    transformNode.setEnabled(parsedTransformNode.isEnabled);
    transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId;
    if (parsedTransformNode.parentId !== undefined) {
      transformNode._waitingParentId = parsedTransformNode.parentId;
    }
    if (parsedTransformNode.parentInstanceIndex !== undefined) {
      transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex;
    }
    if (parsedTransformNode.animations) {
      for (let animationIndex = 0;animationIndex < parsedTransformNode.animations.length; animationIndex++) {
        const parsedAnimation = parsedTransformNode.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          transformNode.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
      Node2.ParseAnimationRanges(transformNode, parsedTransformNode, scene);
    }
    if (parsedTransformNode.autoAnimate) {
      scene.beginAnimation(transformNode, parsedTransformNode.autoAnimateFrom, parsedTransformNode.autoAnimateTo, parsedTransformNode.autoAnimateLoop, parsedTransformNode.autoAnimateSpeed || 1);
    }
    return transformNode;
  }
  getChildTransformNodes(directDescendantsOnly, predicate) {
    const results = [];
    this._getDescendants(results, directDescendantsOnly, (node) => {
      return (!predicate || predicate(node)) && node instanceof TransformNode;
    });
    return results;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this.getScene().stopAnimation(this);
    this.getScene().removeTransformNode(this);
    if (this._parentContainer) {
      const index = this._parentContainer.transformNodes.indexOf(this);
      if (index > -1) {
        this._parentContainer.transformNodes.splice(index, 1);
      }
      this._parentContainer = null;
    }
    this.onAfterWorldMatrixUpdateObservable.clear();
    if (doNotRecurse) {
      const transformNodes = this.getChildTransformNodes(true);
      for (const transformNode of transformNodes) {
        transformNode.parent = null;
        transformNode.computeWorldMatrix(true);
      }
    }
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {
    let storedRotation = null;
    let storedRotationQuaternion = null;
    if (ignoreRotation) {
      if (this.rotationQuaternion) {
        storedRotationQuaternion = this.rotationQuaternion.clone();
        this.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
      } else if (this.rotation) {
        storedRotation = this.rotation.clone();
        this.rotation.copyFromFloats(0, 0, 0);
      }
    }
    const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate);
    const sizeVec = boundingVectors.max.subtract(boundingVectors.min);
    const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
    if (maxDimension === 0) {
      return this;
    }
    const scale = 1 / maxDimension;
    this.scaling.scaleInPlace(scale);
    if (ignoreRotation) {
      if (this.rotationQuaternion && storedRotationQuaternion) {
        this.rotationQuaternion.copyFrom(storedRotationQuaternion);
      } else if (this.rotation && storedRotation) {
        this.rotation.copyFrom(storedRotation);
      }
    }
    return this;
  }
  _syncAbsoluteScalingAndRotation() {
    if (!this._isAbsoluteSynced) {
      this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion);
      this._isAbsoluteSynced = true;
    }
  }
}
TransformNode.BILLBOARDMODE_NONE = 0;
TransformNode.BILLBOARDMODE_X = 1;
TransformNode.BILLBOARDMODE_Y = 2;
TransformNode.BILLBOARDMODE_Z = 4;
TransformNode.BILLBOARDMODE_ALL = 7;
TransformNode.BILLBOARDMODE_USE_POSITION = 128;
TransformNode.BillboardUseParentOrientation = false;
TransformNode._TmpRotation = Quaternion.Zero();
TransformNode._TmpScaling = Vector3.Zero();
TransformNode._TmpTranslation = Vector3.Zero();
TransformNode._LookAtVectorCache = new Vector3(0, 0, 0);
TransformNode._RotationAxisCache = new Quaternion;
__decorate([
  serializeAsVector3("position")
], TransformNode.prototype, "_position", undefined);
__decorate([
  serializeAsVector3("rotation")
], TransformNode.prototype, "_rotation", undefined);
__decorate([
  serializeAsQuaternion("rotationQuaternion")
], TransformNode.prototype, "_rotationQuaternion", undefined);
__decorate([
  serializeAsVector3("scaling")
], TransformNode.prototype, "_scaling", undefined);
__decorate([
  serialize("billboardMode")
], TransformNode.prototype, "_billboardMode", undefined);
__decorate([
  serialize()
], TransformNode.prototype, "scalingDeterminant", undefined);
__decorate([
  serialize("infiniteDistance")
], TransformNode.prototype, "_infiniteDistance", undefined);
__decorate([
  serialize()
], TransformNode.prototype, "ignoreNonUniformScaling", undefined);
__decorate([
  serialize()
], TransformNode.prototype, "reIntegrateRotationIntoRotationQuaternion", undefined);

// node_modules/@babylonjs/core/Meshes/abstractMesh.js
init_pickingInfo();
init_uniformBuffer();

// node_modules/@babylonjs/core/Collisions/meshCollisionData.js
init_math_vector();

class _MeshCollisionData {
  constructor() {
    this._checkCollisions = false;
    this._collisionMask = -1;
    this._collisionGroup = -1;
    this._surroundingMeshes = null;
    this._collider = null;
    this._oldPositionForCollisions = new Vector3(0, 0, 0);
    this._diffPositionForCollisions = new Vector3(0, 0, 0);
    this._collisionResponse = true;
  }
}

// node_modules/@babylonjs/core/Meshes/abstractMesh.js
init_devTools();
init_math_functions();
init_math_color();
init_math_constants();
init_math_axis();
init_typeStore();
init_decorators();
init_abstractEngine();
function applyMorph(data, kind, morphTargetManager) {
  let getTargetData = null;
  switch (kind) {
    case VertexBuffer.PositionKind:
      getTargetData = (target) => target.getPositions();
      break;
    case VertexBuffer.NormalKind:
      getTargetData = (target) => target.getNormals();
      break;
    case VertexBuffer.TangentKind:
      getTargetData = (target) => target.getTangents();
      break;
    case VertexBuffer.UVKind:
      getTargetData = (target) => target.getUVs();
      break;
    case VertexBuffer.UV2Kind:
      getTargetData = (target) => target.getUV2s();
      break;
    case VertexBuffer.ColorKind:
      getTargetData = (target) => target.getColors();
      break;
    default:
      return;
  }
  for (let index = 0;index < data.length; index++) {
    let value = data[index];
    for (let targetCount = 0;targetCount < morphTargetManager.numTargets; targetCount++) {
      const target = morphTargetManager.getTarget(targetCount);
      const influence = target.influence;
      if (influence !== 0) {
        const targetData = getTargetData(target);
        if (targetData) {
          value += (targetData[index] - data[index]) * influence;
        }
      }
    }
    data[index] = value;
  }
}
function applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) {
  const tempVector = TmpVectors.Vector3[0];
  const finalMatrix = TmpVectors.Matrix[0];
  const tempMatrix = TmpVectors.Matrix[1];
  const transformFromFloatsToRef = kind === VertexBuffer.NormalKind ? Vector3.TransformNormalFromFloatsToRef : Vector3.TransformCoordinatesFromFloatsToRef;
  for (let index = 0, matWeightIdx = 0;index < data.length; index += 3, matWeightIdx += 4) {
    finalMatrix.reset();
    let inf;
    let weight;
    for (inf = 0;inf < 4; inf++) {
      weight = matricesWeightsData[matWeightIdx + inf];
      if (weight > 0) {
        Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
        finalMatrix.addToSelf(tempMatrix);
      }
    }
    if (matricesIndicesExtraData && matricesWeightsExtraData) {
      for (inf = 0;inf < 4; inf++) {
        weight = matricesWeightsExtraData[matWeightIdx + inf];
        if (weight > 0) {
          Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
          finalMatrix.addToSelf(tempMatrix);
        }
      }
    }
    transformFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
    tempVector.toArray(data, index);
  }
}

class _FacetDataStorage {
  constructor() {
    this.facetNb = 0;
    this.partitioningSubdivisions = 10;
    this.partitioningBBoxRatio = 1.01;
    this.facetDataEnabled = false;
    this.facetParameters = {};
    this.bbSize = Vector3.Zero();
    this.subDiv = {
      max: 1,
      X: 1,
      Y: 1,
      Z: 1
    };
    this.facetDepthSort = false;
    this.facetDepthSortEnabled = false;
  }
}

class _InternalAbstractMeshDataInfo {
  constructor() {
    this._hasVertexAlpha = false;
    this._useVertexColors = true;
    this._numBoneInfluencers = 4;
    this._applyFog = true;
    this._receiveShadows = false;
    this._facetData = new _FacetDataStorage;
    this._visibility = 1;
    this._skeleton = null;
    this._layerMask = 268435455;
    this._computeBonesUsingShaders = true;
    this._isActive = false;
    this._onlyForInstances = false;
    this._isActiveIntermediate = false;
    this._onlyForInstancesIntermediate = false;
    this._actAsRegularMesh = false;
    this._currentLOD = new Map;
    this._collisionRetryCount = 3;
    this._morphTargetManager = null;
    this._renderingGroupId = 0;
    this._bakedVertexAnimationManager = null;
    this._material = null;
    this._positions = null;
    this._pointerOverDisableMeshTesting = false;
    this._meshCollisionData = new _MeshCollisionData;
    this._enableDistantPicking = false;
    this._rawBoundingInfo = null;
    this._sideOrientationHint = false;
    this._inheritVisibility = false;
  }
}

class AbstractMesh extends TransformNode {
  static get BILLBOARDMODE_NONE() {
    return TransformNode.BILLBOARDMODE_NONE;
  }
  static get BILLBOARDMODE_X() {
    return TransformNode.BILLBOARDMODE_X;
  }
  static get BILLBOARDMODE_Y() {
    return TransformNode.BILLBOARDMODE_Y;
  }
  static get BILLBOARDMODE_Z() {
    return TransformNode.BILLBOARDMODE_Z;
  }
  static get BILLBOARDMODE_ALL() {
    return TransformNode.BILLBOARDMODE_ALL;
  }
  static get BILLBOARDMODE_USE_POSITION() {
    return TransformNode.BILLBOARDMODE_USE_POSITION;
  }
  get facetNb() {
    return this._internalAbstractMeshDataInfo._facetData.facetNb;
  }
  get partitioningSubdivisions() {
    return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions;
  }
  set partitioningSubdivisions(nb) {
    this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb;
  }
  get partitioningBBoxRatio() {
    return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio;
  }
  set partitioningBBoxRatio(ratio) {
    this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio;
  }
  get mustDepthSortFacets() {
    return this._internalAbstractMeshDataInfo._facetData.facetDepthSort;
  }
  set mustDepthSortFacets(sort) {
    this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort;
  }
  get facetDepthSortFrom() {
    return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom;
  }
  set facetDepthSortFrom(location2) {
    this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location2;
  }
  get collisionRetryCount() {
    return this._internalAbstractMeshDataInfo._collisionRetryCount;
  }
  set collisionRetryCount(retryCount) {
    this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount;
  }
  get isFacetDataEnabled() {
    return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled;
  }
  get morphTargetManager() {
    return this._internalAbstractMeshDataInfo._morphTargetManager;
  }
  set morphTargetManager(value) {
    if (this._internalAbstractMeshDataInfo._morphTargetManager === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._morphTargetManager = value;
    this._syncGeometryWithMorphTargetManager();
  }
  get bakedVertexAnimationManager() {
    return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager;
  }
  set bakedVertexAnimationManager(value) {
    if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value;
    this._markSubMeshesAsAttributesDirty();
  }
  _syncGeometryWithMorphTargetManager() {}
  _updateNonUniformScalingState(value) {
    if (!super._updateNonUniformScalingState(value)) {
      return false;
    }
    this._markSubMeshesAsMiscDirty();
    return true;
  }
  get rawBoundingInfo() {
    return this._internalAbstractMeshDataInfo._rawBoundingInfo;
  }
  set rawBoundingInfo(boundingInfo) {
    this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo;
  }
  set onCollide(callback) {
    if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) {
      this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver);
    }
    this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback);
  }
  set onCollisionPositionChange(callback) {
    if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) {
      this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver);
    }
    this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  }
  get visibility() {
    return this._internalAbstractMeshDataInfo._visibility;
  }
  set visibility(value) {
    if (this._internalAbstractMeshDataInfo._visibility === value) {
      return;
    }
    const oldValue = this._internalAbstractMeshDataInfo._visibility;
    this._internalAbstractMeshDataInfo._visibility = value;
    if (oldValue === 1 && value !== 1 || oldValue !== 1 && value === 1) {
      this._markSubMeshesAsDirty((defines) => {
        defines.markAsMiscDirty();
        defines.markAsPrePassDirty();
      });
    }
  }
  get inheritVisibility() {
    return this._internalAbstractMeshDataInfo._inheritVisibility;
  }
  set inheritVisibility(value) {
    this._internalAbstractMeshDataInfo._inheritVisibility = value;
  }
  get isVisible() {
    if (!this._isVisible || !this.inheritVisibility || !this._parentNode) {
      return this._isVisible;
    }
    if (this._isVisible) {
      let parent = this._parentNode;
      while (parent) {
        const parentVisible = parent.isVisible;
        if (typeof parentVisible !== "undefined") {
          return parentVisible;
        }
        parent = parent.parent;
      }
    }
    return this._isVisible;
  }
  set isVisible(value) {
    this._isVisible = value;
  }
  get pointerOverDisableMeshTesting() {
    return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting;
  }
  set pointerOverDisableMeshTesting(disable) {
    this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable;
  }
  get renderingGroupId() {
    return this._internalAbstractMeshDataInfo._renderingGroupId;
  }
  set renderingGroupId(value) {
    this._internalAbstractMeshDataInfo._renderingGroupId = value;
  }
  get material() {
    return this._internalAbstractMeshDataInfo._material;
  }
  set material(value) {
    this._setMaterial(value);
  }
  _setMaterial(value) {
    if (this._internalAbstractMeshDataInfo._material === value) {
      return;
    }
    if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {
      this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;
    }
    this._internalAbstractMeshDataInfo._material = value;
    if (value && value.meshMap) {
      value.meshMap[this.uniqueId] = this;
    }
    if (this.onMaterialChangedObservable.hasObservers()) {
      this.onMaterialChangedObservable.notifyObservers(this);
    }
    if (!this.subMeshes) {
      return;
    }
    this.resetDrawCache(undefined, value == null);
    this._unBindEffect();
  }
  getMaterialForRenderPass(renderPassId) {
    return this._internalAbstractMeshDataInfo._materialForRenderPass?.[renderPassId];
  }
  setMaterialForRenderPass(renderPassId, material) {
    this.resetDrawCache(renderPassId);
    if (!this._internalAbstractMeshDataInfo._materialForRenderPass) {
      this._internalAbstractMeshDataInfo._materialForRenderPass = [];
    }
    const currentMaterial = this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId];
    if (currentMaterial?.meshMap?.[this.uniqueId]) {
      currentMaterial.meshMap[this.uniqueId] = undefined;
    }
    this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material;
    if (material && material.meshMap) {
      material.meshMap[this.uniqueId] = this;
    }
  }
  get receiveShadows() {
    return this._internalAbstractMeshDataInfo._receiveShadows;
  }
  set receiveShadows(value) {
    if (this._internalAbstractMeshDataInfo._receiveShadows === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._receiveShadows = value;
    this._markSubMeshesAsLightDirty();
  }
  get hasVertexAlpha() {
    return this._internalAbstractMeshDataInfo._hasVertexAlpha;
  }
  set hasVertexAlpha(value) {
    if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._hasVertexAlpha = value;
    this._markSubMeshesAsAttributesDirty();
    this._markSubMeshesAsMiscDirty();
  }
  get useVertexColors() {
    return this._internalAbstractMeshDataInfo._useVertexColors;
  }
  set useVertexColors(value) {
    if (this._internalAbstractMeshDataInfo._useVertexColors === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._useVertexColors = value;
    this._markSubMeshesAsAttributesDirty();
  }
  get computeBonesUsingShaders() {
    return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
  }
  set computeBonesUsingShaders(value) {
    if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;
    this._markSubMeshesAsAttributesDirty();
  }
  get numBoneInfluencers() {
    return this._internalAbstractMeshDataInfo._numBoneInfluencers;
  }
  set numBoneInfluencers(value) {
    if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._numBoneInfluencers = value;
    this._markSubMeshesAsAttributesDirty();
  }
  get applyFog() {
    return this._internalAbstractMeshDataInfo._applyFog;
  }
  set applyFog(value) {
    if (this._internalAbstractMeshDataInfo._applyFog === value) {
      return;
    }
    this._internalAbstractMeshDataInfo._applyFog = value;
    this._markSubMeshesAsMiscDirty();
  }
  get enableDistantPicking() {
    return this._internalAbstractMeshDataInfo._enableDistantPicking;
  }
  set enableDistantPicking(value) {
    this._internalAbstractMeshDataInfo._enableDistantPicking = value;
  }
  get layerMask() {
    return this._internalAbstractMeshDataInfo._layerMask;
  }
  set layerMask(value) {
    if (value === this._internalAbstractMeshDataInfo._layerMask) {
      return;
    }
    this._internalAbstractMeshDataInfo._layerMask = value;
    this._resyncLightSources();
  }
  get collisionMask() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask;
  }
  set collisionMask(mask) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1;
  }
  get collisionResponse() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse;
  }
  set collisionResponse(response) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response;
  }
  get collisionGroup() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup;
  }
  set collisionGroup(mask) {
    this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1;
  }
  get surroundingMeshes() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes;
  }
  set surroundingMeshes(meshes) {
    this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes;
  }
  get lightSources() {
    return this._lightSources;
  }
  set skeleton(value) {
    const skeleton = this._internalAbstractMeshDataInfo._skeleton;
    if (skeleton && skeleton.needInitialSkinMatrix) {
      skeleton._unregisterMeshWithPoseMatrix(this);
    }
    if (value && value.needInitialSkinMatrix) {
      value._registerMeshWithPoseMatrix(this);
    }
    this._internalAbstractMeshDataInfo._skeleton = value;
    if (!this._internalAbstractMeshDataInfo._skeleton) {
      this._bonesTransformMatrices = null;
    }
    this._markSubMeshesAsAttributesDirty();
  }
  get skeleton() {
    return this._internalAbstractMeshDataInfo._skeleton;
  }
  constructor(name18, scene = null) {
    super(name18, scene, false);
    this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo;
    this._waitingMaterialId = null;
    this._waitingMorphTargetManagerId = null;
    this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;
    this.onCollideObservable = new Observable;
    this.onCollisionPositionChangeObservable = new Observable;
    this.onMaterialChangedObservable = new Observable;
    this.definedFacingForward = true;
    this._occlusionQuery = null;
    this._renderingGroup = null;
    this.alphaIndex = Number.MAX_VALUE;
    this._isVisible = true;
    this.isPickable = true;
    this.isNearPickable = false;
    this.isNearGrabbable = false;
    this.showSubMeshesBoundingBox = false;
    this.isBlocker = false;
    this.enablePointerMoveEvents = false;
    this.outlineColor = Color3.Red();
    this.outlineWidth = 0.02;
    this.overlayColor = Color3.Red();
    this.overlayAlpha = 0.5;
    this.useOctreeForRenderingSelection = true;
    this.useOctreeForPicking = true;
    this.useOctreeForCollisions = true;
    this.alwaysSelectAsActiveMesh = false;
    this.doNotSyncBoundingInfo = false;
    this.actionManager = null;
    this.ellipsoid = new Vector3(0.5, 1, 0.5);
    this.ellipsoidOffset = new Vector3(0, 0, 0);
    this.edgesWidth = 1;
    this.edgesColor = new Color4(1, 0, 0, 1);
    this._edgesRenderer = null;
    this._masterMesh = null;
    this._boundingInfo = null;
    this._boundingInfoIsDirty = true;
    this._renderId = 0;
    this._intersectionsInProgress = new Array;
    this._unIndexed = false;
    this._lightSources = new Array;
    this._waitingData = {
      lods: null,
      actions: null,
      freezeWorldMatrix: null
    };
    this._bonesTransformMatrices = null;
    this._transformMatrixTexture = null;
    this.onRebuildObservable = new Observable;
    this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
      newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);
      if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > AbstractEngine.CollisionsEpsilon) {
        this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);
      }
      if (collidedMesh) {
        this.onCollideObservable.notifyObservers(collidedMesh);
      }
      this.onCollisionPositionChangeObservable.notifyObservers(this.position);
    };
    scene = this.getScene();
    scene.addMesh(this);
    this._resyncLightSources();
    this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name18, !this.getScene().getEngine().isWebGPU);
    this._buildUniformLayout();
    switch (scene.performancePriority) {
      case 2:
        this.doNotSyncBoundingInfo = true;
      case 1:
        this.alwaysSelectAsActiveMesh = true;
        this.isPickable = false;
        break;
    }
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("world", 16);
    this._uniformBuffer.addUniform("visibility", 1);
    this._uniformBuffer.create();
  }
  transferToEffect(world) {
    const ubo = this._uniformBuffer;
    ubo.updateMatrix("world", world);
    ubo.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility);
    ubo.update();
  }
  getMeshUniformBuffer() {
    return this._uniformBuffer;
  }
  getClassName() {
    return "AbstractMesh";
  }
  toString(fullDetails) {
    let ret = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO");
    ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
    const skeleton = this._internalAbstractMeshDataInfo._skeleton;
    if (skeleton) {
      ret += ", skeleton: " + skeleton.name;
    }
    if (fullDetails) {
      ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode];
      ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO");
    }
    return ret;
  }
  _getEffectiveParent() {
    if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
      return this._masterMesh;
    }
    return super._getEffectiveParent();
  }
  _getActionManagerForTrigger(trigger, initialCall = true) {
    if (this.actionManager && (initialCall || this.actionManager.isRecursive)) {
      if (trigger) {
        if (this.actionManager.hasSpecificTrigger(trigger)) {
          return this.actionManager;
        }
      } else {
        return this.actionManager;
      }
    }
    if (!this.parent) {
      return null;
    }
    return this.parent._getActionManagerForTrigger(trigger, false);
  }
  _rebuild(dispose = false) {
    this.onRebuildObservable.notifyObservers(this);
    if (this._occlusionQuery !== null) {
      this._occlusionQuery = null;
    }
    if (!this.subMeshes) {
      return;
    }
    for (const subMesh of this.subMeshes) {
      subMesh._rebuild();
    }
    this.resetDrawCache();
  }
  _resyncLightSources() {
    this._lightSources.length = 0;
    for (const light of this.getScene().lights) {
      if (!light.isEnabled()) {
        continue;
      }
      if (light.canAffectMesh(this)) {
        this._lightSources.push(light);
      }
    }
    this._markSubMeshesAsLightDirty();
  }
  _resyncLightSource(light) {
    const isIn = light.isEnabled() && light.canAffectMesh(this);
    const index = this._lightSources.indexOf(light);
    let removed = false;
    if (index === -1) {
      if (!isIn) {
        return;
      }
      this._lightSources.push(light);
    } else {
      if (isIn) {
        return;
      }
      removed = true;
      this._lightSources.splice(index, 1);
    }
    this._markSubMeshesAsLightDirty(removed);
  }
  _unBindEffect() {
    for (const subMesh of this.subMeshes) {
      subMesh.setEffect(null);
    }
  }
  _removeLightSource(light, dispose) {
    const index = this._lightSources.indexOf(light);
    if (index === -1) {
      return;
    }
    this._lightSources.splice(index, 1);
    this._markSubMeshesAsLightDirty(dispose);
  }
  _markSubMeshesAsDirty(func) {
    if (!this.subMeshes) {
      return;
    }
    for (const subMesh of this.subMeshes) {
      for (let i = 0;i < subMesh._drawWrappers.length; ++i) {
        const drawWrapper = subMesh._drawWrappers[i];
        if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {
          continue;
        }
        func(drawWrapper.defines);
      }
    }
  }
  _markSubMeshesAsLightDirty(dispose = false) {
    this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose));
  }
  _markSubMeshesAsAttributesDirty() {
    this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty());
  }
  _markSubMeshesAsMiscDirty() {
    this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty());
  }
  markAsDirty(property) {
    this._currentRenderId = Number.MAX_VALUE;
    super.markAsDirty(property);
    this._isDirty = true;
    return this;
  }
  resetDrawCache(passId, immediate = false) {
    if (!this.subMeshes) {
      return;
    }
    for (const subMesh of this.subMeshes) {
      subMesh.resetDrawCache(passId, immediate);
    }
  }
  get isBlocked() {
    return false;
  }
  getLOD(camera) {
    return this;
  }
  getTotalVertices() {
    return 0;
  }
  getTotalIndices() {
    return 0;
  }
  getIndices() {
    return null;
  }
  getVerticesData(kind) {
    return null;
  }
  setVerticesData(kind, data, updatable, stride) {
    return this;
  }
  updateVerticesData(kind, data, updateExtends, makeItUnique) {
    return this;
  }
  setIndices(indices, totalVertices) {
    return this;
  }
  isVerticesDataPresent(kind) {
    return false;
  }
  getBoundingInfo() {
    if (this._masterMesh) {
      return this._masterMesh.getBoundingInfo();
    }
    if (this._boundingInfoIsDirty) {
      this._boundingInfoIsDirty = false;
      this._updateBoundingInfo();
    }
    return this._boundingInfo;
  }
  getRawBoundingInfo() {
    return this.rawBoundingInfo ?? this.getBoundingInfo();
  }
  setBoundingInfo(boundingInfo) {
    this._boundingInfo = boundingInfo;
    return this;
  }
  get hasBoundingInfo() {
    return this._boundingInfo !== null;
  }
  buildBoundingInfo(minimum, maximum, worldMatrix) {
    this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix);
    return this._boundingInfo;
  }
  normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {
    return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate);
  }
  get useBones() {
    return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind);
  }
  _preActivate() {}
  _preActivateForIntermediateRendering(renderId) {}
  _activate(renderId, intermediateRendering) {
    this._renderId = renderId;
    return true;
  }
  _postActivate() {}
  _freeze() {}
  _unFreeze() {}
  getWorldMatrix() {
    if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) {
      return this._masterMesh.getWorldMatrix();
    }
    return super.getWorldMatrix();
  }
  _getWorldMatrixDeterminant() {
    if (this._masterMesh) {
      return this._masterMesh._getWorldMatrixDeterminant();
    }
    return super._getWorldMatrixDeterminant();
  }
  get isAnInstance() {
    return false;
  }
  get hasInstances() {
    return false;
  }
  get hasThinInstances() {
    return false;
  }
  movePOV(amountRight, amountUp, amountForward) {
    this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
    return this;
  }
  calcMovePOV(amountRight, amountUp, amountForward) {
    const rotMatrix = new Matrix;
    const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
    rotQuaternion.toRotationMatrix(rotMatrix);
    const translationDelta = Vector3.Zero();
    const defForwardMult = this.definedFacingForward ? -1 : 1;
    Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
    return translationDelta;
  }
  rotatePOV(flipBack, twirlClockwise, tiltRight) {
    this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
    return this;
  }
  calcRotatePOV(flipBack, twirlClockwise, tiltRight) {
    const defForwardMult = this.definedFacingForward ? 1 : -1;
    return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  }
  _refreshBoundingInfo(data, bias) {
    if (data) {
      const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias);
      if (this._boundingInfo) {
        this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
      } else {
        this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
      }
    }
    if (this.subMeshes) {
      for (let index = 0;index < this.subMeshes.length; index++) {
        this.subMeshes[index].refreshBoundingInfo(data);
      }
    }
    this._updateBoundingInfo();
  }
  _refreshBoundingInfoDirect(extend) {
    if (this._boundingInfo) {
      this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
    } else {
      this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
    }
    if (this.subMeshes) {
      for (let index = 0;index < this.subMeshes.length; index++) {
        this.subMeshes[index].refreshBoundingInfo(null);
      }
    }
    this._updateBoundingInfo();
  }
  static _ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) {
    applySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData);
  }
  _getData(options, data, kind = VertexBuffer.PositionKind) {
    const cache = options.cache;
    const getVertexData = (kind2) => {
      if (cache) {
        const vertexData = cache._vertexData || (cache._vertexData = {});
        if (!vertexData[kind2]) {
          this.copyVerticesData(kind2, vertexData);
        }
        return vertexData[kind2];
      }
      return this.getVerticesData(kind2);
    };
    data || (data = getVertexData(kind));
    if (!data) {
      return null;
    }
    if (cache) {
      if (cache._outputData) {
        cache._outputData.set(data);
      } else {
        cache._outputData = new Float32Array(data);
      }
      data = cache._outputData;
    } else if (options.applyMorph && this.morphTargetManager || options.applySkeleton && this.skeleton) {
      data = data.slice();
    }
    if (options.applyMorph && this.morphTargetManager) {
      applyMorph(data, kind, this.morphTargetManager);
    }
    if (options.applySkeleton && this.skeleton) {
      const matricesIndicesData = getVertexData(VertexBuffer.MatricesIndicesKind);
      const matricesWeightsData = getVertexData(VertexBuffer.MatricesWeightsKind);
      if (matricesWeightsData && matricesIndicesData) {
        const needExtras = this.numBoneInfluencers > 4;
        const matricesIndicesExtraData = needExtras ? getVertexData(VertexBuffer.MatricesIndicesExtraKind) : null;
        const matricesWeightsExtraData = needExtras ? getVertexData(VertexBuffer.MatricesWeightsExtraKind) : null;
        const skeletonMatrices = this.skeleton.getTransformMatrices(this);
        AbstractMesh._ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData);
      }
    }
    if (options.updatePositionsArray !== false && kind === VertexBuffer.PositionKind) {
      const positions = this._internalAbstractMeshDataInfo._positions || [];
      const previousLength = positions.length;
      positions.length = data.length / 3;
      if (previousLength < positions.length) {
        for (let positionIndex = previousLength;positionIndex < positions.length; positionIndex++) {
          positions[positionIndex] = new Vector3;
        }
      }
      for (let positionIndex = 0, dataIndex = 0;positionIndex < positions.length; positionIndex++, dataIndex += 3) {
        positions[positionIndex].copyFromFloats(data[dataIndex], data[dataIndex + 1], data[dataIndex + 2]);
      }
      this._internalAbstractMeshDataInfo._positions = positions;
    }
    return data;
  }
  getNormalsData(applySkeleton2 = false, applyMorph2 = false) {
    return this._getData({ applySkeleton: applySkeleton2, applyMorph: applyMorph2, updatePositionsArray: false }, null, VertexBuffer.NormalKind);
  }
  getPositionData(applySkeleton2 = false, applyMorph2 = false, data = null) {
    return this._getData({ applySkeleton: applySkeleton2, applyMorph: applyMorph2, updatePositionsArray: false }, data, VertexBuffer.PositionKind);
  }
  _updateBoundingInfo() {
    if (this._boundingInfo) {
      this._boundingInfo.update(this.worldMatrixFromCache);
    } else {
      this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache);
    }
    this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
    return this;
  }
  _updateSubMeshesBoundingInfo(matrix) {
    if (!this.subMeshes) {
      return this;
    }
    const count = this.subMeshes.length;
    for (let subIndex = 0;subIndex < count; subIndex++) {
      const subMesh = this.subMeshes[subIndex];
      if (count > 1 || !subMesh.IsGlobal) {
        subMesh.updateBoundingInfo(matrix);
      }
    }
    return this;
  }
  _afterComputeWorldMatrix() {
    if (this.doNotSyncBoundingInfo) {
      return;
    }
    this._boundingInfoIsDirty = true;
  }
  isInFrustum(frustumPlanes) {
    return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy);
  }
  isCompletelyInFrustum(frustumPlanes) {
    return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  }
  intersectsMesh(mesh, precise = false, includeDescendants) {
    const boundingInfo = this.getBoundingInfo();
    const otherBoundingInfo = mesh.getBoundingInfo();
    if (boundingInfo.intersects(otherBoundingInfo, precise)) {
      return true;
    }
    if (includeDescendants) {
      for (const child of this.getChildMeshes()) {
        if (child.intersectsMesh(mesh, precise, true)) {
          return true;
        }
      }
    }
    return false;
  }
  intersectsPoint(point) {
    return this.getBoundingInfo().intersectsPoint(point);
  }
  get checkCollisions() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions;
  }
  set checkCollisions(collisionEnabled) {
    this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled;
  }
  get collider() {
    return this._internalAbstractMeshDataInfo._meshCollisionData._collider;
  }
  moveWithCollisions(displacement) {
    const globalPosition = this.getAbsolutePosition();
    globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);
    const coordinator = this.getScene().collisionCoordinator;
    if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) {
      this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider();
    }
    this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid;
    coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId);
    return this;
  }
  _collideForSubMesh(subMesh, transformMatrix, collider) {
    this._generatePointsArray();
    if (!this._positions) {
      return this;
    }
    if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
      subMesh._lastColliderTransformMatrix = transformMatrix.clone();
      subMesh._lastColliderWorldVertices = [];
      subMesh._trianglePlanes = [];
      const start = subMesh.verticesStart;
      const end = subMesh.verticesStart + subMesh.verticesCount;
      for (let i = start;i < end; i++) {
        subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
      }
    }
    collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), subMesh.getMaterial()?.fillMode === 7);
    return this;
  }
  _processCollisionsForSubMeshes(collider, transformMatrix) {
    const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
    const len = subMeshes.length;
    for (let index = 0;index < len; index++) {
      const subMesh = subMeshes.data[index];
      if (len > 1 && !subMesh._checkCollision(collider)) {
        continue;
      }
      this._collideForSubMesh(subMesh, transformMatrix, collider);
    }
    return this;
  }
  _shouldConvertRHS() {
    return false;
  }
  _checkCollision(collider) {
    if (!this.getBoundingInfo()._checkCollision(collider)) {
      return this;
    }
    const collisionsScalingMatrix = TmpVectors.Matrix[0];
    const collisionsTransformMatrix = TmpVectors.Matrix[1];
    Matrix.ScalingToRef(1 / collider._radius.x, 1 / collider._radius.y, 1 / collider._radius.z, collisionsScalingMatrix);
    this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
    this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
    return this;
  }
  _generatePointsArray() {
    return false;
  }
  intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {
    const pickingInfo = new PickingInfo;
    const className = this.getClassName();
    const intersectionThreshold = className === "InstancedLinesMesh" || className === "LinesMesh" || className === "GreasedLineMesh" ? this.intersectionThreshold : 0;
    const boundingInfo = this.getBoundingInfo();
    if (!this.subMeshes) {
      return pickingInfo;
    }
    if (!skipBoundingInfo && (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) {
      return pickingInfo;
    }
    if (onlyBoundingInfo) {
      pickingInfo.hit = skipBoundingInfo ? false : true;
      pickingInfo.pickedMesh = skipBoundingInfo ? null : this;
      pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);
      pickingInfo.subMeshId = 0;
      return pickingInfo;
    }
    if (!this._generatePointsArray()) {
      return pickingInfo;
    }
    let intersectInfo = null;
    const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
    const len = subMeshes.length;
    let anySubmeshSupportIntersect = false;
    for (let index = 0;index < len; index++) {
      const subMesh = subMeshes.data[index];
      const material = subMesh.getMaterial();
      if (!material) {
        continue;
      }
      if (material.fillMode == 7 || material.fillMode == 0 || material.fillMode == 1 || material.fillMode == 2 || material.fillMode == 4) {
        anySubmeshSupportIntersect = true;
        break;
      }
    }
    if (!anySubmeshSupportIntersect) {
      pickingInfo.hit = true;
      pickingInfo.pickedMesh = this;
      pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);
      pickingInfo.subMeshId = -1;
      return pickingInfo;
    }
    for (let index = 0;index < len; index++) {
      const subMesh = subMeshes.data[index];
      if (len > 1 && !skipBoundingInfo && !subMesh.canIntersects(ray)) {
        continue;
      }
      const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate);
      if (currentIntersectInfo) {
        if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
          intersectInfo = currentIntersectInfo;
          intersectInfo.subMeshId = index;
          if (fastCheck) {
            break;
          }
        }
      }
    }
    if (intersectInfo) {
      const world = worldToUse ?? this.getWorldMatrix();
      const worldOrigin = TmpVectors.Vector3[0];
      const direction = TmpVectors.Vector3[1];
      Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);
      ray.direction.scaleToRef(intersectInfo.distance, direction);
      const worldDirection = Vector3.TransformNormal(direction, world);
      const pickedPoint = worldDirection.addInPlace(worldOrigin);
      pickingInfo.hit = true;
      pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
      pickingInfo.pickedPoint = pickedPoint;
      pickingInfo.pickedMesh = this;
      pickingInfo.bu = intersectInfo.bu || 0;
      pickingInfo.bv = intersectInfo.bv || 0;
      pickingInfo.subMeshFaceId = intersectInfo.faceId;
      pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3);
      pickingInfo.subMeshId = intersectInfo.subMeshId;
      return pickingInfo;
    }
    return pickingInfo;
  }
  clone(name18, newParent, doNotCloneChildren) {
    return null;
  }
  releaseSubMeshes(immediate = false) {
    if (this.subMeshes) {
      while (this.subMeshes.length) {
        this.subMeshes[0].dispose(immediate);
      }
    } else {
      this.subMeshes = [];
    }
    return this;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    let index;
    const scene = this.getScene();
    if (this._scene.useMaterialMeshMap) {
      if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {
        this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;
      }
    }
    scene.freeActiveMeshes();
    scene.freeRenderingGroups();
    if (scene.renderingManager.maintainStateBetweenFrames) {
      scene.renderingManager.restoreDispachedFlags();
    }
    if (this.actionManager !== undefined && this.actionManager !== null) {
      if (this.actionManager.disposeWhenUnowned && !this._scene.meshes.some((m) => m !== this && m.actionManager === this.actionManager)) {
        this.actionManager.dispose();
      }
      this.actionManager = null;
    }
    this._internalAbstractMeshDataInfo._skeleton = null;
    if (this._transformMatrixTexture) {
      this._transformMatrixTexture.dispose();
      this._transformMatrixTexture = null;
    }
    for (index = 0;index < this._intersectionsInProgress.length; index++) {
      const other = this._intersectionsInProgress[index];
      const pos = other._intersectionsInProgress.indexOf(this);
      other._intersectionsInProgress.splice(pos, 1);
    }
    this._intersectionsInProgress.length = 0;
    const lights = scene.lights;
    lights.forEach((light) => {
      let meshIndex = light.includedOnlyMeshes.indexOf(this);
      if (meshIndex !== -1) {
        light.includedOnlyMeshes.splice(meshIndex, 1);
      }
      meshIndex = light.excludedMeshes.indexOf(this);
      if (meshIndex !== -1) {
        light.excludedMeshes.splice(meshIndex, 1);
      }
      const generators = light.getShadowGenerators();
      if (generators) {
        const iterator = generators.values();
        for (let key = iterator.next();key.done !== true; key = iterator.next()) {
          const generator = key.value;
          const shadowMap = generator.getShadowMap();
          if (shadowMap && shadowMap.renderList) {
            meshIndex = shadowMap.renderList.indexOf(this);
            if (meshIndex !== -1) {
              shadowMap.renderList.splice(meshIndex, 1);
            }
          }
        }
      }
    });
    if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") {
      this.releaseSubMeshes(true);
    }
    const engine = scene.getEngine();
    if (this._occlusionQuery !== null) {
      this.isOcclusionQueryInProgress = false;
      engine.deleteQuery(this._occlusionQuery);
      this._occlusionQuery = null;
    }
    engine.wipeCaches();
    scene.removeMesh(this);
    if (this._parentContainer) {
      const index2 = this._parentContainer.meshes.indexOf(this);
      if (index2 > -1) {
        this._parentContainer.meshes.splice(index2, 1);
      }
      this._parentContainer = null;
    }
    if (disposeMaterialAndTextures) {
      if (this.material) {
        if (this.material.getClassName() === "MultiMaterial") {
          this.material.dispose(false, true, true);
        } else {
          this.material.dispose(false, true);
        }
      }
    }
    if (!doNotRecurse) {
      for (index = 0;index < scene.particleSystems.length; index++) {
        if (scene.particleSystems[index].emitter === this) {
          scene.particleSystems[index].dispose();
          index--;
        }
      }
    }
    if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) {
      this.disableFacetData();
    }
    this._uniformBuffer.dispose();
    this.onAfterWorldMatrixUpdateObservable.clear();
    this.onCollideObservable.clear();
    this.onCollisionPositionChangeObservable.clear();
    this.onRebuildObservable.clear();
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  _initFacetData() {
    const data = this._internalAbstractMeshDataInfo._facetData;
    if (!data.facetNormals) {
      data.facetNormals = [];
    }
    if (!data.facetPositions) {
      data.facetPositions = [];
    }
    if (!data.facetPartitioning) {
      data.facetPartitioning = new Array;
    }
    data.facetNb = this.getIndices().length / 3 | 0;
    data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10;
    data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01;
    for (let f = 0;f < data.facetNb; f++) {
      data.facetNormals[f] = Vector3.Zero();
      data.facetPositions[f] = Vector3.Zero();
    }
    data.facetDataEnabled = true;
    return this;
  }
  updateFacetData() {
    const data = this._internalAbstractMeshDataInfo._facetData;
    if (!data.facetDataEnabled) {
      this._initFacetData();
    }
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    const indices = this.getIndices();
    const normals = this.getVerticesData(VertexBuffer.NormalKind);
    const bInfo = this.getBoundingInfo();
    if (data.facetDepthSort && !data.facetDepthSortEnabled) {
      data.facetDepthSortEnabled = true;
      if (indices instanceof Uint16Array) {
        data.depthSortedIndices = new Uint16Array(indices);
      } else if (indices instanceof Uint32Array) {
        data.depthSortedIndices = new Uint32Array(indices);
      } else {
        let needs32bits = false;
        for (let i = 0;i < indices.length; i++) {
          if (indices[i] > 65535) {
            needs32bits = true;
            break;
          }
        }
        if (needs32bits) {
          data.depthSortedIndices = new Uint32Array(indices);
        } else {
          data.depthSortedIndices = new Uint16Array(indices);
        }
      }
      data.facetDepthSortFunction = function(f1, f2) {
        return f2.sqDistance - f1.sqDistance;
      };
      if (!data.facetDepthSortFrom) {
        const camera = this.getScene().activeCamera;
        data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero();
      }
      data.depthSortedFacets = [];
      for (let f = 0;f < data.facetNb; f++) {
        const depthSortedFacet = { ind: f * 3, sqDistance: 0 };
        data.depthSortedFacets.push(depthSortedFacet);
      }
      data.invertedMatrix = Matrix.Identity();
      data.facetDepthSortOrigin = Vector3.Zero();
    }
    data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
    data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
    data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
    let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y;
    bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z;
    data.subDiv.max = data.partitioningSubdivisions;
    data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax);
    data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax);
    data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
    data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X;
    data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
    data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
    data.facetParameters.facetNormals = this.getFacetLocalNormals();
    data.facetParameters.facetPositions = this.getFacetLocalPositions();
    data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
    data.facetParameters.bInfo = bInfo;
    data.facetParameters.bbSize = data.bbSize;
    data.facetParameters.subDiv = data.subDiv;
    data.facetParameters.ratio = this.partitioningBBoxRatio;
    data.facetParameters.depthSort = data.facetDepthSort;
    if (data.facetDepthSort && data.facetDepthSortEnabled) {
      this.computeWorldMatrix(true);
      this._worldMatrix.invertToRef(data.invertedMatrix);
      Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
      data.facetParameters.distanceTo = data.facetDepthSortOrigin;
    }
    data.facetParameters.depthSortedFacets = data.depthSortedFacets;
    if (normals) {
      VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
    }
    if (data.facetDepthSort && data.facetDepthSortEnabled) {
      data.depthSortedFacets.sort(data.facetDepthSortFunction);
      const l = data.depthSortedIndices.length / 3 | 0;
      for (let f = 0;f < l; f++) {
        const sind = data.depthSortedFacets[f].ind;
        data.depthSortedIndices[f * 3] = indices[sind];
        data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
        data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
      }
      this.updateIndices(data.depthSortedIndices, undefined, true);
    }
    return this;
  }
  getFacetLocalNormals() {
    const facetData = this._internalAbstractMeshDataInfo._facetData;
    if (!facetData.facetNormals) {
      this.updateFacetData();
    }
    return facetData.facetNormals;
  }
  getFacetLocalPositions() {
    const facetData = this._internalAbstractMeshDataInfo._facetData;
    if (!facetData.facetPositions) {
      this.updateFacetData();
    }
    return facetData.facetPositions;
  }
  getFacetLocalPartitioning() {
    const facetData = this._internalAbstractMeshDataInfo._facetData;
    if (!facetData.facetPartitioning) {
      this.updateFacetData();
    }
    return facetData.facetPartitioning;
  }
  getFacetPosition(i) {
    const pos = Vector3.Zero();
    this.getFacetPositionToRef(i, pos);
    return pos;
  }
  getFacetPositionToRef(i, ref) {
    const localPos = this.getFacetLocalPositions()[i];
    const world = this.getWorldMatrix();
    Vector3.TransformCoordinatesToRef(localPos, world, ref);
    return this;
  }
  getFacetNormal(i) {
    const norm = Vector3.Zero();
    this.getFacetNormalToRef(i, norm);
    return norm;
  }
  getFacetNormalToRef(i, ref) {
    const localNorm = this.getFacetLocalNormals()[i];
    Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
    return this;
  }
  getFacetsAtLocalCoordinates(x, y, z) {
    const bInfo = this.getBoundingInfo();
    const data = this._internalAbstractMeshDataInfo._facetData;
    const ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
    const oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
    const oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
    if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
      return null;
    }
    return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  }
  getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) {
    const world = this.getWorldMatrix();
    const invMat = TmpVectors.Matrix[5];
    world.invertToRef(invMat);
    const invVect = TmpVectors.Vector3[8];
    Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect);
    const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
    if (projected) {
      Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
    }
    return closest;
  }
  getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) {
    let closest = null;
    let tmpx = 0;
    let tmpy = 0;
    let tmpz = 0;
    let d = 0;
    let t0 = 0;
    let projx = 0;
    let projy = 0;
    let projz = 0;
    const facetPositions = this.getFacetLocalPositions();
    const facetNormals = this.getFacetLocalNormals();
    const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
    if (!facetsInBlock) {
      return null;
    }
    let shortest = Number.MAX_VALUE;
    let tmpDistance = shortest;
    let fib;
    let norm;
    let p0;
    for (let idx = 0;idx < facetsInBlock.length; idx++) {
      fib = facetsInBlock[idx];
      norm = facetNormals[fib];
      p0 = facetPositions[fib];
      d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
      if (!checkFace || checkFace && facing && d >= 0 || checkFace && !facing && d <= 0) {
        d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
        t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
        projx = x + norm.x * t0;
        projy = y + norm.y * t0;
        projz = z + norm.z * t0;
        tmpx = projx - x;
        tmpy = projy - y;
        tmpz = projz - z;
        tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz;
        if (tmpDistance < shortest) {
          shortest = tmpDistance;
          closest = fib;
          if (projected) {
            projected.x = projx;
            projected.y = projy;
            projected.z = projz;
          }
        }
      }
    }
    return closest;
  }
  getFacetDataParameters() {
    return this._internalAbstractMeshDataInfo._facetData.facetParameters;
  }
  disableFacetData() {
    const facetData = this._internalAbstractMeshDataInfo._facetData;
    if (facetData.facetDataEnabled) {
      facetData.facetDataEnabled = false;
      facetData.facetPositions = [];
      facetData.facetNormals = [];
      facetData.facetPartitioning = new Array;
      facetData.facetParameters = {};
      facetData.depthSortedIndices = new Uint32Array(0);
    }
    return this;
  }
  updateIndices(indices, offset, gpuMemoryOnly = false) {
    return this;
  }
  createNormals(updatable) {
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    const indices = this.getIndices();
    let normals;
    if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      normals = this.getVerticesData(VertexBuffer.NormalKind);
    } else {
      normals = [];
    }
    VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
    this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
    return this;
  }
  async optimizeIndicesAsync() {
    const indices = this.getIndices();
    if (!indices) {
      return this;
    }
    const { OptimizeIndices: OptimizeIndices2 } = await Promise.resolve().then(() => (init_mesh_vertexData_functions(), exports_mesh_vertexData_functions));
    OptimizeIndices2(indices);
    this.setIndices(indices, this.getTotalVertices());
    return this;
  }
  alignWithNormal(normal, upDirection) {
    if (!upDirection) {
      upDirection = Axis.Y;
    }
    const axisX = TmpVectors.Vector3[0];
    const axisZ = TmpVectors.Vector3[1];
    Vector3.CrossToRef(upDirection, normal, axisZ);
    Vector3.CrossToRef(normal, axisZ, axisX);
    if (this.rotationQuaternion) {
      Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
    } else {
      Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
    }
    return this;
  }
  _checkOcclusionQuery() {
    return false;
  }
  disableEdgesRendering() {
    throw _WarnImport("EdgesRenderer");
  }
  enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) {
    throw _WarnImport("EdgesRenderer");
  }
  getConnectedParticleSystems() {
    return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this);
  }
}
AbstractMesh.OCCLUSION_TYPE_NONE = 0;
AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
__decorate([
  nativeOverride.filter((...[data, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData]) => !Array.isArray(data) && !Array.isArray(matricesIndicesData) && !Array.isArray(matricesWeightsData) && !Array.isArray(matricesIndicesExtraData) && !Array.isArray(matricesWeightsExtraData))
], AbstractMesh, "_ApplySkeleton", null);
RegisterClass("BABYLON.AbstractMesh", AbstractMesh);

// node_modules/@babylonjs/core/Materials/material.js
init_tslib_es6();
init_decorators();
init_tools();
init_observable();
init_engineStore();
init_uniformBuffer();
init_logger();
init_math_plane();
init_drawWrapper();

// node_modules/@babylonjs/core/Materials/materialStencilState.js
init_tslib_es6();
init_decorators_serialization();
init_decorators();

class MaterialStencilState {
  constructor() {
    this.reset();
  }
  reset() {
    this.enabled = false;
    this.mask = 255;
    this.func = 519;
    this.funcRef = 1;
    this.funcMask = 255;
    this.opStencilFail = 7680;
    this.opDepthFail = 7680;
    this.opStencilDepthPass = 7681;
  }
  get func() {
    return this._func;
  }
  set func(value) {
    this._func = value;
  }
  get funcRef() {
    return this._funcRef;
  }
  set funcRef(value) {
    this._funcRef = value;
  }
  get funcMask() {
    return this._funcMask;
  }
  set funcMask(value) {
    this._funcMask = value;
  }
  get opStencilFail() {
    return this._opStencilFail;
  }
  set opStencilFail(value) {
    this._opStencilFail = value;
  }
  get opDepthFail() {
    return this._opDepthFail;
  }
  set opDepthFail(value) {
    this._opDepthFail = value;
  }
  get opStencilDepthPass() {
    return this._opStencilDepthPass;
  }
  set opStencilDepthPass(value) {
    this._opStencilDepthPass = value;
  }
  get mask() {
    return this._mask;
  }
  set mask(value) {
    this._mask = value;
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(value) {
    this._enabled = value;
  }
  getClassName() {
    return "MaterialStencilState";
  }
  copyTo(stencilState) {
    SerializationHelper.Clone(() => stencilState, this);
  }
  serialize() {
    return SerializationHelper.Serialize(this);
  }
  parse(source, scene, rootUrl) {
    SerializationHelper.Parse(() => this, source, scene, rootUrl);
  }
}
__decorate([
  serialize()
], MaterialStencilState.prototype, "func", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "funcRef", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "funcMask", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "opStencilFail", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "opDepthFail", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "opStencilDepthPass", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "mask", null);
__decorate([
  serialize()
], MaterialStencilState.prototype, "enabled", null);

// node_modules/@babylonjs/core/Materials/material.js
init_materialHelper_functions();
init_decorators_serialization();

class Material {
  get _supportGlowLayer() {
    return false;
  }
  set _glowModeEnabled(value) {}
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  get canRenderToMRT() {
    return false;
  }
  set alpha(value) {
    if (this._alpha === value) {
      return;
    }
    const oldValue = this._alpha;
    this._alpha = value;
    if (oldValue === 1 || value === 1) {
      this.markAsDirty(Material.MiscDirtyFlag + Material.PrePassDirtyFlag);
    }
  }
  get alpha() {
    return this._alpha;
  }
  set backFaceCulling(value) {
    if (this._backFaceCulling === value) {
      return;
    }
    this._backFaceCulling = value;
    this.markAsDirty(Material.TextureDirtyFlag);
  }
  get backFaceCulling() {
    return this._backFaceCulling;
  }
  set cullBackFaces(value) {
    if (this._cullBackFaces === value) {
      return;
    }
    this._cullBackFaces = value;
    this.markAsDirty(Material.TextureDirtyFlag);
  }
  get cullBackFaces() {
    return this._cullBackFaces;
  }
  get blockDirtyMechanism() {
    return this._blockDirtyMechanism;
  }
  set blockDirtyMechanism(value) {
    if (this._blockDirtyMechanism === value) {
      return;
    }
    this._blockDirtyMechanism = value;
    if (!value) {
      this.markDirty();
    }
  }
  atomicMaterialsUpdate(callback) {
    this.blockDirtyMechanism = true;
    try {
      callback(this);
    } finally {
      this.blockDirtyMechanism = false;
    }
  }
  get hasRenderTargetTextures() {
    this._eventInfo.hasRenderTargetTextures = false;
    this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
    return this._eventInfo.hasRenderTargetTextures;
  }
  set onDispose(callback) {
    if (this._onDisposeObserver) {
      this.onDisposeObservable.remove(this._onDisposeObserver);
    }
    this._onDisposeObserver = this.onDisposeObservable.add(callback);
  }
  get onBindObservable() {
    if (!this._onBindObservable) {
      this._onBindObservable = new Observable;
    }
    return this._onBindObservable;
  }
  set onBind(callback) {
    if (this._onBindObserver) {
      this.onBindObservable.remove(this._onBindObserver);
    }
    this._onBindObserver = this.onBindObservable.add(callback);
  }
  get onUnBindObservable() {
    if (!this._onUnBindObservable) {
      this._onUnBindObservable = new Observable;
    }
    return this._onUnBindObservable;
  }
  get onEffectCreatedObservable() {
    if (!this._onEffectCreatedObservable) {
      this._onEffectCreatedObservable = new Observable;
    }
    return this._onEffectCreatedObservable;
  }
  set alphaMode(value) {
    if (this._alphaMode === value) {
      return;
    }
    this._alphaMode = value;
    this.markAsDirty(Material.TextureDirtyFlag);
  }
  get alphaMode() {
    return this._alphaMode;
  }
  set needDepthPrePass(value) {
    if (this._needDepthPrePass === value) {
      return;
    }
    this._needDepthPrePass = value;
    if (this._needDepthPrePass) {
      this.checkReadyOnEveryCall = true;
    }
  }
  get needDepthPrePass() {
    return this._needDepthPrePass;
  }
  get isPrePassCapable() {
    return false;
  }
  set fogEnabled(value) {
    if (this._fogEnabled === value) {
      return;
    }
    this._fogEnabled = value;
    this.markAsDirty(Material.MiscDirtyFlag);
  }
  get fogEnabled() {
    return this._fogEnabled;
  }
  get wireframe() {
    switch (this._fillMode) {
      case Material.WireFrameFillMode:
      case Material.LineListDrawMode:
      case Material.LineLoopDrawMode:
      case Material.LineStripDrawMode:
        return true;
    }
    return this._scene.forceWireframe;
  }
  set wireframe(value) {
    this.fillMode = value ? Material.WireFrameFillMode : Material.TriangleFillMode;
  }
  get pointsCloud() {
    switch (this._fillMode) {
      case Material.PointFillMode:
      case Material.PointListDrawMode:
        return true;
    }
    return this._scene.forcePointsCloud;
  }
  set pointsCloud(value) {
    this.fillMode = value ? Material.PointFillMode : Material.TriangleFillMode;
  }
  get fillMode() {
    return this._fillMode;
  }
  set fillMode(value) {
    if (this._fillMode === value) {
      return;
    }
    this._fillMode = value;
    this.markAsDirty(Material.MiscDirtyFlag);
  }
  get useLogarithmicDepth() {
    return this._useLogarithmicDepth;
  }
  set useLogarithmicDepth(value) {
    const fragmentDepthSupported = this.getScene().getEngine().getCaps().fragmentDepthSupported;
    if (value && !fragmentDepthSupported) {
      Logger.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it.");
    }
    this._useLogarithmicDepth = value && fragmentDepthSupported;
    this._markAllSubMeshesAsMiscDirty();
  }
  _getDrawWrapper() {
    return this._drawWrapper;
  }
  _setDrawWrapper(drawWrapper) {
    this._drawWrapper = drawWrapper;
  }
  constructor(name18, scene, doNotAdd, forceGLSL = false) {
    this.shadowDepthWrapper = null;
    this.allowShaderHotSwapping = true;
    this._shaderLanguage = 0;
    this._forceGLSL = false;
    this.metadata = null;
    this.reservedDataStore = null;
    this.checkReadyOnEveryCall = false;
    this.checkReadyOnlyOnce = false;
    this.state = "";
    this._alpha = 1;
    this._backFaceCulling = true;
    this._cullBackFaces = true;
    this._blockDirtyMechanism = false;
    this.sideOrientation = null;
    this.onCompiled = null;
    this.onError = null;
    this.getRenderTargetTextures = null;
    this.doNotSerialize = false;
    this._storeEffectOnSubMeshes = false;
    this.animations = null;
    this.onDisposeObservable = new Observable;
    this._onDisposeObserver = null;
    this._onUnBindObservable = null;
    this._onBindObserver = null;
    this._alphaMode = 2;
    this._needDepthPrePass = false;
    this.disableDepthWrite = false;
    this.disableColorWrite = false;
    this.forceDepthWrite = false;
    this.depthFunction = 0;
    this.separateCullingPass = false;
    this._fogEnabled = true;
    this.pointSize = 1;
    this.zOffset = 0;
    this.zOffsetUnits = 0;
    this.stencil = new MaterialStencilState;
    this._useUBO = false;
    this._fillMode = Material.TriangleFillMode;
    this._cachedDepthWriteState = false;
    this._cachedColorWriteState = false;
    this._cachedDepthFunctionState = 0;
    this._indexInSceneMaterialArray = -1;
    this.meshMap = null;
    this._parentContainer = null;
    this._uniformBufferLayoutBuilt = false;
    this._eventInfo = {};
    this._callbackPluginEventGeneric = () => {
      return;
    };
    this._callbackPluginEventIsReadyForSubMesh = () => {
      return;
    };
    this._callbackPluginEventPrepareDefines = () => {
      return;
    };
    this._callbackPluginEventPrepareDefinesBeforeAttributes = () => {
      return;
    };
    this._callbackPluginEventHardBindForSubMesh = () => {
      return;
    };
    this._callbackPluginEventBindForSubMesh = () => {
      return;
    };
    this._callbackPluginEventHasRenderTargetTextures = () => {
      return;
    };
    this._callbackPluginEventFillRenderTargetTextures = () => {
      return;
    };
    this._transparencyMode = null;
    this.name = name18;
    const setScene = scene || EngineStore.LastCreatedScene;
    if (!setScene) {
      return;
    }
    this._scene = setScene;
    this._dirtyCallbacks = {};
    this._forceGLSL = forceGLSL;
    this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this);
    this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this);
    this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this);
    this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this);
    this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this);
    this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this);
    this._dirtyCallbacks[127] = this._markAllSubMeshesAsAllDirty.bind(this);
    this.id = name18 || Tools.RandomId();
    this.uniqueId = this._scene.getUniqueId();
    this._materialContext = this._scene.getEngine().createMaterialContext();
    this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false);
    this._drawWrapper.materialContext = this._materialContext;
    this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name18);
    this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
    this._createUniformBuffer();
    if (!doNotAdd) {
      this._scene.addMaterial(this);
    }
    if (this._scene.useMaterialMeshMap) {
      this.meshMap = {};
    }
    Material.OnEventObservable.notifyObservers(this, 1);
  }
  _createUniformBuffer() {
    const engine = this.getScene().getEngine();
    this._uniformBuffer?.dispose();
    if (engine.isWebGPU && !this._forceGLSL) {
      this._uniformBuffer = new UniformBuffer(engine, undefined, undefined, this.name, true);
      this._shaderLanguage = 1;
    } else {
      this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, this.name);
    }
    this._uniformBufferLayoutBuilt = false;
  }
  toString(fullDetails) {
    const ret = "Name: " + this.name;
    return ret;
  }
  getClassName() {
    return "Material";
  }
  get _isMaterial() {
    return true;
  }
  get isFrozen() {
    return this.checkReadyOnlyOnce;
  }
  freeze() {
    this.markDirty();
    this.checkReadyOnlyOnce = true;
  }
  unfreeze() {
    this.markDirty();
    this.checkReadyOnlyOnce = false;
  }
  isReady(mesh, useInstances) {
    return true;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances) {
    const defines = subMesh.materialDefines;
    if (!defines) {
      return false;
    }
    this._eventInfo.isReadyForSubMesh = true;
    this._eventInfo.defines = defines;
    this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
    return this._eventInfo.isReadyForSubMesh;
  }
  getEffect() {
    return this._drawWrapper.effect;
  }
  getScene() {
    return this._scene;
  }
  _getEffectiveOrientation(mesh) {
    return this.sideOrientation !== null ? this.sideOrientation : mesh.sideOrientation;
  }
  get transparencyMode() {
    return this._transparencyMode;
  }
  set transparencyMode(value) {
    if (this._transparencyMode === value) {
      return;
    }
    this._transparencyMode = value;
    this._markAllSubMeshesAsTexturesAndMiscDirty();
  }
  get _hasTransparencyMode() {
    return this._transparencyMode != null;
  }
  get _transparencyModeIsBlend() {
    return this._transparencyMode === Material.MATERIAL_ALPHABLEND || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND;
  }
  get _transparencyModeIsTest() {
    return this._transparencyMode === Material.MATERIAL_ALPHATEST || this._transparencyMode === Material.MATERIAL_ALPHATESTANDBLEND;
  }
  get _disableAlphaBlending() {
    return this._transparencyMode === Material.MATERIAL_OPAQUE || this._transparencyMode === Material.MATERIAL_ALPHATEST;
  }
  needAlphaBlending() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsBlend;
    }
    if (this._disableAlphaBlending) {
      return false;
    }
    return this.alpha < 1;
  }
  needAlphaBlendingForMesh(mesh) {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsBlend;
    }
    if (mesh.visibility < 1) {
      return true;
    }
    if (this._disableAlphaBlending) {
      return false;
    }
    return mesh.hasVertexAlpha || this.needAlphaBlending();
  }
  needAlphaTesting() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsTest;
    }
    return false;
  }
  needAlphaTestingForMesh(mesh) {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsTest;
    }
    return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting();
  }
  getAlphaTestTexture() {
    return null;
  }
  markDirty(forceMaterialDirty = false) {
    const meshes = this.getScene().meshes;
    for (const mesh of meshes) {
      if (!mesh.subMeshes) {
        continue;
      }
      for (const subMesh of mesh.subMeshes) {
        if (subMesh.getMaterial() !== this) {
          continue;
        }
        for (const drawWrapper of subMesh._drawWrappers) {
          if (!drawWrapper) {
            continue;
          }
          if (this._materialContext === drawWrapper.materialContext) {
            drawWrapper._wasPreviouslyReady = false;
            drawWrapper._wasPreviouslyUsingInstances = null;
            drawWrapper._forceRebindOnNextCall = forceMaterialDirty;
          }
        }
      }
    }
    if (forceMaterialDirty) {
      this.markAsDirty(Material.AllDirtyFlag);
    }
  }
  _preBind(effect, overrideOrientation = null) {
    const engine = this._scene.getEngine();
    const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation;
    const reverse = orientation === Material.ClockWiseSideOrientation;
    engine.enableEffect(effect ? effect : this._getDrawWrapper());
    engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits);
    return reverse;
  }
  bind(world, mesh) {}
  buildUniformLayout() {
    const ubo = this._uniformBuffer;
    this._eventInfo.ubo = ubo;
    this._callbackPluginEventGeneric(8, this._eventInfo);
    ubo.create();
    this._uniformBufferLayoutBuilt = true;
  }
  bindForSubMesh(world, mesh, subMesh) {
    const drawWrapper = subMesh._drawWrapper;
    this._eventInfo.subMesh = subMesh;
    this._callbackPluginEventBindForSubMesh(this._eventInfo);
    drawWrapper._forceRebindOnNextCall = false;
  }
  bindOnlyWorldMatrix(world) {}
  bindView(effect) {
    if (!this._useUBO) {
      effect.setMatrix("view", this.getScene().getViewMatrix());
    } else {
      this._needToBindSceneUbo = true;
    }
  }
  bindViewProjection(effect) {
    if (!this._useUBO) {
      effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
      effect.setMatrix("projection", this.getScene().getProjectionMatrix());
    } else {
      this._needToBindSceneUbo = true;
    }
  }
  bindEyePosition(effect, variableName) {
    if (!this._useUBO) {
      this._scene.bindEyePosition(effect, variableName);
    } else {
      this._needToBindSceneUbo = true;
    }
  }
  _afterBind(mesh, effect = null, _subMesh) {
    this._scene._cachedMaterial = this;
    if (this._needToBindSceneUbo) {
      if (effect) {
        this._needToBindSceneUbo = false;
        BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
        this._scene.finalizeSceneUbo();
      }
    }
    if (mesh) {
      this._scene._cachedVisibility = mesh.visibility;
    } else {
      this._scene._cachedVisibility = 1;
    }
    if (this._onBindObservable && mesh) {
      this._onBindObservable.notifyObservers(mesh);
    }
    if (this.disableDepthWrite) {
      const engine = this._scene.getEngine();
      this._cachedDepthWriteState = engine.getDepthWrite();
      engine.setDepthWrite(false);
    }
    if (this.disableColorWrite) {
      const engine = this._scene.getEngine();
      this._cachedColorWriteState = engine.getColorWrite();
      engine.setColorWrite(false);
    }
    if (this.depthFunction !== 0) {
      const engine = this._scene.getEngine();
      this._cachedDepthFunctionState = engine.getDepthFunction() || 0;
      engine.setDepthFunction(this.depthFunction);
    }
  }
  unbind() {
    this._scene.getSceneUniformBuffer().unbindEffect();
    if (this._onUnBindObservable) {
      this._onUnBindObservable.notifyObservers(this);
    }
    if (this.depthFunction !== 0) {
      const engine = this._scene.getEngine();
      engine.setDepthFunction(this._cachedDepthFunctionState);
    }
    if (this.disableDepthWrite) {
      const engine = this._scene.getEngine();
      engine.setDepthWrite(this._cachedDepthWriteState);
    }
    if (this.disableColorWrite) {
      const engine = this._scene.getEngine();
      engine.setColorWrite(this._cachedColorWriteState);
    }
  }
  getAnimatables() {
    this._eventInfo.animatables = [];
    this._callbackPluginEventGeneric(256, this._eventInfo);
    return this._eventInfo.animatables;
  }
  getActiveTextures() {
    this._eventInfo.activeTextures = [];
    this._callbackPluginEventGeneric(512, this._eventInfo);
    return this._eventInfo.activeTextures;
  }
  hasTexture(texture) {
    this._eventInfo.hasTexture = false;
    this._eventInfo.texture = texture;
    this._callbackPluginEventGeneric(1024, this._eventInfo);
    return this._eventInfo.hasTexture;
  }
  clone(name18) {
    return null;
  }
  _clonePlugins(targetMaterial, rootUrl) {
    const serializationObject = {};
    this._serializePlugins(serializationObject);
    Material._ParsePlugins(serializationObject, targetMaterial, this._scene, rootUrl);
    if (this.pluginManager) {
      for (const plugin of this.pluginManager._plugins) {
        const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name);
        if (targetPlugin) {
          plugin.copyTo(targetPlugin);
        }
      }
    }
  }
  getBindedMeshes() {
    if (this.meshMap) {
      const result = [];
      for (const meshId in this.meshMap) {
        const mesh = this.meshMap[meshId];
        if (mesh) {
          result.push(mesh);
        }
      }
      return result;
    } else {
      const meshes = this._scene.meshes;
      return meshes.filter((mesh) => mesh.material === this);
    }
  }
  forceCompilation(mesh, onCompiled, options, onError) {
    const localOptions = {
      clipPlane: false,
      useInstances: false,
      ...options
    };
    const scene = this.getScene();
    const currentHotSwapingState = this.allowShaderHotSwapping;
    this.allowShaderHotSwapping = false;
    const checkReady = () => {
      if (!this._scene || !this._scene.getEngine()) {
        return;
      }
      const clipPlaneState = scene.clipPlane;
      if (localOptions.clipPlane) {
        scene.clipPlane = new Plane(0, 0, 0, 1);
      }
      if (this._storeEffectOnSubMeshes) {
        let allDone = true, lastError = null;
        if (mesh.subMeshes) {
          const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false);
          if (tempSubMesh.materialDefines) {
            tempSubMesh.materialDefines._renderId = -1;
          }
          if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) {
            if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) {
              lastError = tempSubMesh.effect.getCompilationError();
            } else {
              allDone = false;
              setTimeout(checkReady, 16);
            }
          }
        }
        if (allDone) {
          this.allowShaderHotSwapping = currentHotSwapingState;
          if (lastError) {
            if (onError) {
              onError(lastError);
            }
          }
          if (onCompiled) {
            onCompiled(this);
          }
        }
      } else {
        if (this.isReady()) {
          this.allowShaderHotSwapping = currentHotSwapingState;
          if (onCompiled) {
            onCompiled(this);
          }
        } else {
          setTimeout(checkReady, 16);
        }
      }
      if (localOptions.clipPlane) {
        scene.clipPlane = clipPlaneState;
      }
    };
    checkReady();
  }
  forceCompilationAsync(mesh, options) {
    return new Promise((resolve3, reject) => {
      this.forceCompilation(mesh, () => {
        resolve3();
      }, options, (reason) => {
        reject(reason);
      });
    });
  }
  markAsDirty(flag) {
    if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
      return;
    }
    Material._DirtyCallbackArray.length = 0;
    if (flag & Material.ImageProcessingDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._ImageProcessingDirtyCallBack);
    }
    if (flag & Material.TextureDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
    }
    if (flag & Material.LightDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
    }
    if (flag & Material.FresnelDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
    }
    if (flag & Material.AttributesDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
    }
    if (flag & Material.MiscDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
    }
    if (flag & Material.PrePassDirtyFlag) {
      Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack);
    }
    if (Material._DirtyCallbackArray.length) {
      this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
    }
    this.getScene().resetCachedMaterial();
  }
  resetDrawCache() {
    const meshes = this.getScene().meshes;
    for (const mesh of meshes) {
      if (!mesh.subMeshes) {
        continue;
      }
      for (const subMesh of mesh.subMeshes) {
        if (subMesh.getMaterial() !== this) {
          continue;
        }
        subMesh.resetDrawCache();
      }
    }
  }
  _markAllSubMeshesAsDirty(func) {
    const scene = this.getScene();
    if (scene.blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
      return;
    }
    const meshes = scene.meshes;
    for (const mesh of meshes) {
      if (!mesh.subMeshes) {
        continue;
      }
      for (const subMesh of mesh.subMeshes) {
        const material = subMesh.getMaterial() || (scene._hasDefaultMaterial ? scene.defaultMaterial : null);
        if (material !== this) {
          continue;
        }
        for (const drawWrapper of subMesh._drawWrappers) {
          if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {
            continue;
          }
          if (this._materialContext === drawWrapper.materialContext) {
            func(drawWrapper.defines);
          }
        }
      }
    }
  }
  _markScenePrePassDirty() {
    if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {
      return;
    }
    const prePassRenderer = this.getScene().enablePrePassRenderer();
    if (prePassRenderer) {
      prePassRenderer.markAsDirty();
    }
  }
  _markAllSubMeshesAsAllDirty() {
    this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);
  }
  _markAllSubMeshesAsImageProcessingDirty() {
    this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  }
  _markAllSubMeshesAsTexturesDirty() {
    this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  }
  _markAllSubMeshesAsFresnelDirty() {
    this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  }
  _markAllSubMeshesAsFresnelAndMiscDirty() {
    this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  }
  _markAllSubMeshesAsLightsDirty() {
    this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  }
  _markAllSubMeshesAsAttributesDirty() {
    this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  }
  _markAllSubMeshesAsMiscDirty() {
    this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  }
  _markAllSubMeshesAsPrePassDirty() {
    this._markAllSubMeshesAsDirty(Material._PrePassDirtyCallBack);
  }
  _markAllSubMeshesAsTexturesAndMiscDirty() {
    this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  }
  _checkScenePerformancePriority() {
    if (this._scene.performancePriority !== 0) {
      this.checkReadyOnlyOnce = true;
      const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => {
        this.checkReadyOnlyOnce = false;
      });
      this.onDisposeObservable.add(() => {
        this._scene.onScenePerformancePriorityChangedObservable.remove(observer);
      });
    }
  }
  setPrePassRenderer(prePassRenderer) {
    return false;
  }
  dispose(_forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
    const scene = this.getScene();
    scene.stopAnimation(this);
    scene.freeProcessedMaterials();
    scene.removeMaterial(this);
    this._eventInfo.forceDisposeTextures = forceDisposeTextures;
    this._callbackPluginEventGeneric(2, this._eventInfo);
    if (this._parentContainer) {
      const index = this._parentContainer.materials.indexOf(this);
      if (index > -1) {
        this._parentContainer.materials.splice(index, 1);
      }
      this._parentContainer = null;
    }
    if (notBoundToMesh !== true) {
      if (this.meshMap) {
        for (const meshId in this.meshMap) {
          const mesh = this.meshMap[meshId];
          this._disposeMeshResources(mesh);
        }
      } else {
        const meshes = scene.meshes;
        for (const mesh of meshes) {
          this._disposeMeshResources(mesh);
        }
      }
    }
    this._uniformBuffer.dispose();
    if (this._drawWrapper.effect) {
      if (!this._storeEffectOnSubMeshes) {
        this._drawWrapper.effect.dispose();
      }
      this._drawWrapper.effect = null;
    }
    this.metadata = null;
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    if (this._onBindObservable) {
      this._onBindObservable.clear();
    }
    if (this._onUnBindObservable) {
      this._onUnBindObservable.clear();
    }
    if (this._onEffectCreatedObservable) {
      this._onEffectCreatedObservable.clear();
    }
    if (this._eventInfo) {
      this._eventInfo = {};
    }
  }
  _disposeMeshResources(mesh) {
    if (!mesh) {
      return;
    }
    const geometry = mesh.geometry;
    const materialForRenderPass = mesh._internalAbstractMeshDataInfo._materialForRenderPass;
    if (this._storeEffectOnSubMeshes) {
      if (mesh.subMeshes && materialForRenderPass) {
        for (const subMesh of mesh.subMeshes) {
          const drawWrappers = subMesh._drawWrappers;
          for (let renderPassIndex = 0;renderPassIndex < drawWrappers.length; renderPassIndex++) {
            const effect = drawWrappers[renderPassIndex]?.effect;
            if (!effect) {
              continue;
            }
            const material = materialForRenderPass[renderPassIndex];
            if (material === this) {
              geometry?._releaseVertexArrayObject(effect);
              subMesh._removeDrawWrapper(renderPassIndex, true, true);
            }
          }
        }
      }
    } else {
      geometry?._releaseVertexArrayObject(this._drawWrapper.effect);
    }
    if (mesh.material === this && !mesh.sourceMesh) {
      mesh.material = null;
    }
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.stencil = this.stencil.serialize();
    serializationObject.uniqueId = this.uniqueId;
    this._serializePlugins(serializationObject);
    return serializationObject;
  }
  _serializePlugins(serializationObject) {
    serializationObject.plugins = {};
    if (this.pluginManager) {
      for (const plugin of this.pluginManager._plugins) {
        if (!plugin.doNotSerialize) {
          serializationObject.plugins[plugin.getClassName()] = plugin.serialize();
        }
      }
    }
  }
  static Parse(parsedMaterial, scene, rootUrl) {
    if (!parsedMaterial.customType) {
      parsedMaterial.customType = "BABYLON.StandardMaterial";
    } else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
      parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
      if (!BABYLON.LegacyPBRMaterial) {
        Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
        return null;
      }
    }
    const materialType = Tools.Instantiate(parsedMaterial.customType);
    const material = materialType.Parse(parsedMaterial, scene, rootUrl);
    material._loadedUniqueId = parsedMaterial.uniqueId;
    return material;
  }
  static _ParsePlugins(serializationObject, material, scene, rootUrl) {
    if (!serializationObject.plugins) {
      return;
    }
    for (const pluginClassName in serializationObject.plugins) {
      const pluginData = serializationObject.plugins[pluginClassName];
      let plugin = material.pluginManager?.getPlugin(pluginData.name);
      if (!plugin) {
        const pluginClassType = Tools.Instantiate("BABYLON." + pluginClassName);
        if (pluginClassType) {
          plugin = new pluginClassType(material);
        }
      }
      plugin?.parse(pluginData, scene, rootUrl);
    }
  }
}
Material.TriangleFillMode = 0;
Material.WireFrameFillMode = 1;
Material.PointFillMode = 2;
Material.PointListDrawMode = 3;
Material.LineListDrawMode = 4;
Material.LineLoopDrawMode = 5;
Material.LineStripDrawMode = 6;
Material.TriangleStripDrawMode = 7;
Material.TriangleFanDrawMode = 8;
Material.ClockWiseSideOrientation = 0;
Material.CounterClockWiseSideOrientation = 1;
Material.ImageProcessingDirtyFlag = 64;
Material.TextureDirtyFlag = 1;
Material.LightDirtyFlag = 2;
Material.FresnelDirtyFlag = 4;
Material.AttributesDirtyFlag = 8;
Material.MiscDirtyFlag = 16;
Material.PrePassDirtyFlag = 32;
Material.AllDirtyFlag = 127;
Material.MATERIAL_OPAQUE = 0;
Material.MATERIAL_ALPHATEST = 1;
Material.MATERIAL_ALPHABLEND = 2;
Material.MATERIAL_ALPHATESTANDBLEND = 3;
Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;
Material.MATERIAL_NORMALBLENDMETHOD_RNM = 1;
Material.OnEventObservable = new Observable;
Material._AllDirtyCallBack = (defines) => defines.markAllAsDirty();
Material._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty();
Material._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty();
Material._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty();
Material._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty();
Material._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty();
Material._LightsDirtyCallBack = (defines) => defines.markAsLightDirty();
Material._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty();
Material._FresnelAndMiscDirtyCallBack = (defines) => {
  Material._FresnelDirtyCallBack(defines);
  Material._MiscDirtyCallBack(defines);
};
Material._TextureAndMiscDirtyCallBack = (defines) => {
  Material._TextureDirtyCallBack(defines);
  Material._MiscDirtyCallBack(defines);
};
Material._DirtyCallbackArray = [];
Material._RunDirtyCallBacks = (defines) => {
  for (const cb of Material._DirtyCallbackArray) {
    cb(defines);
  }
};
__decorate([
  serialize()
], Material.prototype, "id", undefined);
__decorate([
  serialize()
], Material.prototype, "uniqueId", undefined);
__decorate([
  serialize()
], Material.prototype, "name", undefined);
__decorate([
  serialize()
], Material.prototype, "metadata", undefined);
__decorate([
  serialize()
], Material.prototype, "checkReadyOnEveryCall", undefined);
__decorate([
  serialize()
], Material.prototype, "checkReadyOnlyOnce", undefined);
__decorate([
  serialize()
], Material.prototype, "state", undefined);
__decorate([
  serialize("alpha")
], Material.prototype, "_alpha", undefined);
__decorate([
  serialize("backFaceCulling")
], Material.prototype, "_backFaceCulling", undefined);
__decorate([
  serialize("cullBackFaces")
], Material.prototype, "_cullBackFaces", undefined);
__decorate([
  serialize()
], Material.prototype, "sideOrientation", undefined);
__decorate([
  serialize("alphaMode")
], Material.prototype, "_alphaMode", undefined);
__decorate([
  serialize()
], Material.prototype, "_needDepthPrePass", undefined);
__decorate([
  serialize()
], Material.prototype, "disableDepthWrite", undefined);
__decorate([
  serialize()
], Material.prototype, "disableColorWrite", undefined);
__decorate([
  serialize()
], Material.prototype, "forceDepthWrite", undefined);
__decorate([
  serialize()
], Material.prototype, "depthFunction", undefined);
__decorate([
  serialize()
], Material.prototype, "separateCullingPass", undefined);
__decorate([
  serialize("fogEnabled")
], Material.prototype, "_fogEnabled", undefined);
__decorate([
  serialize()
], Material.prototype, "pointSize", undefined);
__decorate([
  serialize()
], Material.prototype, "zOffset", undefined);
__decorate([
  serialize()
], Material.prototype, "zOffsetUnits", undefined);
__decorate([
  serialize()
], Material.prototype, "pointsCloud", null);
__decorate([
  serialize()
], Material.prototype, "fillMode", null);
__decorate([
  serialize()
], Material.prototype, "useLogarithmicDepth", null);
__decorate([
  serialize()
], Material.prototype, "transparencyMode", null);

// node_modules/@babylonjs/core/Materials/multiMaterial.js
init_tags();
init_typeStore();

class MultiMaterial extends Material {
  get subMaterials() {
    return this._subMaterials;
  }
  set subMaterials(value) {
    this._subMaterials = value;
    this._hookArray(value);
  }
  getChildren() {
    return this.subMaterials;
  }
  constructor(name18, scene) {
    super(name18, scene, true);
    this._waitingSubMaterialsUniqueIds = [];
    this.getScene().addMultiMaterial(this);
    this.subMaterials = [];
    this._storeEffectOnSubMeshes = true;
  }
  _hookArray(array) {
    const oldPush = array.push;
    array.push = (...items) => {
      const result = oldPush.apply(array, items);
      this._markAllSubMeshesAsTexturesDirty();
      return result;
    };
    const oldSplice = array.splice;
    array.splice = (index, deleteCount) => {
      const deleted = oldSplice.apply(array, [index, deleteCount]);
      this._markAllSubMeshesAsTexturesDirty();
      return deleted;
    };
  }
  getSubMaterial(index) {
    if (index < 0 || index >= this.subMaterials.length) {
      return this.getScene().defaultMaterial;
    }
    return this.subMaterials[index];
  }
  getActiveTextures() {
    return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => {
      if (subMaterial) {
        return subMaterial.getActiveTextures();
      } else {
        return [];
      }
    }));
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    for (let i = 0;i < this.subMaterials.length; i++) {
      if (this.subMaterials[i]?.hasTexture(texture)) {
        return true;
      }
    }
    return false;
  }
  getClassName() {
    return "MultiMaterial";
  }
  isReadyForSubMesh(mesh, subMesh, useInstances) {
    for (let index = 0;index < this.subMaterials.length; index++) {
      const subMaterial = this.subMaterials[index];
      if (subMaterial) {
        if (subMaterial._storeEffectOnSubMeshes) {
          if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
            return false;
          }
          continue;
        }
        if (!subMaterial.isReady(mesh)) {
          return false;
        }
      }
    }
    return true;
  }
  clone(name18, cloneChildren) {
    const newMultiMaterial = new MultiMaterial(name18, this.getScene());
    for (let index = 0;index < this.subMaterials.length; index++) {
      let subMaterial = null;
      const current = this.subMaterials[index];
      if (cloneChildren && current) {
        subMaterial = current.clone(name18 + "-" + current.name);
      } else {
        subMaterial = this.subMaterials[index];
      }
      newMultiMaterial.subMaterials.push(subMaterial);
    }
    return newMultiMaterial;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.id = this.id;
    serializationObject.uniqueId = this.uniqueId;
    if (Tags) {
      serializationObject.tags = Tags.GetTags(this);
    }
    serializationObject.materialsUniqueIds = [];
    serializationObject.materials = [];
    for (let matIndex = 0;matIndex < this.subMaterials.length; matIndex++) {
      const subMat = this.subMaterials[matIndex];
      if (subMat) {
        serializationObject.materialsUniqueIds.push(subMat.uniqueId);
        serializationObject.materials.push(subMat.id);
      } else {
        serializationObject.materialsUniqueIds.push(null);
        serializationObject.materials.push(null);
      }
    }
    return serializationObject;
  }
  dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    if (forceDisposeChildren) {
      for (let index2 = 0;index2 < this.subMaterials.length; index2++) {
        const subMaterial = this.subMaterials[index2];
        if (subMaterial) {
          subMaterial.dispose(forceDisposeEffect, forceDisposeTextures);
        }
      }
    }
    const index = scene.multiMaterials.indexOf(this);
    if (index >= 0) {
      scene.multiMaterials.splice(index, 1);
    }
    super.dispose(forceDisposeEffect, forceDisposeTextures);
  }
  static ParseMultiMaterial(parsedMultiMaterial, scene) {
    const multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene);
    multiMaterial.id = parsedMultiMaterial.id;
    multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId;
    if (Tags) {
      Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
    }
    if (parsedMultiMaterial.materialsUniqueIds) {
      multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds;
    } else {
      parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId)));
    }
    return multiMaterial;
  }
}
RegisterClass("BABYLON.MultiMaterial", MultiMaterial);

// node_modules/@babylonjs/core/Meshes/mesh.js
init_decorators_serialization();
init_logger();
init_typeStore();
init_devTools();
init_sceneComponent();

// node_modules/@babylonjs/core/Meshes/meshLODLevel.js
class MeshLODLevel {
  constructor(distanceOrScreenCoverage, mesh) {
    this.distanceOrScreenCoverage = distanceOrScreenCoverage;
    this.mesh = mesh;
  }
}

// node_modules/@babylonjs/core/Meshes/mesh.js
class _CreationDataStorage {
}

class _InstanceDataStorage {
  constructor() {
    this.visibleInstances = {};
    this.batchCache = new _InstancesBatch;
    this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch;
    this.instancesBufferSize = 32 * 16 * 4;
  }
}

class _InstancesBatch {
  constructor() {
    this.mustReturn = false;
    this.visibleInstances = new Array;
    this.renderSelf = [];
    this.hardwareInstancedRendering = [];
  }
}

class _ThinInstanceDataStorage {
  constructor() {
    this.instancesCount = 0;
    this.matrixBuffer = null;
    this.previousMatrixBuffer = null;
    this.matrixBufferSize = 32 * 16;
    this.matrixData = null;
    this.boundingVectors = [];
    this.worldMatrices = null;
  }
}

class _InternalMeshDataInfo {
  constructor() {
    this._areNormalsFrozen = false;
    this._source = null;
    this.meshMap = null;
    this._preActivateId = -1;
    this._LODLevels = new Array;
    this._useLODScreenCoverage = false;
    this._effectiveMaterial = null;
    this._forcedInstanceCount = 0;
    this._overrideRenderingFillMode = null;
  }
}
var meshCreationOptions = {
  source: null,
  parent: null,
  doNotCloneChildren: false,
  clonePhysicsImpostor: true,
  cloneThinInstances: false
};

class Mesh extends AbstractMesh {
  static _GetDefaultSideOrientation(orientation) {
    return orientation || Mesh.FRONTSIDE;
  }
  get useLODScreenCoverage() {
    return this._internalMeshDataInfo._useLODScreenCoverage;
  }
  set useLODScreenCoverage(value) {
    this._internalMeshDataInfo._useLODScreenCoverage = value;
    this._sortLODLevels();
  }
  get computeBonesUsingShaders() {
    return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;
  }
  set computeBonesUsingShaders(value) {
    if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {
      return;
    }
    if (value && this._internalMeshDataInfo._sourcePositions) {
      this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true);
      if (this._internalMeshDataInfo._sourceNormals) {
        this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true);
      }
      this._internalMeshDataInfo._sourcePositions = null;
      this._internalMeshDataInfo._sourceNormals = null;
    }
    this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;
    this._markSubMeshesAsAttributesDirty();
  }
  get onBeforeRenderObservable() {
    if (!this._internalMeshDataInfo._onBeforeRenderObservable) {
      this._internalMeshDataInfo._onBeforeRenderObservable = new Observable;
    }
    return this._internalMeshDataInfo._onBeforeRenderObservable;
  }
  get onBeforeBindObservable() {
    if (!this._internalMeshDataInfo._onBeforeBindObservable) {
      this._internalMeshDataInfo._onBeforeBindObservable = new Observable;
    }
    return this._internalMeshDataInfo._onBeforeBindObservable;
  }
  get onAfterRenderObservable() {
    if (!this._internalMeshDataInfo._onAfterRenderObservable) {
      this._internalMeshDataInfo._onAfterRenderObservable = new Observable;
    }
    return this._internalMeshDataInfo._onAfterRenderObservable;
  }
  get onBetweenPassObservable() {
    if (!this._internalMeshDataInfo._onBetweenPassObservable) {
      this._internalMeshDataInfo._onBetweenPassObservable = new Observable;
    }
    return this._internalMeshDataInfo._onBetweenPassObservable;
  }
  get onBeforeDrawObservable() {
    if (!this._internalMeshDataInfo._onBeforeDrawObservable) {
      this._internalMeshDataInfo._onBeforeDrawObservable = new Observable;
    }
    return this._internalMeshDataInfo._onBeforeDrawObservable;
  }
  set onBeforeDraw(callback) {
    if (this._onBeforeDrawObserver) {
      this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
    }
    this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  }
  get hasInstances() {
    return this.instances.length > 0;
  }
  get hasThinInstances() {
    return (this.forcedInstanceCount || this._thinInstanceDataStorage.instancesCount || 0) > 0;
  }
  get forcedInstanceCount() {
    return this._internalMeshDataInfo._forcedInstanceCount;
  }
  set forcedInstanceCount(count) {
    this._internalMeshDataInfo._forcedInstanceCount = count;
  }
  get sideOrientation() {
    return this._internalMeshDataInfo._sideOrientation;
  }
  set sideOrientation(value) {
    this._internalMeshDataInfo._sideOrientation = value;
    this._internalAbstractMeshDataInfo._sideOrientationHint = this._scene.useRightHandedSystem && value === 1 || !this._scene.useRightHandedSystem && value === 0;
  }
  get overrideMaterialSideOrientation() {
    return this.sideOrientation;
  }
  set overrideMaterialSideOrientation(value) {
    this.sideOrientation = value;
    if (this.material) {
      this.material.sideOrientation = null;
    }
  }
  get overrideRenderingFillMode() {
    return this._internalMeshDataInfo._overrideRenderingFillMode;
  }
  set overrideRenderingFillMode(fillMode) {
    this._internalMeshDataInfo._overrideRenderingFillMode = fillMode;
  }
  get material() {
    return this._internalAbstractMeshDataInfo._material;
  }
  set material(value) {
    if (value && (this.material && this.material.sideOrientation === null || this._internalAbstractMeshDataInfo._sideOrientationHint)) {
      value.sideOrientation = null;
    }
    this._setMaterial(value);
  }
  get source() {
    return this._internalMeshDataInfo._source;
  }
  get cloneMeshMap() {
    return this._internalMeshDataInfo.meshMap;
  }
  get isUnIndexed() {
    return this._unIndexed;
  }
  set isUnIndexed(value) {
    if (this._unIndexed !== value) {
      this._unIndexed = value;
      this._markSubMeshesAsAttributesDirty();
    }
  }
  get worldMatrixInstancedBuffer() {
    return this._instanceDataStorage.instancesData;
  }
  get previousWorldMatrixInstancedBuffer() {
    return this._instanceDataStorage.instancesPreviousData;
  }
  get manualUpdateOfWorldMatrixInstancedBuffer() {
    return this._instanceDataStorage.manualUpdate;
  }
  set manualUpdateOfWorldMatrixInstancedBuffer(value) {
    this._instanceDataStorage.manualUpdate = value;
  }
  get manualUpdateOfPreviousWorldMatrixInstancedBuffer() {
    return this._instanceDataStorage.previousManualUpdate;
  }
  set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value) {
    this._instanceDataStorage.previousManualUpdate = value;
  }
  get forceWorldMatrixInstancedBufferUpdate() {
    return this._instanceDataStorage.forceMatrixUpdates;
  }
  set forceWorldMatrixInstancedBufferUpdate(value) {
    this._instanceDataStorage.forceMatrixUpdates = value;
  }
  _copySource(source, doNotCloneChildren, clonePhysicsImpostor = true, cloneThinInstances = false) {
    const scene = this.getScene();
    if (source._geometry) {
      source._geometry.applyToMesh(this);
    }
    DeepCopier.DeepCopy(source, this, [
      "name",
      "material",
      "skeleton",
      "instances",
      "parent",
      "uniqueId",
      "source",
      "metadata",
      "morphTargetManager",
      "hasInstances",
      "worldMatrixInstancedBuffer",
      "previousWorldMatrixInstancedBuffer",
      "hasLODLevels",
      "geometry",
      "isBlocked",
      "areNormalsFrozen",
      "facetNb",
      "isFacetDataEnabled",
      "lightSources",
      "useBones",
      "isAnInstance",
      "collider",
      "edgesRenderer",
      "forward",
      "up",
      "right",
      "absolutePosition",
      "absoluteScaling",
      "absoluteRotationQuaternion",
      "isWorldMatrixFrozen",
      "nonUniformScaling",
      "behaviors",
      "worldMatrixFromCache",
      "hasThinInstances",
      "cloneMeshMap",
      "hasBoundingInfo",
      "physicsBody",
      "physicsImpostor"
    ], ["_poseMatrix"]);
    this._internalMeshDataInfo._source = source;
    if (scene.useClonedMeshMap) {
      if (!source._internalMeshDataInfo.meshMap) {
        source._internalMeshDataInfo.meshMap = {};
      }
      source._internalMeshDataInfo.meshMap[this.uniqueId] = this;
    }
    this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
    this._creationDataStorage = source._creationDataStorage;
    if (source._ranges) {
      const ranges = source._ranges;
      for (const name18 in ranges) {
        if (!Object.prototype.hasOwnProperty.call(ranges, name18)) {
          continue;
        }
        if (!ranges[name18]) {
          continue;
        }
        this.createAnimationRange(name18, ranges[name18].from, ranges[name18].to);
      }
    }
    if (source.metadata && source.metadata.clone) {
      this.metadata = source.metadata.clone();
    } else {
      this.metadata = source.metadata;
    }
    this._internalMetadata = source._internalMetadata;
    if (Tags && Tags.HasTags(source)) {
      Tags.AddTagsTo(this, Tags.GetTags(source, true));
    }
    this.setEnabled(source.isEnabled(false));
    this.parent = source.parent;
    this.setPivotMatrix(source.getPivotMatrix(), this._postMultiplyPivotMatrix);
    this.id = this.name + "." + source.id;
    this.material = source.material;
    if (!doNotCloneChildren) {
      const directDescendants = source.getDescendants(true);
      for (let index = 0;index < directDescendants.length; index++) {
        const child = directDescendants[index];
        if (child._isMesh) {
          meshCreationOptions.parent = this;
          meshCreationOptions.doNotCloneChildren = doNotCloneChildren;
          meshCreationOptions.clonePhysicsImpostor = clonePhysicsImpostor;
          meshCreationOptions.cloneThinInstances = cloneThinInstances;
          child.clone(this.name + "." + child.name, meshCreationOptions);
        } else if (child.clone) {
          child.clone(this.name + "." + child.name, this);
        }
      }
    }
    if (source.morphTargetManager) {
      this.morphTargetManager = source.morphTargetManager;
    }
    if (scene.getPhysicsEngine) {
      const physicsEngine = scene.getPhysicsEngine();
      if (clonePhysicsImpostor && physicsEngine) {
        if (physicsEngine.getPluginVersion() === 1) {
          const impostor = physicsEngine.getImpostorForPhysicsObject(source);
          if (impostor) {
            this.physicsImpostor = impostor.clone(this);
          }
        } else if (physicsEngine.getPluginVersion() === 2) {
          if (source.physicsBody) {
            source.physicsBody.clone(this);
          }
        }
      }
    }
    for (let index = 0;index < scene.particleSystems.length; index++) {
      const system = scene.particleSystems[index];
      if (system.emitter === source) {
        system.clone(system.name, this);
      }
    }
    this.skeleton = source.skeleton;
    if (cloneThinInstances) {
      if (source._thinInstanceDataStorage.matrixData) {
        this.thinInstanceSetBuffer("matrix", new Float32Array(source._thinInstanceDataStorage.matrixData), 16, !source._thinInstanceDataStorage.matrixBuffer.isUpdatable());
        this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize;
        this._thinInstanceDataStorage.instancesCount = source._thinInstanceDataStorage.instancesCount;
      } else {
        this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize;
      }
      if (source._userThinInstanceBuffersStorage) {
        const userThinInstance = source._userThinInstanceBuffersStorage;
        for (const kind in userThinInstance.data) {
          this.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], !userThinInstance.vertexBuffers?.[kind]?.isUpdatable());
          this._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind];
        }
      }
    }
    this.refreshBoundingInfo(true, true);
    this.computeWorldMatrix(true);
  }
  constructor(name18, scene = null, parentOrOptions = null, source = null, doNotCloneChildren, clonePhysicsImpostor = true) {
    super(name18, scene);
    this._internalMeshDataInfo = new _InternalMeshDataInfo;
    this.delayLoadState = 0;
    this.instances = [];
    this._creationDataStorage = null;
    this._geometry = null;
    this._instanceDataStorage = new _InstanceDataStorage;
    this._thinInstanceDataStorage = new _ThinInstanceDataStorage;
    this._shouldGenerateFlatShading = false;
    this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
    this.ignoreCameraMaxZ = false;
    scene = this.getScene();
    if (this._scene.useRightHandedSystem) {
      this.sideOrientation = 0;
    } else {
      this.sideOrientation = 1;
    }
    this._onBeforeDraw = (isInstance, world, effectiveMaterial) => {
      if (isInstance && effectiveMaterial) {
        if (this._uniformBuffer) {
          this.transferToEffect(world);
        } else {
          effectiveMaterial.bindOnlyWorldMatrix(world);
        }
      }
    };
    let parent = null;
    let cloneThinInstances = false;
    if (parentOrOptions && parentOrOptions._addToSceneRootNodes === undefined) {
      const options = parentOrOptions;
      parent = options.parent ?? null;
      source = options.source ?? null;
      doNotCloneChildren = options.doNotCloneChildren ?? false;
      clonePhysicsImpostor = options.clonePhysicsImpostor ?? true;
      cloneThinInstances = options.cloneThinInstances ?? false;
    } else {
      parent = parentOrOptions;
    }
    if (source) {
      this._copySource(source, doNotCloneChildren, clonePhysicsImpostor, cloneThinInstances);
    }
    if (parent !== null) {
      this.parent = parent;
    }
    this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays;
    this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer) => {
      observer.unregisterOnNextCall = true;
      if (this.isReady(true)) {
        this.onMeshReadyObservable.notifyObservers(this);
      } else {
        if (!this._internalMeshDataInfo._checkReadinessObserver) {
          this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => {
            if (this.isReady(true)) {
              this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver);
              this._internalMeshDataInfo._checkReadinessObserver = null;
              this.onMeshReadyObservable.notifyObservers(this);
            }
          });
        }
      }
    };
    this.onMeshReadyObservable = new Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded);
    if (source) {
      source.onClonedObservable.notifyObservers(this);
    }
  }
  instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
    const instance = this.getTotalVertices() === 0 || options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this)) ? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true) : this.createInstance("instance of " + (this.name || this.id));
    instance.parent = newParent || this.parent;
    instance.position = this.position.clone();
    instance.scaling = this.scaling.clone();
    if (this.rotationQuaternion) {
      instance.rotationQuaternion = this.rotationQuaternion.clone();
    } else {
      instance.rotation = this.rotation.clone();
    }
    if (onNewNodeCreated) {
      onNewNodeCreated(this, instance);
    }
    for (const child of this.getChildTransformNodes(true)) {
      if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && child.sourceMesh === this) {
        child.instantiateHierarchy(instance, {
          doNotInstantiate: options && options.doNotInstantiate || false,
          newSourcedMesh: instance
        }, onNewNodeCreated);
      } else {
        child.instantiateHierarchy(instance, options, onNewNodeCreated);
      }
    }
    return instance;
  }
  getClassName() {
    return "Mesh";
  }
  get _isMesh() {
    return true;
  }
  toString(fullDetails) {
    let ret = super.toString(fullDetails);
    ret += ", n vertices: " + this.getTotalVertices();
    ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE");
    if (this.animations) {
      for (let i = 0;i < this.animations.length; i++) {
        ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
      }
    }
    if (fullDetails) {
      if (this._geometry) {
        const ib = this.getIndices();
        const vb = this.getVerticesData(VertexBuffer.PositionKind);
        if (vb && ib) {
          ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
        }
      } else {
        ret += ", flat shading: UNKNOWN";
      }
    }
    return ret;
  }
  _unBindEffect() {
    super._unBindEffect();
    for (const instance of this.instances) {
      instance._unBindEffect();
    }
  }
  get hasLODLevels() {
    return this._internalMeshDataInfo._LODLevels.length > 0;
  }
  getLODLevels() {
    return this._internalMeshDataInfo._LODLevels;
  }
  _sortLODLevels() {
    const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1;
    this._internalMeshDataInfo._LODLevels.sort((a, b) => {
      if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) {
        return sortingOrderFactor;
      }
      if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) {
        return -sortingOrderFactor;
      }
      return 0;
    });
  }
  addLODLevel(distanceOrScreenCoverage, mesh) {
    if (mesh && mesh._masterMesh) {
      Logger.Warn("You cannot use a mesh as LOD level twice");
      return this;
    }
    const level = new MeshLODLevel(distanceOrScreenCoverage, mesh);
    this._internalMeshDataInfo._LODLevels.push(level);
    if (mesh) {
      mesh._masterMesh = this;
    }
    this._sortLODLevels();
    return this;
  }
  getLODLevelAtDistance(distance) {
    const internalDataInfo = this._internalMeshDataInfo;
    for (let index = 0;index < internalDataInfo._LODLevels.length; index++) {
      const level = internalDataInfo._LODLevels[index];
      if (level.distanceOrScreenCoverage === distance) {
        return level.mesh;
      }
    }
    return null;
  }
  removeLODLevel(mesh) {
    const internalDataInfo = this._internalMeshDataInfo;
    for (let index = 0;index < internalDataInfo._LODLevels.length; index++) {
      if (internalDataInfo._LODLevels[index].mesh === mesh) {
        internalDataInfo._LODLevels.splice(index, 1);
        if (mesh) {
          mesh._masterMesh = null;
        }
      }
    }
    this._sortLODLevels();
    return this;
  }
  getLOD(camera, boundingSphere) {
    const internalDataInfo = this._internalMeshDataInfo;
    if (!internalDataInfo._LODLevels || internalDataInfo._LODLevels.length === 0) {
      return this;
    }
    const bSphere = boundingSphere || this.getBoundingInfo().boundingSphere;
    const distanceToCamera = camera.mode === Camera.ORTHOGRAPHIC_CAMERA ? camera.minZ : bSphere.centerWorld.subtract(camera.globalPosition).length();
    let compareValue = distanceToCamera;
    let compareSign = 1;
    if (internalDataInfo._useLODScreenCoverage) {
      const screenArea = camera.screenArea;
      let meshArea = bSphere.radiusWorld * camera.minZ / distanceToCamera;
      meshArea = meshArea * meshArea * Math.PI;
      compareValue = meshArea / screenArea;
      compareSign = -1;
    }
    if (compareSign * internalDataInfo._LODLevels[internalDataInfo._LODLevels.length - 1].distanceOrScreenCoverage > compareSign * compareValue) {
      if (this.onLODLevelSelection) {
        this.onLODLevelSelection(compareValue, this, this);
      }
      return this;
    }
    for (let index = 0;index < internalDataInfo._LODLevels.length; index++) {
      const level = internalDataInfo._LODLevels[index];
      if (compareSign * level.distanceOrScreenCoverage < compareSign * compareValue) {
        if (level.mesh) {
          if (level.mesh.delayLoadState === 4) {
            level.mesh._checkDelayState();
            return this;
          }
          if (level.mesh.delayLoadState === 2) {
            return this;
          }
          level.mesh._preActivate();
          level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
        }
        if (this.onLODLevelSelection) {
          this.onLODLevelSelection(compareValue, this, level.mesh);
        }
        return level.mesh;
      }
    }
    if (this.onLODLevelSelection) {
      this.onLODLevelSelection(compareValue, this, this);
    }
    return this;
  }
  get geometry() {
    return this._geometry;
  }
  getTotalVertices() {
    if (this._geometry === null || this._geometry === undefined) {
      return 0;
    }
    return this._geometry.getTotalVertices();
  }
  getVerticesData(kind, copyWhenShared, forceCopy, bypassInstanceData) {
    if (!this._geometry) {
      return null;
    }
    let data = bypassInstanceData ? undefined : this._userInstancedBuffersStorage?.vertexBuffers[kind]?.getFloatData(this.instances.length + 1, forceCopy || copyWhenShared && this._geometry.meshes.length !== 1);
    if (!data) {
      data = this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
    }
    return data;
  }
  copyVerticesData(kind, vertexData) {
    if (this._geometry) {
      this._geometry.copyVerticesData(kind, vertexData);
    }
  }
  getVertexBuffer(kind, bypassInstanceData) {
    if (!this._geometry) {
      return null;
    }
    return (bypassInstanceData ? undefined : this._userInstancedBuffersStorage?.vertexBuffers[kind]) ?? this._geometry.getVertexBuffer(kind);
  }
  isVerticesDataPresent(kind, bypassInstanceData) {
    if (!this._geometry) {
      if (this._delayInfo) {
        return this._delayInfo.indexOf(kind) !== -1;
      }
      return false;
    }
    return !bypassInstanceData && this._userInstancedBuffersStorage?.vertexBuffers[kind] !== undefined || this._geometry.isVerticesDataPresent(kind);
  }
  isVertexBufferUpdatable(kind, bypassInstanceData) {
    if (!this._geometry) {
      if (this._delayInfo) {
        return this._delayInfo.indexOf(kind) !== -1;
      }
      return false;
    }
    if (!bypassInstanceData) {
      const buffer = this._userInstancedBuffersStorage?.vertexBuffers[kind];
      if (buffer) {
        return buffer.isUpdatable();
      }
    }
    return this._geometry.isVertexBufferUpdatable(kind);
  }
  getVerticesDataKinds(bypassInstanceData) {
    if (!this._geometry) {
      const result = [];
      if (this._delayInfo) {
        this._delayInfo.forEach(function(kind) {
          result.push(kind);
        });
      }
      return result;
    }
    const kinds = this._geometry.getVerticesDataKinds();
    if (!bypassInstanceData && this._userInstancedBuffersStorage) {
      for (const kind in this._userInstancedBuffersStorage.vertexBuffers) {
        if (kinds.indexOf(kind) === -1) {
          kinds.push(kind);
        }
      }
    }
    return kinds;
  }
  getTotalIndices() {
    if (!this._geometry) {
      return 0;
    }
    return this._geometry.getTotalIndices();
  }
  getIndices(copyWhenShared, forceCopy) {
    if (!this._geometry) {
      return [];
    }
    return this._geometry.getIndices(copyWhenShared, forceCopy);
  }
  get isBlocked() {
    return this._masterMesh !== null && this._masterMesh !== undefined;
  }
  isReady(completeCheck = false, forceInstanceSupport = false) {
    if (this.delayLoadState === 2) {
      return false;
    }
    if (!super.isReady(completeCheck)) {
      return false;
    }
    if (!this.subMeshes || this.subMeshes.length === 0) {
      return true;
    }
    if (!completeCheck) {
      return true;
    }
    const engine = this.getEngine();
    const scene = this.getScene();
    const hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances);
    this.computeWorldMatrix();
    const mat = this.material || scene.defaultMaterial;
    if (mat) {
      if (mat._storeEffectOnSubMeshes) {
        for (const subMesh of this.subMeshes) {
          const effectiveMaterial = subMesh.getMaterial();
          if (effectiveMaterial) {
            if (effectiveMaterial._storeEffectOnSubMeshes) {
              if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
                return false;
              }
            } else {
              if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
                return false;
              }
            }
          }
        }
      } else {
        if (!mat.isReady(this, hardwareInstancedRendering)) {
          return false;
        }
      }
    }
    const currentRenderPassId = engine.currentRenderPassId;
    for (const light of this.lightSources) {
      const generators = light.getShadowGenerators();
      if (!generators) {
        continue;
      }
      const iterator = generators.values();
      for (let key = iterator.next();key.done !== true; key = iterator.next()) {
        const generator = key.value;
        if (generator && (!generator.getShadowMap()?.renderList || generator.getShadowMap()?.renderList && generator.getShadowMap()?.renderList?.indexOf(this) !== -1)) {
          const shadowMap = generator.getShadowMap();
          const renderPassIds = shadowMap.renderPassIds ?? [engine.currentRenderPassId];
          for (let p = 0;p < renderPassIds.length; ++p) {
            engine.currentRenderPassId = renderPassIds[p];
            for (const subMesh of this.subMeshes) {
              if (!generator.isReady(subMesh, hardwareInstancedRendering, subMesh.getMaterial()?.needAlphaBlendingForMesh(this) ?? false)) {
                engine.currentRenderPassId = currentRenderPassId;
                return false;
              }
            }
          }
          engine.currentRenderPassId = currentRenderPassId;
        }
      }
    }
    for (const lod of this._internalMeshDataInfo._LODLevels) {
      if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
        return false;
      }
    }
    return true;
  }
  get areNormalsFrozen() {
    return this._internalMeshDataInfo._areNormalsFrozen;
  }
  freezeNormals() {
    this._internalMeshDataInfo._areNormalsFrozen = true;
    return this;
  }
  unfreezeNormals() {
    this._internalMeshDataInfo._areNormalsFrozen = false;
    return this;
  }
  set overridenInstanceCount(count) {
    this._instanceDataStorage.overridenInstanceCount = count;
  }
  _preActivate() {
    const internalDataInfo = this._internalMeshDataInfo;
    const sceneRenderId = this.getScene().getRenderId();
    if (internalDataInfo._preActivateId === sceneRenderId) {
      return this;
    }
    internalDataInfo._preActivateId = sceneRenderId;
    this._instanceDataStorage.visibleInstances = null;
    return this;
  }
  _preActivateForIntermediateRendering(renderId) {
    if (this._instanceDataStorage.visibleInstances) {
      this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
    }
    return this;
  }
  _registerInstanceForRenderId(instance, renderId) {
    if (!this._instanceDataStorage.visibleInstances) {
      this._instanceDataStorage.visibleInstances = {
        defaultRenderId: renderId,
        selfDefaultRenderId: this._renderId
      };
    }
    if (!this._instanceDataStorage.visibleInstances[renderId]) {
      if (this._instanceDataStorage.previousRenderId !== undefined && this._instanceDataStorage.isFrozen) {
        this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null;
      }
      this._instanceDataStorage.previousRenderId = renderId;
      this._instanceDataStorage.visibleInstances[renderId] = new Array;
    }
    this._instanceDataStorage.visibleInstances[renderId].push(instance);
    return this;
  }
  _afterComputeWorldMatrix() {
    super._afterComputeWorldMatrix();
    if (!this.hasThinInstances) {
      return;
    }
    if (!this.doNotSyncBoundingInfo) {
      this.thinInstanceRefreshBoundingInfo(false);
    }
  }
  _postActivate() {
    if (this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup) {
      this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer);
      this.edgesRenderer.customInstances.push(this.getWorldMatrix());
    }
  }
  refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph2 = false) {
    if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {
      return this;
    }
    let options;
    if (typeof applySkeletonOrOptions === "object") {
      options = applySkeletonOrOptions;
    } else {
      options = {
        applySkeleton: applySkeletonOrOptions,
        applyMorph: applyMorph2
      };
    }
    const bias = this.geometry ? this.geometry.boundingBias : null;
    this._refreshBoundingInfo(this._getData(options, null, VertexBuffer.PositionKind), bias);
    return this;
  }
  _createGlobalSubMesh(force) {
    const totalVertices = this.getTotalVertices();
    if (!totalVertices || !this.getIndices()) {
      return null;
    }
    if (this.subMeshes && this.subMeshes.length > 0) {
      const ib = this.getIndices();
      if (!ib) {
        return null;
      }
      const totalIndices = ib.length;
      let needToRecreate = false;
      if (force) {
        needToRecreate = true;
      } else {
        for (const submesh of this.subMeshes) {
          if (submesh.indexStart + submesh.indexCount > totalIndices) {
            needToRecreate = true;
            break;
          }
          if (submesh.verticesStart + submesh.verticesCount > totalVertices) {
            needToRecreate = true;
            break;
          }
        }
      }
      if (!needToRecreate) {
        return this.subMeshes[0];
      }
    }
    this.releaseSubMeshes();
    return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices() || totalVertices, this);
  }
  subdivide(count) {
    if (count < 1) {
      return;
    }
    const totalIndices = this.getTotalIndices();
    let subdivisionSize = totalIndices / count | 0;
    let offset = 0;
    while (subdivisionSize % 3 !== 0) {
      subdivisionSize++;
    }
    this.releaseSubMeshes();
    for (let index = 0;index < count; index++) {
      if (offset >= totalIndices) {
        break;
      }
      SubMesh.CreateFromIndices(0, offset, index === count - 1 ? totalIndices - offset : subdivisionSize, this, undefined, false);
      offset += subdivisionSize;
    }
    this.refreshBoundingInfo();
    this.synchronizeInstances();
  }
  setVerticesData(kind, data, updatable = false, stride) {
    if (!this._geometry) {
      const vertexData = new VertexData;
      vertexData.set(data, kind);
      const scene = this.getScene();
      new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
    } else {
      this._geometry.setVerticesData(kind, data, updatable, stride);
    }
    return this;
  }
  removeVerticesData(kind) {
    if (!this._geometry) {
      return;
    }
    this._geometry.removeVerticesData(kind);
  }
  markVerticesDataAsUpdatable(kind, updatable = true) {
    const vb = this.getVertexBuffer(kind);
    if (!vb || vb.isUpdatable() === updatable) {
      return;
    }
    this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  }
  setVerticesBuffer(buffer, disposeExistingBuffer = true) {
    if (!this._geometry) {
      this._geometry = Geometry.CreateGeometryForMesh(this);
    }
    this._geometry.setVerticesBuffer(buffer, null, disposeExistingBuffer);
    return this;
  }
  updateVerticesData(kind, data, updateExtends, makeItUnique) {
    if (!this._geometry) {
      return this;
    }
    if (!makeItUnique) {
      this._geometry.updateVerticesData(kind, data, updateExtends);
    } else {
      this.makeGeometryUnique();
      this.updateVerticesData(kind, data, updateExtends, false);
    }
    return this;
  }
  updateMeshPositions(positionFunction, computeNormals = true) {
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    if (!positions) {
      return this;
    }
    positionFunction(positions);
    this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
    if (computeNormals) {
      const indices = this.getIndices();
      const normals = this.getVerticesData(VertexBuffer.NormalKind);
      if (!normals) {
        return this;
      }
      VertexData.ComputeNormals(positions, indices, normals);
      this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
    }
    return this;
  }
  makeGeometryUnique() {
    if (!this._geometry) {
      return this;
    }
    if (this._geometry.meshes.length === 1) {
      return this;
    }
    const oldGeometry = this._geometry;
    const geometry = this._geometry.copy(Geometry.RandomId());
    oldGeometry.releaseForMesh(this, true);
    geometry.applyToMesh(this);
    return this;
  }
  setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) {
    let geometry = this._geometry;
    if (!geometry) {
      geometry = new Geometry(Geometry.RandomId(), this.getScene(), undefined, undefined, this);
    }
    geometry.setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits);
  }
  setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) {
    if (!this._geometry) {
      const vertexData = new VertexData;
      vertexData.indices = indices;
      const scene = this.getScene();
      new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
    } else {
      this._geometry.setIndices(indices, totalVertices, updatable, dontForceSubMeshRecreation);
    }
    return this;
  }
  updateIndices(indices, offset, gpuMemoryOnly = false) {
    if (!this._geometry) {
      return this;
    }
    this._geometry.updateIndices(indices, offset, gpuMemoryOnly);
    return this;
  }
  toLeftHanded() {
    if (!this._geometry) {
      return this;
    }
    this._geometry.toLeftHanded();
    return this;
  }
  _bind(subMesh, effect, fillMode, allowInstancedRendering = true) {
    if (!this._geometry) {
      return this;
    }
    const engine = this.getScene().getEngine();
    let indexToBind;
    if (this._unIndexed) {
      switch (this._getRenderingFillMode(fillMode)) {
        case Material.WireFrameFillMode:
          indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
          break;
        default:
          indexToBind = null;
          break;
      }
    } else {
      switch (this._getRenderingFillMode(fillMode)) {
        case Material.PointFillMode:
          indexToBind = null;
          break;
        case Material.WireFrameFillMode:
          indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
          break;
        default:
        case Material.TriangleFillMode:
          indexToBind = this._geometry.getIndexBuffer();
          break;
      }
    }
    return this._bindDirect(effect, indexToBind, allowInstancedRendering);
  }
  _bindDirect(effect, indexToBind, allowInstancedRendering = true) {
    if (!this._geometry) {
      return this;
    }
    if (this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets) {
      this.morphTargetManager._bind(effect);
    }
    if (!allowInstancedRendering || !this._userInstancedBuffersStorage || this.hasThinInstances) {
      this._geometry._bind(effect, indexToBind);
    } else {
      this._geometry._bind(effect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects);
    }
    return this;
  }
  _draw(subMesh, fillMode, instancesCount) {
    if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
      return this;
    }
    if (this._internalMeshDataInfo._onBeforeDrawObservable) {
      this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);
    }
    const scene = this.getScene();
    const engine = scene.getEngine();
    if (this._unIndexed && fillMode !== Material.WireFrameFillMode || fillMode == Material.PointFillMode) {
      engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, this.forcedInstanceCount || instancesCount);
    } else if (fillMode == Material.WireFrameFillMode) {
      engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, this.forcedInstanceCount || instancesCount);
    } else {
      engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount);
    }
    return this;
  }
  registerBeforeRender(func) {
    this.onBeforeRenderObservable.add(func);
    return this;
  }
  unregisterBeforeRender(func) {
    this.onBeforeRenderObservable.removeCallback(func);
    return this;
  }
  registerAfterRender(func) {
    this.onAfterRenderObservable.add(func);
    return this;
  }
  unregisterAfterRender(func) {
    this.onAfterRenderObservable.removeCallback(func);
    return this;
  }
  _getInstancesRenderList(subMeshId, isReplacementMode = false) {
    if (this._instanceDataStorage.isFrozen) {
      if (isReplacementMode) {
        this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[subMeshId] = false;
        this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[subMeshId] = true;
        return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;
      }
      if (this._instanceDataStorage.previousBatch) {
        return this._instanceDataStorage.previousBatch;
      }
    }
    const scene = this.getScene();
    const isInIntermediateRendering = scene._isInIntermediateRendering();
    const onlyForInstances = isInIntermediateRendering ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate : this._internalAbstractMeshDataInfo._onlyForInstances;
    const batchCache = this._instanceDataStorage.batchCache;
    batchCache.mustReturn = false;
    batchCache.renderSelf[subMeshId] = isReplacementMode || !onlyForInstances && this.isEnabled() && this.isVisible;
    batchCache.visibleInstances[subMeshId] = null;
    if (this._instanceDataStorage.visibleInstances && !isReplacementMode) {
      const visibleInstances = this._instanceDataStorage.visibleInstances;
      const currentRenderId = scene.getRenderId();
      const defaultRenderId = isInIntermediateRendering ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId;
      batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
      if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
        batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
      }
    }
    batchCache.hardwareInstancedRendering[subMeshId] = !isReplacementMode && this._instanceDataStorage.hardwareInstancedRendering && batchCache.visibleInstances[subMeshId] !== null && batchCache.visibleInstances[subMeshId] !== undefined;
    this._instanceDataStorage.previousBatch = batchCache;
    return batchCache;
  }
  _updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect) {
    const visibleInstances = batch.visibleInstances[subMesh._id];
    const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0;
    const instanceStorage = this._instanceDataStorage;
    let instancesBuffer = instanceStorage.instancesBuffer;
    let instancesPreviousBuffer = instanceStorage.instancesPreviousBuffer;
    let offset = 0;
    let instancesCount = 0;
    const renderSelf = batch.renderSelf[subMesh._id];
    const needUpdateBuffer = !instancesBuffer || currentInstancesBufferSize !== instanceStorage.instancesBufferSize || this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousBuffer;
    if (!this._instanceDataStorage.manualUpdate && (!instanceStorage.isFrozen || needUpdateBuffer)) {
      const world = this.getWorldMatrix();
      if (renderSelf) {
        if (this._scene.needsPreviousWorldMatrices) {
          if (!instanceStorage.masterMeshPreviousWorldMatrix) {
            instanceStorage.masterMeshPreviousWorldMatrix = world.clone();
            instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
          } else {
            instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
            instanceStorage.masterMeshPreviousWorldMatrix.copyFrom(world);
          }
        }
        world.copyToArray(instanceStorage.instancesData, offset);
        offset += 16;
        instancesCount++;
      }
      if (visibleInstances) {
        if (Mesh.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && subMesh.getMaterial()?.needAlphaBlendingForMesh(subMesh.getRenderingMesh())) {
          const cameraPosition = this._scene.activeCamera.globalPosition;
          for (let instanceIndex = 0;instanceIndex < visibleInstances.length; instanceIndex++) {
            const instanceMesh = visibleInstances[instanceIndex];
            instanceMesh._distanceToCamera = Vector3.Distance(instanceMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition);
          }
          visibleInstances.sort((m1, m2) => {
            return m1._distanceToCamera > m2._distanceToCamera ? -1 : m1._distanceToCamera < m2._distanceToCamera ? 1 : 0;
          });
        }
        for (let instanceIndex = 0;instanceIndex < visibleInstances.length; instanceIndex++) {
          const instance = visibleInstances[instanceIndex];
          const matrix = instance.getWorldMatrix();
          matrix.copyToArray(instanceStorage.instancesData, offset);
          if (this._scene.needsPreviousWorldMatrices) {
            if (!instance._previousWorldMatrix) {
              instance._previousWorldMatrix = matrix.clone();
              instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
            } else {
              instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset);
              instance._previousWorldMatrix.copyFrom(matrix);
            }
          }
          offset += 16;
          instancesCount++;
        }
      }
    } else {
      instancesCount = (renderSelf ? 1 : 0) + visibleInstanceCount;
    }
    if (needUpdateBuffer) {
      if (instancesBuffer) {
        instancesBuffer.dispose();
      }
      if (instancesPreviousBuffer) {
        instancesPreviousBuffer.dispose();
      }
      instancesBuffer = new Buffer2(engine, instanceStorage.instancesData, true, 16, false, true);
      instanceStorage.instancesBuffer = instancesBuffer;
      if (!this._userInstancedBuffersStorage) {
        this._userInstancedBuffersStorage = {
          data: {},
          vertexBuffers: {},
          strides: {},
          sizes: {},
          vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined
        };
      }
      this._userInstancedBuffersStorage.vertexBuffers["world0"] = instancesBuffer.createVertexBuffer("world0", 0, 4);
      this._userInstancedBuffersStorage.vertexBuffers["world1"] = instancesBuffer.createVertexBuffer("world1", 4, 4);
      this._userInstancedBuffersStorage.vertexBuffers["world2"] = instancesBuffer.createVertexBuffer("world2", 8, 4);
      this._userInstancedBuffersStorage.vertexBuffers["world3"] = instancesBuffer.createVertexBuffer("world3", 12, 4);
      if (this._scene.needsPreviousWorldMatrices) {
        instancesPreviousBuffer = new Buffer2(engine, instanceStorage.instancesPreviousData, true, 16, false, true);
        instanceStorage.instancesPreviousBuffer = instancesPreviousBuffer;
        this._userInstancedBuffersStorage.vertexBuffers["previousWorld0"] = instancesPreviousBuffer.createVertexBuffer("previousWorld0", 0, 4);
        this._userInstancedBuffersStorage.vertexBuffers["previousWorld1"] = instancesPreviousBuffer.createVertexBuffer("previousWorld1", 4, 4);
        this._userInstancedBuffersStorage.vertexBuffers["previousWorld2"] = instancesPreviousBuffer.createVertexBuffer("previousWorld2", 8, 4);
        this._userInstancedBuffersStorage.vertexBuffers["previousWorld3"] = instancesPreviousBuffer.createVertexBuffer("previousWorld3", 12, 4);
      }
      this._invalidateInstanceVertexArrayObject();
    } else {
      if (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) {
        instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
        if (this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate)) {
          instancesPreviousBuffer.updateDirectly(instanceStorage.instancesPreviousData, 0, instancesCount);
        }
      }
    }
    this._processInstancedBuffers(visibleInstances, renderSelf);
    if (effect && fillMode !== undefined) {
      this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false);
      if (engine._currentDrawContext) {
        engine._currentDrawContext.useInstancing = true;
      }
      this._bind(subMesh, effect, fillMode);
      this._draw(subMesh, fillMode, instancesCount);
    }
    if (this._scene.needsPreviousWorldMatrices && !needUpdateBuffer && this._instanceDataStorage.manualUpdate && (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && !this._instanceDataStorage.previousManualUpdate) {
      instancesPreviousBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
    }
  }
  _renderWithInstances(subMesh, fillMode, batch, effect, engine) {
    const visibleInstances = batch.visibleInstances[subMesh._id];
    const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0;
    const instanceStorage = this._instanceDataStorage;
    const currentInstancesBufferSize = instanceStorage.instancesBufferSize;
    const matricesCount = visibleInstanceCount + 1;
    const bufferSize = matricesCount * 16 * 4;
    while (instanceStorage.instancesBufferSize < bufferSize) {
      instanceStorage.instancesBufferSize *= 2;
    }
    if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
      instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
    }
    if (this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
      instanceStorage.instancesPreviousData = new Float32Array(instanceStorage.instancesBufferSize / 4);
    }
    this._updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect);
    engine.unbindInstanceAttributes();
    return this;
  }
  _renderWithThinInstances(subMesh, fillMode, effect, engine) {
    const instancesCount = this._thinInstanceDataStorage?.instancesCount ?? 0;
    this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false);
    if (engine._currentDrawContext) {
      engine._currentDrawContext.useInstancing = true;
    }
    this._bind(subMesh, effect, fillMode);
    this._draw(subMesh, fillMode, instancesCount);
    if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData) {
      if (!this._thinInstanceDataStorage.previousMatrixBuffer) {
        this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, false);
      } else {
        this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, instancesCount);
      }
    }
    engine.unbindInstanceAttributes();
  }
  _processInstancedBuffers(visibleInstances, renderSelf) {}
  _processRendering(renderingMesh, subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
    const scene = this.getScene();
    const engine = scene.getEngine();
    fillMode = this._getRenderingFillMode(fillMode);
    if (hardwareInstancedRendering && subMesh.getRenderingMesh().hasThinInstances) {
      this._renderWithThinInstances(subMesh, fillMode, effect, engine);
      return this;
    }
    if (hardwareInstancedRendering) {
      this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
    } else {
      if (engine._currentDrawContext) {
        engine._currentDrawContext.useInstancing = false;
      }
      let instanceCount = 0;
      if (batch.renderSelf[subMesh._id]) {
        if (onBeforeDraw) {
          onBeforeDraw(false, renderingMesh.getWorldMatrix(), effectiveMaterial);
        }
        instanceCount++;
        this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
      }
      const visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
      if (visibleInstancesForSubMesh) {
        const visibleInstanceCount = visibleInstancesForSubMesh.length;
        instanceCount += visibleInstanceCount;
        for (let instanceIndex = 0;instanceIndex < visibleInstanceCount; instanceIndex++) {
          const instance = visibleInstancesForSubMesh[instanceIndex];
          const world = instance.getWorldMatrix();
          if (onBeforeDraw) {
            onBeforeDraw(true, world, effectiveMaterial);
          }
          this._draw(subMesh, fillMode);
        }
      }
      scene._activeIndices.addCount(subMesh.indexCount * instanceCount, false);
    }
    return this;
  }
  _rebuild(dispose = false) {
    if (this._instanceDataStorage.instancesBuffer) {
      if (dispose) {
        this._instanceDataStorage.instancesBuffer.dispose();
      }
      this._instanceDataStorage.instancesBuffer = null;
    }
    if (this._userInstancedBuffersStorage) {
      for (const kind in this._userInstancedBuffersStorage.vertexBuffers) {
        const buffer = this._userInstancedBuffersStorage.vertexBuffers[kind];
        if (buffer) {
          if (dispose) {
            buffer.dispose();
          }
          this._userInstancedBuffersStorage.vertexBuffers[kind] = null;
        }
      }
      if (this._userInstancedBuffersStorage.vertexArrayObjects) {
        this._userInstancedBuffersStorage.vertexArrayObjects = {};
      }
    }
    this._internalMeshDataInfo._effectiveMaterial = null;
    super._rebuild(dispose);
  }
  _freeze() {
    if (!this.subMeshes) {
      return;
    }
    for (let index = 0;index < this.subMeshes.length; index++) {
      this._getInstancesRenderList(index);
    }
    this._internalMeshDataInfo._effectiveMaterial = null;
    this._instanceDataStorage.isFrozen = true;
  }
  _unFreeze() {
    this._instanceDataStorage.isFrozen = false;
    this._instanceDataStorage.previousBatch = null;
  }
  renderWithRenderPassId(renderPassId, enableAlphaMode, effectiveMeshReplacement, subMesh, checkFrustumCulling = true) {
    const engine = this._scene.getEngine();
    const currentRenderPassId = engine.currentRenderPassId;
    if (renderPassId !== undefined) {
      engine.currentRenderPassId = renderPassId;
    }
    if (subMesh) {
      if (!checkFrustumCulling || checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes)) {
        this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement);
      }
    } else {
      for (let s = 0;s < this.subMeshes.length; s++) {
        const subMesh2 = this.subMeshes[s];
        if (!checkFrustumCulling || checkFrustumCulling && subMesh2.isInFrustum(this._scene._frustumPlanes)) {
          this.render(subMesh2, !!enableAlphaMode, effectiveMeshReplacement);
        }
      }
    }
    if (renderPassId !== undefined) {
      engine.currentRenderPassId = currentRenderPassId;
    }
    return this;
  }
  directRender() {
    if (!this.subMeshes) {
      return this;
    }
    for (const submesh of this.subMeshes) {
      this.render(submesh, false);
    }
    return this;
  }
  render(subMesh, enableAlphaMode, effectiveMeshReplacement) {
    const scene = this.getScene();
    if (this._internalAbstractMeshDataInfo._isActiveIntermediate) {
      this._internalAbstractMeshDataInfo._isActiveIntermediate = false;
    } else {
      this._internalAbstractMeshDataInfo._isActive = false;
    }
    const numActiveCameras = scene.activeCameras?.length ?? 0;
    const canCheckOcclusionQuery = numActiveCameras > 1 && scene.activeCamera === scene.activeCameras[0] || numActiveCameras <= 1;
    if (canCheckOcclusionQuery && this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded) {
      return this;
    }
    const batch = this._getInstancesRenderList(subMesh._id, !!effectiveMeshReplacement);
    if (batch.mustReturn) {
      return this;
    }
    if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
      return this;
    }
    const engine = scene.getEngine();
    let oldCameraMaxZ = 0;
    let oldCamera = null;
    if (this.ignoreCameraMaxZ && scene.activeCamera && !scene._isInIntermediateRendering()) {
      oldCameraMaxZ = scene.activeCamera.maxZ;
      oldCamera = scene.activeCamera;
      scene.activeCamera.maxZ = 0;
      scene.updateTransformMatrix(true);
    }
    if (this._internalMeshDataInfo._onBeforeRenderObservable) {
      this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);
    }
    const renderingMesh = subMesh.getRenderingMesh();
    const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances || !!this._userInstancedBuffersStorage && !subMesh.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh;
    const instanceDataStorage = this._instanceDataStorage;
    const material = subMesh.getMaterial();
    if (!material) {
      if (oldCamera) {
        oldCamera.maxZ = oldCameraMaxZ;
        scene.updateTransformMatrix(true);
      }
      return this;
    }
    if (!instanceDataStorage.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== material) {
      if (material._storeEffectOnSubMeshes) {
        if (!material.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
          if (oldCamera) {
            oldCamera.maxZ = oldCameraMaxZ;
            scene.updateTransformMatrix(true);
          }
          return this;
        }
      } else if (!material.isReady(this, hardwareInstancedRendering)) {
        if (oldCamera) {
          oldCamera.maxZ = oldCameraMaxZ;
          scene.updateTransformMatrix(true);
        }
        return this;
      }
      this._internalMeshDataInfo._effectiveMaterial = material;
    } else if (material._storeEffectOnSubMeshes && !subMesh._drawWrapper?._wasPreviouslyReady || !material._storeEffectOnSubMeshes && !material._getDrawWrapper()._wasPreviouslyReady) {
      if (oldCamera) {
        oldCamera.maxZ = oldCameraMaxZ;
        scene.updateTransformMatrix(true);
      }
      return this;
    }
    if (enableAlphaMode) {
      engine.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);
    }
    let drawWrapper;
    if (this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes) {
      drawWrapper = subMesh._drawWrapper;
    } else {
      drawWrapper = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();
    }
    const effect = drawWrapper?.effect ?? null;
    for (const step of scene._beforeRenderingMeshStage) {
      step.action(this, subMesh, batch, effect);
    }
    if (!drawWrapper || !effect) {
      if (oldCamera) {
        oldCamera.maxZ = oldCameraMaxZ;
        scene.updateTransformMatrix(true);
      }
      return this;
    }
    const effectiveMesh = effectiveMeshReplacement || this;
    let sideOrientation;
    if (!instanceDataStorage.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this._internalMeshDataInfo._effectiveMaterial.sideOrientation !== null || this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)) {
      const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();
      sideOrientation = this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this);
      if (mainDeterminant < 0) {
        sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
      }
      instanceDataStorage.sideOrientation = sideOrientation;
    } else {
      sideOrientation = instanceDataStorage.sideOrientation;
    }
    const reverse = this._internalMeshDataInfo._effectiveMaterial._preBind(drawWrapper, sideOrientation);
    if (this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite) {
      engine.setDepthWrite(true);
    }
    const effectiveMaterial = this._internalMeshDataInfo._effectiveMaterial;
    const fillMode = effectiveMaterial.fillMode;
    if (this._internalMeshDataInfo._onBeforeBindObservable) {
      this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this);
    }
    if (!hardwareInstancedRendering) {
      this._bind(subMesh, effect, fillMode, false);
    }
    const world = effectiveMesh.getWorldMatrix();
    if (effectiveMaterial._storeEffectOnSubMeshes) {
      effectiveMaterial.bindForSubMesh(world, this, subMesh);
    } else {
      effectiveMaterial.bind(world, this);
    }
    if (!effectiveMaterial.backFaceCulling && effectiveMaterial.separateCullingPass) {
      engine.setState(true, effectiveMaterial.zOffset, false, !reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits);
      this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial);
      engine.setState(true, effectiveMaterial.zOffset, false, reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits);
      if (this._internalMeshDataInfo._onBetweenPassObservable) {
        this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(subMesh);
      }
    }
    this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial);
    this._internalMeshDataInfo._effectiveMaterial.unbind();
    for (const step of scene._afterRenderingMeshStage) {
      step.action(this, subMesh, batch, effect);
    }
    if (this._internalMeshDataInfo._onAfterRenderObservable) {
      this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this);
    }
    if (oldCamera) {
      oldCamera.maxZ = oldCameraMaxZ;
      scene.updateTransformMatrix(true);
    }
    if (scene.performancePriority === 2 && !instanceDataStorage.isFrozen) {
      this._freeze();
    }
    return this;
  }
  cleanMatrixWeights() {
    if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
      if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
        this._normalizeSkinWeightsAndExtra();
      } else {
        this._normalizeSkinFourWeights();
      }
    }
  }
  _normalizeSkinFourWeights() {
    const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
    const numWeights = matricesWeights.length;
    for (let a = 0;a < numWeights; a += 4) {
      const t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
      if (t === 0) {
        matricesWeights[a] = 1;
      } else {
        const recip = 1 / t;
        matricesWeights[a] *= recip;
        matricesWeights[a + 1] *= recip;
        matricesWeights[a + 2] *= recip;
        matricesWeights[a + 3] *= recip;
      }
    }
    this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
  }
  _normalizeSkinWeightsAndExtra() {
    const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind);
    const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
    const numWeights = matricesWeights.length;
    for (let a = 0;a < numWeights; a += 4) {
      let t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
      t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
      if (t === 0) {
        matricesWeights[a] = 1;
      } else {
        const recip = 1 / t;
        matricesWeights[a] *= recip;
        matricesWeights[a + 1] *= recip;
        matricesWeights[a + 2] *= recip;
        matricesWeights[a + 3] *= recip;
        matricesWeightsExtra[a] *= recip;
        matricesWeightsExtra[a + 1] *= recip;
        matricesWeightsExtra[a + 2] *= recip;
        matricesWeightsExtra[a + 3] *= recip;
      }
    }
    this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
    this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  }
  validateSkinning() {
    const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind);
    const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
    if (matricesWeights === null || this.skeleton == null) {
      return { skinned: false, valid: true, report: "not skinned" };
    }
    const numWeights = matricesWeights.length;
    let numberNotSorted = 0;
    let missingWeights = 0;
    let maxUsedWeights = 0;
    let numberNotNormalized = 0;
    const numInfluences = matricesWeightsExtra === null ? 4 : 8;
    const usedWeightCounts = [];
    for (let a = 0;a <= numInfluences; a++) {
      usedWeightCounts[a] = 0;
    }
    const toleranceEpsilon = 0.001;
    for (let a = 0;a < numWeights; a += 4) {
      let lastWeight = matricesWeights[a];
      let t = lastWeight;
      let usedWeights = t === 0 ? 0 : 1;
      for (let b = 1;b < numInfluences; b++) {
        const d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
        if (d > lastWeight) {
          numberNotSorted++;
        }
        if (d !== 0) {
          usedWeights++;
        }
        t += d;
        lastWeight = d;
      }
      usedWeightCounts[usedWeights]++;
      if (usedWeights > maxUsedWeights) {
        maxUsedWeights = usedWeights;
      }
      if (t === 0) {
        missingWeights++;
      } else {
        const recip = 1 / t;
        let tolerance = 0;
        for (let b = 0;b < numInfluences; b++) {
          if (b < 4) {
            tolerance += Math.abs(matricesWeights[a + b] - matricesWeights[a + b] * recip);
          } else {
            tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - matricesWeightsExtra[a + b - 4] * recip);
          }
        }
        if (tolerance > toleranceEpsilon) {
          numberNotNormalized++;
        }
      }
    }
    const numBones = this.skeleton.bones.length;
    const matricesIndices = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
    const matricesIndicesExtra = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);
    let numBadBoneIndices = 0;
    for (let a = 0;a < numWeights; a += 4) {
      for (let b = 0;b < numInfluences; b++) {
        const index = b < 4 ? matricesIndices[a + b] : matricesIndicesExtra[a + b - 4];
        if (index >= numBones || index < 0) {
          numBadBoneIndices++;
        }
      }
    }
    const output = "Number of Weights = " + numWeights / 4 + `
Maximum influences = ` + maxUsedWeights + `
Missing Weights = ` + missingWeights + `
Not Sorted = ` + numberNotSorted + `
Not Normalized = ` + numberNotNormalized + `
WeightCounts = [` + usedWeightCounts + "]" + `
Number of bones = ` + numBones + `
Bad Bone Indices = ` + numBadBoneIndices;
    return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  }
  _checkDelayState() {
    const scene = this.getScene();
    if (this._geometry) {
      this._geometry.load(scene);
    } else if (this.delayLoadState === 4) {
      this.delayLoadState = 2;
      this._queueLoad(scene);
    }
    return this;
  }
  _queueLoad(scene) {
    scene.addPendingData(this);
    const getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
    Tools.LoadFile(this.delayLoadingFile, (data) => {
      if (data instanceof ArrayBuffer) {
        this._delayLoadingFunction(data, this);
      } else {
        this._delayLoadingFunction(JSON.parse(data), this);
      }
      this.instances.forEach((instance) => {
        instance.refreshBoundingInfo();
        instance._syncSubMeshes();
      });
      this.delayLoadState = 1;
      scene.removePendingData(this);
    }, () => {}, scene.offlineProvider, getBinaryData);
    return this;
  }
  isInFrustum(frustumPlanes) {
    if (this.delayLoadState === 2) {
      return false;
    }
    if (!super.isInFrustum(frustumPlanes)) {
      return false;
    }
    this._checkDelayState();
    return true;
  }
  setMaterialById(id) {
    const materials = this.getScene().materials;
    let index;
    for (index = materials.length - 1;index > -1; index--) {
      if (materials[index].id === id) {
        this.material = materials[index];
        return this;
      }
    }
    const multiMaterials = this.getScene().multiMaterials;
    for (index = multiMaterials.length - 1;index > -1; index--) {
      if (multiMaterials[index].id === id) {
        this.material = multiMaterials[index];
        return this;
      }
    }
    return this;
  }
  getAnimatables() {
    const results = [];
    if (this.material) {
      results.push(this.material);
    }
    if (this.skeleton) {
      results.push(this.skeleton);
    }
    return results;
  }
  bakeTransformIntoVertices(transform) {
    if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
      return this;
    }
    const submeshes = this.subMeshes.splice(0);
    this._resetPointsArrayCache();
    let data = this.getVerticesData(VertexBuffer.PositionKind);
    const temp = Vector3.Zero();
    let index;
    for (index = 0;index < data.length; index += 3) {
      Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).toArray(data, index);
    }
    this.setVerticesData(VertexBuffer.PositionKind, data, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
    if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      data = this.getVerticesData(VertexBuffer.NormalKind);
      for (index = 0;index < data.length; index += 3) {
        Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).normalize().toArray(data, index);
      }
      this.setVerticesData(VertexBuffer.NormalKind, data, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
    }
    if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
      data = this.getVerticesData(VertexBuffer.TangentKind);
      for (index = 0;index < data.length; index += 4) {
        Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).normalize().toArray(data, index);
      }
      this.setVerticesData(VertexBuffer.TangentKind, data, this.getVertexBuffer(VertexBuffer.TangentKind).isUpdatable());
    }
    if (transform.determinant() < 0) {
      this.flipFaces();
    }
    this.releaseSubMeshes();
    this.subMeshes = submeshes;
    return this;
  }
  bakeCurrentTransformIntoVertices(bakeIndependentlyOfChildren = true, forceUnique = false) {
    if (forceUnique) {
      this.makeGeometryUnique();
    }
    this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
    this.resetLocalMatrix(bakeIndependentlyOfChildren);
    return this;
  }
  get _positions() {
    return this._internalAbstractMeshDataInfo._positions || this._geometry && this._geometry._positions || null;
  }
  _resetPointsArrayCache() {
    if (this._geometry) {
      this._geometry._resetPointsArrayCache();
    }
    return this;
  }
  _generatePointsArray() {
    if (this._geometry) {
      return this._geometry._generatePointsArray();
    }
    return false;
  }
  clone(name18 = "", newParent = null, doNotCloneChildren, clonePhysicsImpostor = true) {
    if (newParent && newParent._addToSceneRootNodes === undefined) {
      const cloneOptions = newParent;
      meshCreationOptions.source = this;
      meshCreationOptions.doNotCloneChildren = cloneOptions.doNotCloneChildren;
      meshCreationOptions.clonePhysicsImpostor = cloneOptions.clonePhysicsImpostor;
      meshCreationOptions.cloneThinInstances = cloneOptions.cloneThinInstances;
      return new Mesh(name18, this.getScene(), meshCreationOptions);
    }
    return new Mesh(name18, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this.morphTargetManager = null;
    if (this._geometry) {
      this._geometry.releaseForMesh(this, true);
    }
    const internalDataInfo = this._internalMeshDataInfo;
    if (internalDataInfo._onBeforeDrawObservable) {
      internalDataInfo._onBeforeDrawObservable.clear();
    }
    if (internalDataInfo._onBeforeBindObservable) {
      internalDataInfo._onBeforeBindObservable.clear();
    }
    if (internalDataInfo._onBeforeRenderObservable) {
      internalDataInfo._onBeforeRenderObservable.clear();
    }
    if (internalDataInfo._onAfterRenderObservable) {
      internalDataInfo._onAfterRenderObservable.clear();
    }
    if (internalDataInfo._onBetweenPassObservable) {
      internalDataInfo._onBetweenPassObservable.clear();
    }
    if (this._scene.useClonedMeshMap) {
      if (internalDataInfo.meshMap) {
        for (const uniqueId in internalDataInfo.meshMap) {
          const mesh = internalDataInfo.meshMap[uniqueId];
          if (mesh) {
            mesh._internalMeshDataInfo._source = null;
            internalDataInfo.meshMap[uniqueId] = undefined;
          }
        }
      }
      if (internalDataInfo._source && internalDataInfo._source._internalMeshDataInfo.meshMap) {
        internalDataInfo._source._internalMeshDataInfo.meshMap[this.uniqueId] = undefined;
      }
    } else {
      const meshes = this.getScene().meshes;
      for (const abstractMesh of meshes) {
        const mesh = abstractMesh;
        if (mesh._internalMeshDataInfo && mesh._internalMeshDataInfo._source && mesh._internalMeshDataInfo._source === this) {
          mesh._internalMeshDataInfo._source = null;
        }
      }
    }
    internalDataInfo._source = null;
    this._instanceDataStorage.visibleInstances = {};
    this._disposeInstanceSpecificData();
    this._disposeThinInstanceSpecificData();
    if (this._internalMeshDataInfo._checkReadinessObserver) {
      this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver);
    }
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  _disposeInstanceSpecificData() {}
  _disposeThinInstanceSpecificData() {}
  _invalidateInstanceVertexArrayObject() {}
  applyDisplacementMap(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate = false, onError) {
    const scene = this.getScene();
    const onload = (img) => {
      const heightMapWidth = img.width;
      const heightMapHeight = img.height;
      const canvas = this.getEngine().createCanvas(heightMapWidth, heightMapHeight);
      const context = canvas.getContext("2d");
      context.drawImage(img, 0, 0);
      const buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
      this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
      if (onSuccess) {
        onSuccess(this);
      }
    };
    Tools.LoadImage(url, onload, onError ? onError : () => {}, scene.offlineProvider);
    return this;
  }
  applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate = false) {
    if (!this.isVerticesDataPresent(VertexBuffer.PositionKind) || !this.isVerticesDataPresent(VertexBuffer.NormalKind) || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
      Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
      return this;
    }
    const positions = this.getVerticesData(VertexBuffer.PositionKind, true, true);
    const normals = this.getVerticesData(VertexBuffer.NormalKind);
    const uvs = this.getVerticesData(VertexBuffer.UVKind);
    let position = Vector3.Zero();
    const normal = Vector3.Zero();
    const uv = Vector2.Zero();
    uvOffset = uvOffset || Vector2.Zero();
    uvScale = uvScale || new Vector2(1, 1);
    for (let index = 0;index < positions.length; index += 3) {
      Vector3.FromArrayToRef(positions, index, position);
      Vector3.FromArrayToRef(normals, index, normal);
      Vector2.FromArrayToRef(uvs, index / 3 * 2, uv);
      const u = Math.abs(uv.x * uvScale.x + uvOffset.x % 1) * (heightMapWidth - 1) % heightMapWidth | 0;
      const v = Math.abs(uv.y * uvScale.y + uvOffset.y % 1) * (heightMapHeight - 1) % heightMapHeight | 0;
      const pos = (u + v * heightMapWidth) * 4;
      const r = buffer[pos] / 255;
      const g = buffer[pos + 1] / 255;
      const b = buffer[pos + 2] / 255;
      const gradient = r * 0.3 + g * 0.59 + b * 0.11;
      normal.normalize();
      normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
      position = position.add(normal);
      position.toArray(positions, index);
    }
    VertexData.ComputeNormals(positions, this.getIndices(), normals);
    if (forceUpdate) {
      this.setVerticesData(VertexBuffer.PositionKind, positions);
      this.setVerticesData(VertexBuffer.NormalKind, normals);
      this.setVerticesData(VertexBuffer.UVKind, uvs);
    } else {
      this.updateVerticesData(VertexBuffer.PositionKind, positions);
      this.updateVerticesData(VertexBuffer.NormalKind, normals);
    }
    return this;
  }
  _getFlattenedNormals(indices, positions) {
    const normals = new Float32Array(indices.length * 3);
    let normalsCount = 0;
    const flipNormalGeneration = this.sideOrientation === (this._scene.useRightHandedSystem ? 1 : 0);
    for (let index = 0;index < indices.length; index += 3) {
      const p1 = Vector3.FromArray(positions, indices[index] * 3);
      const p2 = Vector3.FromArray(positions, indices[index + 1] * 3);
      const p3 = Vector3.FromArray(positions, indices[index + 2] * 3);
      const p1p2 = p1.subtract(p2);
      const p3p2 = p3.subtract(p2);
      const normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
      if (flipNormalGeneration) {
        normal.scaleInPlace(-1);
      }
      for (let localIndex = 0;localIndex < 3; localIndex++) {
        normals[normalsCount++] = normal.x;
        normals[normalsCount++] = normal.y;
        normals[normalsCount++] = normal.z;
      }
    }
    return normals;
  }
  _convertToUnIndexedMesh(flattenNormals = false) {
    const kinds = this.getVerticesDataKinds().filter((kind) => !this.getVertexBuffer(kind)?.getIsInstanced());
    const indices = this.getIndices();
    const data = {};
    const separateVertices = (data2, size) => {
      const newData = new Float32Array(indices.length * size);
      let count = 0;
      for (let index = 0;index < indices.length; index++) {
        for (let offset = 0;offset < size; offset++) {
          newData[count++] = data2[indices[index] * size + offset];
        }
      }
      return newData;
    };
    const meshBoundingInfo = this.getBoundingInfo();
    const previousSubmeshes = this.geometry ? this.subMeshes.slice(0) : [];
    for (const kind of kinds) {
      data[kind] = this.getVerticesData(kind);
    }
    for (const kind of kinds) {
      const vertexBuffer = this.getVertexBuffer(kind);
      const size = vertexBuffer.getSize();
      if (flattenNormals && kind === VertexBuffer.NormalKind) {
        const normals = this._getFlattenedNormals(indices, data[VertexBuffer.PositionKind]);
        this.setVerticesData(VertexBuffer.NormalKind, normals, vertexBuffer.isUpdatable(), size);
      } else {
        this.setVerticesData(kind, separateVertices(data[kind], size), vertexBuffer.isUpdatable(), size);
      }
    }
    if (this.morphTargetManager) {
      for (let targetIndex = 0;targetIndex < this.morphTargetManager.numTargets; targetIndex++) {
        const target = this.morphTargetManager.getTarget(targetIndex);
        const positions = target.getPositions();
        target.setPositions(separateVertices(positions, 3));
        const normals = target.getNormals();
        if (normals) {
          target.setNormals(flattenNormals ? this._getFlattenedNormals(indices, positions) : separateVertices(normals, 3));
        }
        const tangents = target.getTangents();
        if (tangents) {
          target.setTangents(separateVertices(tangents, 3));
        }
        const uvs = target.getUVs();
        if (uvs) {
          target.setUVs(separateVertices(uvs, 2));
        }
        const colors = target.getColors();
        if (colors) {
          target.setColors(separateVertices(colors, 4));
        }
      }
      this.morphTargetManager.synchronize();
    }
    for (let index = 0;index < indices.length; index++) {
      indices[index] = index;
    }
    this.setIndices(indices);
    this._unIndexed = true;
    this.releaseSubMeshes();
    for (const previousOne of previousSubmeshes) {
      const boundingInfo = previousOne.getBoundingInfo();
      const subMesh = SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
      subMesh.setBoundingInfo(boundingInfo);
    }
    this.setBoundingInfo(meshBoundingInfo);
    this.synchronizeInstances();
    return this;
  }
  convertToFlatShadedMesh() {
    return this._convertToUnIndexedMesh(true);
  }
  convertToUnIndexedMesh() {
    return this._convertToUnIndexedMesh();
  }
  flipFaces(flipNormals = false) {
    const vertex_data = VertexData.ExtractFromMesh(this);
    let i;
    if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
      for (i = 0;i < vertex_data.normals.length; i++) {
        vertex_data.normals[i] *= -1;
      }
      this.setVerticesData(VertexBuffer.NormalKind, vertex_data.normals, this.isVertexBufferUpdatable(VertexBuffer.NormalKind));
    }
    if (vertex_data.indices) {
      let temp;
      for (i = 0;i < vertex_data.indices.length; i += 3) {
        temp = vertex_data.indices[i + 1];
        vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
        vertex_data.indices[i + 2] = temp;
      }
      this.setIndices(vertex_data.indices, null, this.isVertexBufferUpdatable(VertexBuffer.PositionKind), true);
    }
    return this;
  }
  increaseVertices(numberPerEdge = 1) {
    const vertex_data = VertexData.ExtractFromMesh(this);
    const currentIndices = vertex_data.indices && !Array.isArray(vertex_data.indices) && Array.from ? Array.from(vertex_data.indices) : vertex_data.indices;
    const positions = vertex_data.positions && !Array.isArray(vertex_data.positions) && Array.from ? Array.from(vertex_data.positions) : vertex_data.positions;
    const uvs = vertex_data.uvs && !Array.isArray(vertex_data.uvs) && Array.from ? Array.from(vertex_data.uvs) : vertex_data.uvs;
    const normals = vertex_data.normals && !Array.isArray(vertex_data.normals) && Array.from ? Array.from(vertex_data.normals) : vertex_data.normals;
    if (!currentIndices || !positions) {
      Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions");
    } else {
      vertex_data.indices = currentIndices;
      vertex_data.positions = positions;
      if (uvs) {
        vertex_data.uvs = uvs;
      }
      if (normals) {
        vertex_data.normals = normals;
      }
      const segments = numberPerEdge + 1;
      const tempIndices = new Array;
      for (let i = 0;i < segments + 1; i++) {
        tempIndices[i] = new Array;
      }
      let a;
      let b;
      const deltaPosition = new Vector3(0, 0, 0);
      const deltaNormal = new Vector3(0, 0, 0);
      const deltaUV = new Vector2(0, 0);
      const indices = new Array;
      const vertexIndex = new Array;
      const side = new Array;
      let len;
      let positionPtr = positions.length;
      let uvPtr;
      if (uvs) {
        uvPtr = uvs.length;
      }
      let normalsPtr;
      if (normals) {
        normalsPtr = normals.length;
      }
      for (let i = 0;i < currentIndices.length; i += 3) {
        vertexIndex[0] = currentIndices[i];
        vertexIndex[1] = currentIndices[i + 1];
        vertexIndex[2] = currentIndices[i + 2];
        for (let j = 0;j < 3; j++) {
          a = vertexIndex[j];
          b = vertexIndex[(j + 1) % 3];
          if (side[a] === undefined && side[b] === undefined) {
            side[a] = new Array;
            side[b] = new Array;
          } else {
            if (side[a] === undefined) {
              side[a] = new Array;
            }
            if (side[b] === undefined) {
              side[b] = new Array;
            }
          }
          if (side[a][b] === undefined && side[b][a] === undefined) {
            side[a][b] = [];
            deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments;
            deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments;
            deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments;
            if (normals) {
              deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments;
              deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments;
              deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments;
            }
            if (uvs) {
              deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments;
              deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments;
            }
            side[a][b].push(a);
            for (let k = 1;k < segments; k++) {
              side[a][b].push(positions.length / 3);
              positions[positionPtr++] = positions[3 * a] + k * deltaPosition.x;
              positions[positionPtr++] = positions[3 * a + 1] + k * deltaPosition.y;
              positions[positionPtr++] = positions[3 * a + 2] + k * deltaPosition.z;
              if (normals) {
                normals[normalsPtr++] = normals[3 * a] + k * deltaNormal.x;
                normals[normalsPtr++] = normals[3 * a + 1] + k * deltaNormal.y;
                normals[normalsPtr++] = normals[3 * a + 2] + k * deltaNormal.z;
              }
              if (uvs) {
                uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x;
                uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y;
              }
            }
            side[a][b].push(b);
            side[b][a] = new Array;
            len = side[a][b].length;
            for (let idx = 0;idx < len; idx++) {
              side[b][a][idx] = side[a][b][len - 1 - idx];
            }
          }
        }
        tempIndices[0][0] = currentIndices[i];
        tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1];
        tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1];
        for (let k = 2;k < segments; k++) {
          tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k];
          tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k];
          deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k;
          deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k;
          deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k;
          if (normals) {
            deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k;
            deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k;
            deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k;
          }
          if (uvs) {
            deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k;
            deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k;
          }
          for (let j = 1;j < k; j++) {
            tempIndices[k][j] = positions.length / 3;
            positions[positionPtr++] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x;
            positions[positionPtr++] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y;
            positions[positionPtr++] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z;
            if (normals) {
              normals[normalsPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x;
              normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y;
              normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z;
            }
            if (uvs) {
              uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x;
              uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y;
            }
          }
        }
        tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]];
        indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]);
        for (let k = 1;k < segments; k++) {
          let j;
          for (j = 0;j < k; j++) {
            indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
            indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]);
          }
          indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
        }
      }
      vertex_data.indices = indices;
      vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind));
    }
  }
  forceSharedVertices() {
    const vertex_data = VertexData.ExtractFromMesh(this);
    const currentUVs = vertex_data.uvs;
    const currentIndices = vertex_data.indices;
    const currentPositions = vertex_data.positions;
    const currentColors = vertex_data.colors;
    const currentMatrixIndices = vertex_data.matricesIndices;
    const currentMatrixWeights = vertex_data.matricesWeights;
    const currentMatrixIndicesExtra = vertex_data.matricesIndicesExtra;
    const currentMatrixWeightsExtra = vertex_data.matricesWeightsExtra;
    if (currentIndices === undefined || currentPositions === undefined || currentIndices === null || currentPositions === null) {
      Logger.Warn("VertexData contains empty entries");
    } else {
      const positions = new Array;
      const indices = new Array;
      const uvs = new Array;
      const colors = new Array;
      const matrixIndices = new Array;
      const matrixWeights = new Array;
      const matrixIndicesExtra = new Array;
      const matrixWeightsExtra = new Array;
      let pstring = new Array;
      let indexPtr = 0;
      const uniquePositions = {};
      let ptr3;
      let facet;
      for (let i = 0;i < currentIndices.length; i += 3) {
        facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]];
        pstring = [];
        for (let j = 0;j < 3; j++) {
          pstring[j] = "";
          for (let k = 0;k < 3; k++) {
            if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) {
              currentPositions[3 * facet[j] + k] = 0;
            }
            pstring[j] += currentPositions[3 * facet[j] + k] + "|";
          }
        }
        if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) {
          for (let j = 0;j < 3; j++) {
            ptr3 = uniquePositions[pstring[j]];
            if (ptr3 === undefined) {
              uniquePositions[pstring[j]] = indexPtr;
              ptr3 = indexPtr++;
              for (let k = 0;k < 3; k++) {
                positions.push(currentPositions[3 * facet[j] + k]);
              }
              if (currentColors !== null && currentColors !== undefined) {
                for (let k = 0;k < 4; k++) {
                  colors.push(currentColors[4 * facet[j] + k]);
                }
              }
              if (currentUVs !== null && currentUVs !== undefined) {
                for (let k = 0;k < 2; k++) {
                  uvs.push(currentUVs[2 * facet[j] + k]);
                }
              }
              if (currentMatrixIndices !== null && currentMatrixIndices !== undefined) {
                for (let k = 0;k < 4; k++) {
                  matrixIndices.push(currentMatrixIndices[4 * facet[j] + k]);
                }
              }
              if (currentMatrixWeights !== null && currentMatrixWeights !== undefined) {
                for (let k = 0;k < 4; k++) {
                  matrixWeights.push(currentMatrixWeights[4 * facet[j] + k]);
                }
              }
              if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== undefined) {
                for (let k = 0;k < 4; k++) {
                  matrixIndicesExtra.push(currentMatrixIndicesExtra[4 * facet[j] + k]);
                }
              }
              if (currentMatrixWeightsExtra !== null && currentMatrixWeightsExtra !== undefined) {
                for (let k = 0;k < 4; k++) {
                  matrixWeightsExtra.push(currentMatrixWeightsExtra[4 * facet[j] + k]);
                }
              }
            }
            indices.push(ptr3);
          }
        }
      }
      const normals = new Array;
      VertexData.ComputeNormals(positions, indices, normals);
      vertex_data.positions = positions;
      vertex_data.indices = indices;
      vertex_data.normals = normals;
      if (currentUVs !== null && currentUVs !== undefined) {
        vertex_data.uvs = uvs;
      }
      if (currentColors !== null && currentColors !== undefined) {
        vertex_data.colors = colors;
      }
      if (currentMatrixIndices !== null && currentMatrixIndices !== undefined) {
        vertex_data.matricesIndices = matrixIndices;
      }
      if (currentMatrixWeights !== null && currentMatrixWeights !== undefined) {
        vertex_data.matricesWeights = matrixWeights;
      }
      if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== undefined) {
        vertex_data.matricesIndicesExtra = matrixIndicesExtra;
      }
      if (currentMatrixWeights !== null && currentMatrixWeights !== undefined) {
        vertex_data.matricesWeightsExtra = matrixWeightsExtra;
      }
      vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind));
    }
  }
  static _instancedMeshFactory(name18, mesh) {
    throw _WarnImport("InstancedMesh");
  }
  static _PhysicsImpostorParser(scene, physicObject, jsonObject) {
    throw _WarnImport("PhysicsImpostor");
  }
  createInstance(name18) {
    const instance = Mesh._instancedMeshFactory(name18, this);
    instance.parent = this.parent;
    return instance;
  }
  synchronizeInstances() {
    for (let instanceIndex = 0;instanceIndex < this.instances.length; instanceIndex++) {
      const instance = this.instances[instanceIndex];
      instance._syncSubMeshes();
    }
    return this;
  }
  optimizeIndices(successCallback) {
    const indices = this.getIndices();
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    if (!positions || !indices) {
      return this;
    }
    const vectorPositions = [];
    for (let pos = 0;pos < positions.length; pos = pos + 3) {
      vectorPositions.push(Vector3.FromArray(positions, pos));
    }
    const dupes = [];
    AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
      const realPos = vectorPositions.length - 1 - iteration;
      const testedPosition = vectorPositions[realPos];
      for (let j = 0;j < realPos; ++j) {
        const againstPosition = vectorPositions[j];
        if (testedPosition.equals(againstPosition)) {
          dupes[realPos] = j;
          break;
        }
      }
    }, () => {
      for (let i = 0;i < indices.length; ++i) {
        indices[i] = dupes[indices[i]] || indices[i];
      }
      const originalSubMeshes = this.subMeshes.slice(0);
      this.setIndices(indices);
      this.subMeshes = originalSubMeshes;
      if (successCallback) {
        successCallback(this);
      }
    });
    return this;
  }
  serialize(serializationObject = {}) {
    serializationObject.name = this.name;
    serializationObject.id = this.id;
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.type = this.getClassName();
    if (Tags && Tags.HasTags(this)) {
      serializationObject.tags = Tags.GetTags(this);
    }
    serializationObject.position = this.position.asArray();
    if (this.rotationQuaternion) {
      serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
    } else if (this.rotation) {
      serializationObject.rotation = this.rotation.asArray();
    }
    serializationObject.scaling = this.scaling.asArray();
    if (this._postMultiplyPivotMatrix) {
      serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
    } else {
      serializationObject.localMatrix = this.getPivotMatrix().asArray();
    }
    serializationObject.isEnabled = this.isEnabled(false);
    serializationObject.isVisible = this.isVisible;
    serializationObject.infiniteDistance = this.infiniteDistance;
    serializationObject.pickable = this.isPickable;
    serializationObject.receiveShadows = this.receiveShadows;
    serializationObject.billboardMode = this.billboardMode;
    serializationObject.visibility = this.visibility;
    serializationObject.alwaysSelectAsActiveMesh = this.alwaysSelectAsActiveMesh;
    serializationObject.checkCollisions = this.checkCollisions;
    serializationObject.ellipsoid = this.ellipsoid.asArray();
    serializationObject.ellipsoidOffset = this.ellipsoidOffset.asArray();
    serializationObject.doNotSyncBoundingInfo = this.doNotSyncBoundingInfo;
    serializationObject.isBlocker = this.isBlocker;
    serializationObject.sideOrientation = this.sideOrientation;
    if (this.parent) {
      this.parent._serializeAsParent(serializationObject);
    }
    serializationObject.isUnIndexed = this.isUnIndexed;
    const geometry = this._geometry;
    if (geometry && this.subMeshes) {
      serializationObject.geometryUniqueId = geometry.uniqueId;
      serializationObject.geometryId = geometry.id;
      serializationObject.subMeshes = [];
      for (let subIndex = 0;subIndex < this.subMeshes.length; subIndex++) {
        const subMesh = this.subMeshes[subIndex];
        serializationObject.subMeshes.push({
          materialIndex: subMesh.materialIndex,
          verticesStart: subMesh.verticesStart,
          verticesCount: subMesh.verticesCount,
          indexStart: subMesh.indexStart,
          indexCount: subMesh.indexCount
        });
      }
    }
    if (this.material) {
      if (!this.material.doNotSerialize) {
        serializationObject.materialUniqueId = this.material.uniqueId;
        serializationObject.materialId = this.material.id;
      }
    } else {
      this.material = null;
      serializationObject.materialUniqueId = this._scene.defaultMaterial.uniqueId;
      serializationObject.materialId = this._scene.defaultMaterial.id;
    }
    if (this.morphTargetManager) {
      serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
    }
    if (this.skeleton) {
      serializationObject.skeletonId = this.skeleton.id;
      serializationObject.numBoneInfluencers = this.numBoneInfluencers;
    }
    if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
      const impostor = this.getPhysicsImpostor();
      if (impostor) {
        serializationObject.physicsMass = impostor.getParam("mass");
        serializationObject.physicsFriction = impostor.getParam("friction");
        serializationObject.physicsRestitution = impostor.getParam("mass");
        serializationObject.physicsImpostor = impostor.type;
      }
    }
    if (this.metadata) {
      serializationObject.metadata = this.metadata;
    }
    serializationObject.instances = [];
    for (let index = 0;index < this.instances.length; index++) {
      const instance = this.instances[index];
      if (instance.doNotSerialize) {
        continue;
      }
      const serializationInstance = {
        name: instance.name,
        id: instance.id,
        isEnabled: instance.isEnabled(false),
        isVisible: instance.isVisible,
        isPickable: instance.isPickable,
        checkCollisions: instance.checkCollisions,
        position: instance.position.asArray(),
        scaling: instance.scaling.asArray()
      };
      if (instance.parent) {
        instance.parent._serializeAsParent(serializationInstance);
      }
      if (instance.rotationQuaternion) {
        serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
      } else if (instance.rotation) {
        serializationInstance.rotation = instance.rotation.asArray();
      }
      if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) {
        const impostor = instance.getPhysicsImpostor();
        if (impostor) {
          serializationInstance.physicsMass = impostor.getParam("mass");
          serializationInstance.physicsFriction = impostor.getParam("friction");
          serializationInstance.physicsRestitution = impostor.getParam("mass");
          serializationInstance.physicsImpostor = impostor.type;
        }
      }
      if (instance.metadata) {
        serializationInstance.metadata = instance.metadata;
      }
      if (instance.actionManager) {
        serializationInstance.actions = instance.actionManager.serialize(instance.name);
      }
      serializationObject.instances.push(serializationInstance);
      SerializationHelper.AppendSerializedAnimations(instance, serializationInstance);
      serializationInstance.ranges = instance.serializeAnimationRanges();
    }
    if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData) {
      serializationObject.thinInstances = {
        instancesCount: this._thinInstanceDataStorage.instancesCount,
        matrixData: Array.from(this._thinInstanceDataStorage.matrixData),
        matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize,
        enablePicking: this.thinInstanceEnablePicking
      };
      if (this._userThinInstanceBuffersStorage) {
        const userThinInstance = {
          data: {},
          sizes: {},
          strides: {}
        };
        for (const kind in this._userThinInstanceBuffersStorage.data) {
          userThinInstance.data[kind] = Array.from(this._userThinInstanceBuffersStorage.data[kind]);
          userThinInstance.sizes[kind] = this._userThinInstanceBuffersStorage.sizes[kind];
          userThinInstance.strides[kind] = this._userThinInstanceBuffersStorage.strides[kind];
        }
        serializationObject.thinInstances.userThinInstance = userThinInstance;
      }
    }
    SerializationHelper.AppendSerializedAnimations(this, serializationObject);
    serializationObject.ranges = this.serializeAnimationRanges();
    serializationObject.layerMask = this.layerMask;
    serializationObject.alphaIndex = this.alphaIndex;
    serializationObject.hasVertexAlpha = this.hasVertexAlpha;
    serializationObject.overlayAlpha = this.overlayAlpha;
    serializationObject.overlayColor = this.overlayColor.asArray();
    serializationObject.renderOverlay = this.renderOverlay;
    serializationObject.applyFog = this.applyFog;
    if (this.actionManager) {
      serializationObject.actions = this.actionManager.serialize(this.name);
    }
    return serializationObject;
  }
  _syncGeometryWithMorphTargetManager() {
    if (!this.geometry) {
      return;
    }
    this._markSubMeshesAsAttributesDirty();
    const morphTargetManager = this._internalAbstractMeshDataInfo._morphTargetManager;
    if (morphTargetManager && morphTargetManager.vertexCount) {
      if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
        Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
        this.morphTargetManager = null;
        return;
      }
      if (morphTargetManager.isUsingTextureForTargets) {
        return;
      }
      for (let index = 0;index < morphTargetManager.numInfluencers; index++) {
        const morphTarget = morphTargetManager.getActiveTarget(index);
        const positions = morphTarget.getPositions();
        if (!positions) {
          Logger.Error("Invalid morph target. Target must have positions.");
          return;
        }
        this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
        const normals = morphTarget.getNormals();
        if (normals) {
          this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
        }
        const tangents = morphTarget.getTangents();
        if (tangents) {
          this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
        }
        const uvs = morphTarget.getUVs();
        if (uvs) {
          this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + index, uvs, false, 2);
        }
        const uv2s = morphTarget.getUV2s();
        if (uv2s) {
          this.geometry.setVerticesData(VertexBuffer.UV2Kind + "_" + index, uv2s, false, 2);
        }
        const colors = morphTarget.getColors();
        if (colors) {
          this.geometry.setVerticesData(VertexBuffer.ColorKind + index, colors, false, 4);
        }
      }
    } else {
      let index = 0;
      while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
        this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
        if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
          this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
        }
        if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
          this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
        }
        if (this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + index)) {
          this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + index);
        }
        if (this.geometry.isVerticesDataPresent(VertexBuffer.UV2Kind + index)) {
          this.geometry.removeVerticesData(VertexBuffer.UV2Kind + "_" + index);
        }
        if (this.geometry.isVerticesDataPresent(VertexBuffer.ColorKind + index)) {
          this.geometry.removeVerticesData(VertexBuffer.ColorKind + index);
        }
        index++;
      }
    }
  }
  static Parse(parsedMesh, scene, rootUrl) {
    let mesh;
    if (parsedMesh.type && parsedMesh.type === "LinesMesh") {
      mesh = Mesh._LinesMeshParser(parsedMesh, scene);
    } else if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
      mesh = Mesh._GroundMeshParser(parsedMesh, scene);
    } else if (parsedMesh.type && parsedMesh.type === "GoldbergMesh") {
      mesh = Mesh._GoldbergMeshParser(parsedMesh, scene);
    } else if (parsedMesh.type && parsedMesh.type === "GreasedLineMesh") {
      mesh = Mesh._GreasedLineMeshParser(parsedMesh, scene);
    } else if (parsedMesh.type && parsedMesh.type === "TrailMesh") {
      mesh = Mesh._TrailMeshParser(parsedMesh, scene);
    } else {
      mesh = new Mesh(parsedMesh.name, scene);
    }
    mesh.id = parsedMesh.id;
    mesh._waitingParsedUniqueId = parsedMesh.uniqueId;
    if (Tags) {
      Tags.AddTagsTo(mesh, parsedMesh.tags);
    }
    mesh.position = Vector3.FromArray(parsedMesh.position);
    if (parsedMesh.metadata !== undefined) {
      mesh.metadata = parsedMesh.metadata;
    }
    if (parsedMesh.rotationQuaternion) {
      mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
    } else if (parsedMesh.rotation) {
      mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
    }
    mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
    if (parsedMesh.localMatrix) {
      mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix));
    } else if (parsedMesh.pivotMatrix) {
      mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
    }
    mesh.setEnabled(parsedMesh.isEnabled);
    mesh.isVisible = parsedMesh.isVisible;
    mesh.infiniteDistance = parsedMesh.infiniteDistance;
    mesh.alwaysSelectAsActiveMesh = !!parsedMesh.alwaysSelectAsActiveMesh;
    mesh.showBoundingBox = parsedMesh.showBoundingBox;
    mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
    if (parsedMesh.applyFog !== undefined) {
      mesh.applyFog = parsedMesh.applyFog;
    }
    if (parsedMesh.pickable !== undefined) {
      mesh.isPickable = parsedMesh.pickable;
    }
    if (parsedMesh.alphaIndex !== undefined) {
      mesh.alphaIndex = parsedMesh.alphaIndex;
    }
    mesh.receiveShadows = parsedMesh.receiveShadows;
    if (parsedMesh.billboardMode !== undefined) {
      mesh.billboardMode = parsedMesh.billboardMode;
    }
    if (parsedMesh.visibility !== undefined) {
      mesh.visibility = parsedMesh.visibility;
    }
    mesh.checkCollisions = parsedMesh.checkCollisions;
    mesh.doNotSyncBoundingInfo = !!parsedMesh.doNotSyncBoundingInfo;
    if (parsedMesh.ellipsoid) {
      mesh.ellipsoid = Vector3.FromArray(parsedMesh.ellipsoid);
    }
    if (parsedMesh.ellipsoidOffset) {
      mesh.ellipsoidOffset = Vector3.FromArray(parsedMesh.ellipsoidOffset);
    }
    if (parsedMesh.overrideMaterialSideOrientation != null) {
      mesh.sideOrientation = parsedMesh.overrideMaterialSideOrientation;
    }
    if (parsedMesh.sideOrientation !== undefined) {
      mesh.sideOrientation = parsedMesh.sideOrientation;
    }
    if (parsedMesh.isBlocker !== undefined) {
      mesh.isBlocker = parsedMesh.isBlocker;
    }
    mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
    if (parsedMesh.freezeWorldMatrix) {
      mesh._waitingData.freezeWorldMatrix = parsedMesh.freezeWorldMatrix;
    }
    if (parsedMesh.parentId !== undefined) {
      mesh._waitingParentId = parsedMesh.parentId;
    }
    if (parsedMesh.parentInstanceIndex !== undefined) {
      mesh._waitingParentInstanceIndex = parsedMesh.parentInstanceIndex;
    }
    if (parsedMesh.actions !== undefined) {
      mesh._waitingData.actions = parsedMesh.actions;
    }
    if (parsedMesh.overlayAlpha !== undefined) {
      mesh.overlayAlpha = parsedMesh.overlayAlpha;
    }
    if (parsedMesh.overlayColor !== undefined) {
      mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
    }
    if (parsedMesh.renderOverlay !== undefined) {
      mesh.renderOverlay = parsedMesh.renderOverlay;
    }
    mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
    mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
    if (parsedMesh.delayLoadingFile) {
      mesh.delayLoadState = 4;
      mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
      mesh.buildBoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
      if (parsedMesh._binaryInfo) {
        mesh._binaryInfo = parsedMesh._binaryInfo;
      }
      mesh._delayInfo = [];
      if (parsedMesh.hasUVs) {
        mesh._delayInfo.push(VertexBuffer.UVKind);
      }
      if (parsedMesh.hasUVs2) {
        mesh._delayInfo.push(VertexBuffer.UV2Kind);
      }
      if (parsedMesh.hasUVs3) {
        mesh._delayInfo.push(VertexBuffer.UV3Kind);
      }
      if (parsedMesh.hasUVs4) {
        mesh._delayInfo.push(VertexBuffer.UV4Kind);
      }
      if (parsedMesh.hasUVs5) {
        mesh._delayInfo.push(VertexBuffer.UV5Kind);
      }
      if (parsedMesh.hasUVs6) {
        mesh._delayInfo.push(VertexBuffer.UV6Kind);
      }
      if (parsedMesh.hasColors) {
        mesh._delayInfo.push(VertexBuffer.ColorKind);
      }
      if (parsedMesh.hasMatricesIndices) {
        mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
      }
      if (parsedMesh.hasMatricesWeights) {
        mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
      }
      mesh._delayLoadingFunction = Geometry._ImportGeometry;
      if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) {
        mesh._checkDelayState();
      }
    } else {
      Geometry._ImportGeometry(parsedMesh, mesh);
    }
    if (parsedMesh.materialUniqueId) {
      mesh._waitingMaterialId = parsedMesh.materialUniqueId;
    } else if (parsedMesh.materialId) {
      mesh._waitingMaterialId = parsedMesh.materialId;
    }
    if (parsedMesh.morphTargetManagerId > -1) {
      mesh._waitingMorphTargetManagerId = parsedMesh.morphTargetManagerId;
    }
    if (parsedMesh.skeletonId !== undefined && parsedMesh.skeletonId !== null) {
      mesh.skeleton = scene.getLastSkeletonById(parsedMesh.skeletonId);
      if (parsedMesh.numBoneInfluencers) {
        mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
      }
    }
    if (parsedMesh.animations) {
      for (let animationIndex = 0;animationIndex < parsedMesh.animations.length; animationIndex++) {
        const parsedAnimation = parsedMesh.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          mesh.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
      Node2.ParseAnimationRanges(mesh, parsedMesh, scene);
    }
    if (parsedMesh.autoAnimate) {
      scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1);
    }
    if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) {
      mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
    } else {
      mesh.layerMask = 268435455;
    }
    if (parsedMesh.physicsImpostor) {
      mesh.physicsImpostor = Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh);
    }
    if (parsedMesh.lodMeshIds) {
      mesh._waitingData.lods = {
        ids: parsedMesh.lodMeshIds,
        distances: parsedMesh.lodDistances ? parsedMesh.lodDistances : null,
        coverages: parsedMesh.lodCoverages ? parsedMesh.lodCoverages : null
      };
    }
    if (parsedMesh.instances) {
      for (let index = 0;index < parsedMesh.instances.length; index++) {
        const parsedInstance = parsedMesh.instances[index];
        const instance = mesh.createInstance(parsedInstance.name);
        if (parsedInstance.id) {
          instance.id = parsedInstance.id;
        }
        if (Tags) {
          if (parsedInstance.tags) {
            Tags.AddTagsTo(instance, parsedInstance.tags);
          } else {
            Tags.AddTagsTo(instance, parsedMesh.tags);
          }
        }
        instance.position = Vector3.FromArray(parsedInstance.position);
        if (parsedInstance.metadata !== undefined) {
          instance.metadata = parsedInstance.metadata;
        }
        if (parsedInstance.parentId !== undefined) {
          instance._waitingParentId = parsedInstance.parentId;
        }
        if (parsedInstance.parentInstanceIndex !== undefined) {
          instance._waitingParentInstanceIndex = parsedInstance.parentInstanceIndex;
        }
        if (parsedInstance.isEnabled !== undefined && parsedInstance.isEnabled !== null) {
          instance.setEnabled(parsedInstance.isEnabled);
        }
        if (parsedInstance.isVisible !== undefined && parsedInstance.isVisible !== null) {
          instance.isVisible = parsedInstance.isVisible;
        }
        if (parsedInstance.isPickable !== undefined && parsedInstance.isPickable !== null) {
          instance.isPickable = parsedInstance.isPickable;
        }
        if (parsedInstance.rotationQuaternion) {
          instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
        } else if (parsedInstance.rotation) {
          instance.rotation = Vector3.FromArray(parsedInstance.rotation);
        }
        instance.scaling = Vector3.FromArray(parsedInstance.scaling);
        if (parsedInstance.checkCollisions != null && parsedInstance.checkCollisions != null) {
          instance.checkCollisions = parsedInstance.checkCollisions;
        }
        if (parsedInstance.pickable != null && parsedInstance.pickable != null) {
          instance.isPickable = parsedInstance.pickable;
        }
        if (parsedInstance.showBoundingBox != null && parsedInstance.showBoundingBox != null) {
          instance.showBoundingBox = parsedInstance.showBoundingBox;
        }
        if (parsedInstance.showSubMeshesBoundingBox != null && parsedInstance.showSubMeshesBoundingBox != null) {
          instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
        }
        if (parsedInstance.alphaIndex != null && parsedInstance.showSubMeshesBoundingBox != null) {
          instance.alphaIndex = parsedInstance.alphaIndex;
        }
        if (parsedInstance.physicsImpostor) {
          instance.physicsImpostor = Mesh._PhysicsImpostorParser(scene, instance, parsedInstance);
        }
        if (parsedInstance.actions !== undefined) {
          instance._waitingData.actions = parsedInstance.actions;
        }
        if (parsedInstance.animations) {
          for (let animationIndex = 0;animationIndex < parsedInstance.animations.length; animationIndex++) {
            const parsedAnimation = parsedInstance.animations[animationIndex];
            const internalClass = GetClass("BABYLON.Animation");
            if (internalClass) {
              instance.animations.push(internalClass.Parse(parsedAnimation));
            }
          }
          Node2.ParseAnimationRanges(instance, parsedInstance, scene);
          if (parsedInstance.autoAnimate) {
            scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1);
          }
        }
      }
    }
    if (parsedMesh.thinInstances) {
      const thinInstances = parsedMesh.thinInstances;
      mesh.thinInstanceEnablePicking = !!thinInstances.enablePicking;
      if (thinInstances.matrixData) {
        mesh.thinInstanceSetBuffer("matrix", new Float32Array(thinInstances.matrixData), 16, false);
        mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize;
        mesh._thinInstanceDataStorage.instancesCount = thinInstances.instancesCount;
      } else {
        mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize;
      }
      if (parsedMesh.thinInstances.userThinInstance) {
        const userThinInstance = parsedMesh.thinInstances.userThinInstance;
        for (const kind in userThinInstance.data) {
          mesh.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], false);
          mesh._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind];
        }
      }
    }
    return mesh;
  }
  setPositionsForCPUSkinning() {
    const internalDataInfo = this._internalMeshDataInfo;
    if (!internalDataInfo._sourcePositions) {
      const source = this.getVerticesData(VertexBuffer.PositionKind);
      if (!source) {
        return internalDataInfo._sourcePositions;
      }
      internalDataInfo._sourcePositions = new Float32Array(source);
      if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
        this.setVerticesData(VertexBuffer.PositionKind, source, true);
      }
    }
    return internalDataInfo._sourcePositions;
  }
  setNormalsForCPUSkinning() {
    const internalDataInfo = this._internalMeshDataInfo;
    if (!internalDataInfo._sourceNormals) {
      const source = this.getVerticesData(VertexBuffer.NormalKind);
      if (!source) {
        return internalDataInfo._sourceNormals;
      }
      internalDataInfo._sourceNormals = new Float32Array(source);
      if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
        this.setVerticesData(VertexBuffer.NormalKind, source, true);
      }
    }
    return internalDataInfo._sourceNormals;
  }
  applySkeleton(skeleton) {
    if (!this.geometry) {
      return this;
    }
    if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
      return this;
    }
    this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
    if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
      return this;
    }
    if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
      return this;
    }
    if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
      return this;
    }
    const hasNormals = this.isVerticesDataPresent(VertexBuffer.NormalKind);
    const internalDataInfo = this._internalMeshDataInfo;
    if (!internalDataInfo._sourcePositions) {
      const submeshes = this.subMeshes.slice();
      this.setPositionsForCPUSkinning();
      this.subMeshes = submeshes;
    }
    if (hasNormals && !internalDataInfo._sourceNormals) {
      this.setNormalsForCPUSkinning();
    }
    let positionsData = this.getVerticesData(VertexBuffer.PositionKind);
    if (!positionsData) {
      return this;
    }
    if (!(positionsData instanceof Float32Array)) {
      positionsData = new Float32Array(positionsData);
    }
    let normalsData = this.getVerticesData(VertexBuffer.NormalKind);
    if (hasNormals) {
      if (!normalsData) {
        return this;
      }
      if (!(normalsData instanceof Float32Array)) {
        normalsData = new Float32Array(normalsData);
      }
    }
    const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
    const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
    if (!matricesWeightsData || !matricesIndicesData) {
      return this;
    }
    const needExtras = this.numBoneInfluencers > 4;
    const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
    const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
    const skeletonMatrices = skeleton.getTransformMatrices(this);
    const tempVector3 = Vector3.Zero();
    const finalMatrix = new Matrix;
    const tempMatrix = new Matrix;
    let matWeightIdx = 0;
    let inf;
    for (let index = 0;index < positionsData.length; index += 3, matWeightIdx += 4) {
      let weight;
      for (inf = 0;inf < 4; inf++) {
        weight = matricesWeightsData[matWeightIdx + inf];
        if (weight > 0) {
          Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
          finalMatrix.addToSelf(tempMatrix);
        }
      }
      if (needExtras) {
        for (inf = 0;inf < 4; inf++) {
          weight = matricesWeightsExtraData[matWeightIdx + inf];
          if (weight > 0) {
            Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
            finalMatrix.addToSelf(tempMatrix);
          }
        }
      }
      Vector3.TransformCoordinatesFromFloatsToRef(internalDataInfo._sourcePositions[index], internalDataInfo._sourcePositions[index + 1], internalDataInfo._sourcePositions[index + 2], finalMatrix, tempVector3);
      tempVector3.toArray(positionsData, index);
      if (hasNormals) {
        Vector3.TransformNormalFromFloatsToRef(internalDataInfo._sourceNormals[index], internalDataInfo._sourceNormals[index + 1], internalDataInfo._sourceNormals[index + 2], finalMatrix, tempVector3);
        tempVector3.toArray(normalsData, index);
      }
      finalMatrix.reset();
    }
    this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
    if (hasNormals) {
      this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
    }
    return this;
  }
  static MinMax(meshes) {
    let minVector = null;
    let maxVector = null;
    meshes.forEach(function(mesh) {
      const boundingInfo = mesh.getBoundingInfo();
      const boundingBox = boundingInfo.boundingBox;
      if (!minVector || !maxVector) {
        minVector = boundingBox.minimumWorld;
        maxVector = boundingBox.maximumWorld;
      } else {
        minVector.minimizeInPlace(boundingBox.minimumWorld);
        maxVector.maximizeInPlace(boundingBox.maximumWorld);
      }
    });
    if (!minVector || !maxVector) {
      return {
        min: Vector3.Zero(),
        max: Vector3.Zero()
      };
    }
    return {
      min: minVector,
      max: maxVector
    };
  }
  static Center(meshesOrMinMaxVector) {
    const minMaxVector = meshesOrMinMaxVector instanceof Array ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
    return Vector3.Center(minMaxVector.min, minMaxVector.max);
  }
  static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) {
    return runCoroutineSync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, false));
  }
  static MergeMeshesAsync(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) {
    return runCoroutineAsync(Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, true), createYieldingScheduler());
  }
  static *_MergeMeshesCoroutine(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, isAsync) {
    meshes = meshes.filter(Boolean);
    if (meshes.length === 0) {
      return null;
    }
    let index;
    if (!allow32BitsIndices) {
      let totalVertices = 0;
      for (index = 0;index < meshes.length; index++) {
        totalVertices += meshes[index].getTotalVertices();
        if (totalVertices >= 65536) {
          Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
          return null;
        }
      }
    }
    if (multiMultiMaterials) {
      subdivideWithSubMeshes = false;
    }
    const materialArray = new Array;
    const materialIndexArray = new Array;
    const indiceArray = new Array;
    const currentsideOrientation = meshes[0].sideOrientation;
    for (index = 0;index < meshes.length; index++) {
      const mesh = meshes[index];
      if (mesh.isAnInstance) {
        Logger.Warn("Cannot merge instance meshes.");
        return null;
      }
      if (currentsideOrientation !== mesh.sideOrientation) {
        Logger.Warn("Cannot merge meshes with different sideOrientation values.");
        return null;
      }
      if (subdivideWithSubMeshes) {
        indiceArray.push(mesh.getTotalIndices());
      }
      if (multiMultiMaterials) {
        if (mesh.material) {
          const material = mesh.material;
          if (material instanceof MultiMaterial) {
            for (let matIndex = 0;matIndex < material.subMaterials.length; matIndex++) {
              if (materialArray.indexOf(material.subMaterials[matIndex]) < 0) {
                materialArray.push(material.subMaterials[matIndex]);
              }
            }
            for (let subIndex = 0;subIndex < mesh.subMeshes.length; subIndex++) {
              materialIndexArray.push(materialArray.indexOf(material.subMaterials[mesh.subMeshes[subIndex].materialIndex]));
              indiceArray.push(mesh.subMeshes[subIndex].indexCount);
            }
          } else {
            if (materialArray.indexOf(material) < 0) {
              materialArray.push(material);
            }
            for (let subIndex = 0;subIndex < mesh.subMeshes.length; subIndex++) {
              materialIndexArray.push(materialArray.indexOf(material));
              indiceArray.push(mesh.subMeshes[subIndex].indexCount);
            }
          }
        } else {
          for (let subIndex = 0;subIndex < mesh.subMeshes.length; subIndex++) {
            materialIndexArray.push(0);
            indiceArray.push(mesh.subMeshes[subIndex].indexCount);
          }
        }
      }
    }
    const source = meshes[0];
    const getVertexDataFromMesh = (mesh) => {
      const wm = mesh.computeWorldMatrix(true);
      const vertexData2 = VertexData.ExtractFromMesh(mesh, false, false);
      return { vertexData: vertexData2, transform: wm };
    };
    const { vertexData: sourceVertexData, transform: sourceTransform } = getVertexDataFromMesh(source);
    if (isAsync) {
      yield;
    }
    const meshVertexDatas = new Array(meshes.length - 1);
    for (let i = 1;i < meshes.length; i++) {
      meshVertexDatas[i - 1] = getVertexDataFromMesh(meshes[i]);
      if (isAsync) {
        yield;
      }
    }
    const mergeCoroutine = sourceVertexData._mergeCoroutine(sourceTransform, meshVertexDatas, allow32BitsIndices, isAsync, !disposeSource);
    let mergeCoroutineStep = mergeCoroutine.next();
    while (!mergeCoroutineStep.done) {
      if (isAsync) {
        yield;
      }
      mergeCoroutineStep = mergeCoroutine.next();
    }
    const vertexData = mergeCoroutineStep.value;
    if (!meshSubclass) {
      meshSubclass = new Mesh(source.name + "_merged", source.getScene());
    }
    const applyToCoroutine = vertexData._applyToCoroutine(meshSubclass, undefined, isAsync);
    let applyToCoroutineStep = applyToCoroutine.next();
    while (!applyToCoroutineStep.done) {
      if (isAsync) {
        yield;
      }
      applyToCoroutineStep = applyToCoroutine.next();
    }
    meshSubclass.checkCollisions = source.checkCollisions;
    meshSubclass.sideOrientation = source.sideOrientation;
    if (disposeSource) {
      for (index = 0;index < meshes.length; index++) {
        meshes[index].dispose();
      }
    }
    if (subdivideWithSubMeshes || multiMultiMaterials) {
      meshSubclass.releaseSubMeshes();
      index = 0;
      let offset = 0;
      while (index < indiceArray.length) {
        SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass, undefined, false);
        offset += indiceArray[index];
        index++;
      }
      for (const subMesh of meshSubclass.subMeshes) {
        subMesh.refreshBoundingInfo();
      }
      meshSubclass.computeWorldMatrix(true);
    }
    if (multiMultiMaterials) {
      const newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene());
      newMultiMaterial.subMaterials = materialArray;
      for (let subIndex = 0;subIndex < meshSubclass.subMeshes.length; subIndex++) {
        meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex];
      }
      meshSubclass.material = newMultiMaterial;
    } else {
      meshSubclass.material = source.material;
    }
    return meshSubclass;
  }
  addInstance(instance) {
    instance._indexInSourceMeshInstanceArray = this.instances.length;
    this.instances.push(instance);
  }
  removeInstance(instance) {
    const index = instance._indexInSourceMeshInstanceArray;
    if (index != -1) {
      if (index !== this.instances.length - 1) {
        const last = this.instances[this.instances.length - 1];
        this.instances[index] = last;
        last._indexInSourceMeshInstanceArray = index;
      }
      instance._indexInSourceMeshInstanceArray = -1;
      this.instances.pop();
    }
  }
  _shouldConvertRHS() {
    return this._scene.useRightHandedSystem && this.sideOrientation === Material.CounterClockWiseSideOrientation;
  }
  _getRenderingFillMode(fillMode) {
    const scene = this.getScene();
    if (scene.forcePointsCloud)
      return Material.PointFillMode;
    if (scene.forceWireframe)
      return Material.WireFrameFillMode;
    return this.overrideRenderingFillMode ?? fillMode;
  }
  setMaterialByID(id) {
    return this.setMaterialById(id);
  }
  static CreateRibbon(name18, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateDisc(name18, radius, tessellation, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateBox(name18, size, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateSphere(name18, segments, diameter, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateHemisphere(name18, segments, diameter, scene) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateCylinder(name18, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateTorus(name18, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateTorusKnot(name18, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateLines(name18, points, scene, updatable, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateDashedLines(name18, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreatePolygon(name18, shape, scene, holes, updatable, sideOrientation, earcutInjection) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static ExtrudePolygon(name18, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static ExtrudeShape(name18, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static ExtrudeShapeCustom(name18, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateLathe(name18, shape, radius, tessellation, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreatePlane(name18, size, scene, updatable, sideOrientation) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateGround(name18, width, height, subdivisions, scene, updatable) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateTiledGround(name18, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateGroundFromHeightMap(name18, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateTube(name18, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreatePolyhedron(name18, options, scene) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateIcoSphere(name18, options, scene) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateDecal(name18, sourceMesh, position, normal, size, angle) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static CreateCapsule(name18, options, scene) {
    throw new Error("Import MeshBuilder to populate this function");
  }
  static ExtendToGoldberg(mesh) {
    throw new Error("Import MeshBuilder to populate this function");
  }
}
Mesh.FRONTSIDE = VertexData.FRONTSIDE;
Mesh.BACKSIDE = VertexData.BACKSIDE;
Mesh.DOUBLESIDE = VertexData.DOUBLESIDE;
Mesh.DEFAULTSIDE = VertexData.DEFAULTSIDE;
Mesh.NO_CAP = 0;
Mesh.CAP_START = 1;
Mesh.CAP_END = 2;
Mesh.CAP_ALL = 3;
Mesh.NO_FLIP = 0;
Mesh.FLIP_TILE = 1;
Mesh.ROTATE_TILE = 2;
Mesh.FLIP_ROW = 3;
Mesh.ROTATE_ROW = 4;
Mesh.FLIP_N_ROTATE_TILE = 5;
Mesh.FLIP_N_ROTATE_ROW = 6;
Mesh.CENTER = 0;
Mesh.LEFT = 1;
Mesh.RIGHT = 2;
Mesh.TOP = 3;
Mesh.BOTTOM = 4;
Mesh.INSTANCEDMESH_SORT_TRANSPARENT = false;
Mesh._GroundMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("GroundMesh");
};
Mesh._GoldbergMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("GoldbergMesh");
};
Mesh._LinesMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("LinesMesh");
};
Mesh._GreasedLineMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("GreasedLineMesh");
};
Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("GreasedLineRibbonMesh");
};
Mesh._TrailMeshParser = (parsedMesh, scene) => {
  throw _WarnImport("TrailMesh");
};
RegisterClass("BABYLON.Mesh", Mesh);

// node_modules/@babylonjs/core/assetContainer.js
init_logger();
init_engineStore();

// node_modules/@babylonjs/core/Meshes/instancedMesh.js
init_math_vector();
init_logger();
init_deepCopier();
init_buffer();
init_tools();
init_typeStore();
Mesh._instancedMeshFactory = (name18, mesh) => {
  const instance = new InstancedMesh(name18, mesh);
  if (mesh.instancedBuffers) {
    instance.instancedBuffers = {};
    for (const key in mesh.instancedBuffers) {
      instance.instancedBuffers[key] = mesh.instancedBuffers[key];
    }
  }
  return instance;
};

class InstancedMesh extends AbstractMesh {
  constructor(name18, source) {
    super(name18, source.getScene());
    this._indexInSourceMeshInstanceArray = -1;
    this._distanceToCamera = 0;
    source.addInstance(this);
    this._sourceMesh = source;
    this._unIndexed = source._unIndexed;
    this.position.copyFrom(source.position);
    this.rotation.copyFrom(source.rotation);
    this.scaling.copyFrom(source.scaling);
    if (source.rotationQuaternion) {
      this.rotationQuaternion = source.rotationQuaternion.clone();
    }
    this.animations = source.animations.slice();
    for (const range of source.getAnimationRanges()) {
      if (range != null) {
        this.createAnimationRange(range.name, range.from, range.to);
      }
    }
    this.infiniteDistance = source.infiniteDistance;
    this.setPivotMatrix(source.getPivotMatrix());
    this.refreshBoundingInfo(true, true);
    this._syncSubMeshes();
  }
  getClassName() {
    return "InstancedMesh";
  }
  get lightSources() {
    return this._sourceMesh._lightSources;
  }
  _resyncLightSources() {}
  _resyncLightSource() {}
  _removeLightSource() {}
  get receiveShadows() {
    return this._sourceMesh.receiveShadows;
  }
  set receiveShadows(_value) {
    if (this._sourceMesh?.receiveShadows !== _value) {
      Tools.Warn("Setting receiveShadows on an instanced mesh has no effect");
    }
  }
  get material() {
    return this._sourceMesh.material;
  }
  set material(_value) {
    if (this._sourceMesh?.material !== _value) {
      Tools.Warn("Setting material on an instanced mesh has no effect");
    }
  }
  get visibility() {
    return this._sourceMesh.visibility;
  }
  set visibility(_value) {
    if (this._sourceMesh?.visibility !== _value) {
      Tools.Warn("Setting visibility on an instanced mesh has no effect");
    }
  }
  get skeleton() {
    return this._sourceMesh.skeleton;
  }
  set skeleton(_value) {
    if (this._sourceMesh?.skeleton !== _value) {
      Tools.Warn("Setting skeleton on an instanced mesh has no effect");
    }
  }
  get renderingGroupId() {
    return this._sourceMesh.renderingGroupId;
  }
  set renderingGroupId(value) {
    if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
      return;
    }
    Logger.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  }
  getTotalVertices() {
    return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0;
  }
  getTotalIndices() {
    return this._sourceMesh.getTotalIndices();
  }
  get sourceMesh() {
    return this._sourceMesh;
  }
  get geometry() {
    return this._sourceMesh._geometry;
  }
  createInstance(name18) {
    return this._sourceMesh.createInstance(name18);
  }
  isReady(completeCheck = false) {
    return this._sourceMesh.isReady(completeCheck, true);
  }
  getVerticesData(kind, copyWhenShared, forceCopy) {
    return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy);
  }
  copyVerticesData(kind, vertexData) {
    this._sourceMesh.copyVerticesData(kind, vertexData);
  }
  setVerticesData(kind, data, updatable, stride) {
    if (this.sourceMesh) {
      this.sourceMesh.setVerticesData(kind, data, updatable, stride);
    }
    return this.sourceMesh;
  }
  updateVerticesData(kind, data, updateExtends, makeItUnique) {
    if (this.sourceMesh) {
      this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
    }
    return this.sourceMesh;
  }
  setIndices(indices, totalVertices = null) {
    if (this.sourceMesh) {
      this.sourceMesh.setIndices(indices, totalVertices);
    }
    return this.sourceMesh;
  }
  isVerticesDataPresent(kind) {
    return this._sourceMesh.isVerticesDataPresent(kind);
  }
  getIndices() {
    return this._sourceMesh.getIndices();
  }
  get _positions() {
    return this._sourceMesh._positions;
  }
  refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph2 = false) {
    if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {
      return this;
    }
    let options;
    if (typeof applySkeletonOrOptions === "object") {
      options = applySkeletonOrOptions;
    } else {
      options = {
        applySkeleton: applySkeletonOrOptions,
        applyMorph: applyMorph2
      };
    }
    const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
    this._refreshBoundingInfo(this._sourceMesh._getData(options, null, VertexBuffer.PositionKind), bias);
    return this;
  }
  _preActivate() {
    if (this._currentLOD) {
      this._currentLOD._preActivate();
    }
    return this;
  }
  _activate(renderId, intermediateRendering) {
    super._activate(renderId, intermediateRendering);
    if (!this._sourceMesh.subMeshes) {
      Logger.Warn("Instances should only be created for meshes with geometry.");
    }
    if (this._currentLOD) {
      const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0;
      if (differentSign) {
        this._internalAbstractMeshDataInfo._actAsRegularMesh = true;
        return true;
      }
      this._internalAbstractMeshDataInfo._actAsRegularMesh = false;
      this._currentLOD._registerInstanceForRenderId(this, renderId);
      if (intermediateRendering) {
        if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) {
          this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true;
          return true;
        }
      } else {
        if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) {
          this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true;
          return true;
        }
      }
    }
    return false;
  }
  _postActivate() {
    if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {
      this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer);
      this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix());
    } else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {
      this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);
    }
  }
  getWorldMatrix() {
    if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {
      if (!this._billboardWorldMatrix) {
        this._billboardWorldMatrix = new Matrix;
      }
      const tempMaster = this._currentLOD._masterMesh;
      this._currentLOD._masterMesh = this;
      TmpVectors.Vector3[7].copyFrom(this._currentLOD.position);
      this._currentLOD.position.set(0, 0, 0);
      this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true));
      this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]);
      this._currentLOD._masterMesh = tempMaster;
      return this._billboardWorldMatrix;
    }
    return super.getWorldMatrix();
  }
  get isAnInstance() {
    return true;
  }
  getLOD(camera) {
    if (!camera) {
      return this;
    }
    const sourceMeshLODLevels = this.sourceMesh.getLODLevels();
    if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) {
      this._currentLOD = this.sourceMesh;
    } else {
      const boundingInfo = this.getBoundingInfo();
      this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
    }
    return this._currentLOD;
  }
  _preActivateForIntermediateRendering(renderId) {
    return this.sourceMesh._preActivateForIntermediateRendering(renderId);
  }
  _syncSubMeshes() {
    this.releaseSubMeshes();
    if (this._sourceMesh.subMeshes) {
      for (let index = 0;index < this._sourceMesh.subMeshes.length; index++) {
        this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
      }
    }
    return this;
  }
  _generatePointsArray() {
    return this._sourceMesh._generatePointsArray();
  }
  _updateBoundingInfo() {
    if (this.hasBoundingInfo) {
      this.getBoundingInfo().update(this.worldMatrixFromCache);
    } else {
      this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
    }
    this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
    return this;
  }
  clone(name18, newParent = null, doNotCloneChildren, newSourceMesh) {
    const result = (newSourceMesh || this._sourceMesh).createInstance(name18);
    DeepCopier.DeepCopy(this, result, [
      "name",
      "subMeshes",
      "uniqueId",
      "parent",
      "lightSources",
      "receiveShadows",
      "material",
      "visibility",
      "skeleton",
      "sourceMesh",
      "isAnInstance",
      "facetNb",
      "isFacetDataEnabled",
      "isBlocked",
      "useBones",
      "hasInstances",
      "collider",
      "edgesRenderer",
      "forward",
      "up",
      "right",
      "absolutePosition",
      "absoluteScaling",
      "absoluteRotationQuaternion",
      "isWorldMatrixFrozen",
      "nonUniformScaling",
      "behaviors",
      "worldMatrixFromCache",
      "hasThinInstances",
      "hasBoundingInfo"
    ], []);
    this.refreshBoundingInfo();
    if (newParent) {
      result.parent = newParent;
    }
    if (!doNotCloneChildren) {
      for (let index = 0;index < this.getScene().meshes.length; index++) {
        const mesh = this.getScene().meshes[index];
        if (mesh.parent === this) {
          mesh.clone(mesh.name, result);
        }
      }
    }
    result.computeWorldMatrix(true);
    this.onClonedObservable.notifyObservers(result);
    return result;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this._sourceMesh.removeInstance(this);
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  _serializeAsParent(serializationObject) {
    super._serializeAsParent(serializationObject);
    serializationObject.parentId = this._sourceMesh.uniqueId;
    serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray;
  }
  instantiateHierarchy(newParent = null, options, onNewNodeCreated) {
    const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh);
    if (clone) {
      if (onNewNodeCreated) {
        onNewNodeCreated(this, clone);
      }
    }
    for (const child of this.getChildTransformNodes(true)) {
      child.instantiateHierarchy(clone, options, onNewNodeCreated);
    }
    return clone;
  }
}
Mesh.prototype.registerInstancedBuffer = function(kind, stride) {
  this._userInstancedBuffersStorage?.vertexBuffers[kind]?.dispose();
  if (!this.instancedBuffers) {
    this.instancedBuffers = {};
    for (const instance of this.instances) {
      instance.instancedBuffers = {};
    }
  }
  if (!this._userInstancedBuffersStorage) {
    this._userInstancedBuffersStorage = {
      data: {},
      vertexBuffers: {},
      strides: {},
      sizes: {},
      vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined
    };
  }
  this.instancedBuffers[kind] = null;
  this._userInstancedBuffersStorage.strides[kind] = stride;
  this._userInstancedBuffersStorage.sizes[kind] = stride * 32;
  this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]);
  this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);
  for (const instance of this.instances) {
    instance.instancedBuffers[kind] = null;
  }
  this._invalidateInstanceVertexArrayObject();
  this._markSubMeshesAsAttributesDirty();
};
Mesh.prototype._processInstancedBuffers = function(visibleInstances, renderSelf) {
  const instanceCount = visibleInstances ? visibleInstances.length : 0;
  for (const kind in this.instancedBuffers) {
    let size = this._userInstancedBuffersStorage.sizes[kind];
    const stride = this._userInstancedBuffersStorage.strides[kind];
    const expectedSize = (instanceCount + 1) * stride;
    while (size < expectedSize) {
      size *= 2;
    }
    if (this._userInstancedBuffersStorage.data[kind].length != size) {
      this._userInstancedBuffersStorage.data[kind] = new Float32Array(size);
      this._userInstancedBuffersStorage.sizes[kind] = size;
      if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {
        this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();
        this._userInstancedBuffersStorage.vertexBuffers[kind] = null;
      }
    }
    const data = this._userInstancedBuffersStorage.data[kind];
    let offset = 0;
    if (renderSelf) {
      const value = this.instancedBuffers[kind];
      if (value.toArray) {
        value.toArray(data, offset);
      } else if (value.copyToArray) {
        value.copyToArray(data, offset);
      } else {
        data[offset] = value;
      }
      offset += stride;
    }
    for (let instanceIndex = 0;instanceIndex < instanceCount; instanceIndex++) {
      const instance = visibleInstances[instanceIndex];
      const value = instance.instancedBuffers[kind];
      if (value.toArray) {
        value.toArray(data, offset);
      } else if (value.copyToArray) {
        value.copyToArray(data, offset);
      } else {
        data[offset] = value;
      }
      offset += stride;
    }
    if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) {
      this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);
      this._invalidateInstanceVertexArrayObject();
    } else {
      this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0);
    }
  }
};
Mesh.prototype._invalidateInstanceVertexArrayObject = function() {
  if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) {
    return;
  }
  for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) {
    this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]);
  }
  this._userInstancedBuffersStorage.vertexArrayObjects = {};
};
Mesh.prototype._disposeInstanceSpecificData = function() {
  if (this._instanceDataStorage.instancesBuffer) {
    this._instanceDataStorage.instancesBuffer.dispose();
    this._instanceDataStorage.instancesBuffer = null;
  }
  while (this.instances.length) {
    this.instances[0].dispose();
  }
  for (const kind in this.instancedBuffers) {
    if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {
      this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();
    }
  }
  this._invalidateInstanceVertexArrayObject();
  this.instancedBuffers = {};
};
RegisterClass("BABYLON.InstancedMesh", InstancedMesh);

// node_modules/@babylonjs/core/Lights/light.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_math_color();
init_node();
init_uniformBuffer();
init_typeStore();
init_lightConstants();
init_decorators_serialization();

class Light extends Node2 {
  get range() {
    return this._range;
  }
  set range(value) {
    this._range = value;
    this._inverseSquaredRange = 1 / (this.range * this.range);
  }
  get intensityMode() {
    return this._intensityMode;
  }
  set intensityMode(value) {
    this._intensityMode = value;
    this._computePhotometricScale();
  }
  get radius() {
    return this._radius;
  }
  set radius(value) {
    this._radius = value;
    this._computePhotometricScale();
  }
  get shadowEnabled() {
    return this._shadowEnabled;
  }
  set shadowEnabled(value) {
    if (this._shadowEnabled === value) {
      return;
    }
    this._shadowEnabled = value;
    this._markMeshesAsLightDirty();
  }
  get includedOnlyMeshes() {
    return this._includedOnlyMeshes;
  }
  set includedOnlyMeshes(value) {
    this._includedOnlyMeshes = value;
    this._hookArrayForIncludedOnly(value);
  }
  get excludedMeshes() {
    return this._excludedMeshes;
  }
  set excludedMeshes(value) {
    this._excludedMeshes = value;
    this._hookArrayForExcluded(value);
  }
  get excludeWithLayerMask() {
    return this._excludeWithLayerMask;
  }
  set excludeWithLayerMask(value) {
    this._excludeWithLayerMask = value;
    this._resyncMeshes();
  }
  get includeOnlyWithLayerMask() {
    return this._includeOnlyWithLayerMask;
  }
  set includeOnlyWithLayerMask(value) {
    this._includeOnlyWithLayerMask = value;
    this._resyncMeshes();
  }
  get lightmapMode() {
    return this._lightmapMode;
  }
  set lightmapMode(value) {
    if (this._lightmapMode === value) {
      return;
    }
    this._lightmapMode = value;
    this._markMeshesAsLightDirty();
  }
  getViewMatrix(_faceIndex) {
    return null;
  }
  getProjectionMatrix(_viewMatrix, _renderList) {
    return null;
  }
  constructor(name18, scene) {
    super(name18, scene, false);
    this.diffuse = new Color3(1, 1, 1);
    this.specular = new Color3(1, 1, 1);
    this.falloffType = Light.FALLOFF_DEFAULT;
    this.intensity = 1;
    this._range = Number.MAX_VALUE;
    this._inverseSquaredRange = 0;
    this._photometricScale = 1;
    this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
    this._radius = 0.00001;
    this.renderPriority = 0;
    this._shadowEnabled = true;
    this._excludeWithLayerMask = 0;
    this._includeOnlyWithLayerMask = 0;
    this._lightmapMode = 0;
    this._shadowGenerators = null;
    this._excludedMeshesIds = new Array;
    this._includedOnlyMeshesIds = new Array;
    this._isLight = true;
    this.getScene().addLight(this);
    this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name18);
    this._buildUniformLayout();
    this.includedOnlyMeshes = [];
    this.excludedMeshes = [];
    this._resyncMeshes();
  }
  transferTexturesToEffect(effect, lightIndex) {
    return this;
  }
  _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) {
    const iAsString = lightIndex.toString();
    let needUpdate = false;
    this._uniformBuffer.bindToEffect(effect, "Light" + iAsString);
    if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) {
      this._renderId = scene.getRenderId();
      this._lastUseSpecular = useSpecular;
      const scaledIntensity = this.getScaledIntensity();
      this.transferToEffect(effect, iAsString);
      this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);
      this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString);
      if (useSpecular) {
        this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);
        this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString);
      }
      needUpdate = true;
    }
    this.transferTexturesToEffect(effect, iAsString);
    if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) {
      const shadowGenerator = this.getShadowGenerator(scene.activeCamera) ?? this.getShadowGenerator();
      if (shadowGenerator) {
        shadowGenerator.bindShadowLight(iAsString, effect);
        needUpdate = true;
      }
    }
    if (needUpdate) {
      this._uniformBuffer.update();
    } else {
      this._uniformBuffer.bindUniformBuffer();
    }
  }
  getClassName() {
    return "Light";
  }
  toString(fullDetails) {
    let ret = "Name: " + this.name;
    ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()];
    if (this.animations) {
      for (let i = 0;i < this.animations.length; i++) {
        ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
      }
    }
    return ret;
  }
  _syncParentEnabledState() {
    super._syncParentEnabledState();
    if (!this.isDisposed()) {
      this._resyncMeshes();
    }
  }
  setEnabled(value) {
    super.setEnabled(value);
    this._resyncMeshes();
  }
  getShadowGenerator(camera = null) {
    if (this._shadowGenerators === null) {
      return null;
    }
    return this._shadowGenerators.get(camera) ?? null;
  }
  getShadowGenerators() {
    return this._shadowGenerators;
  }
  getAbsolutePosition() {
    return Vector3.Zero();
  }
  canAffectMesh(mesh) {
    if (!mesh) {
      return true;
    }
    if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
      return false;
    }
    if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
      return false;
    }
    if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
      return false;
    }
    if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
      return false;
    }
    return true;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    if (this._shadowGenerators) {
      const iterator = this._shadowGenerators.values();
      for (let key = iterator.next();key.done !== true; key = iterator.next()) {
        const shadowGenerator = key.value;
        shadowGenerator.dispose();
      }
      this._shadowGenerators = null;
    }
    this.getScene().stopAnimation(this);
    if (this._parentContainer) {
      const index = this._parentContainer.lights.indexOf(this);
      if (index > -1) {
        this._parentContainer.lights.splice(index, 1);
      }
      this._parentContainer = null;
    }
    for (const mesh of this.getScene().meshes) {
      mesh._removeLightSource(this, true);
    }
    this._uniformBuffer.dispose();
    this.getScene().removeLight(this);
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  getTypeID() {
    return 0;
  }
  getScaledIntensity() {
    return this._photometricScale * this.intensity;
  }
  clone(name18, newParent = null) {
    const constructor = Light.GetConstructorFromName(this.getTypeID(), name18, this.getScene());
    if (!constructor) {
      return null;
    }
    const clonedLight = SerializationHelper.Clone(constructor, this);
    if (name18) {
      clonedLight.name = name18;
    }
    if (newParent) {
      clonedLight.parent = newParent;
    }
    clonedLight.setEnabled(this.isEnabled());
    this.onClonedObservable.notifyObservers(clonedLight);
    return clonedLight;
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.type = this.getTypeID();
    if (this.parent) {
      this.parent._serializeAsParent(serializationObject);
    }
    if (this.excludedMeshes.length > 0) {
      serializationObject.excludedMeshesIds = [];
      this.excludedMeshes.forEach((mesh) => {
        serializationObject.excludedMeshesIds.push(mesh.id);
      });
    }
    if (this.includedOnlyMeshes.length > 0) {
      serializationObject.includedOnlyMeshesIds = [];
      this.includedOnlyMeshes.forEach((mesh) => {
        serializationObject.includedOnlyMeshesIds.push(mesh.id);
      });
    }
    SerializationHelper.AppendSerializedAnimations(this, serializationObject);
    serializationObject.ranges = this.serializeAnimationRanges();
    serializationObject.isEnabled = this.isEnabled();
    return serializationObject;
  }
  static GetConstructorFromName(type, name18, scene) {
    const constructorFunc = Node2.Construct("Light_Type_" + type, name18, scene);
    if (constructorFunc) {
      return constructorFunc;
    }
    return null;
  }
  static Parse(parsedLight, scene) {
    const constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
    if (!constructor) {
      return null;
    }
    const light = SerializationHelper.Parse(constructor, parsedLight, scene);
    if (parsedLight.excludedMeshesIds) {
      light._excludedMeshesIds = parsedLight.excludedMeshesIds;
    }
    if (parsedLight.includedOnlyMeshesIds) {
      light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
    }
    if (parsedLight.parentId !== undefined) {
      light._waitingParentId = parsedLight.parentId;
    }
    if (parsedLight.parentInstanceIndex !== undefined) {
      light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex;
    }
    if (parsedLight.falloffType !== undefined) {
      light.falloffType = parsedLight.falloffType;
    }
    if (parsedLight.lightmapMode !== undefined) {
      light.lightmapMode = parsedLight.lightmapMode;
    }
    if (parsedLight.animations) {
      for (let animationIndex = 0;animationIndex < parsedLight.animations.length; animationIndex++) {
        const parsedAnimation = parsedLight.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          light.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
      Node2.ParseAnimationRanges(light, parsedLight, scene);
    }
    if (parsedLight.autoAnimate) {
      scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1);
    }
    if (parsedLight.isEnabled !== undefined) {
      light.setEnabled(parsedLight.isEnabled);
    }
    return light;
  }
  _hookArrayForExcluded(array) {
    const oldPush = array.push;
    array.push = (...items) => {
      const result = oldPush.apply(array, items);
      for (const item of items) {
        item._resyncLightSource(this);
      }
      return result;
    };
    const oldSplice = array.splice;
    array.splice = (index, deleteCount) => {
      const deleted = oldSplice.apply(array, [index, deleteCount]);
      for (const item of deleted) {
        item._resyncLightSource(this);
      }
      return deleted;
    };
    for (const item of array) {
      item._resyncLightSource(this);
    }
  }
  _hookArrayForIncludedOnly(array) {
    const oldPush = array.push;
    array.push = (...items) => {
      const result = oldPush.apply(array, items);
      this._resyncMeshes();
      return result;
    };
    const oldSplice = array.splice;
    array.splice = (index, deleteCount) => {
      const deleted = oldSplice.apply(array, [index, deleteCount]);
      this._resyncMeshes();
      return deleted;
    };
    this._resyncMeshes();
  }
  _resyncMeshes() {
    for (const mesh of this.getScene().meshes) {
      mesh._resyncLightSource(this);
    }
  }
  _markMeshesAsLightDirty() {
    for (const mesh of this.getScene().meshes) {
      if (mesh.lightSources.indexOf(this) !== -1) {
        mesh._markSubMeshesAsLightDirty();
      }
    }
  }
  _computePhotometricScale() {
    this._photometricScale = this._getPhotometricScale();
    this.getScene().resetCachedMaterial();
  }
  _getPhotometricScale() {
    let photometricScale = 0;
    const lightTypeID = this.getTypeID();
    let photometricMode = this.intensityMode;
    if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
      if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
        photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
      } else {
        photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
      }
    }
    switch (lightTypeID) {
      case Light.LIGHTTYPEID_POINTLIGHT:
      case Light.LIGHTTYPEID_SPOTLIGHT:
        switch (photometricMode) {
          case Light.INTENSITYMODE_LUMINOUSPOWER:
            photometricScale = 1 / (4 * Math.PI);
            break;
          case Light.INTENSITYMODE_LUMINOUSINTENSITY:
            photometricScale = 1;
            break;
          case Light.INTENSITYMODE_LUMINANCE:
            photometricScale = this.radius * this.radius;
            break;
        }
        break;
      case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
        switch (photometricMode) {
          case Light.INTENSITYMODE_ILLUMINANCE:
            photometricScale = 1;
            break;
          case Light.INTENSITYMODE_LUMINANCE: {
            let apexAngleRadians = this.radius;
            apexAngleRadians = Math.max(apexAngleRadians, 0.001);
            const solidAngle = 2 * Math.PI * (1 - Math.cos(apexAngleRadians));
            photometricScale = solidAngle;
            break;
          }
        }
        break;
      case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
        photometricScale = 1;
        break;
    }
    return photometricScale;
  }
  _reorderLightsInScene() {
    const scene = this.getScene();
    if (this._renderPriority != 0) {
      scene.requireLightSorting = true;
    }
    this.getScene().sortLightsByPriority();
  }
  _isReady() {
    return true;
  }
}
Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT;
Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL;
Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF;
Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD;
Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT;
Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR;
Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY;
Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC;
Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER;
Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY;
Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE;
Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE;
Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT;
Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT;
Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT;
Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT;
Light.LIGHTTYPEID_RECT_AREALIGHT = LightConstants.LIGHTTYPEID_RECT_AREALIGHT;
__decorate([
  serializeAsColor3()
], Light.prototype, "diffuse", undefined);
__decorate([
  serializeAsColor3()
], Light.prototype, "specular", undefined);
__decorate([
  serialize()
], Light.prototype, "falloffType", undefined);
__decorate([
  serialize()
], Light.prototype, "intensity", undefined);
__decorate([
  serialize()
], Light.prototype, "range", null);
__decorate([
  serialize()
], Light.prototype, "intensityMode", null);
__decorate([
  serialize()
], Light.prototype, "radius", null);
__decorate([
  serialize()
], Light.prototype, "_renderPriority", undefined);
__decorate([
  expandToProperty("_reorderLightsInScene")
], Light.prototype, "renderPriority", undefined);
__decorate([
  serialize("shadowEnabled")
], Light.prototype, "_shadowEnabled", undefined);
__decorate([
  serialize("excludeWithLayerMask")
], Light.prototype, "_excludeWithLayerMask", undefined);
__decorate([
  serialize("includeOnlyWithLayerMask")
], Light.prototype, "_includeOnlyWithLayerMask", undefined);
__decorate([
  serialize("lightmapMode")
], Light.prototype, "_lightmapMode", undefined);

// node_modules/@babylonjs/core/assetContainer.js
init_tools();
init_tags();

class AbstractAssetContainer {
  constructor() {
    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.sounds = null;
    this.effectLayers = [];
    this.layers = [];
    this.reflectionProbes = [];
  }
  get environmentTexture() {
    return this._environmentTexture;
  }
  set environmentTexture(value) {
    this._environmentTexture = value;
  }
  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;
  }
}

class KeepAssets extends AbstractAssetContainer {
}

class InstantiatedEntries {
  constructor() {
    this.rootNodes = [];
    this.skeletons = [];
    this.animationGroups = [];
  }
  dispose() {
    this.rootNodes.slice(0).forEach((o) => {
      o.dispose();
    });
    this.rootNodes.length = 0;
    this.skeletons.slice(0).forEach((o) => {
      o.dispose();
    });
    this.skeletons.length = 0;
    this.animationGroups.slice(0).forEach((o) => {
      o.dispose();
    });
    this.animationGroups.length = 0;
  }
}

class AssetContainer extends AbstractAssetContainer {
  constructor(scene) {
    super();
    this._wasAddedToScene = false;
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this.scene = scene;
    this["proceduralTextures"] = [];
    scene.onDisposeObservable.add(() => {
      if (!this._wasAddedToScene) {
        this.dispose();
      }
    });
    this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => {
      for (const geometry of this.geometries) {
        geometry._rebuild();
      }
      for (const mesh of this.meshes) {
        mesh._rebuild();
      }
      for (const system of this.particleSystems) {
        system.rebuild();
      }
      for (const texture of this.textures) {
        texture._rebuild();
      }
    });
  }
  _topologicalSort(nodes) {
    const nodesUidMap = new Map;
    for (const node of nodes) {
      nodesUidMap.set(node.uniqueId, node);
    }
    const dependencyGraph = {
      dependsOn: new Map,
      dependedBy: new Map
    };
    for (const node of nodes) {
      const nodeId = node.uniqueId;
      dependencyGraph.dependsOn.set(nodeId, new Set);
      dependencyGraph.dependedBy.set(nodeId, new Set);
    }
    for (const node of nodes) {
      const nodeId = node.uniqueId;
      const dependsOn = dependencyGraph.dependsOn.get(nodeId);
      if (node instanceof InstancedMesh) {
        const masterMesh = node.sourceMesh;
        if (nodesUidMap.has(masterMesh.uniqueId)) {
          dependsOn.add(masterMesh.uniqueId);
          dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId);
        }
      }
      const dependedBy = dependencyGraph.dependedBy.get(nodeId);
      for (const child of node.getDescendants()) {
        const childId = child.uniqueId;
        if (nodesUidMap.has(childId)) {
          dependedBy.add(childId);
          const childDependsOn = dependencyGraph.dependsOn.get(childId);
          childDependsOn.add(nodeId);
        }
      }
    }
    const sortedNodes = [];
    const leaves = [];
    for (const node of nodes) {
      const nodeId = node.uniqueId;
      if (dependencyGraph.dependsOn.get(nodeId).size === 0) {
        leaves.push(node);
        nodesUidMap.delete(nodeId);
      }
    }
    const visitList = leaves;
    while (visitList.length > 0) {
      const nodeToVisit = visitList.shift();
      sortedNodes.push(nodeToVisit);
      const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId);
      for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) {
        const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId);
        dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId);
        if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) {
          visitList.push(nodesUidMap.get(dependedByVisitedNodeId));
          nodesUidMap.delete(dependedByVisitedNodeId);
        }
      }
    }
    if (nodesUidMap.size > 0) {
      Logger.Error("SceneSerializer._topologicalSort: There were unvisited nodes:");
      nodesUidMap.forEach((node) => Logger.Error(node.name));
    }
    return sortedNodes;
  }
  _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) {
    if (!rootNode || predicate && !predicate(rootNode) || addedIds.has(rootNode.uniqueId)) {
      return;
    }
    list.push(rootNode);
    addedIds.add(rootNode.uniqueId);
    for (const child of rootNode.getDescendants(true)) {
      this._addNodeAndDescendantsToList(list, addedIds, child, predicate);
    }
  }
  _isNodeInContainer(node) {
    if (node instanceof AbstractMesh && this.meshes.indexOf(node) !== -1) {
      return true;
    }
    if (node instanceof TransformNode && this.transformNodes.indexOf(node) !== -1) {
      return true;
    }
    if (node instanceof Light && this.lights.indexOf(node) !== -1) {
      return true;
    }
    if (node instanceof Camera && this.cameras.indexOf(node) !== -1) {
      return true;
    }
    return false;
  }
  _isValidHierarchy() {
    for (const node of this.meshes) {
      if (node.parent && !this._isNodeInContainer(node.parent)) {
        Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
        return false;
      }
    }
    for (const node of this.transformNodes) {
      if (node.parent && !this._isNodeInContainer(node.parent)) {
        Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
        return false;
      }
    }
    for (const node of this.lights) {
      if (node.parent && !this._isNodeInContainer(node.parent)) {
        Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
        return false;
      }
    }
    for (const node of this.cameras) {
      if (node.parent && !this._isNodeInContainer(node.parent)) {
        Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);
        return false;
      }
    }
    return true;
  }
  instantiateModelsToScene(nameFunction, cloneMaterials = false, options) {
    if (!this._isValidHierarchy()) {
      Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");
    }
    const conversionMap = {};
    const storeMap = {};
    const result = new InstantiatedEntries;
    const alreadySwappedSkeletons = [];
    const alreadySwappedMaterials = [];
    const localOptions = {
      doNotInstantiate: true,
      ...options
    };
    const onClone = (source, clone) => {
      conversionMap[source.uniqueId] = clone.uniqueId;
      storeMap[clone.uniqueId] = clone;
      if (nameFunction) {
        clone.name = nameFunction(source.name);
      }
      if (clone instanceof Mesh) {
        const clonedMesh = clone;
        if (clonedMesh.morphTargetManager) {
          const oldMorphTargetManager = source.morphTargetManager;
          clonedMesh.morphTargetManager = oldMorphTargetManager.clone();
          for (let index = 0;index < oldMorphTargetManager.numTargets; index++) {
            const oldTarget = oldMorphTargetManager.getTarget(index);
            const newTarget = clonedMesh.morphTargetManager.getTarget(index);
            conversionMap[oldTarget.uniqueId] = newTarget.uniqueId;
            storeMap[newTarget.uniqueId] = newTarget;
          }
        }
      }
    };
    const nodesToSort = [];
    const idsOnSortList = new Set;
    for (const transformNode of this.transformNodes) {
      if (transformNode.parent === null) {
        this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate);
      }
    }
    for (const mesh of this.meshes) {
      if (mesh.parent === null) {
        this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate);
      }
    }
    const sortedNodes = this._topologicalSort(nodesToSort);
    const onNewCreated = (source, clone) => {
      onClone(source, clone);
      if (source.parent) {
        const replicatedParentId = conversionMap[source.parent.uniqueId];
        const replicatedParent = storeMap[replicatedParentId];
        if (replicatedParent) {
          clone.parent = replicatedParent;
        } else {
          clone.parent = source.parent;
        }
      }
      if (clone.position && source.position) {
        clone.position.copyFrom(source.position);
      }
      if (clone.rotationQuaternion && source.rotationQuaternion) {
        clone.rotationQuaternion.copyFrom(source.rotationQuaternion);
      }
      if (clone.rotation && source.rotation) {
        clone.rotation.copyFrom(source.rotation);
      }
      if (clone.scaling && source.scaling) {
        clone.scaling.copyFrom(source.scaling);
      }
      if (clone.material) {
        const mesh = clone;
        if (mesh.material) {
          if (cloneMaterials) {
            const sourceMaterial = source.material;
            if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) {
              let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : "Clone of " + sourceMaterial.name);
              alreadySwappedMaterials.push(sourceMaterial);
              conversionMap[sourceMaterial.uniqueId] = swap.uniqueId;
              storeMap[swap.uniqueId] = swap;
              if (sourceMaterial.getClassName() === "MultiMaterial") {
                const multi = sourceMaterial;
                for (const material of multi.subMaterials) {
                  if (!material) {
                    continue;
                  }
                  swap = material.clone(nameFunction ? nameFunction(material.name) : "Clone of " + material.name);
                  alreadySwappedMaterials.push(material);
                  conversionMap[material.uniqueId] = swap.uniqueId;
                  storeMap[swap.uniqueId] = swap;
                }
                multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]);
              }
            }
            if (mesh.getClassName() !== "InstancedMesh") {
              mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]];
            }
          } else {
            if (mesh.material.getClassName() === "MultiMaterial") {
              if (this.scene.multiMaterials.indexOf(mesh.material) === -1) {
                this.scene.addMultiMaterial(mesh.material);
              }
            } else {
              if (this.scene.materials.indexOf(mesh.material) === -1) {
                this.scene.addMaterial(mesh.material);
              }
            }
          }
        }
      }
      if (clone.parent === null) {
        result.rootNodes.push(clone);
      }
    };
    sortedNodes.forEach((node) => {
      if (node.getClassName() === "InstancedMesh") {
        const instancedNode = node;
        const sourceMesh = instancedNode.sourceMesh;
        const replicatedSourceId = conversionMap[sourceMesh.uniqueId];
        const replicatedSource = typeof replicatedSourceId === "number" ? storeMap[replicatedSourceId] : sourceMesh;
        const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name);
        onNewCreated(instancedNode, replicatedInstancedNode);
      } else {
        let canInstance = true;
        if (node.getClassName() === "TransformNode" || node.getClassName() === "Node" || node.skeleton || !node.getTotalVertices || node.getTotalVertices() === 0) {
          canInstance = false;
        } else if (localOptions.doNotInstantiate) {
          if (typeof localOptions.doNotInstantiate === "function") {
            canInstance = !localOptions.doNotInstantiate(node);
          } else {
            canInstance = !localOptions.doNotInstantiate;
          }
        }
        const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true);
        if (!replicatedNode) {
          throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`);
        }
        onNewCreated(node, replicatedNode);
      }
    });
    this.skeletons.forEach((s) => {
      if (localOptions.predicate && !localOptions.predicate(s)) {
        return;
      }
      const clone = s.clone(nameFunction ? nameFunction(s.name) : "Clone of " + s.name);
      for (const m of this.meshes) {
        if (m.skeleton === s && !m.isAnInstance) {
          const copy = storeMap[conversionMap[m.uniqueId]];
          if (!copy || copy.isAnInstance) {
            continue;
          }
          copy.skeleton = clone;
          if (alreadySwappedSkeletons.indexOf(clone) !== -1) {
            continue;
          }
          alreadySwappedSkeletons.push(clone);
          for (const bone of clone.bones) {
            if (bone._linkedTransformNode) {
              bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]];
            }
          }
        }
      }
      result.skeletons.push(clone);
    });
    this.animationGroups.forEach((o) => {
      if (localOptions.predicate && !localOptions.predicate(o)) {
        return;
      }
      const clone = o.clone(nameFunction ? nameFunction(o.name) : "Clone of " + o.name, (oldTarget) => {
        const newTarget = storeMap[conversionMap[oldTarget.uniqueId]];
        return newTarget || oldTarget;
      });
      result.animationGroups.push(clone);
    });
    return result;
  }
  addAllToScene() {
    if (this._wasAddedToScene) {
      return;
    }
    if (!this._isValidHierarchy()) {
      Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid.");
    }
    this._wasAddedToScene = true;
    this.addToScene(null);
    if (this.environmentTexture) {
      this.scene.environmentTexture = this.environmentTexture;
    }
    for (const component of this.scene._serializableComponents) {
      component.addFromContainer(this);
    }
    this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
    this._onContextRestoredObserver = null;
  }
  addToScene(predicate = null) {
    const addedNodes = [];
    this.cameras.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addCamera(o);
      addedNodes.push(o);
    });
    this.lights.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addLight(o);
      addedNodes.push(o);
    });
    this.meshes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addMesh(o);
      addedNodes.push(o);
    });
    this.skeletons.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addSkeleton(o);
    });
    this.animations.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addAnimation(o);
    });
    this.animationGroups.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addAnimationGroup(o);
    });
    this.multiMaterials.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addMultiMaterial(o);
    });
    this.materials.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addMaterial(o);
    });
    this.morphTargetManagers.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addMorphTargetManager(o);
    });
    this.geometries.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addGeometry(o);
    });
    this.transformNodes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addTransformNode(o);
      addedNodes.push(o);
    });
    this.actionManagers.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addActionManager(o);
    });
    this.textures.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addTexture(o);
    });
    this.reflectionProbes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.addReflectionProbe(o);
    });
    for (const addedNode of addedNodes) {
      if (addedNode.parent && this.scene.getNodes().indexOf(addedNode.parent) === -1) {
        if (addedNode.setParent) {
          addedNode.setParent(null);
        } else {
          addedNode.parent = null;
        }
      }
    }
  }
  removeAllFromScene() {
    if (!this._isValidHierarchy()) {
      Tools.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid.");
    }
    this._wasAddedToScene = false;
    this.removeFromScene(null);
    if (this.environmentTexture === this.scene.environmentTexture) {
      this.scene.environmentTexture = null;
    }
    for (const component of this.scene._serializableComponents) {
      component.removeFromContainer(this);
    }
  }
  removeFromScene(predicate = null) {
    this.cameras.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeCamera(o);
    });
    this.lights.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeLight(o);
    });
    this.meshes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeMesh(o, true);
    });
    this.skeletons.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeSkeleton(o);
    });
    this.animations.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeAnimation(o);
    });
    this.animationGroups.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeAnimationGroup(o);
    });
    this.multiMaterials.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeMultiMaterial(o);
    });
    this.materials.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeMaterial(o);
    });
    this.morphTargetManagers.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeMorphTargetManager(o);
    });
    this.geometries.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeGeometry(o);
    });
    this.transformNodes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeTransformNode(o);
    });
    this.actionManagers.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeActionManager(o);
    });
    this.textures.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeTexture(o);
    });
    this.reflectionProbes.forEach((o) => {
      if (predicate && !predicate(o)) {
        return;
      }
      this.scene.removeReflectionProbe(o);
    });
  }
  dispose() {
    this.cameras.slice(0).forEach((o) => {
      o.dispose();
    });
    this.cameras.length = 0;
    this.lights.slice(0).forEach((o) => {
      o.dispose();
    });
    this.lights.length = 0;
    this.meshes.slice(0).forEach((o) => {
      o.dispose();
    });
    this.meshes.length = 0;
    this.skeletons.slice(0).forEach((o) => {
      o.dispose();
    });
    this.skeletons.length = 0;
    this.animationGroups.slice(0).forEach((o) => {
      o.dispose();
    });
    this.animationGroups.length = 0;
    this.multiMaterials.slice(0).forEach((o) => {
      o.dispose();
    });
    this.multiMaterials.length = 0;
    this.materials.slice(0).forEach((o) => {
      o.dispose();
    });
    this.materials.length = 0;
    this.geometries.slice(0).forEach((o) => {
      o.dispose();
    });
    this.geometries.length = 0;
    this.transformNodes.slice(0).forEach((o) => {
      o.dispose();
    });
    this.transformNodes.length = 0;
    this.actionManagers.slice(0).forEach((o) => {
      o.dispose();
    });
    this.actionManagers.length = 0;
    this.textures.slice(0).forEach((o) => {
      o.dispose();
    });
    this.textures.length = 0;
    this.reflectionProbes.slice(0).forEach((o) => {
      o.dispose();
    });
    this.reflectionProbes.length = 0;
    this.morphTargetManagers.slice(0).forEach((o) => {
      o.dispose();
    });
    this.morphTargetManagers.length = 0;
    if (this.environmentTexture) {
      this.environmentTexture.dispose();
      this.environmentTexture = null;
    }
    for (const component of this.scene._serializableComponents) {
      component.removeFromContainer(this, true);
    }
    if (this._onContextRestoredObserver) {
      this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
      this._onContextRestoredObserver = null;
    }
  }
  _moveAssets(sourceAssets, targetAssets, keepAssets) {
    if (!sourceAssets || !targetAssets) {
      return;
    }
    for (const asset of sourceAssets) {
      let move = true;
      if (keepAssets) {
        for (const keepAsset of keepAssets) {
          if (asset === keepAsset) {
            move = false;
            break;
          }
        }
      }
      if (move) {
        targetAssets.push(asset);
        asset._parentContainer = this;
      }
    }
  }
  moveAllFromScene(keepAssets) {
    this._wasAddedToScene = false;
    if (keepAssets === undefined) {
      keepAssets = new KeepAssets;
    }
    for (const key in this) {
      if (Object.prototype.hasOwnProperty.call(this, key)) {
        this[key] = this[key] || (key === "_environmentTexture" ? null : []);
        this._moveAssets(this.scene[key], this[key], keepAssets[key]);
      }
    }
    this.environmentTexture = this.scene.environmentTexture;
    this.removeAllFromScene();
  }
  createRootMesh() {
    const rootMesh = new Mesh("assetContainerRootMesh", this.scene);
    this.meshes.forEach((m) => {
      if (!m.parent) {
        rootMesh.addChild(m);
      }
    });
    this.meshes.unshift(rootMesh);
    return rootMesh;
  }
  mergeAnimationsTo(scene = EngineStore.LastCreatedScene, animatables, targetConverter = null) {
    if (!scene) {
      Logger.Error("No scene available to merge animations to");
      return [];
    }
    const _targetConverter = targetConverter ? targetConverter : (target) => {
      let node = null;
      const targetProperty = target.animations.length ? target.animations[0].targetProperty : "";
      const name18 = target.name.split(".").join("").split("_primitive")[0];
      switch (targetProperty) {
        case "position":
        case "rotationQuaternion":
          node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name18);
          break;
        case "influence":
          node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name18);
          break;
        default:
          node = scene.getNodeByName(target.name) || scene.getNodeByName(name18);
      }
      return node;
    };
    const nodesInAC = this.getNodes();
    nodesInAC.forEach((nodeInAC) => {
      const nodeInScene = _targetConverter(nodeInAC);
      if (nodeInScene !== null) {
        for (const animationInAC of nodeInAC.animations) {
          const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => {
            return animationInScene.targetProperty === animationInAC.targetProperty;
          });
          for (const animationWithSameProperty of animationsWithSameProperty) {
            const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0);
            if (index > -1) {
              nodeInScene.animations.splice(index, 1);
            }
          }
        }
        nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations);
      }
    });
    const newAnimationGroups = [];
    this.animationGroups.slice().forEach((animationGroupInAC) => {
      newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter));
      animationGroupInAC.animatables.forEach((animatable2) => {
        animatable2.stop();
      });
    });
    animatables.forEach((animatable2) => {
      const target = _targetConverter(animatable2.target);
      if (target) {
        scene.beginAnimation(target, animatable2.fromFrame, animatable2.toFrame, animatable2.loopAnimation, animatable2.speedRatio, animatable2.onAnimationEnd ? animatable2.onAnimationEnd : undefined, undefined, true, undefined, animatable2.onAnimationLoop ? animatable2.onAnimationLoop : undefined);
        scene.stopAnimation(animatable2.target);
      }
    });
    return newAnimationGroups;
  }
  populateRootNodes() {
    this.rootNodes.length = 0;
    this.meshes.forEach((m) => {
      if (!m.parent && this.rootNodes.indexOf(m) === -1) {
        this.rootNodes.push(m);
      }
    });
    this.transformNodes.forEach((t) => {
      if (!t.parent && this.rootNodes.indexOf(t) === -1) {
        this.rootNodes.push(t);
      }
    });
    this.lights.forEach((l) => {
      if (!l.parent && this.rootNodes.indexOf(l) === -1) {
        this.rootNodes.push(l);
      }
    });
    this.cameras.forEach((c) => {
      if (!c.parent && this.rootNodes.indexOf(c) === -1) {
        this.rootNodes.push(c);
      }
    });
  }
  addAllAssetsToContainer(root) {
    if (!root) {
      return;
    }
    const nodesToVisit = [];
    const visitedNodes = new Set;
    nodesToVisit.push(root);
    while (nodesToVisit.length > 0) {
      const nodeToVisit = nodesToVisit.pop();
      if (nodeToVisit instanceof Mesh) {
        if (nodeToVisit.geometry && this.geometries.indexOf(nodeToVisit.geometry) === -1) {
          this.geometries.push(nodeToVisit.geometry);
        }
        this.meshes.push(nodeToVisit);
      } else if (nodeToVisit instanceof TransformNode) {
        this.transformNodes.push(nodeToVisit);
      } else if (nodeToVisit instanceof Light) {
        this.lights.push(nodeToVisit);
      } else if (nodeToVisit instanceof Camera) {
        this.cameras.push(nodeToVisit);
      }
      if (nodeToVisit instanceof AbstractMesh) {
        if (nodeToVisit.material && this.materials.indexOf(nodeToVisit.material) === -1) {
          this.materials.push(nodeToVisit.material);
          for (const texture of nodeToVisit.material.getActiveTextures()) {
            if (this.textures.indexOf(texture) === -1) {
              this.textures.push(texture);
            }
          }
        }
        if (nodeToVisit.skeleton && this.skeletons.indexOf(nodeToVisit.skeleton) === -1) {
          this.skeletons.push(nodeToVisit.skeleton);
        }
        if (nodeToVisit.morphTargetManager && this.morphTargetManagers.indexOf(nodeToVisit.morphTargetManager) === -1) {
          this.morphTargetManagers.push(nodeToVisit.morphTargetManager);
        }
      }
      for (const child of nodeToVisit.getChildren()) {
        if (!visitedNodes.has(child)) {
          nodesToVisit.push(child);
        }
      }
      visitedNodes.add(nodeToVisit);
    }
    this.populateRootNodes();
  }
  _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);
  }
  getMaterialsByTags(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);
  }
}
// node_modules/@babylonjs/core/Audio/analyser.js
init_tools();
init_engineStore();
init_abstractEngine();
// node_modules/@babylonjs/core/Audio/audioEngine.js
init_observable();
init_logger();
init_abstractEngine();
init_domManagement();
AbstractEngine.AudioEngineFactory = (hostElement, audioContext, audioDestination) => {
  return new AudioEngine(hostElement, audioContext, audioDestination);
};

class AudioEngine {
  get audioContext() {
    if (!this._audioContextInitialized) {
      this._initializeAudioContext();
    }
    return this._audioContext;
  }
  constructor(hostElement = null, audioContext = null, audioDestination = null) {
    this._audioContext = null;
    this._audioContextInitialized = false;
    this._muteButton = null;
    this._audioDestination = null;
    this.canUseWebAudio = false;
    this.WarnedWebAudioUnsupported = false;
    this.isMP3supported = false;
    this.isOGGsupported = false;
    this.unlocked = false;
    this.useCustomUnlockedButton = false;
    this.onAudioUnlockedObservable = new Observable;
    this.onAudioLockedObservable = new Observable;
    this._tryToRun = false;
    this._onResize = () => {
      this._moveButtonToTopLeft();
    };
    if (!IsWindowObjectExist()) {
      return;
    }
    if (typeof window.AudioContext !== "undefined") {
      this.canUseWebAudio = true;
    }
    const audioElem = document.createElement("audio");
    this._hostElement = hostElement;
    this._audioContext = audioContext;
    this._audioDestination = audioDestination;
    try {
      if (audioElem && !!audioElem.canPlayType && (audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "") || audioElem.canPlayType("audio/mp3").replace(/^no$/, ""))) {
        this.isMP3supported = true;
      }
    } catch (e) {}
    try {
      if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "")) {
        this.isOGGsupported = true;
      }
    } catch (e) {}
  }
  lock() {
    this._triggerSuspendedState();
  }
  unlock() {
    if (this._audioContext?.state === "running") {
      this._hideMuteButton();
      if (!this.unlocked) {
        this.unlocked = true;
        this.onAudioUnlockedObservable.notifyObservers(this);
      }
      return;
    }
    if (this._tryToRun) {
      this._audioContext?.suspend().then(() => {
        this._tryToRun = false;
        this._triggerRunningState();
      });
    } else {
      this._triggerRunningState();
    }
  }
  _resumeAudioContextOnStateChange() {
    this._audioContext?.addEventListener("statechange", () => {
      if (this.unlocked && this._audioContext?.state !== "running") {
        this._resumeAudioContext();
      }
    }, {
      once: true,
      passive: true,
      signal: AbortSignal.timeout(3000)
    });
  }
  _resumeAudioContext() {
    if (this._audioContext?.resume) {
      return this._audioContext.resume();
    }
    return Promise.resolve();
  }
  _initializeAudioContext() {
    try {
      if (this.canUseWebAudio) {
        if (!this._audioContext) {
          this._audioContext = new AudioContext;
        }
        this.masterGain = this._audioContext.createGain();
        this.masterGain.gain.value = 1;
        if (!this._audioDestination) {
          this._audioDestination = this._audioContext.destination;
        }
        this.masterGain.connect(this._audioDestination);
        this._audioContextInitialized = true;
        if (this._audioContext.state === "running") {
          this._triggerRunningState();
        }
      }
    } catch (e) {
      this.canUseWebAudio = false;
      Logger.Error("Web Audio: " + e.message);
    }
  }
  _triggerRunningState() {
    if (this._tryToRun) {
      return;
    }
    this._tryToRun = true;
    this._resumeAudioContext().then(() => {
      this._tryToRun = false;
      if (this._muteButton) {
        this._hideMuteButton();
      }
      this.unlocked = true;
      this.onAudioUnlockedObservable.notifyObservers(this);
    }).catch(() => {
      this._tryToRun = false;
      this.unlocked = false;
    });
  }
  _triggerSuspendedState() {
    this.unlocked = false;
    this.onAudioLockedObservable.notifyObservers(this);
    this._displayMuteButton();
  }
  _displayMuteButton() {
    if (this.useCustomUnlockedButton || this._muteButton) {
      return;
    }
    this._muteButton = document.createElement("BUTTON");
    this._muteButton.className = "babylonUnmuteIcon";
    this._muteButton.id = "babylonUnmuteIconBtn";
    this._muteButton.title = "Unmute";
    const imageUrl = !window.SVGSVGElement ? "https://cdn.babylonjs.com/Assets/audio.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";
    const css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + imageUrl + ");  background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
    const style = document.createElement("style");
    style.appendChild(document.createTextNode(css));
    document.getElementsByTagName("head")[0].appendChild(style);
    document.body.appendChild(this._muteButton);
    this._moveButtonToTopLeft();
    this._muteButton.addEventListener("touchend", () => {
      this._triggerRunningState();
    }, true);
    this._muteButton.addEventListener("click", () => {
      this.unlock();
    }, true);
    window.addEventListener("resize", this._onResize);
  }
  _moveButtonToTopLeft() {
    if (this._hostElement && this._muteButton) {
      this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
      this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
    }
  }
  _hideMuteButton() {
    if (this._muteButton) {
      document.body.removeChild(this._muteButton);
      this._muteButton = null;
    }
  }
  dispose() {
    if (this.canUseWebAudio && this._audioContextInitialized) {
      if (this._connectedAnalyser && this._audioContext) {
        this._connectedAnalyser.stopDebugCanvas();
        this._connectedAnalyser.dispose();
        this.masterGain.disconnect();
        this.masterGain.connect(this._audioContext.destination);
        this._connectedAnalyser = null;
      }
      this.masterGain.gain.value = 1;
    }
    this.WarnedWebAudioUnsupported = false;
    this._hideMuteButton();
    window.removeEventListener("resize", this._onResize);
    this.onAudioUnlockedObservable.clear();
    this.onAudioLockedObservable.clear();
  }
  getGlobalVolume() {
    if (this.canUseWebAudio && this._audioContextInitialized) {
      return this.masterGain.gain.value;
    } else {
      return -1;
    }
  }
  setGlobalVolume(newVolume) {
    if (this.canUseWebAudio && this._audioContextInitialized) {
      this.masterGain.gain.value = newVolume;
    }
  }
  connectToAnalyser(analyser) {
    if (this._connectedAnalyser) {
      this._connectedAnalyser.stopDebugCanvas();
    }
    if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
      this._connectedAnalyser = analyser;
      this.masterGain.disconnect();
      this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
    }
  }
}
// node_modules/@babylonjs/core/Audio/sound.js
init_tools();
init_observable();
init_math_vector();
init_logger();
init_devTools();
init_engineStore();
init_typeStore();
init_abstractEngine();
init_timingTools();

class Sound {
  get loop() {
    return this._loop;
  }
  set loop(value) {
    if (value === this._loop) {
      return;
    }
    this._loop = value;
    this.updateOptions({ loop: value });
  }
  get currentTime() {
    if (this._htmlAudioElement) {
      return this._htmlAudioElement.currentTime;
    }
    if (AbstractEngine.audioEngine?.audioContext && (this.isPlaying || this.isPaused)) {
      const timeSinceLastStart = this.isPaused ? 0 : AbstractEngine.audioEngine.audioContext.currentTime - this._startTime;
      return this._currentTime + timeSinceLastStart;
    }
    return 0;
  }
  get spatialSound() {
    return this._spatialSound;
  }
  set spatialSound(newValue) {
    if (newValue == this._spatialSound) {
      return;
    }
    const wasPlaying = this.isPlaying;
    this.pause();
    if (newValue) {
      this._spatialSound = newValue;
      this._updateSpatialParameters();
    } else {
      this._disableSpatialSound();
    }
    if (wasPlaying) {
      this.play();
    }
  }
  constructor(name18, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) {
    this.autoplay = false;
    this._loop = false;
    this.useCustomAttenuation = false;
    this.isPlaying = false;
    this.isPaused = false;
    this.refDistance = 1;
    this.rolloffFactor = 1;
    this.maxDistance = 100;
    this.distanceModel = "linear";
    this.metadata = null;
    this.onEndedObservable = new Observable;
    this._spatialSound = false;
    this._panningModel = "equalpower";
    this._playbackRate = 1;
    this._streaming = false;
    this._startTime = 0;
    this._currentTime = 0;
    this._position = Vector3.Zero();
    this._localDirection = new Vector3(1, 0, 0);
    this._volume = 1;
    this._isReadyToPlay = false;
    this._isDirectional = false;
    this._coneInnerAngle = 360;
    this._coneOuterAngle = 360;
    this._coneOuterGain = 0;
    this._isOutputConnected = false;
    this._urlType = "Unknown";
    this.name = name18;
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this._scene = scene;
    Sound._SceneComponentInitialization(scene);
    this._readyToPlayCallback = readyToPlayCallback;
    this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => {
      if (currentDistance < maxDistance) {
        return currentVolume * (1 - currentDistance / maxDistance);
      } else {
        return 0;
      }
    };
    if (options) {
      this.autoplay = options.autoplay || false;
      this._loop = options.loop || false;
      if (options.volume !== undefined) {
        this._volume = options.volume;
      }
      this._spatialSound = options.spatialSound ?? false;
      this.maxDistance = options.maxDistance ?? 100;
      this.useCustomAttenuation = options.useCustomAttenuation ?? false;
      this.rolloffFactor = options.rolloffFactor || 1;
      this.refDistance = options.refDistance || 1;
      this.distanceModel = options.distanceModel || "linear";
      this._playbackRate = options.playbackRate || 1;
      this._streaming = options.streaming ?? false;
      this._length = options.length;
      this._offset = options.offset;
    }
    if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) {
      this._soundGain = AbstractEngine.audioEngine.audioContext.createGain();
      this._soundGain.gain.value = this._volume;
      this._inputAudioNode = this._soundGain;
      this._outputAudioNode = this._soundGain;
      if (this._spatialSound) {
        this._createSpatialParameters();
      }
      this._scene.mainSoundTrack.addSound(this);
      let validParameter = true;
      if (urlOrArrayBuffer) {
        try {
          if (typeof urlOrArrayBuffer === "string") {
            this._urlType = "String";
            this._url = urlOrArrayBuffer;
          } else if (urlOrArrayBuffer instanceof ArrayBuffer) {
            this._urlType = "ArrayBuffer";
          } else if (urlOrArrayBuffer instanceof HTMLMediaElement) {
            this._urlType = "MediaElement";
          } else if (urlOrArrayBuffer instanceof MediaStream) {
            this._urlType = "MediaStream";
          } else if (urlOrArrayBuffer instanceof AudioBuffer) {
            this._urlType = "AudioBuffer";
          } else if (Array.isArray(urlOrArrayBuffer)) {
            this._urlType = "Array";
          }
          let urls = [];
          let codecSupportedFound = false;
          switch (this._urlType) {
            case "MediaElement":
              this._streaming = true;
              this._isReadyToPlay = true;
              this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
              if (this.autoplay) {
                this.play(0, this._offset, this._length);
              }
              if (this._readyToPlayCallback) {
                this._readyToPlayCallback();
              }
              break;
            case "MediaStream":
              this._streaming = true;
              this._isReadyToPlay = true;
              this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
              if (this.autoplay) {
                this.play(0, this._offset, this._length);
              }
              if (this._readyToPlayCallback) {
                this._readyToPlayCallback();
              }
              break;
            case "ArrayBuffer":
              if (urlOrArrayBuffer.byteLength > 0) {
                codecSupportedFound = true;
                this._soundLoaded(urlOrArrayBuffer);
              }
              break;
            case "AudioBuffer":
              this._audioBufferLoaded(urlOrArrayBuffer);
              break;
            case "String":
              urls.push(urlOrArrayBuffer);
            case "Array":
              if (urls.length === 0) {
                urls = urlOrArrayBuffer;
              }
              for (let i = 0;i < urls.length; i++) {
                const url = urls[i];
                codecSupportedFound = options && options.skipCodecCheck || url.indexOf(".mp3", url.length - 4) !== -1 && AbstractEngine.audioEngine.isMP3supported || url.indexOf(".ogg", url.length - 4) !== -1 && AbstractEngine.audioEngine.isOGGsupported || url.indexOf(".wav", url.length - 4) !== -1 || url.indexOf(".m4a", url.length - 4) !== -1 || url.indexOf(".mp4", url.length - 4) !== -1 || url.indexOf("blob:") !== -1;
                if (codecSupportedFound) {
                  if (!this._streaming) {
                    this._scene._loadFile(url, (data) => {
                      this._soundLoaded(data);
                    }, undefined, true, true, (exception) => {
                      if (exception) {
                        Logger.Error("XHR " + exception.status + " error on: " + url + ".");
                      }
                      Logger.Error("Sound creation aborted.");
                      this._scene.mainSoundTrack.removeSound(this);
                    });
                  } else {
                    this._htmlAudioElement = new Audio(url);
                    this._htmlAudioElement.controls = false;
                    this._htmlAudioElement.loop = this.loop;
                    Tools.SetCorsBehavior(url, this._htmlAudioElement);
                    this._htmlAudioElement.preload = "auto";
                    this._htmlAudioElement.addEventListener("canplaythrough", () => {
                      this._isReadyToPlay = true;
                      if (this.autoplay) {
                        this.play(0, this._offset, this._length);
                      }
                      if (this._readyToPlayCallback) {
                        this._readyToPlayCallback();
                      }
                    }, { once: true });
                    document.body.appendChild(this._htmlAudioElement);
                    this._htmlAudioElement.load();
                  }
                  break;
                }
              }
              break;
            default:
              validParameter = false;
              break;
          }
          if (!validParameter) {
            Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
          } else {
            if (!codecSupportedFound) {
              this._isReadyToPlay = true;
              if (this._readyToPlayCallback) {
                setTimeout(() => {
                  if (this._readyToPlayCallback) {
                    this._readyToPlayCallback();
                  }
                }, 1000);
              }
            }
          }
        } catch (ex) {
          Logger.Error("Unexpected error. Sound creation aborted.");
          this._scene.mainSoundTrack.removeSound(this);
        }
      }
    } else {
      this._scene.mainSoundTrack.addSound(this);
      if (AbstractEngine.audioEngine && !AbstractEngine.audioEngine.WarnedWebAudioUnsupported) {
        Logger.Error("Web Audio is not supported by your browser.");
        AbstractEngine.audioEngine.WarnedWebAudioUnsupported = true;
      }
      if (this._readyToPlayCallback) {
        setTimeout(() => {
          if (this._readyToPlayCallback) {
            this._readyToPlayCallback();
          }
        }, 1000);
      }
    }
  }
  dispose() {
    if (AbstractEngine.audioEngine?.canUseWebAudio) {
      if (this.isPlaying) {
        this.stop();
      }
      this._isReadyToPlay = false;
      if (this.soundTrackId === -1) {
        this._scene.mainSoundTrack.removeSound(this);
      } else if (this._scene.soundTracks) {
        this._scene.soundTracks[this.soundTrackId].removeSound(this);
      }
      if (this._soundGain) {
        this._soundGain.disconnect();
        this._soundGain = null;
      }
      if (this._soundPanner) {
        this._soundPanner.disconnect();
        this._soundPanner = null;
      }
      if (this._soundSource) {
        this._soundSource.disconnect();
        this._soundSource = null;
      }
      this._audioBuffer = null;
      if (this._htmlAudioElement) {
        this._htmlAudioElement.pause();
        this._htmlAudioElement.src = "";
        document.body.removeChild(this._htmlAudioElement);
        this._htmlAudioElement = null;
      }
      if (this._streamingSource) {
        this._streamingSource.disconnect();
        this._streamingSource = null;
      }
      if (this._connectedTransformNode && this._registerFunc) {
        this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
        this._connectedTransformNode = null;
      }
      this._clearTimeoutsAndObservers();
    }
  }
  isReady() {
    return this._isReadyToPlay;
  }
  getClassName() {
    return "Sound";
  }
  _audioBufferLoaded(buffer) {
    if (!AbstractEngine.audioEngine?.audioContext) {
      return;
    }
    this._audioBuffer = buffer;
    this._isReadyToPlay = true;
    if (this.autoplay) {
      this.play(0, this._offset, this._length);
    }
    if (this._readyToPlayCallback) {
      this._readyToPlayCallback();
    }
  }
  _soundLoaded(audioData) {
    if (!AbstractEngine.audioEngine?.audioContext) {
      return;
    }
    AbstractEngine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => {
      this._audioBufferLoaded(buffer);
    }, (err) => {
      Logger.Error("Error while decoding audio data for: " + this.name + " / Error: " + err);
    });
  }
  setAudioBuffer(audioBuffer) {
    if (AbstractEngine.audioEngine?.canUseWebAudio) {
      this._audioBuffer = audioBuffer;
      this._isReadyToPlay = true;
    }
  }
  updateOptions(options) {
    if (options) {
      this.loop = options.loop ?? this.loop;
      this.maxDistance = options.maxDistance ?? this.maxDistance;
      this.useCustomAttenuation = options.useCustomAttenuation ?? this.useCustomAttenuation;
      this.rolloffFactor = options.rolloffFactor ?? this.rolloffFactor;
      this.refDistance = options.refDistance ?? this.refDistance;
      this.distanceModel = options.distanceModel ?? this.distanceModel;
      this._playbackRate = options.playbackRate ?? this._playbackRate;
      this._length = options.length ?? undefined;
      this.spatialSound = options.spatialSound ?? this._spatialSound;
      this._setOffset(options.offset ?? undefined);
      this.setVolume(options.volume ?? this._volume);
      this._updateSpatialParameters();
      if (this.isPlaying) {
        if (this._streaming && this._htmlAudioElement) {
          this._htmlAudioElement.playbackRate = this._playbackRate;
          if (this._htmlAudioElement.loop !== this.loop) {
            this._htmlAudioElement.loop = this.loop;
          }
        } else {
          if (this._soundSource) {
            this._soundSource.playbackRate.value = this._playbackRate;
            if (this._soundSource.loop !== this.loop) {
              this._soundSource.loop = this.loop;
            }
            if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) {
              this._soundSource.loopStart = this._offset;
            }
            if (this._length !== undefined && this._length !== this._soundSource.loopEnd) {
              this._soundSource.loopEnd = (this._offset | 0) + this._length;
            }
          }
        }
      }
    }
  }
  _createSpatialParameters() {
    if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) {
      if (this._scene.headphone) {
        this._panningModel = "HRTF";
      }
      this._soundPanner = this._soundPanner ?? AbstractEngine.audioEngine.audioContext.createPanner();
      if (this._soundPanner && this._outputAudioNode) {
        this._updateSpatialParameters();
        this._soundPanner.connect(this._outputAudioNode);
        this._inputAudioNode = this._soundPanner;
      }
    }
  }
  _disableSpatialSound() {
    if (!this._spatialSound) {
      return;
    }
    this._inputAudioNode = this._soundGain;
    this._soundPanner?.disconnect();
    this._soundPanner = null;
    this._spatialSound = false;
  }
  _updateSpatialParameters() {
    if (!this._spatialSound) {
      return;
    }
    if (this._soundPanner) {
      if (this.useCustomAttenuation) {
        this._soundPanner.distanceModel = "linear";
        this._soundPanner.maxDistance = Number.MAX_VALUE;
        this._soundPanner.refDistance = 1;
        this._soundPanner.rolloffFactor = 1;
        this._soundPanner.panningModel = this._panningModel;
      } else {
        this._soundPanner.distanceModel = this.distanceModel;
        this._soundPanner.maxDistance = this.maxDistance;
        this._soundPanner.refDistance = this.refDistance;
        this._soundPanner.rolloffFactor = this.rolloffFactor;
        this._soundPanner.panningModel = this._panningModel;
      }
    } else {
      this._createSpatialParameters();
    }
  }
  switchPanningModelToHRTF() {
    this._panningModel = "HRTF";
    this._switchPanningModel();
  }
  switchPanningModelToEqualPower() {
    this._panningModel = "equalpower";
    this._switchPanningModel();
  }
  _switchPanningModel() {
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
      this._soundPanner.panningModel = this._panningModel;
    }
  }
  connectToSoundTrackAudioNode(soundTrackAudioNode) {
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) {
      if (this._isOutputConnected) {
        this._outputAudioNode.disconnect();
      }
      this._outputAudioNode.connect(soundTrackAudioNode);
      this._isOutputConnected = true;
    }
  }
  setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
    if (coneOuterAngle < coneInnerAngle) {
      Logger.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
      return;
    }
    this._coneInnerAngle = coneInnerAngle;
    this._coneOuterAngle = coneOuterAngle;
    this._coneOuterGain = coneOuterGain;
    this._isDirectional = true;
    if (this.isPlaying && this.loop) {
      this.stop();
      this.play(0, this._offset, this._length);
    }
  }
  get directionalConeInnerAngle() {
    return this._coneInnerAngle;
  }
  set directionalConeInnerAngle(value) {
    if (value != this._coneInnerAngle) {
      if (this._coneOuterAngle < value) {
        Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
        return;
      }
      this._coneInnerAngle = value;
      if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
        this._soundPanner.coneInnerAngle = this._coneInnerAngle;
      }
    }
  }
  get directionalConeOuterAngle() {
    return this._coneOuterAngle;
  }
  set directionalConeOuterAngle(value) {
    if (value != this._coneOuterAngle) {
      if (value < this._coneInnerAngle) {
        Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
        return;
      }
      this._coneOuterAngle = value;
      if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner) {
        this._soundPanner.coneOuterAngle = this._coneOuterAngle;
      }
    }
  }
  setPosition(newPosition) {
    if (newPosition.equals(this._position)) {
      return;
    }
    this._position.copyFrom(newPosition);
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
      this._soundPanner.positionX.value = this._position.x;
      this._soundPanner.positionY.value = this._position.y;
      this._soundPanner.positionZ.value = this._position.z;
    }
  }
  setLocalDirectionToMesh(newLocalDirection) {
    this._localDirection = newLocalDirection;
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.isPlaying) {
      this._updateDirection();
    }
  }
  _updateDirection() {
    if (!this._connectedTransformNode || !this._soundPanner) {
      return;
    }
    const mat = this._connectedTransformNode.getWorldMatrix();
    const direction = Vector3.TransformNormal(this._localDirection, mat);
    direction.normalize();
    this._soundPanner.orientationX.value = direction.x;
    this._soundPanner.orientationY.value = direction.y;
    this._soundPanner.orientationZ.value = direction.z;
  }
  updateDistanceFromListener() {
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
      const distance = this._scene.audioListenerPositionProvider ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length() : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
      this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
    }
  }
  setAttenuationFunction(callback) {
    this._customAttenuationFunction = callback;
  }
  play(time, offset, length) {
    if (this._isReadyToPlay && this._scene.audioEnabled && AbstractEngine.audioEngine?.audioContext) {
      try {
        this._clearTimeoutsAndObservers();
        let startTime = time ? AbstractEngine.audioEngine?.audioContext.currentTime + time : AbstractEngine.audioEngine?.audioContext.currentTime;
        if (!this._soundSource || !this._streamingSource) {
          if (this._spatialSound && this._soundPanner) {
            if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
              this._soundPanner.positionX.value = this._position.x;
              this._soundPanner.positionY.value = this._position.y;
              this._soundPanner.positionZ.value = this._position.z;
            }
            if (this._isDirectional) {
              this._soundPanner.coneInnerAngle = this._coneInnerAngle;
              this._soundPanner.coneOuterAngle = this._coneOuterAngle;
              this._soundPanner.coneOuterGain = this._coneOuterGain;
              if (this._connectedTransformNode) {
                this._updateDirection();
              } else {
                this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
              }
            }
          }
        }
        if (this._streaming) {
          if (!this._streamingSource && this._htmlAudioElement) {
            this._streamingSource = AbstractEngine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
            this._htmlAudioElement.onended = () => {
              this._onended();
            };
            this._htmlAudioElement.playbackRate = this._playbackRate;
          }
          if (this._streamingSource) {
            this._streamingSource.disconnect();
            if (this._inputAudioNode) {
              this._streamingSource.connect(this._inputAudioNode);
            }
          }
          if (this._htmlAudioElement) {
            const tryToPlay = () => {
              if (AbstractEngine.audioEngine?.unlocked) {
                if (!this._htmlAudioElement) {
                  return;
                }
                this._htmlAudioElement.currentTime = offset ?? 0;
                const playPromise = this._htmlAudioElement.play();
                if (playPromise !== undefined) {
                  playPromise.catch(() => {
                    AbstractEngine.audioEngine?.lock();
                    if (this.loop || this.autoplay) {
                      this._audioUnlockedObserver = AbstractEngine.audioEngine?.onAudioUnlockedObservable.addOnce(() => {
                        tryToPlay();
                      });
                    }
                  });
                }
              } else {
                if (this.loop || this.autoplay) {
                  this._audioUnlockedObserver = AbstractEngine.audioEngine?.onAudioUnlockedObservable.addOnce(() => {
                    tryToPlay();
                  });
                }
              }
            };
            tryToPlay();
          }
        } else {
          const tryToPlay = () => {
            if (AbstractEngine.audioEngine?.audioContext) {
              length = length || this._length;
              if (offset !== undefined) {
                this._setOffset(offset);
              }
              if (this._soundSource) {
                const oldSource = this._soundSource;
                oldSource.onended = () => {
                  oldSource.disconnect();
                };
              }
              this._soundSource = AbstractEngine.audioEngine?.audioContext.createBufferSource();
              if (this._soundSource && this._inputAudioNode) {
                this._soundSource.buffer = this._audioBuffer;
                this._soundSource.connect(this._inputAudioNode);
                this._soundSource.loop = this.loop;
                if (offset !== undefined) {
                  this._soundSource.loopStart = offset;
                }
                if (length !== undefined) {
                  this._soundSource.loopEnd = (offset | 0) + length;
                }
                this._soundSource.playbackRate.value = this._playbackRate;
                this._soundSource.onended = () => {
                  this._onended();
                };
                startTime = time ? AbstractEngine.audioEngine?.audioContext.currentTime + time : AbstractEngine.audioEngine.audioContext.currentTime;
                const actualOffset = ((this.isPaused ? this.currentTime : 0) + (this._offset ?? 0)) % this._soundSource.buffer.duration;
                this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length);
              }
            }
          };
          if (AbstractEngine.audioEngine?.audioContext.state === "suspended") {
            this._tryToPlayTimeout = setTimeout(() => {
              if (AbstractEngine.audioEngine?.audioContext.state === "suspended") {
                AbstractEngine.audioEngine.lock();
                if (this.loop || this.autoplay) {
                  this._audioUnlockedObserver = AbstractEngine.audioEngine.onAudioUnlockedObservable.addOnce(() => {
                    tryToPlay();
                  });
                }
              } else {
                tryToPlay();
              }
            }, 500);
          } else {
            tryToPlay();
          }
        }
        this._startTime = startTime;
        this.isPlaying = true;
        this.isPaused = false;
      } catch (ex) {
        Logger.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
      }
    }
  }
  _onended() {
    this.isPlaying = false;
    this._startTime = 0;
    this._currentTime = 0;
    if (this.onended) {
      this.onended();
    }
    this.onEndedObservable.notifyObservers(this);
  }
  stop(time) {
    if (this.isPlaying) {
      this._clearTimeoutsAndObservers();
      if (this._streaming) {
        if (this._htmlAudioElement) {
          this._htmlAudioElement.pause();
          if (this._htmlAudioElement.currentTime > 0) {
            this._htmlAudioElement.currentTime = 0;
          }
        } else {
          this._streamingSource?.disconnect();
        }
        this.isPlaying = false;
      } else if (AbstractEngine.audioEngine?.audioContext && this._soundSource) {
        const stopTime = time ? AbstractEngine.audioEngine.audioContext.currentTime + time : undefined;
        this._soundSource.onended = () => {
          this.isPlaying = false;
          this.isPaused = false;
          this._startTime = 0;
          this._currentTime = 0;
          if (this._soundSource) {
            this._soundSource.onended = () => {
              return;
            };
          }
          this._onended();
        };
        this._soundSource.stop(stopTime);
      } else {
        this.isPlaying = false;
      }
    } else if (this.isPaused) {
      this.isPaused = false;
      this._startTime = 0;
      this._currentTime = 0;
    }
  }
  pause() {
    if (this.isPlaying) {
      this._clearTimeoutsAndObservers();
      if (this._streaming) {
        if (this._htmlAudioElement) {
          this._htmlAudioElement.pause();
        } else {
          this._streamingSource?.disconnect();
        }
        this.isPlaying = false;
        this.isPaused = true;
      } else if (AbstractEngine.audioEngine?.audioContext && this._soundSource) {
        this._soundSource.onended = () => {
          return;
        };
        this._soundSource.stop();
        this.isPlaying = false;
        this.isPaused = true;
        this._currentTime += AbstractEngine.audioEngine.audioContext.currentTime - this._startTime;
      }
    }
  }
  setVolume(newVolume, time) {
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._soundGain) {
      if (time && AbstractEngine.audioEngine.audioContext) {
        this._soundGain.gain.cancelScheduledValues(AbstractEngine.audioEngine.audioContext.currentTime);
        this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, AbstractEngine.audioEngine.audioContext.currentTime);
        this._soundGain.gain.linearRampToValueAtTime(newVolume, AbstractEngine.audioEngine.audioContext.currentTime + time);
      } else {
        this._soundGain.gain.value = newVolume;
      }
    }
    this._volume = newVolume;
  }
  setPlaybackRate(newPlaybackRate) {
    this._playbackRate = newPlaybackRate;
    if (this.isPlaying) {
      if (this._streaming && this._htmlAudioElement) {
        this._htmlAudioElement.playbackRate = this._playbackRate;
      } else if (this._soundSource) {
        this._soundSource.playbackRate.value = this._playbackRate;
      }
    }
  }
  getPlaybackRate() {
    return this._playbackRate;
  }
  getVolume() {
    return this._volume;
  }
  attachToMesh(transformNode) {
    if (this._connectedTransformNode && this._registerFunc) {
      this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
      this._registerFunc = null;
    }
    this._connectedTransformNode = transformNode;
    if (!this._spatialSound) {
      this._spatialSound = true;
      this._createSpatialParameters();
      if (this.isPlaying && this.loop) {
        this.stop();
        this.play(0, this._offset, this._length);
      }
    }
    this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);
    this._registerFunc = (transformNode2) => this._onRegisterAfterWorldMatrixUpdate(transformNode2);
    this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);
  }
  detachFromMesh() {
    if (this._connectedTransformNode && this._registerFunc) {
      this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
      this._registerFunc = null;
      this._connectedTransformNode = null;
    }
  }
  _onRegisterAfterWorldMatrixUpdate(node) {
    if (!node.getBoundingInfo) {
      this.setPosition(node.absolutePosition);
    } else {
      const mesh = node;
      const boundingInfo = mesh.getBoundingInfo();
      this.setPosition(boundingInfo.boundingSphere.centerWorld);
    }
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._isDirectional && this.isPlaying) {
      this._updateDirection();
    }
  }
  clone() {
    if (!this._streaming) {
      const setBufferAndRun = () => {
        _retryWithInterval(() => this._isReadyToPlay, () => {
          clonedSound._audioBuffer = this.getAudioBuffer();
          clonedSound._isReadyToPlay = true;
          if (clonedSound.autoplay) {
            clonedSound.play(0, this._offset, this._length);
          }
        }, undefined, 300);
      };
      const currentOptions = {
        autoplay: this.autoplay,
        loop: this.loop,
        volume: this._volume,
        spatialSound: this._spatialSound,
        maxDistance: this.maxDistance,
        useCustomAttenuation: this.useCustomAttenuation,
        rolloffFactor: this.rolloffFactor,
        refDistance: this.refDistance,
        distanceModel: this.distanceModel
      };
      const clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
      if (this.useCustomAttenuation) {
        clonedSound.setAttenuationFunction(this._customAttenuationFunction);
      }
      clonedSound.setPosition(this._position);
      clonedSound.setPlaybackRate(this._playbackRate);
      setBufferAndRun();
      return clonedSound;
    } else {
      return null;
    }
  }
  getAudioBuffer() {
    return this._audioBuffer;
  }
  getSoundSource() {
    return this._soundSource;
  }
  getSoundGain() {
    return this._soundGain;
  }
  serialize() {
    const serializationObject = {
      name: this.name,
      url: this._url,
      autoplay: this.autoplay,
      loop: this.loop,
      volume: this._volume,
      spatialSound: this._spatialSound,
      maxDistance: this.maxDistance,
      rolloffFactor: this.rolloffFactor,
      refDistance: this.refDistance,
      distanceModel: this.distanceModel,
      playbackRate: this._playbackRate,
      panningModel: this._panningModel,
      soundTrackId: this.soundTrackId,
      metadata: this.metadata
    };
    if (this._spatialSound) {
      if (this._connectedTransformNode) {
        serializationObject.connectedMeshId = this._connectedTransformNode.id;
      }
      serializationObject.position = this._position.asArray();
      serializationObject.refDistance = this.refDistance;
      serializationObject.distanceModel = this.distanceModel;
      serializationObject.isDirectional = this._isDirectional;
      serializationObject.localDirectionToMesh = this._localDirection.asArray();
      serializationObject.coneInnerAngle = this._coneInnerAngle;
      serializationObject.coneOuterAngle = this._coneOuterAngle;
      serializationObject.coneOuterGain = this._coneOuterGain;
    }
    return serializationObject;
  }
  static Parse(parsedSound, scene, rootUrl, sourceSound) {
    const soundName = parsedSound.name;
    let soundUrl;
    if (parsedSound.url) {
      soundUrl = rootUrl + parsedSound.url;
    } else {
      soundUrl = rootUrl + soundName;
    }
    const options = {
      autoplay: parsedSound.autoplay,
      loop: parsedSound.loop,
      volume: parsedSound.volume,
      spatialSound: parsedSound.spatialSound,
      maxDistance: parsedSound.maxDistance,
      rolloffFactor: parsedSound.rolloffFactor,
      refDistance: parsedSound.refDistance,
      distanceModel: parsedSound.distanceModel,
      playbackRate: parsedSound.playbackRate
    };
    let newSound;
    if (!sourceSound) {
      newSound = new Sound(soundName, soundUrl, scene, () => {
        scene.removePendingData(newSound);
      }, options);
      scene.addPendingData(newSound);
    } else {
      const setBufferAndRun = () => {
        _retryWithInterval(() => sourceSound._isReadyToPlay, () => {
          newSound._audioBuffer = sourceSound.getAudioBuffer();
          newSound._isReadyToPlay = true;
          if (newSound.autoplay) {
            newSound.play(0, newSound._offset, newSound._length);
          }
        }, undefined, 300);
      };
      newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
      setBufferAndRun();
    }
    if (parsedSound.position) {
      const soundPosition = Vector3.FromArray(parsedSound.position);
      newSound.setPosition(soundPosition);
    }
    if (parsedSound.isDirectional) {
      newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
      if (parsedSound.localDirectionToMesh) {
        const localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh);
        newSound.setLocalDirectionToMesh(localDirectionToMesh);
      }
    }
    if (parsedSound.connectedMeshId) {
      const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId);
      if (connectedMesh) {
        newSound.attachToMesh(connectedMesh);
      }
    }
    if (parsedSound.metadata) {
      newSound.metadata = parsedSound.metadata;
    }
    return newSound;
  }
  _setOffset(value) {
    if (this._offset === value) {
      return;
    }
    if (this.isPaused) {
      this.stop();
      this.isPaused = false;
    }
    this._offset = value;
  }
  _clearTimeoutsAndObservers() {
    if (this._tryToPlayTimeout) {
      clearTimeout(this._tryToPlayTimeout);
      this._tryToPlayTimeout = null;
    }
    if (this._audioUnlockedObserver) {
      AbstractEngine.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver);
      this._audioUnlockedObserver = null;
    }
  }
}
Sound._SceneComponentInitialization = (_) => {
  throw _WarnImport("AudioSceneComponent");
};
RegisterClass("BABYLON.Sound", Sound);

// node_modules/@babylonjs/core/Audio/soundTrack.js
init_engineStore();
init_abstractEngine();

class SoundTrack {
  constructor(scene, options = {}) {
    this.id = -1;
    this._isInitialized = false;
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this._scene = scene;
    this.soundCollection = [];
    this._options = options;
    if (!this._options.mainTrack && this._scene.soundTracks) {
      this._scene.soundTracks.push(this);
      this.id = this._scene.soundTracks.length - 1;
    }
  }
  _initializeSoundTrackAudioGraph() {
    if (AbstractEngine.audioEngine?.canUseWebAudio && AbstractEngine.audioEngine.audioContext) {
      this._outputAudioNode = AbstractEngine.audioEngine.audioContext.createGain();
      this._outputAudioNode.connect(AbstractEngine.audioEngine.masterGain);
      if (this._options) {
        if (this._options.volume) {
          this._outputAudioNode.gain.value = this._options.volume;
        }
      }
      this._isInitialized = true;
    }
  }
  dispose() {
    if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.canUseWebAudio) {
      if (this._connectedAnalyser) {
        this._connectedAnalyser.stopDebugCanvas();
      }
      while (this.soundCollection.length) {
        this.soundCollection[0].dispose();
      }
      if (this._outputAudioNode) {
        this._outputAudioNode.disconnect();
      }
      this._outputAudioNode = null;
    }
  }
  addSound(sound) {
    if (!this._isInitialized) {
      this._initializeSoundTrackAudioGraph();
    }
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) {
      sound.connectToSoundTrackAudioNode(this._outputAudioNode);
    }
    if (sound.soundTrackId !== undefined) {
      if (sound.soundTrackId === -1) {
        this._scene.mainSoundTrack.removeSound(sound);
      } else if (this._scene.soundTracks) {
        this._scene.soundTracks[sound.soundTrackId].removeSound(sound);
      }
    }
    this.soundCollection.push(sound);
    sound.soundTrackId = this.id;
  }
  removeSound(sound) {
    const index = this.soundCollection.indexOf(sound);
    if (index !== -1) {
      this.soundCollection.splice(index, 1);
    }
  }
  setVolume(newVolume) {
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) {
      this._outputAudioNode.gain.value = newVolume;
    }
  }
  switchPanningModelToHRTF() {
    if (AbstractEngine.audioEngine?.canUseWebAudio) {
      for (let i = 0;i < this.soundCollection.length; i++) {
        this.soundCollection[i].switchPanningModelToHRTF();
      }
    }
  }
  switchPanningModelToEqualPower() {
    if (AbstractEngine.audioEngine?.canUseWebAudio) {
      for (let i = 0;i < this.soundCollection.length; i++) {
        this.soundCollection[i].switchPanningModelToEqualPower();
      }
    }
  }
  connectToAnalyser(analyser) {
    if (this._connectedAnalyser) {
      this._connectedAnalyser.stopDebugCanvas();
    }
    this._connectedAnalyser = analyser;
    if (AbstractEngine.audioEngine?.canUseWebAudio && this._outputAudioNode) {
      this._outputAudioNode.disconnect();
      this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, AbstractEngine.audioEngine.masterGain);
    }
  }
}

// node_modules/@babylonjs/core/Audio/audioSceneComponent.js
init_math_vector();
init_sceneComponent();
init_scene();
init_precisionDate();
init_engineStore();
init_abstractEngine();

// node_modules/@babylonjs/core/Loading/Plugins/babylonFileParser.function.js
var _BabylonFileParsers = {};
var _IndividualBabylonFileParsers = {};
function AddParser(name18, parser) {
  _BabylonFileParsers[name18] = parser;
}
function AddIndividualParser(name18, parser) {
  _IndividualBabylonFileParsers[name18] = parser;
}
function GetIndividualParser(name18) {
  if (_IndividualBabylonFileParsers[name18]) {
    return _IndividualBabylonFileParsers[name18];
  }
  return null;
}
function Parse(jsonData, scene, container, rootUrl) {
  for (const parserName in _BabylonFileParsers) {
    if (Object.prototype.hasOwnProperty.call(_BabylonFileParsers, parserName)) {
      _BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
    }
  }
}

// node_modules/@babylonjs/core/Audio/audioSceneComponent.js
AddParser(SceneComponentConstants.NAME_AUDIO, (parsedData, scene, container, rootUrl) => {
  let loadedSounds = [];
  let loadedSound;
  container.sounds = container.sounds || [];
  if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
    for (let index = 0, cache = parsedData.sounds.length;index < cache; index++) {
      const parsedSound = parsedData.sounds[index];
      if (AbstractEngine.audioEngine?.canUseWebAudio) {
        if (!parsedSound.url) {
          parsedSound.url = parsedSound.name;
        }
        if (!loadedSounds[parsedSound.url]) {
          loadedSound = Sound.Parse(parsedSound, scene, rootUrl);
          loadedSounds[parsedSound.url] = loadedSound;
          container.sounds.push(loadedSound);
        } else {
          container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
        }
      } else {
        container.sounds.push(new Sound(parsedSound.name, null, scene));
      }
    }
  }
  loadedSounds = [];
});
Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    if (!this._mainSoundTrack) {
      this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
    }
    return this._mainSoundTrack;
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.getSoundByName = function(name18) {
  let index;
  for (index = 0;index < this.mainSoundTrack.soundCollection.length; index++) {
    if (this.mainSoundTrack.soundCollection[index].name === name18) {
      return this.mainSoundTrack.soundCollection[index];
    }
  }
  if (this.soundTracks) {
    for (let sdIndex = 0;sdIndex < this.soundTracks.length; sdIndex++) {
      for (index = 0;index < this.soundTracks[sdIndex].soundCollection.length; index++) {
        if (this.soundTracks[sdIndex].soundCollection[index].name === name18) {
          return this.soundTracks[sdIndex].soundCollection[index];
        }
      }
    }
  }
  return null;
};
Object.defineProperty(Scene.prototype, "audioEnabled", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    return compo.audioEnabled;
  },
  set: function(value) {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    if (value) {
      compo.enableAudio();
    } else {
      compo.disableAudio();
    }
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Scene.prototype, "headphone", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    return compo.headphone;
  },
  set: function(value) {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    if (value) {
      compo.switchAudioModeForHeadphones();
    } else {
      compo.switchAudioModeForNormalSpeakers();
    }
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Scene.prototype, "audioListenerPositionProvider", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    return compo.audioListenerPositionProvider;
  },
  set: function(value) {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    if (value && typeof value !== "function") {
      throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");
    } else {
      compo.audioListenerPositionProvider = value;
    }
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Scene.prototype, "audioListenerRotationProvider", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    return compo.audioListenerRotationProvider;
  },
  set: function(value) {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    if (value && typeof value !== "function") {
      throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");
    } else {
      compo.audioListenerRotationProvider = value;
    }
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Scene.prototype, "audioPositioningRefreshRate", {
  get: function() {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    return compo.audioPositioningRefreshRate;
  },
  set: function(value) {
    let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);
    if (!compo) {
      compo = new AudioSceneComponent(this);
      this._addComponent(compo);
    }
    compo.audioPositioningRefreshRate = value;
  },
  enumerable: true,
  configurable: true
});

class AudioSceneComponent {
  get audioEnabled() {
    return this._audioEnabled;
  }
  get headphone() {
    return this._headphone;
  }
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_AUDIO;
    this._audioEnabled = true;
    this._headphone = false;
    this.audioPositioningRefreshRate = 500;
    this.audioListenerPositionProvider = null;
    this.audioListenerRotationProvider = null;
    this._cachedCameraDirection = new Vector3;
    this._cachedCameraPosition = new Vector3;
    this._lastCheck = 0;
    this._invertMatrixTemp = new Matrix;
    this._cameraDirectionTemp = new Vector3;
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this.scene = scene;
    scene.soundTracks = [];
    scene.sounds = [];
  }
  register() {
    this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  }
  rebuild() {}
  serialize(serializationObject) {
    serializationObject.sounds = [];
    if (this.scene.soundTracks) {
      for (let index = 0;index < this.scene.soundTracks.length; index++) {
        const soundtrack = this.scene.soundTracks[index];
        for (let soundId = 0;soundId < soundtrack.soundCollection.length; soundId++) {
          serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
        }
      }
    }
  }
  addFromContainer(container) {
    if (!container.sounds) {
      return;
    }
    container.sounds.forEach((sound) => {
      sound.play();
      sound.autoplay = true;
      this.scene.mainSoundTrack.addSound(sound);
    });
  }
  removeFromContainer(container, dispose = false) {
    if (!container.sounds) {
      return;
    }
    container.sounds.forEach((sound) => {
      sound.stop();
      sound.autoplay = false;
      this.scene.mainSoundTrack.removeSound(sound);
      if (dispose) {
        sound.dispose();
      }
    });
  }
  dispose() {
    const scene = this.scene;
    if (scene._mainSoundTrack) {
      scene.mainSoundTrack.dispose();
    }
    if (scene.soundTracks) {
      for (let scIndex = 0;scIndex < scene.soundTracks.length; scIndex++) {
        scene.soundTracks[scIndex].dispose();
      }
    }
  }
  disableAudio() {
    const scene = this.scene;
    this._audioEnabled = false;
    if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.audioContext) {
      AbstractEngine.audioEngine.audioContext.suspend();
    }
    let i;
    for (i = 0;i < scene.mainSoundTrack.soundCollection.length; i++) {
      scene.mainSoundTrack.soundCollection[i].pause();
    }
    if (scene.soundTracks) {
      for (i = 0;i < scene.soundTracks.length; i++) {
        for (let j = 0;j < scene.soundTracks[i].soundCollection.length; j++) {
          scene.soundTracks[i].soundCollection[j].pause();
        }
      }
    }
  }
  enableAudio() {
    const scene = this.scene;
    this._audioEnabled = true;
    if (AbstractEngine.audioEngine && AbstractEngine.audioEngine.audioContext) {
      AbstractEngine.audioEngine.audioContext.resume();
    }
    let i;
    for (i = 0;i < scene.mainSoundTrack.soundCollection.length; i++) {
      if (scene.mainSoundTrack.soundCollection[i].isPaused) {
        scene.mainSoundTrack.soundCollection[i].play();
      }
    }
    if (scene.soundTracks) {
      for (i = 0;i < scene.soundTracks.length; i++) {
        for (let j = 0;j < scene.soundTracks[i].soundCollection.length; j++) {
          if (scene.soundTracks[i].soundCollection[j].isPaused) {
            scene.soundTracks[i].soundCollection[j].play();
          }
        }
      }
    }
  }
  switchAudioModeForHeadphones() {
    const scene = this.scene;
    this._headphone = true;
    scene.mainSoundTrack.switchPanningModelToHRTF();
    if (scene.soundTracks) {
      for (let i = 0;i < scene.soundTracks.length; i++) {
        scene.soundTracks[i].switchPanningModelToHRTF();
      }
    }
  }
  switchAudioModeForNormalSpeakers() {
    const scene = this.scene;
    this._headphone = false;
    scene.mainSoundTrack.switchPanningModelToEqualPower();
    if (scene.soundTracks) {
      for (let i = 0;i < scene.soundTracks.length; i++) {
        scene.soundTracks[i].switchPanningModelToEqualPower();
      }
    }
  }
  _afterRender() {
    const now = PrecisionDate.Now;
    if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) {
      return;
    }
    this._lastCheck = now;
    const scene = this.scene;
    if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1) {
      return;
    }
    const audioEngine = AbstractEngine.audioEngine;
    if (!audioEngine) {
      return;
    }
    if (audioEngine.audioContext) {
      let listeningCamera = scene.activeCamera;
      if (scene.activeCameras && scene.activeCameras.length > 0) {
        listeningCamera = scene.activeCameras[0];
      }
      if (this.audioListenerPositionProvider) {
        const position = this.audioListenerPositionProvider();
        audioEngine.audioContext.listener.setPosition(position.x || 0, position.y || 0, position.z || 0);
      } else if (listeningCamera) {
        if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) {
          this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition);
          audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z);
        }
      } else {
        audioEngine.audioContext.listener.setPosition(0, 0, 0);
      }
      if (this.audioListenerRotationProvider) {
        const rotation = this.audioListenerRotationProvider();
        audioEngine.audioContext.listener.setOrientation(rotation.x || 0, rotation.y || 0, rotation.z || 0, 0, 1, 0);
      } else if (listeningCamera) {
        if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
          listeningCamera = listeningCamera.rigCameras[0];
        }
        listeningCamera.getViewMatrix().invertToRef(this._invertMatrixTemp);
        Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection, this._invertMatrixTemp, this._cameraDirectionTemp);
        this._cameraDirectionTemp.normalize();
        if (!isNaN(this._cameraDirectionTemp.x) && !isNaN(this._cameraDirectionTemp.y) && !isNaN(this._cameraDirectionTemp.z)) {
          if (!this._cachedCameraDirection.equals(this._cameraDirectionTemp)) {
            this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp);
            audioEngine.audioContext.listener.setOrientation(this._cameraDirectionTemp.x, this._cameraDirectionTemp.y, this._cameraDirectionTemp.z, 0, 1, 0);
          }
        }
      } else {
        audioEngine.audioContext.listener.setOrientation(0, 0, 0, 0, 1, 0);
      }
      let i;
      for (i = 0;i < scene.mainSoundTrack.soundCollection.length; i++) {
        const sound = scene.mainSoundTrack.soundCollection[i];
        if (sound.useCustomAttenuation) {
          sound.updateDistanceFromListener();
        }
      }
      if (scene.soundTracks) {
        for (i = 0;i < scene.soundTracks.length; i++) {
          for (let j = 0;j < scene.soundTracks[i].soundCollection.length; j++) {
            const sound = scene.soundTracks[i].soundCollection[j];
            if (sound.useCustomAttenuation) {
              sound.updateDistanceFromListener();
            }
          }
        }
      }
    }
  }
}
AudioSceneComponent._CameraDirection = new Vector3(0, 0, -1);
Sound._SceneComponentInitialization = (scene) => {
  let compo = scene._getComponent(SceneComponentConstants.NAME_AUDIO);
  if (!compo) {
    compo = new AudioSceneComponent(scene);
    scene._addComponent(compo);
  }
};
// node_modules/@babylonjs/core/Audio/weightedsound.js
init_logger();
// node_modules/@babylonjs/core/AudioV2/abstractAudio/index.js
init_abstractAudioBus();
init_abstractAudioNode();
init_abstractSound();
init_audioBus();
init_mainAudioBus();
init_staticSound();
init_streamingSound();

// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/index.js
init_abstractAudioAnalyzer();
init_abstractSpatialAudio();

// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/abstractSpatialAudioListener.js
init_math_vector();
var _SpatialAudioListenerDefaults = {
  position: Vector3.Zero(),
  rotation: Vector3.Zero(),
  rotationQuaternion: new Quaternion
};

// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/index.js
init_abstractStereoAudio();
// node_modules/@babylonjs/core/AudioV2/soundState.js
var SoundState;
(function(SoundState2) {
  SoundState2[SoundState2["Stopping"] = 0] = "Stopping";
  SoundState2[SoundState2["Stopped"] = 1] = "Stopped";
  SoundState2[SoundState2["Starting"] = 2] = "Starting";
  SoundState2[SoundState2["Started"] = 3] = "Started";
  SoundState2[SoundState2["FailedToStart"] = 4] = "FailedToStart";
  SoundState2[SoundState2["Paused"] = 5] = "Paused";
})(SoundState || (SoundState = {}));
// node_modules/@babylonjs/core/AudioV2/spatialAudioAttachmentType.js
var SpatialAudioAttachmentType;
(function(SpatialAudioAttachmentType2) {
  SpatialAudioAttachmentType2[SpatialAudioAttachmentType2["Position"] = 1] = "Position";
  SpatialAudioAttachmentType2[SpatialAudioAttachmentType2["Rotation"] = 2] = "Rotation";
  SpatialAudioAttachmentType2[SpatialAudioAttachmentType2["PositionAndRotation"] = 3] = "PositionAndRotation";
})(SpatialAudioAttachmentType || (SpatialAudioAttachmentType = {}));
// node_modules/@babylonjs/core/AudioV2/webAudio/index.js
init_webAudioBus();

// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioEngine.js
init_observable();

// node_modules/@babylonjs/core/AudioV2/webAudio/subProperties/spatialWebAudioListener.js
init_math_vector();

// node_modules/@babylonjs/core/AudioV2/abstractAudio/subProperties/spatialAudioListener.js
init_spatialAudioAttacherComponent();

// node_modules/@babylonjs/core/AudioV2/webAudio/subProperties/spatialWebAudioListener.js
init_spatialWebAudioUpdaterComponent();
var TmpMatrix2 = Matrix.Zero();
var TmpQuaternion2 = new Quaternion;
var TmpVector2 = Vector3.Zero();

// node_modules/@babylonjs/core/AudioV2/abstractAudio/mainAudioOut.js
init_abstractAudioNode();

// node_modules/@babylonjs/core/AudioV2/webAudio/webAudioUnmuteUI.js
init_engineStore();

// node_modules/@babylonjs/core/AudioV2/webAudio/index.js
init_webAudioMainBus();
init_webAudioStaticSound();
init_webAudioStreamingSound();
// node_modules/@babylonjs/core/BakedVertexAnimation/bakedVertexAnimationManager.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_engineStore();
init_decorators_serialization();

class BakedVertexAnimationManager {
  constructor(scene) {
    this._texture = null;
    this._isEnabled = true;
    this.isEnabled = true;
    this.time = 0;
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this._scene = scene;
    this.animationParameters = new Vector4(0, 0, 0, 30);
  }
  _markSubMeshesAsAttributesDirty() {
    for (const mesh of this._scene.meshes) {
      if (mesh.bakedVertexAnimationManager === this) {
        mesh._markSubMeshesAsAttributesDirty();
      }
    }
  }
  bind(effect, useInstances = false) {
    if (!this._texture || !this._isEnabled) {
      return;
    }
    const size = this._texture.getSize();
    effect.setFloat2("bakedVertexAnimationTextureSizeInverted", 1 / size.width, 1 / size.height);
    effect.setFloat("bakedVertexAnimationTime", this.time);
    if (!useInstances) {
      effect.setVector4("bakedVertexAnimationSettings", this.animationParameters);
    }
    effect.setTexture("bakedVertexAnimationTexture", this._texture);
  }
  clone() {
    const copy = new BakedVertexAnimationManager(this._scene);
    this.copyTo(copy);
    return copy;
  }
  setAnimationParameters(startFrame, endFrame, offset = 0, speedFramesPerSecond = 30) {
    this.animationParameters = new Vector4(startFrame, endFrame, offset, speedFramesPerSecond);
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._texture?.dispose();
    }
  }
  getClassName() {
    return "BakedVertexAnimationManager";
  }
  copyTo(vatMap) {
    SerializationHelper.Clone(() => vatMap, this);
  }
  serialize() {
    return SerializationHelper.Serialize(this);
  }
  parse(source, scene, rootUrl) {
    SerializationHelper.Parse(() => this, source, scene, rootUrl);
  }
}
__decorate([
  serializeAsTexture(),
  expandToProperty("_markSubMeshesAsAttributesDirty")
], BakedVertexAnimationManager.prototype, "texture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markSubMeshesAsAttributesDirty")
], BakedVertexAnimationManager.prototype, "isEnabled", undefined);
__decorate([
  serialize()
], BakedVertexAnimationManager.prototype, "animationParameters", undefined);
__decorate([
  serialize()
], BakedVertexAnimationManager.prototype, "time", undefined);
// node_modules/@babylonjs/core/Materials/Textures/rawTexture.js
init_texture();

class RawTexture extends Texture {
  constructor(data, width, height, format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer, waitDataToBeReady) {
    super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags);
    this.format = format;
    if (!this._engine) {
      return;
    }
    if (!this._engine._caps.textureFloatLinearFiltering && type === 1) {
      samplingMode = 1;
    }
    if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) {
      samplingMode = 1;
    }
    this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags ?? 0, useSRGBBuffer ?? false);
    this.wrapU = Texture.CLAMP_ADDRESSMODE;
    this.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._waitingForData = !!waitDataToBeReady && !data;
  }
  update(data) {
    this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer);
    this._waitingForData = false;
  }
  clone() {
    if (!this._texture) {
      return super.clone();
    }
    const rawTexture = new RawTexture(null, this.getSize().width, this.getSize().height, this.format, this.getScene(), this._texture.generateMipMaps, this._invertY, this.samplingMode, this._texture.type, this._texture._creationFlags, this._useSRGBBuffer);
    rawTexture._texture = this._texture;
    this._texture.incrementReferences();
    return rawTexture;
  }
  isReady() {
    return super.isReady() && !this._waitingForData;
  }
  static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
    return new RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode);
  }
  static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
    return new RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode);
  }
  static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {
    return new RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode);
  }
  static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {
    return new RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);
  }
  static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false, waitDataToBeReady = false) {
    return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer, waitDataToBeReady);
  }
  static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) {
    return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer);
  }
  static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {
    return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type);
  }
  static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {
    return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1);
  }
}

// node_modules/@babylonjs/core/BakedVertexAnimation/vertexAnimationBaker.js
init_texture();
init_stringTools();

// node_modules/@babylonjs/core/Bones/skeleton.js
init_bone();
init_observable();
init_math_vector();
init_animation();
init_engineStore();
init_logger();
init_deepCopier();

class Skeleton {
  get useTextureToStoreBoneMatrices() {
    return this._useTextureToStoreBoneMatrices;
  }
  set useTextureToStoreBoneMatrices(value) {
    this._useTextureToStoreBoneMatrices = value;
    this._markAsDirty();
  }
  get animationPropertiesOverride() {
    if (!this._animationPropertiesOverride) {
      return this._scene.animationPropertiesOverride;
    }
    return this._animationPropertiesOverride;
  }
  set animationPropertiesOverride(value) {
    this._animationPropertiesOverride = value;
  }
  get isUsingTextureForMatrices() {
    return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones;
  }
  get uniqueId() {
    return this._uniqueId;
  }
  constructor(name18, id, scene) {
    this.name = name18;
    this.id = id;
    this.bones = [];
    this.needInitialSkinMatrix = false;
    this._isDirty = true;
    this._meshesWithPoseMatrix = new Array;
    this._identity = Matrix.Identity();
    this._currentRenderId = -1;
    this._ranges = {};
    this._absoluteTransformIsDirty = true;
    this._canUseTextureForBones = false;
    this._uniqueId = 0;
    this._numBonesWithLinkedTransformNode = 0;
    this._hasWaitingData = null;
    this._parentContainer = null;
    this.doNotSerialize = false;
    this._useTextureToStoreBoneMatrices = true;
    this._animationPropertiesOverride = null;
    this.onBeforeComputeObservable = new Observable;
    this.bones = [];
    this._scene = scene || EngineStore.LastCreatedScene;
    this._uniqueId = this._scene.getUniqueId();
    this._scene.addSkeleton(this);
    this._isDirty = true;
    const engineCaps = this._scene.getEngine().getCaps();
    this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  }
  getClassName() {
    return "Skeleton";
  }
  getChildren() {
    return this.bones.filter((b) => !b.getParent());
  }
  getTransformMatrices(mesh) {
    if (this.needInitialSkinMatrix) {
      if (!mesh) {
        throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");
      }
      if (!mesh._bonesTransformMatrices) {
        this.prepare(true);
      }
      return mesh._bonesTransformMatrices;
    }
    if (!this._transformMatrices || this._isDirty) {
      this.prepare(!this._transformMatrices);
    }
    return this._transformMatrices;
  }
  getTransformMatrixTexture(mesh) {
    if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) {
      return mesh._transformMatrixTexture;
    }
    return this._transformMatrixTexture;
  }
  getScene() {
    return this._scene;
  }
  toString(fullDetails) {
    let ret = `Name: ${this.name}, nBones: ${this.bones.length}`;
    ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : "none"}`;
    if (fullDetails) {
      ret += ", Ranges: {";
      let first = true;
      for (const name18 in this._ranges) {
        if (first) {
          ret += ", ";
          first = false;
        }
        ret += name18;
      }
      ret += "}";
    }
    return ret;
  }
  getBoneIndexByName(name18) {
    for (let boneIndex = 0, cache = this.bones.length;boneIndex < cache; boneIndex++) {
      if (this.bones[boneIndex].name === name18) {
        return boneIndex;
      }
    }
    return -1;
  }
  createAnimationRange(name18, from, to) {
    if (!this._ranges[name18]) {
      this._ranges[name18] = new AnimationRange(name18, from, to);
      for (let i = 0, nBones = this.bones.length;i < nBones; i++) {
        if (this.bones[i].animations[0]) {
          this.bones[i].animations[0].createRange(name18, from, to);
        }
      }
    }
  }
  deleteAnimationRange(name18, deleteFrames = true) {
    for (let i = 0, nBones = this.bones.length;i < nBones; i++) {
      if (this.bones[i].animations[0]) {
        this.bones[i].animations[0].deleteRange(name18, deleteFrames);
      }
    }
    this._ranges[name18] = null;
  }
  getAnimationRange(name18) {
    return this._ranges[name18] || null;
  }
  getAnimationRanges() {
    const animationRanges = [];
    let name18;
    for (name18 in this._ranges) {
      animationRanges.push(this._ranges[name18]);
    }
    return animationRanges;
  }
  copyAnimationRange(source, name18, rescaleAsRequired = false) {
    if (this._ranges[name18] || !source.getAnimationRange(name18)) {
      return false;
    }
    let ret = true;
    const frameOffset = this._getHighestAnimationFrame() + 1;
    const boneDict = {};
    const sourceBones = source.bones;
    let nBones;
    let i;
    for (i = 0, nBones = sourceBones.length;i < nBones; i++) {
      boneDict[sourceBones[i].name] = sourceBones[i];
    }
    if (this.bones.length !== sourceBones.length) {
      Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`);
      ret = false;
    }
    const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
    for (i = 0, nBones = this.bones.length;i < nBones; i++) {
      const boneName = this.bones[i].name;
      const sourceBone = boneDict[boneName];
      if (sourceBone) {
        ret = ret && this.bones[i].copyAnimationRange(sourceBone, name18, frameOffset, rescaleAsRequired, skelDimensionsRatio);
      } else {
        Logger.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
        ret = false;
      }
    }
    const range = source.getAnimationRange(name18);
    if (range) {
      this._ranges[name18] = new AnimationRange(name18, range.from + frameOffset, range.to + frameOffset);
    }
    return ret;
  }
  returnToRest() {
    for (const bone of this.bones) {
      if (bone._index !== -1) {
        bone.returnToRest();
      }
    }
  }
  _getHighestAnimationFrame() {
    let ret = 0;
    for (let i = 0, nBones = this.bones.length;i < nBones; i++) {
      if (this.bones[i].animations[0]) {
        const highest = this.bones[i].animations[0].getHighestFrame();
        if (ret < highest) {
          ret = highest;
        }
      }
    }
    return ret;
  }
  beginAnimation(name18, loop, speedRatio, onAnimationEnd) {
    const range = this.getAnimationRange(name18);
    if (!range) {
      return null;
    }
    return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  }
  static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) {
    const rangeValue = skeleton.getAnimationRange(range);
    if (!rangeValue) {
      return null;
    }
    const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton);
    let rangeAnimatable = null;
    for (let index = 0;index < sceneAnimatables.length; index++) {
      const sceneAnimatable = sceneAnimatables[index];
      if (sceneAnimatable.fromFrame === rangeValue?.from && sceneAnimatable.toFrame === rangeValue?.to) {
        rangeAnimatable = sceneAnimatable;
        break;
      }
    }
    const animatables = skeleton.getAnimatables();
    for (let index = 0;index < animatables.length; index++) {
      const animatable2 = animatables[index];
      const animations = animatable2.animations;
      if (!animations) {
        continue;
      }
      for (let animIndex = 0;animIndex < animations.length; animIndex++) {
        Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range);
      }
    }
    if (rangeAnimatable) {
      rangeAnimatable.isAdditive = true;
    }
    return skeleton;
  }
  _markAsDirty() {
    this._isDirty = true;
    this._absoluteTransformIsDirty = true;
  }
  _registerMeshWithPoseMatrix(mesh) {
    this._meshesWithPoseMatrix.push(mesh);
  }
  _unregisterMeshWithPoseMatrix(mesh) {
    const index = this._meshesWithPoseMatrix.indexOf(mesh);
    if (index > -1) {
      this._meshesWithPoseMatrix.splice(index, 1);
    }
  }
  _computeTransformMatrices(targetMatrix, initialSkinMatrix) {
    this.onBeforeComputeObservable.notifyObservers(this);
    for (let index = 0;index < this.bones.length; index++) {
      const bone = this.bones[index];
      bone._childUpdateId++;
      const parentBone = bone.getParent();
      if (parentBone) {
        bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix());
      } else {
        if (initialSkinMatrix) {
          bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix());
        } else {
          bone.getFinalMatrix().copyFrom(bone.getLocalMatrix());
        }
      }
      if (bone._index !== -1) {
        const mappedIndex = bone._index === null ? index : bone._index;
        bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16);
      }
    }
    this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  }
  prepare(dontCheckFrameId = false) {
    if (!dontCheckFrameId) {
      const currentRenderId = this.getScene().getRenderId();
      if (this._currentRenderId === currentRenderId) {
        return;
      }
      this._currentRenderId = currentRenderId;
    }
    if (this._numBonesWithLinkedTransformNode > 0) {
      for (const bone of this.bones) {
        if (bone._linkedTransformNode) {
          const node = bone._linkedTransformNode;
          bone.position = node.position;
          if (node.rotationQuaternion) {
            bone.rotationQuaternion = node.rotationQuaternion;
          } else {
            bone.rotation = node.rotation;
          }
          bone.scaling = node.scaling;
        }
      }
    }
    if (this.needInitialSkinMatrix) {
      for (const mesh of this._meshesWithPoseMatrix) {
        const poseMatrix = mesh.getPoseMatrix();
        let needsUpdate = this._isDirty;
        if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
          mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
          needsUpdate = true;
        }
        if (!needsUpdate) {
          continue;
        }
        if (this._synchronizedWithMesh !== mesh) {
          this._synchronizedWithMesh = mesh;
          for (const bone of this.bones) {
            if (!bone.getParent()) {
              const matrix = bone.getBindMatrix();
              matrix.multiplyToRef(poseMatrix, TmpVectors.Matrix[1]);
              bone._updateAbsoluteBindMatrices(TmpVectors.Matrix[1]);
            }
          }
          if (this.isUsingTextureForMatrices) {
            const textureWidth = (this.bones.length + 1) * 4;
            if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) {
              if (mesh._transformMatrixTexture) {
                mesh._transformMatrixTexture.dispose();
              }
              mesh._transformMatrixTexture = RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);
            }
          }
        }
        this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
        if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) {
          mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices);
        }
      }
    } else {
      if (!this._isDirty) {
        return;
      }
      if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
        this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
        if (this.isUsingTextureForMatrices) {
          if (this._transformMatrixTexture) {
            this._transformMatrixTexture.dispose();
          }
          this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);
        }
      }
      this._computeTransformMatrices(this._transformMatrices, null);
      if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
        this._transformMatrixTexture.update(this._transformMatrices);
      }
    }
    this._isDirty = false;
  }
  getAnimatables() {
    if (!this._animatables || this._animatables.length !== this.bones.length) {
      this._animatables = [];
      for (let index = 0;index < this.bones.length; index++) {
        this._animatables.push(this.bones[index]);
      }
    }
    return this._animatables;
  }
  clone(name18, id) {
    const result = new Skeleton(name18, id || name18, this._scene);
    result.needInitialSkinMatrix = this.needInitialSkinMatrix;
    for (let index = 0;index < this.bones.length; index++) {
      const source = this.bones[index];
      let parentBone = null;
      const parent = source.getParent();
      if (parent) {
        const parentIndex = this.bones.indexOf(parent);
        parentBone = result.bones[parentIndex];
      }
      const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone());
      bone._index = source._index;
      if (source._linkedTransformNode) {
        bone.linkTransformNode(source._linkedTransformNode);
      }
      DeepCopier.DeepCopy(source.animations, bone.animations);
    }
    if (this._ranges) {
      result._ranges = {};
      for (const rangeName in this._ranges) {
        const range = this._ranges[rangeName];
        if (range) {
          result._ranges[rangeName] = range.clone();
        }
      }
    }
    this._isDirty = true;
    result.prepare(true);
    return result;
  }
  enableBlending(blendingSpeed = 0.01) {
    this.bones.forEach((bone) => {
      bone.animations.forEach((animation2) => {
        animation2.enableBlending = true;
        animation2.blendingSpeed = blendingSpeed;
      });
    });
  }
  dispose() {
    this._meshesWithPoseMatrix.length = 0;
    this.getScene().stopAnimation(this);
    this.getScene().removeSkeleton(this);
    if (this._parentContainer) {
      const index = this._parentContainer.skeletons.indexOf(this);
      if (index > -1) {
        this._parentContainer.skeletons.splice(index, 1);
      }
      this._parentContainer = null;
    }
    if (this._transformMatrixTexture) {
      this._transformMatrixTexture.dispose();
      this._transformMatrixTexture = null;
    }
  }
  serialize() {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.id = this.id;
    if (this.dimensionsAtRest) {
      serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
    }
    serializationObject.bones = [];
    serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
    for (let index = 0;index < this.bones.length; index++) {
      const bone = this.bones[index];
      const parent = bone.getParent();
      const serializedBone = {
        parentBoneIndex: parent ? this.bones.indexOf(parent) : -1,
        index: bone.getIndex(),
        name: bone.name,
        id: bone.id,
        matrix: bone.getBindMatrix().asArray(),
        rest: bone.getRestMatrix().asArray(),
        linkedTransformNodeId: bone.getTransformNode()?.id
      };
      serializationObject.bones.push(serializedBone);
      if (bone.length) {
        serializedBone.length = bone.length;
      }
      if (bone.metadata) {
        serializedBone.metadata = bone.metadata;
      }
      if (bone.animations && bone.animations.length > 0) {
        serializedBone.animation = bone.animations[0].serialize();
      }
      serializationObject.ranges = [];
      for (const name18 in this._ranges) {
        const source = this._ranges[name18];
        if (!source) {
          continue;
        }
        const range = {};
        range.name = name18;
        range.from = source.from;
        range.to = source.to;
        serializationObject.ranges.push(range);
      }
    }
    return serializationObject;
  }
  static Parse(parsedSkeleton, scene) {
    const skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
    if (parsedSkeleton.dimensionsAtRest) {
      skeleton.dimensionsAtRest = Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
    }
    skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
    let index;
    for (index = 0;index < parsedSkeleton.bones.length; index++) {
      const parsedBone = parsedSkeleton.bones[index];
      const parsedBoneIndex = parsedSkeleton.bones[index].index;
      let parentBone = null;
      if (parsedBone.parentBoneIndex > -1) {
        parentBone = skeleton.bones[parsedBone.parentBoneIndex];
      }
      const rest = parsedBone.rest ? Matrix.FromArray(parsedBone.rest) : null;
      const bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex);
      if (parsedBone.id !== undefined && parsedBone.id !== null) {
        bone.id = parsedBone.id;
      }
      if (parsedBone.length) {
        bone.length = parsedBone.length;
      }
      if (parsedBone.metadata) {
        bone.metadata = parsedBone.metadata;
      }
      if (parsedBone.animation) {
        bone.animations.push(Animation.Parse(parsedBone.animation));
      }
      if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) {
        skeleton._hasWaitingData = true;
        bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId;
      }
    }
    if (parsedSkeleton.ranges) {
      for (index = 0;index < parsedSkeleton.ranges.length; index++) {
        const data = parsedSkeleton.ranges[index];
        skeleton.createAnimationRange(data.name, data.from, data.to);
      }
    }
    return skeleton;
  }
  computeAbsoluteMatrices(forceUpdate = false) {
    if (this._absoluteTransformIsDirty || forceUpdate) {
      this.bones[0].computeAbsoluteMatrices();
      this._absoluteTransformIsDirty = false;
    }
  }
  computeAbsoluteTransforms(forceUpdate = false) {
    this.computeAbsoluteMatrices(forceUpdate);
  }
  getPoseMatrix() {
    let poseMatrix = null;
    if (this._meshesWithPoseMatrix.length > 0) {
      poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
    }
    return poseMatrix;
  }
  sortBones() {
    const bones = [];
    const visited = new Array(this.bones.length);
    for (let index = 0;index < this.bones.length; index++) {
      this._sortBones(index, bones, visited);
    }
    this.bones = bones;
  }
  _sortBones(index, bones, visited) {
    if (visited[index]) {
      return;
    }
    visited[index] = true;
    const bone = this.bones[index];
    if (!bone)
      return;
    if (bone._index === undefined) {
      bone._index = index;
    }
    const parentBone = bone.getParent();
    if (parentBone) {
      this._sortBones(this.bones.indexOf(parentBone), bones, visited);
    }
    bones.push(bone);
  }
  setCurrentPoseAsRest() {
    this.bones.forEach((b) => {
      b.setCurrentPoseAsRest();
    });
  }
}
// node_modules/@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js
init_pointerEvents();
init_precisionDate();
init_math_constants();

class AutoRotationBehavior {
  constructor() {
    this._zoomStopsAnimation = false;
    this._idleRotationSpeed = 0.05;
    this._idleRotationWaitTime = 2000;
    this._idleRotationSpinupTime = 2000;
    this.targetAlpha = null;
    this._isPointerDown = false;
    this._lastFrameTime = null;
    this._lastInteractionTime = -Infinity;
    this._cameraRotationSpeed = 0;
    this._lastFrameRadius = 0;
  }
  get name() {
    return "AutoRotation";
  }
  set zoomStopsAnimation(flag) {
    this._zoomStopsAnimation = flag;
  }
  get zoomStopsAnimation() {
    return this._zoomStopsAnimation;
  }
  set idleRotationSpeed(speed) {
    this._idleRotationSpeed = speed;
  }
  get idleRotationSpeed() {
    return this._idleRotationSpeed;
  }
  set idleRotationWaitTime(time) {
    this._idleRotationWaitTime = time;
  }
  get idleRotationWaitTime() {
    return this._idleRotationWaitTime;
  }
  set idleRotationSpinupTime(time) {
    this._idleRotationSpinupTime = time;
  }
  get idleRotationSpinupTime() {
    return this._idleRotationSpinupTime;
  }
  get rotationInProgress() {
    return Math.abs(this._cameraRotationSpeed) > 0;
  }
  init() {}
  attach(camera) {
    this._attachedCamera = camera;
    const scene = this._attachedCamera.getScene();
    this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {
      if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {
        this._isPointerDown = true;
        return;
      }
      if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {
        this._isPointerDown = false;
      }
    });
    this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
      if (this._reachTargetAlpha()) {
        return;
      }
      const now = PrecisionDate.Now;
      let dt = 0;
      if (this._lastFrameTime != null) {
        dt = now - this._lastFrameTime;
      }
      this._lastFrameTime = now;
      this._applyUserInteraction();
      const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime;
      const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0);
      this._cameraRotationSpeed = this._idleRotationSpeed * scale;
      if (this._attachedCamera) {
        this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000);
      }
    });
  }
  detach() {
    if (!this._attachedCamera) {
      return;
    }
    const scene = this._attachedCamera.getScene();
    if (this._onPrePointerObservableObserver) {
      scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
    }
    this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
    this._attachedCamera = null;
    this._lastFrameTime = null;
  }
  resetLastInteractionTime(customTime) {
    this._lastInteractionTime = customTime ?? PrecisionDate.Now;
  }
  _reachTargetAlpha() {
    if (this._attachedCamera && this.targetAlpha) {
      return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < Epsilon;
    }
    return false;
  }
  _userIsZooming() {
    if (!this._attachedCamera) {
      return false;
    }
    return this._attachedCamera.inertialRadiusOffset !== 0;
  }
  _shouldAnimationStopForInteraction() {
    if (!this._attachedCamera) {
      return false;
    }
    let zoomHasHitLimit = false;
    if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
      zoomHasHitLimit = true;
    }
    this._lastFrameRadius = this._attachedCamera.radius;
    return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  }
  _applyUserInteraction() {
    if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
      this._lastInteractionTime = PrecisionDate.Now;
    }
  }
  _userIsMoving() {
    if (!this._attachedCamera) {
      return false;
    }
    return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown;
  }
}
// node_modules/@babylonjs/core/Behaviors/Cameras/bouncingBehavior.js
init_easing();
init_animation();

class BouncingBehavior {
  constructor() {
    this.transitionDuration = 450;
    this.lowerRadiusTransitionRange = 2;
    this.upperRadiusTransitionRange = -2;
    this._autoTransitionRange = false;
    this._radiusIsAnimating = false;
    this._radiusBounceTransition = null;
    this._animatables = new Array;
  }
  get name() {
    return "Bouncing";
  }
  get autoTransitionRange() {
    return this._autoTransitionRange;
  }
  set autoTransitionRange(value) {
    if (this._autoTransitionRange === value) {
      return;
    }
    this._autoTransitionRange = value;
    const camera = this._attachedCamera;
    if (!camera) {
      return;
    }
    if (value) {
      this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => {
        if (!transformNode) {
          return;
        }
        transformNode.computeWorldMatrix(true);
        if (transformNode.getBoundingInfo) {
          const diagonal = transformNode.getBoundingInfo().diagonalLength;
          this.lowerRadiusTransitionRange = diagonal * 0.05;
          this.upperRadiusTransitionRange = diagonal * 0.05;
        }
      });
    } else if (this._onMeshTargetChangedObserver) {
      camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
    }
  }
  init() {}
  attach(camera) {
    this._attachedCamera = camera;
    this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
      if (!this._attachedCamera) {
        return;
      }
      if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) {
        this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange);
      }
      if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) {
        this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange);
      }
    });
  }
  detach() {
    if (!this._attachedCamera) {
      return;
    }
    if (this._onAfterCheckInputsObserver) {
      this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
    }
    if (this._onMeshTargetChangedObserver) {
      this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
    }
    this._attachedCamera = null;
  }
  _isRadiusAtLimit(radiusLimit) {
    if (!this._attachedCamera) {
      return false;
    }
    if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
      return true;
    }
    return false;
  }
  _applyBoundRadiusAnimation(radiusDelta) {
    if (!this._attachedCamera) {
      return;
    }
    if (!this._radiusBounceTransition) {
      BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
      this._radiusBounceTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
    }
    this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
    this._attachedCamera.wheelPrecision = Infinity;
    this._attachedCamera.inertialRadiusOffset = 0;
    this.stopAllAnimations();
    this._radiusIsAnimating = true;
    const animatable2 = Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks());
    if (animatable2) {
      this._animatables.push(animatable2);
    }
  }
  _clearAnimationLocks() {
    this._radiusIsAnimating = false;
    if (this._attachedCamera) {
      this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
    }
  }
  stopAllAnimations() {
    if (this._attachedCamera) {
      this._attachedCamera.animations = [];
    }
    while (this._animatables.length) {
      this._animatables[0].onAnimationEnd = null;
      this._animatables[0].stop();
      this._animatables.shift();
    }
  }
}
BouncingBehavior.EasingFunction = new BackEase(0.3);
BouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT;
// node_modules/@babylonjs/core/Behaviors/Cameras/framingBehavior.js
init_easing();
init_observable();
init_pointerEvents();
init_precisionDate();
init_math_vector();
init_animation();

class FramingBehavior {
  constructor() {
    this.onTargetFramingAnimationEndObservable = new Observable;
    this._mode = FramingBehavior.FitFrustumSidesMode;
    this._radiusScale = 1;
    this._positionScale = 0.5;
    this._defaultElevation = 0.3;
    this._elevationReturnTime = 1500;
    this._elevationReturnWaitTime = 1000;
    this._zoomStopsAnimation = false;
    this._framingTime = 1500;
    this.autoCorrectCameraLimitsAndSensibility = true;
    this._isPointerDown = false;
    this._lastInteractionTime = -Infinity;
    this._animatables = new Array;
    this._betaIsAnimating = false;
  }
  get name() {
    return "Framing";
  }
  set mode(mode) {
    this._mode = mode;
  }
  get mode() {
    return this._mode;
  }
  set radiusScale(radius) {
    this._radiusScale = radius;
  }
  get radiusScale() {
    return this._radiusScale;
  }
  set positionScale(scale) {
    this._positionScale = scale;
  }
  get positionScale() {
    return this._positionScale;
  }
  set defaultElevation(elevation) {
    this._defaultElevation = elevation;
  }
  get defaultElevation() {
    return this._defaultElevation;
  }
  set elevationReturnTime(speed) {
    this._elevationReturnTime = speed;
  }
  get elevationReturnTime() {
    return this._elevationReturnTime;
  }
  set elevationReturnWaitTime(time) {
    this._elevationReturnWaitTime = time;
  }
  get elevationReturnWaitTime() {
    return this._elevationReturnWaitTime;
  }
  set zoomStopsAnimation(flag) {
    this._zoomStopsAnimation = flag;
  }
  get zoomStopsAnimation() {
    return this._zoomStopsAnimation;
  }
  set framingTime(time) {
    this._framingTime = time;
  }
  get framingTime() {
    return this._framingTime;
  }
  init() {}
  attach(camera) {
    this._attachedCamera = camera;
    const scene = this._attachedCamera.getScene();
    FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
    this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {
      if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {
        this._isPointerDown = true;
        return;
      }
      if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {
        this._isPointerDown = false;
      }
    });
    this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((transformNode) => {
      if (transformNode && transformNode.getBoundingInfo) {
        this.zoomOnMesh(transformNode, undefined, () => {
          this.onTargetFramingAnimationEndObservable.notifyObservers();
        });
      }
    });
    this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {
      this._applyUserInteraction();
      this._maintainCameraAboveGround();
    });
  }
  detach() {
    if (!this._attachedCamera) {
      return;
    }
    const scene = this._attachedCamera.getScene();
    if (this._onPrePointerObservableObserver) {
      scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
    }
    if (this._onAfterCheckInputsObserver) {
      this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
    }
    if (this._onMeshTargetChangedObserver) {
      this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
    }
    this._attachedCamera = null;
  }
  zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {
    mesh.computeWorldMatrix(true);
    const boundingBox = mesh.getBoundingInfo().boundingBox;
    this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  }
  zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {
    mesh.computeWorldMatrix(true);
    const boundingBox = mesh.getHierarchyBoundingVectors(true);
    this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  }
  zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) {
    const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    for (let i = 0;i < meshes.length; i++) {
      const boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
      Vector3.CheckExtends(boundingInfo.min, min, max);
      Vector3.CheckExtends(boundingInfo.max, min, max);
    }
    this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  }
  zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) {
    let zoomTarget;
    if (!this._attachedCamera) {
      return false;
    }
    const bottom = minimumWorld.y;
    const top = maximumWorld.y;
    const zoomTargetY = bottom + (top - bottom) * this._positionScale;
    const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
    if (!isFinite(zoomTargetY)) {
      return false;
    }
    if (focusOnOriginXZ) {
      zoomTarget = new Vector3(0, zoomTargetY, 0);
    } else {
      const centerWorld = minimumWorld.add(radiusWorld);
      zoomTarget = new Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
    }
    if (!this._vectorTransition) {
      this._vectorTransition = Animation.CreateAnimation("target", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
    }
    this._betaIsAnimating = true;
    let animatable2 = Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
    if (animatable2) {
      this._animatables.push(animatable2);
    }
    let radius = 0;
    if (this._mode === FramingBehavior.FitFrustumSidesMode) {
      const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
      if (this.autoCorrectCameraLimitsAndSensibility) {
        this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
      }
      radius = position;
    } else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
      radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
      if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
        this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
      }
    }
    if (this.autoCorrectCameraLimitsAndSensibility) {
      const extend = maximumWorld.subtract(minimumWorld).length();
      this._attachedCamera.panningSensibility = 5000 / extend;
      this._attachedCamera.wheelPrecision = 100 / radius;
    }
    if (!this._radiusTransition) {
      this._radiusTransition = Animation.CreateAnimation("radius", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
    }
    animatable2 = Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => {
      this.stopAllAnimations();
      if (onAnimationEnd) {
        onAnimationEnd();
      }
      if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) {
        this._attachedCamera.storeState();
      }
    });
    if (animatable2) {
      this._animatables.push(animatable2);
    }
    return true;
  }
  _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) {
    const camera = this._attachedCamera;
    if (!camera) {
      return 0;
    }
    let distance = camera._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, this._radiusScale);
    if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
      distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
    }
    if (camera.upperRadiusLimit) {
      distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
    }
    return distance;
  }
  _maintainCameraAboveGround() {
    if (this._elevationReturnTime < 0) {
      return;
    }
    const timeSinceInteraction = PrecisionDate.Now - this._lastInteractionTime;
    const defaultBeta = Math.PI * 0.5 - this._defaultElevation;
    const limitBeta = Math.PI * 0.5;
    if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
      this._betaIsAnimating = true;
      this.stopAllAnimations();
      if (!this._betaTransition) {
        this._betaTransition = Animation.CreateAnimation("beta", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
      }
      const animatabe = Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => {
        this._clearAnimationLocks();
        this.stopAllAnimations();
      });
      if (animatabe) {
        this._animatables.push(animatabe);
      }
    }
  }
  _clearAnimationLocks() {
    this._betaIsAnimating = false;
  }
  _applyUserInteraction() {
    if (this.isUserIsMoving) {
      this._lastInteractionTime = PrecisionDate.Now;
      this.stopAllAnimations();
      this._clearAnimationLocks();
    }
  }
  stopAllAnimations() {
    if (this._attachedCamera) {
      this._attachedCamera.animations = [];
    }
    while (this._animatables.length) {
      if (this._animatables[0]) {
        this._animatables[0].onAnimationEnd = null;
        this._animatables[0].stop();
      }
      this._animatables.shift();
    }
  }
  get isUserIsMoving() {
    if (!this._attachedCamera) {
      return false;
    }
    return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown;
  }
}
FramingBehavior.EasingFunction = new ExponentialEase;
FramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT;
FramingBehavior.IgnoreBoundsSizeMode = 0;
FramingBehavior.FitFrustumSidesMode = 1;
// node_modules/@babylonjs/core/Behaviors/Meshes/attachToBoxBehavior.js
init_math_vector();
// node_modules/@babylonjs/core/Behaviors/Meshes/pointerDragBehavior.js
init_scene();
init_observable();
init_math_vector();
init_pointerEvents();

// node_modules/@babylonjs/core/Culling/ray.js
init_scene();

// node_modules/@babylonjs/core/Culling/ray.core.js
init_math_constants();
init_math_vector();
init_arrayTools();
init_pickingInfo();
init_engineStore();
init_import_helper();
var PickingCustomization = {
  internalPickerForMesh: undefined
};

class Ray {
  constructor(origin, direction, length = Number.MAX_VALUE, epsilon = Epsilon) {
    this.origin = origin;
    this.direction = direction;
    this.length = length;
    this.epsilon = epsilon;
  }
  clone() {
    return new Ray(this.origin.clone(), this.direction.clone(), this.length);
  }
  intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) {
    const newMinimum = Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
    const newMaximum = Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
    let d = 0;
    let maxValue = Number.MAX_VALUE;
    let inv;
    let min;
    let max;
    let temp;
    if (Math.abs(this.direction.x) < 0.0000001) {
      if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
        return false;
      }
    } else {
      inv = 1 / this.direction.x;
      min = (newMinimum.x - this.origin.x) * inv;
      max = (newMaximum.x - this.origin.x) * inv;
      if (max === -Infinity) {
        max = Infinity;
      }
      if (min > max) {
        temp = min;
        min = max;
        max = temp;
      }
      d = Math.max(min, d);
      maxValue = Math.min(max, maxValue);
      if (d > maxValue) {
        return false;
      }
    }
    if (Math.abs(this.direction.y) < 0.0000001) {
      if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
        return false;
      }
    } else {
      inv = 1 / this.direction.y;
      min = (newMinimum.y - this.origin.y) * inv;
      max = (newMaximum.y - this.origin.y) * inv;
      if (max === -Infinity) {
        max = Infinity;
      }
      if (min > max) {
        temp = min;
        min = max;
        max = temp;
      }
      d = Math.max(min, d);
      maxValue = Math.min(max, maxValue);
      if (d > maxValue) {
        return false;
      }
    }
    if (Math.abs(this.direction.z) < 0.0000001) {
      if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
        return false;
      }
    } else {
      inv = 1 / this.direction.z;
      min = (newMinimum.z - this.origin.z) * inv;
      max = (newMaximum.z - this.origin.z) * inv;
      if (max === -Infinity) {
        max = Infinity;
      }
      if (min > max) {
        temp = min;
        min = max;
        max = temp;
      }
      d = Math.max(min, d);
      maxValue = Math.min(max, maxValue);
      if (d > maxValue) {
        return false;
      }
    }
    return true;
  }
  intersectsBox(box, intersectionTreshold = 0) {
    return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  }
  intersectsSphere(sphere, intersectionTreshold = 0) {
    const x = sphere.center.x - this.origin.x;
    const y = sphere.center.y - this.origin.y;
    const z = sphere.center.z - this.origin.z;
    const pyth = x * x + y * y + z * z;
    const radius = sphere.radius + intersectionTreshold;
    const rr = radius * radius;
    if (pyth <= rr) {
      return true;
    }
    const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z;
    if (dot < 0) {
      return false;
    }
    const temp = pyth - dot * dot;
    return temp <= rr;
  }
  intersectsTriangle(vertex0, vertex1, vertex2) {
    const edge1 = Ray._TmpVector3[0];
    const edge2 = Ray._TmpVector3[1];
    const pvec = Ray._TmpVector3[2];
    const tvec = Ray._TmpVector3[3];
    const qvec = Ray._TmpVector3[4];
    vertex1.subtractToRef(vertex0, edge1);
    vertex2.subtractToRef(vertex0, edge2);
    Vector3.CrossToRef(this.direction, edge2, pvec);
    const det = Vector3.Dot(edge1, pvec);
    if (det === 0) {
      return null;
    }
    const invdet = 1 / det;
    this.origin.subtractToRef(vertex0, tvec);
    const bv = Vector3.Dot(tvec, pvec) * invdet;
    if (bv < -this.epsilon || bv > 1 + this.epsilon) {
      return null;
    }
    Vector3.CrossToRef(tvec, edge1, qvec);
    const bw = Vector3.Dot(this.direction, qvec) * invdet;
    if (bw < -this.epsilon || bv + bw > 1 + this.epsilon) {
      return null;
    }
    const distance = Vector3.Dot(edge2, qvec) * invdet;
    if (distance > this.length) {
      return null;
    }
    return new IntersectionInfo(1 - bv - bw, bv, distance);
  }
  intersectsPlane(plane) {
    let distance;
    const result1 = Vector3.Dot(plane.normal, this.direction);
    if (Math.abs(result1) < 0.000000999999997475243) {
      return null;
    } else {
      const result2 = Vector3.Dot(plane.normal, this.origin);
      distance = (-plane.d - result2) / result1;
      if (distance < 0) {
        if (distance < -0.000000999999997475243) {
          return null;
        } else {
          return 0;
        }
      }
      return distance;
    }
  }
  intersectsAxis(axis, offset = 0) {
    switch (axis) {
      case "y": {
        const t = (this.origin.y - offset) / this.direction.y;
        if (t > 0) {
          return null;
        }
        return new Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t);
      }
      case "x": {
        const t = (this.origin.x - offset) / this.direction.x;
        if (t > 0) {
          return null;
        }
        return new Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t);
      }
      case "z": {
        const t = (this.origin.z - offset) / this.direction.z;
        if (t > 0) {
          return null;
        }
        return new Vector3(this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset);
      }
      default:
        return null;
    }
  }
  intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {
    const tm = TmpVectors.Matrix[0];
    mesh.getWorldMatrix().invertToRef(tm);
    if (this._tmpRay) {
      Ray.TransformToRef(this, tm, this._tmpRay);
    } else {
      this._tmpRay = Ray.Transform(this, tm);
    }
    return mesh.intersects(this._tmpRay, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo);
  }
  intersectsMeshes(meshes, fastCheck, results) {
    if (results) {
      results.length = 0;
    } else {
      results = [];
    }
    for (let i = 0;i < meshes.length; i++) {
      const pickInfo = this.intersectsMesh(meshes[i], fastCheck);
      if (pickInfo.hit) {
        results.push(pickInfo);
      }
    }
    results.sort(this._comparePickingInfo);
    return results;
  }
  _comparePickingInfo(pickingInfoA, pickingInfoB) {
    if (pickingInfoA.distance < pickingInfoB.distance) {
      return -1;
    } else if (pickingInfoA.distance > pickingInfoB.distance) {
      return 1;
    } else {
      return 0;
    }
  }
  intersectionSegment(sega, segb, threshold) {
    const o = this.origin;
    const u = TmpVectors.Vector3[0];
    const rsegb = TmpVectors.Vector3[1];
    const v = TmpVectors.Vector3[2];
    const w = TmpVectors.Vector3[3];
    segb.subtractToRef(sega, u);
    this.direction.scaleToRef(Ray._Rayl, v);
    o.addToRef(v, rsegb);
    sega.subtractToRef(o, w);
    const a = Vector3.Dot(u, u);
    const b = Vector3.Dot(u, v);
    const c = Vector3.Dot(v, v);
    const d = Vector3.Dot(u, w);
    const e = Vector3.Dot(v, w);
    const D = a * c - b * b;
    let sN, sD = D;
    let tN, tD = D;
    if (D < Ray._Smallnum) {
      sN = 0;
      sD = 1;
      tN = e;
      tD = c;
    } else {
      sN = b * e - c * d;
      tN = a * e - b * d;
      if (sN < 0) {
        sN = 0;
        tN = e;
        tD = c;
      } else if (sN > sD) {
        sN = sD;
        tN = e + b;
        tD = c;
      }
    }
    if (tN < 0) {
      tN = 0;
      if (-d < 0) {
        sN = 0;
      } else if (-d > a) {
        sN = sD;
      } else {
        sN = -d;
        sD = a;
      }
    } else if (tN > tD) {
      tN = tD;
      if (-d + b < 0) {
        sN = 0;
      } else if (-d + b > a) {
        sN = sD;
      } else {
        sN = -d + b;
        sD = a;
      }
    }
    const sc = Math.abs(sN) < Ray._Smallnum ? 0 : sN / sD;
    const tc = Math.abs(tN) < Ray._Smallnum ? 0 : tN / tD;
    const qtc = TmpVectors.Vector3[4];
    v.scaleToRef(tc, qtc);
    const qsc = TmpVectors.Vector3[5];
    u.scaleToRef(sc, qsc);
    qsc.addInPlace(w);
    const dP = TmpVectors.Vector3[6];
    qsc.subtractToRef(qtc, dP);
    const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold;
    if (isIntersected) {
      return qsc.length();
    }
    return -1;
  }
  update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) {
    if (enableDistantPicking) {
      if (!Ray._RayDistant) {
        Ray._RayDistant = Ray.Zero();
      }
      Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, Matrix.IdentityReadOnly, view, projection);
      const tm = TmpVectors.Matrix[0];
      world.invertToRef(tm);
      Ray.TransformToRef(Ray._RayDistant, tm, this);
    } else {
      this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection);
    }
    return this;
  }
  static Zero() {
    return new Ray(Vector3.Zero(), Vector3.Zero());
  }
  static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) {
    const result = Ray.Zero();
    return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  }
  static CreateNewFromTo(origin, end, world = Matrix.IdentityReadOnly) {
    const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
    return Ray.CreateFromToToRef(origin, end, result, world);
  }
  static CreateFromToToRef(origin, end, result, world = Matrix.IdentityReadOnly) {
    result.origin.copyFrom(origin);
    const direction = end.subtractToRef(origin, result.direction);
    const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);
    result.length = length;
    result.direction.normalize();
    return Ray.TransformToRef(result, world, result);
  }
  static Transform(ray, matrix) {
    const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
    Ray.TransformToRef(ray, matrix, result);
    return result;
  }
  static TransformToRef(ray, matrix, result) {
    Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
    Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
    result.length = ray.length;
    result.epsilon = ray.epsilon;
    const dir = result.direction;
    const len = dir.length();
    if (!(len === 0 || len === 1)) {
      const num = 1 / len;
      dir.x *= num;
      dir.y *= num;
      dir.z *= num;
      result.length *= len;
    }
    return result;
  }
  unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) {
    const matrix = TmpVectors.Matrix[0];
    world.multiplyToRef(view, matrix);
    matrix.multiplyToRef(projection, matrix);
    matrix.invert();
    const engine = EngineStore.LastCreatedEngine;
    const nearScreenSource = TmpVectors.Vector3[0];
    nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
    nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
    nearScreenSource.z = engine?.useReverseDepthBuffer ? 1 : engine?.isNDCHalfZRange ? 0 : -1;
    const farScreenSource = TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1 - 0.00000001);
    const nearVec3 = TmpVectors.Vector3[2];
    const farVec3 = TmpVectors.Vector3[3];
    Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
    Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
    this.origin.copyFrom(nearVec3);
    farVec3.subtractToRef(nearVec3, this.direction);
    this.direction.normalize();
  }
}
Ray._TmpVector3 = BuildArray(6, Vector3.Zero);
Ray._RayDistant = Ray.Zero();
Ray._Smallnum = 0.00000001;
Ray._Rayl = 1e9;
function CreatePickingRay(scene, x, y, world, camera, cameraViewSpace = false) {
  const result = Ray.Zero();
  CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace);
  return result;
}
function CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {
  const engine = scene.getEngine();
  if (!camera && !(camera = scene.activeCamera)) {
    return scene;
  }
  const cameraViewport = camera.viewport;
  const renderHeight = engine.getRenderHeight();
  const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight);
  const levelInv = 1 / engine.getHardwareScalingLevel();
  x = x * levelInv - vx;
  y = y * levelInv - (renderHeight - vy - height);
  result.update(x, y, width, height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking);
  return scene;
}
function CreatePickingRayInCameraSpace(scene, x, y, camera) {
  const result = Ray.Zero();
  CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera);
  return result;
}
function CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera) {
  if (!PickingInfo) {
    return scene;
  }
  const engine = scene.getEngine();
  if (!camera && !(camera = scene.activeCamera)) {
    throw new Error("Active camera not set");
  }
  const cameraViewport = camera.viewport;
  const renderHeight = engine.getRenderHeight();
  const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight);
  const identity = Matrix.Identity();
  const levelInv = 1 / engine.getHardwareScalingLevel();
  x = x * levelInv - vx;
  y = y * levelInv - (renderHeight - vy - height);
  result.update(x, y, width, height, identity, identity, camera.getProjectionMatrix());
  return scene;
}
function InternalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) {
  const ray = rayFunction(world, mesh.enableDistantPicking);
  const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo);
  if (!result || !result.hit) {
    return null;
  }
  if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
    return null;
  }
  return result;
}
function InternalPick(scene, rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) {
  let pickingInfo = null;
  const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera);
  const currentCamera = scene.cameraToUseForPointers || scene.activeCamera;
  const picker = PickingCustomization.internalPickerForMesh || InternalPickForMesh;
  for (let meshIndex = 0;meshIndex < scene.meshes.length; meshIndex++) {
    const mesh = scene.meshes[meshIndex];
    if (predicate) {
      if (!predicate(mesh, -1)) {
        continue;
      }
    } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
      continue;
    }
    const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();
    const world = mesh.computeWorldMatrix(forceCompute, currentCamera);
    if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {
      const result = picker(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate);
      if (result) {
        if (onlyBoundingInfo) {
          return result;
        }
        const tmpMatrix = TmpVectors.Matrix[1];
        const thinMatrices = mesh.thinInstanceGetWorldMatrices();
        for (let index = 0;index < thinMatrices.length; index++) {
          if (predicate && !predicate(mesh, index)) {
            continue;
          }
          const thinMatrix = thinMatrices[index];
          thinMatrix.multiplyToRef(world, tmpMatrix);
          const result2 = picker(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true);
          if (result2) {
            pickingInfo = result2;
            pickingInfo.thinInstanceIndex = index;
            if (fastCheck) {
              return pickingInfo;
            }
          }
        }
      }
    } else {
      const result = picker(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate);
      if (result) {
        pickingInfo = result;
        if (fastCheck) {
          return pickingInfo;
        }
      }
    }
  }
  return pickingInfo || new PickingInfo;
}
function InternalMultiPick(scene, rayFunction, predicate, trianglePredicate) {
  if (!PickingInfo) {
    return null;
  }
  const pickingInfos = [];
  const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera);
  const currentCamera = scene.cameraToUseForPointers || scene.activeCamera;
  const picker = PickingCustomization.internalPickerForMesh || InternalPickForMesh;
  for (let meshIndex = 0;meshIndex < scene.meshes.length; meshIndex++) {
    const mesh = scene.meshes[meshIndex];
    if (predicate) {
      if (!predicate(mesh, -1)) {
        continue;
      }
    } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
      continue;
    }
    const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();
    const world = mesh.computeWorldMatrix(forceCompute, currentCamera);
    if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {
      const result = picker(null, rayFunction, mesh, world, true, true, trianglePredicate);
      if (result) {
        const tmpMatrix = TmpVectors.Matrix[1];
        const thinMatrices = mesh.thinInstanceGetWorldMatrices();
        for (let index = 0;index < thinMatrices.length; index++) {
          if (predicate && !predicate(mesh, index)) {
            continue;
          }
          const thinMatrix = thinMatrices[index];
          thinMatrix.multiplyToRef(world, tmpMatrix);
          const result2 = picker(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true);
          if (result2) {
            result2.thinInstanceIndex = index;
            pickingInfos.push(result2);
          }
        }
      }
    } else {
      const result = picker(null, rayFunction, mesh, world, false, false, trianglePredicate);
      if (result) {
        pickingInfos.push(result);
      }
    }
  }
  return pickingInfos;
}
function PickWithBoundingInfo(scene, x, y, predicate, fastCheck, camera) {
  if (!PickingInfo) {
    return null;
  }
  const result = InternalPick(scene, (world) => {
    if (!scene._tempPickingRay) {
      scene._tempPickingRay = Ray.Zero();
    }
    CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null);
    return scene._tempPickingRay;
  }, predicate, fastCheck, true);
  if (result) {
    result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null);
  }
  return result;
}
function Pick(scene, x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) {
  const result = InternalPick(scene, (world, enableDistantPicking) => {
    if (!scene._tempPickingRay) {
      scene._tempPickingRay = Ray.Zero();
    }
    CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null, false, enableDistantPicking);
    return scene._tempPickingRay;
  }, predicate, fastCheck, false, trianglePredicate);
  if (result) {
    result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null);
  }
  return result;
}
function PickWithRay(scene, ray, predicate, fastCheck, trianglePredicate) {
  const result = InternalPick(scene, (world) => {
    if (!scene._pickWithRayInverseMatrix) {
      scene._pickWithRayInverseMatrix = Matrix.Identity();
    }
    world.invertToRef(scene._pickWithRayInverseMatrix);
    if (!scene._cachedRayForTransform) {
      scene._cachedRayForTransform = Ray.Zero();
    }
    Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform);
    return scene._cachedRayForTransform;
  }, predicate, fastCheck, false, trianglePredicate);
  if (result) {
    result.ray = ray;
  }
  return result;
}
function MultiPick(scene, x, y, predicate, camera, trianglePredicate) {
  return InternalMultiPick(scene, (world) => CreatePickingRay(scene, x, y, world, camera || null), predicate, trianglePredicate);
}
function MultiPickWithRay(scene, ray, predicate, trianglePredicate) {
  return InternalMultiPick(scene, (world) => {
    if (!scene._pickWithRayInverseMatrix) {
      scene._pickWithRayInverseMatrix = Matrix.Identity();
    }
    world.invertToRef(scene._pickWithRayInverseMatrix);
    if (!scene._cachedRayForTransform) {
      scene._cachedRayForTransform = Ray.Zero();
    }
    Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform);
    return scene._cachedRayForTransform;
  }, predicate, trianglePredicate);
}
function GetForwardRayToRef(camera, refRay, length = 100, transform, origin) {
  if (!transform) {
    transform = camera.getWorldMatrix();
  }
  refRay.length = length;
  if (origin) {
    refRay.origin.copyFrom(origin);
  } else {
    refRay.origin.copyFrom(camera.position);
  }
  const forward = TmpVectors.Vector3[2];
  forward.set(0, 0, camera._scene.useRightHandedSystem ? -1 : 1);
  const worldForward = TmpVectors.Vector3[3];
  Vector3.TransformNormalToRef(forward, transform, worldForward);
  Vector3.NormalizeToRef(worldForward, refRay.direction);
  return refRay;
}
function AddRayExtensions(sceneClass, cameraClass) {
  if (cameraClass) {
    cameraClass.prototype.getForwardRay = function(length = 100, transform, origin) {
      return GetForwardRayToRef(this, new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin);
    };
    cameraClass.prototype.getForwardRayToRef = function(refRay, length = 100, transform, origin) {
      return GetForwardRayToRef(this, refRay, length, transform, origin);
    };
  }
  if (!sceneClass) {
    return;
  }
  _ImportHelper._IsPickingAvailable = true;
  sceneClass.prototype.createPickingRay = function(x, y, world, camera, cameraViewSpace = false) {
    return CreatePickingRay(this, x, y, world, camera, cameraViewSpace);
  };
}

// node_modules/@babylonjs/core/Culling/ray.js
AddRayExtensions(Scene, Camera);
Scene.prototype.createPickingRayToRef = function(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {
  return CreatePickingRayToRef(this, x, y, world, result, camera, cameraViewSpace, enableDistantPicking);
};
Scene.prototype.createPickingRayInCameraSpace = function(x, y, camera) {
  return CreatePickingRayInCameraSpace(this, x, y, camera);
};
Scene.prototype.createPickingRayInCameraSpaceToRef = function(x, y, result, camera) {
  return CreatePickingRayInCameraSpaceToRef(this, x, y, result, camera);
};
Scene.prototype.pickWithBoundingInfo = function(x, y, predicate, fastCheck, camera) {
  return PickWithBoundingInfo(this, x, y, predicate, fastCheck, camera);
};
Scene.prototype.pick = function(x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) {
  return Pick(this, x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking);
};
Scene.prototype.pickWithRay = function(ray, predicate, fastCheck, trianglePredicate) {
  return PickWithRay(this, ray, predicate, fastCheck, trianglePredicate);
};
Scene.prototype.multiPick = function(x, y, predicate, camera, trianglePredicate) {
  return MultiPick(this, x, y, predicate, camera, trianglePredicate);
};
Scene.prototype.multiPickWithRay = function(ray, predicate, trianglePredicate) {
  return MultiPickWithRay(this, ray, predicate, trianglePredicate);
};

// node_modules/@babylonjs/core/Misc/pivotTools.js
init_math_vector();

class PivotTools {
  static _RemoveAndStorePivotPoint(mesh) {
    if (mesh && PivotTools._PivotCached === 0) {
      mesh.getPivotPointToRef(PivotTools._OldPivotPoint);
      PivotTools._PivotPostMultiplyPivotMatrix = mesh._postMultiplyPivotMatrix;
      if (!PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0)) {
        mesh.setPivotMatrix(Matrix.IdentityReadOnly);
        PivotTools._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), PivotTools._PivotTranslation);
        PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);
        PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);
        PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);
        mesh.position.addInPlace(PivotTools._PivotTmpVector);
      }
    }
    PivotTools._PivotCached++;
  }
  static _RestorePivotPoint(mesh) {
    if (mesh && !PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0) && PivotTools._PivotCached === 1) {
      mesh.setPivotPoint(PivotTools._OldPivotPoint);
      mesh._postMultiplyPivotMatrix = PivotTools._PivotPostMultiplyPivotMatrix;
      PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);
      PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);
      PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);
      mesh.position.subtractInPlace(PivotTools._PivotTmpVector);
    }
    this._PivotCached--;
  }
}
PivotTools._PivotCached = 0;
PivotTools._OldPivotPoint = new Vector3;
PivotTools._PivotTranslation = new Vector3;
PivotTools._PivotTmpVector = new Vector3;
PivotTools._PivotPostMultiplyPivotMatrix = false;

// node_modules/@babylonjs/core/Meshes/Builders/planeBuilder.js
init_compatibilityOptions();
function CreatePlaneVertexData(options) {
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  const width = options.width !== undefined ? options.width : options.size !== undefined ? options.size : 1;
  const height = options.height !== undefined ? options.height : options.size !== undefined ? options.size : 1;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const halfWidth = width / 2;
  const halfHeight = height / 2;
  positions.push(-halfWidth, -halfHeight, 0);
  normals.push(0, 0, -1);
  uvs.push(0, useOpenGLOrientationForUV ? 1 : 0);
  positions.push(halfWidth, -halfHeight, 0);
  normals.push(0, 0, -1);
  uvs.push(1, useOpenGLOrientationForUV ? 1 : 0);
  positions.push(halfWidth, halfHeight, 0);
  normals.push(0, 0, -1);
  uvs.push(1, useOpenGLOrientationForUV ? 0 : 1);
  positions.push(-halfWidth, halfHeight, 0);
  normals.push(0, 0, -1);
  uvs.push(0, useOpenGLOrientationForUV ? 0 : 1);
  indices.push(0);
  indices.push(1);
  indices.push(2);
  indices.push(0);
  indices.push(2);
  indices.push(3);
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreatePlane(name18, options = {}, scene = null) {
  const plane = new Mesh(name18, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  plane._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreatePlaneVertexData(options);
  vertexData.applyToMesh(plane, options.updatable);
  if (options.sourcePlane) {
    plane.translate(options.sourcePlane.normal, -options.sourcePlane.d);
    plane.setDirection(options.sourcePlane.normal.scale(-1));
  }
  return plane;
}
VertexData.CreatePlane = CreatePlaneVertexData;
Mesh.CreatePlane = (name18, size, scene, updatable, sideOrientation) => {
  const options = {
    size,
    width: size,
    height: size,
    sideOrientation,
    updatable
  };
  return CreatePlane(name18, options, scene);
};

// node_modules/@babylonjs/core/Behaviors/Meshes/pointerDragBehavior.js
init_math_constants();

class PointerDragBehavior {
  get currentDraggingPointerID() {
    return this.currentDraggingPointerId;
  }
  set currentDraggingPointerID(currentDraggingPointerID) {
    this.currentDraggingPointerId = currentDraggingPointerID;
  }
  set enabled(value) {
    if (value != this._enabled) {
      this.onEnabledObservable.notifyObservers(value);
    }
    this._enabled = value;
  }
  get enabled() {
    return this._enabled;
  }
  get options() {
    return this._options;
  }
  set options(options) {
    this._options = options;
  }
  constructor(options) {
    this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1;
    this._activeDragButton = -1;
    this.maxDragAngle = 0;
    this.dragButtons = [0, 1, 2];
    this._useAlternatePickedPointAboveMaxDragAngle = false;
    this.currentDraggingPointerId = -1;
    this.dragging = false;
    this.dragDeltaRatio = 0.2;
    this.updateDragPlane = true;
    this._debugMode = false;
    this._moving = false;
    this.onDragObservable = new Observable;
    this.onDragStartObservable = new Observable;
    this.onDragEndObservable = new Observable;
    this.onEnabledObservable = new Observable;
    this.moveAttached = true;
    this._enabled = true;
    this.startAndReleaseDragOnPointerEvents = true;
    this.detachCameraControls = true;
    this.useObjectOrientationForDragging = true;
    this.validateDrag = (target) => {
      return true;
    };
    this._tmpVector = new Vector3(0, 0, 0);
    this._alternatePickedPoint = new Vector3(0, 0, 0);
    this._worldDragAxis = new Vector3(0, 0, 0);
    this._targetPosition = new Vector3(0, 0, 0);
    this._attachedToElement = false;
    this._startDragRay = new Ray(new Vector3, new Vector3);
    this._lastPointerRay = {};
    this._dragDelta = new Vector3;
    this._pointA = new Vector3(0, 0, 0);
    this._pointC = new Vector3(0, 0, 0);
    this._localAxis = new Vector3(0, 0, 0);
    this._lookAt = new Vector3(0, 0, 0);
    this._options = options ? options : {};
    let optionCount = 0;
    if (this._options.dragAxis) {
      optionCount++;
    }
    if (this._options.dragPlaneNormal) {
      optionCount++;
    }
    if (optionCount > 1) {
      throw "Multiple drag modes specified in dragBehavior options. Only one expected";
    }
  }
  get name() {
    return "PointerDrag";
  }
  init() {}
  attach(ownerNode, predicate) {
    this._scene = ownerNode.getScene();
    ownerNode.isNearGrabbable = true;
    this.attachedNode = ownerNode;
    if (!PointerDragBehavior._PlaneScene) {
      if (this._debugMode) {
        PointerDragBehavior._PlaneScene = this._scene;
      } else {
        PointerDragBehavior._PlaneScene = new Scene(this._scene.getEngine(), { virtual: true });
        PointerDragBehavior._PlaneScene.detachControl();
        this._scene.onDisposeObservable.addOnce(() => {
          PointerDragBehavior._PlaneScene.dispose();
          PointerDragBehavior._PlaneScene = null;
        });
      }
    }
    this._dragPlane = CreatePlane("pointerDragPlane", { size: this._debugMode ? 1 : 1e4, updatable: false, sideOrientation: Mesh.DOUBLESIDE }, PointerDragBehavior._PlaneScene);
    this.lastDragPosition = new Vector3(0, 0, 0);
    const pickPredicate = predicate ? predicate : (m) => {
      return this.attachedNode == m || m.isDescendantOf(this.attachedNode);
    };
    this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => {
      if (!this.enabled) {
        if (this._attachedToElement) {
          this.releaseDrag();
        }
        return;
      }
      if (this.dragging && this.currentDraggingPointerId == pointerInfo.event.pointerId && pointerInfo.event.button !== -1 && pointerInfo.event.button !== this._activeDragButton) {
        this.releaseDrag();
        return;
      }
      if (pointerInfo.type == PointerEventTypes.POINTERDOWN) {
        if (this.startAndReleaseDragOnPointerEvents && !this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
          if (this._activeDragButton === -1 && this.dragButtons.indexOf(pointerInfo.event.button) !== -1) {
            this._activeDragButton = pointerInfo.event.button;
            this._activePointerInfo = pointerInfo;
            this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
          }
        }
      } else if (pointerInfo.type == PointerEventTypes.POINTERUP) {
        if (this.startAndReleaseDragOnPointerEvents && this.currentDraggingPointerId == pointerInfo.event.pointerId && (this._activeDragButton === pointerInfo.event.button || this._activeDragButton === -1)) {
          this.releaseDrag();
        }
      } else if (pointerInfo.type == PointerEventTypes.POINTERMOVE) {
        const pointerId = pointerInfo.event.pointerId;
        if (this.currentDraggingPointerId === PointerDragBehavior._AnyMouseId && pointerId !== PointerDragBehavior._AnyMouseId) {
          const evt = pointerInfo.event;
          const isMouseEvent = evt.pointerType === "mouse" || !this._scene.getEngine().hostInformation.isMobile && evt instanceof MouseEvent;
          if (isMouseEvent) {
            if (this._lastPointerRay[this.currentDraggingPointerId]) {
              this._lastPointerRay[pointerId] = this._lastPointerRay[this.currentDraggingPointerId];
              delete this._lastPointerRay[this.currentDraggingPointerId];
            }
            this.currentDraggingPointerId = pointerId;
          }
        }
        if (!this._lastPointerRay[pointerId]) {
          this._lastPointerRay[pointerId] = new Ray(new Vector3, new Vector3);
        }
        if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
          this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
          this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
          if (this.currentDraggingPointerId == pointerId && this.dragging) {
            this._moveDrag(pointerInfo.pickInfo.ray);
          }
        }
      }
    });
    this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => {
      if (this._moving && this.moveAttached) {
        let needMatrixUpdate = false;
        PivotTools._RemoveAndStorePivotPoint(this.attachedNode);
        this._targetPosition.subtractToRef(this.attachedNode.absolutePosition, this._tmpVector);
        this._tmpVector.scaleInPlace(this.dragDeltaRatio);
        this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector);
        if (this.validateDrag(this._tmpVector)) {
          this.attachedNode.setAbsolutePosition(this._tmpVector);
          needMatrixUpdate = true;
        }
        PivotTools._RestorePivotPoint(this.attachedNode);
        if (needMatrixUpdate) {
          this.attachedNode.computeWorldMatrix();
        }
      }
    });
  }
  releaseDrag() {
    if (this.dragging) {
      this.dragging = false;
      this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });
    }
    this.currentDraggingPointerId = -1;
    this._activeDragButton = -1;
    this._activePointerInfo = null;
    this._moving = false;
    if (this.detachCameraControls && this._attachedToElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
      if (this._scene.activeCamera.getClassName() === "ArcRotateCamera") {
        const arcRotateCamera = this._scene.activeCamera;
        arcRotateCamera.attachControl(arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton);
      } else {
        this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : true);
      }
      this._attachedToElement = false;
    }
  }
  startDrag(pointerId = PointerDragBehavior._AnyMouseId, fromRay, startPickedPoint) {
    this._startDrag(pointerId, fromRay, startPickedPoint);
    let lastRay = this._lastPointerRay[pointerId];
    if (pointerId === PointerDragBehavior._AnyMouseId) {
      lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
    }
    if (lastRay) {
      this._moveDrag(lastRay);
    }
  }
  _startDrag(pointerId, fromRay, startPickedPoint) {
    if (!this._scene.activeCamera || this.dragging || !this.attachedNode) {
      return;
    }
    PivotTools._RemoveAndStorePivotPoint(this.attachedNode);
    if (fromRay) {
      this._startDragRay.direction.copyFrom(fromRay.direction);
      this._startDragRay.origin.copyFrom(fromRay.origin);
    } else {
      this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
      this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
      this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
    }
    this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
    const pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
    if (pickedPoint) {
      this.dragging = true;
      this.currentDraggingPointerId = pointerId;
      this.lastDragPosition.copyFrom(pickedPoint);
      this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });
      this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition());
      if (this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera) {
        if (this._scene.activeCamera.inputs.attachedToElement) {
          this._scene.activeCamera.detachControl();
          this._attachedToElement = true;
        } else {
          this._attachedToElement = false;
        }
      }
    } else {
      this.releaseDrag();
    }
    PivotTools._RestorePivotPoint(this.attachedNode);
  }
  _moveDrag(ray) {
    this._moving = true;
    const pickedPoint = this._pickWithRayOnDragPlane(ray);
    if (pickedPoint) {
      PivotTools._RemoveAndStorePivotPoint(this.attachedNode);
      if (this.updateDragPlane) {
        this._updateDragPlanePosition(ray, pickedPoint);
      }
      let dragLength = 0;
      if (this._options.dragAxis) {
        this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis) : this._worldDragAxis.copyFrom(this._options.dragAxis);
        pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
        this._worldDragAxis.normalize();
        dragLength = Vector3.Dot(this._tmpVector, this._worldDragAxis);
        this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
      } else {
        dragLength = this._dragDelta.length();
        pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
      }
      this._targetPosition.addInPlace(this._dragDelta);
      this.onDragObservable.notifyObservers({
        dragDistance: dragLength,
        delta: this._dragDelta,
        dragPlanePoint: pickedPoint,
        dragPlaneNormal: this._dragPlane.forward,
        pointerId: this.currentDraggingPointerId,
        pointerInfo: this._activePointerInfo
      });
      this.lastDragPosition.copyFrom(pickedPoint);
      PivotTools._RestorePivotPoint(this.attachedNode);
    }
  }
  _pickWithRayOnDragPlane(ray) {
    if (!ray) {
      return null;
    }
    let angle = Math.acos(Vector3.Dot(this._dragPlane.forward, ray.direction));
    if (angle > Math.PI / 2) {
      angle = Math.PI - angle;
    }
    if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
      if (this._useAlternatePickedPointAboveMaxDragAngle) {
        this._tmpVector.copyFrom(ray.direction);
        this.attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
        this._alternatePickedPoint.normalize();
        this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
        this._tmpVector.addInPlace(this._alternatePickedPoint);
        const dot = Vector3.Dot(this._dragPlane.forward, this._tmpVector);
        this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
        this._alternatePickedPoint.addInPlace(this._tmpVector);
        this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition);
        return this._alternatePickedPoint;
      } else {
        return null;
      }
    }
    const planeNormal = this._dragPlane.forward;
    const planePosition = this._dragPlane.position;
    const dotProduct = ray.direction.dot(planeNormal);
    if (Math.abs(dotProduct) < Epsilon) {
      return null;
    }
    planePosition.subtractToRef(ray.origin, TmpVectors.Vector3[0]);
    const t = TmpVectors.Vector3[0].dot(planeNormal) / dotProduct;
    if (t < 0) {
      return null;
    }
    ray.direction.scaleToRef(t, TmpVectors.Vector3[0]);
    const intersectionPoint = ray.origin.add(TmpVectors.Vector3[0]);
    return intersectionPoint;
  }
  _updateDragPlanePosition(ray, dragPlanePosition) {
    this._pointA.copyFrom(dragPlanePosition);
    if (this._options.dragAxis) {
      this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
      ray.origin.subtractToRef(this._pointA, this._pointC);
      this._pointC.normalize();
      if (Math.abs(Vector3.Dot(this._localAxis, this._pointC)) > 0.999) {
        if (Math.abs(Vector3.Dot(Vector3.UpReadOnly, this._pointC)) > 0.999) {
          this._lookAt.copyFrom(Vector3.Right());
        } else {
          this._lookAt.copyFrom(Vector3.UpReadOnly);
        }
      } else {
        Vector3.CrossToRef(this._localAxis, this._pointC, this._lookAt);
        Vector3.CrossToRef(this._localAxis, this._lookAt, this._lookAt);
        this._lookAt.normalize();
      }
      this._dragPlane.position.copyFrom(this._pointA);
      this._pointA.addToRef(this._lookAt, this._lookAt);
      this._dragPlane.lookAt(this._lookAt);
    } else if (this._options.dragPlaneNormal) {
      this.useObjectOrientationForDragging ? Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
      this._dragPlane.position.copyFrom(this._pointA);
      this._pointA.addToRef(this._localAxis, this._lookAt);
      this._dragPlane.lookAt(this._lookAt);
    } else {
      if (this._scene.activeCamera) {
        this._scene.activeCamera.getForwardRay().direction.normalizeToRef(this._localAxis);
      }
      this._dragPlane.position.copyFrom(this._pointA);
      this._dragPlane.lookAt(this._pointA.add(this._localAxis));
    }
    this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition());
    this._dragPlane.computeWorldMatrix(true);
  }
  detach() {
    this._lastPointerRay = {};
    if (this.attachedNode) {
      this.attachedNode.isNearGrabbable = false;
    }
    if (this._pointerObserver) {
      this._scene.onPointerObservable.remove(this._pointerObserver);
    }
    if (this._beforeRenderObserver) {
      this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
    }
    if (this._dragPlane) {
      this._dragPlane.dispose();
    }
    this.releaseDrag();
  }
}
PointerDragBehavior._AnyMouseId = -2;

// node_modules/@babylonjs/core/Behaviors/Meshes/multiPointerScaleBehavior.js
init_math_vector();
// node_modules/@babylonjs/core/Behaviors/Meshes/sixDofDragBehavior.js
init_math_vector();
init_observable();

// node_modules/@babylonjs/core/Behaviors/Meshes/baseSixDofDragBehavior.js
init_scene();
init_pointerEvents();
init_math_vector();
init_observable();
// node_modules/@babylonjs/core/Behaviors/Meshes/surfaceMagnetismBehavior.js
init_pointerEvents();
init_math_vector();
// node_modules/@babylonjs/core/Behaviors/Meshes/followBehavior.js
init_math_vector();
init_math_constants();
// node_modules/@babylonjs/core/XR/webXRFeaturesManager.js
init_tools();

class WebXRFeatureName {
}
WebXRFeatureName.ANCHOR_SYSTEM = "xr-anchor-system";
WebXRFeatureName.BACKGROUND_REMOVER = "xr-background-remover";
WebXRFeatureName.HIT_TEST = "xr-hit-test";
WebXRFeatureName.MESH_DETECTION = "xr-mesh-detection";
WebXRFeatureName.PHYSICS_CONTROLLERS = "xr-physics-controller";
WebXRFeatureName.PLANE_DETECTION = "xr-plane-detection";
WebXRFeatureName.POINTER_SELECTION = "xr-controller-pointer-selection";
WebXRFeatureName.TELEPORTATION = "xr-controller-teleportation";
WebXRFeatureName.FEATURE_POINTS = "xr-feature-points";
WebXRFeatureName.HAND_TRACKING = "xr-hand-tracking";
WebXRFeatureName.IMAGE_TRACKING = "xr-image-tracking";
WebXRFeatureName.NEAR_INTERACTION = "xr-near-interaction";
WebXRFeatureName.DOM_OVERLAY = "xr-dom-overlay";
WebXRFeatureName.MOVEMENT = "xr-controller-movement";
WebXRFeatureName.LIGHT_ESTIMATION = "xr-light-estimation";
WebXRFeatureName.EYE_TRACKING = "xr-eye-tracking";
WebXRFeatureName.WALKING_LOCOMOTION = "xr-walking-locomotion";
WebXRFeatureName.LAYERS = "xr-layers";
WebXRFeatureName.DEPTH_SENSING = "xr-depth-sensing";
WebXRFeatureName.SPACE_WARP = "xr-space-warp";
WebXRFeatureName.RAW_CAMERA_ACCESS = "xr-raw-camera-access";

class WebXRFeaturesManager {
  constructor(_xrSessionManager) {
    this._xrSessionManager = _xrSessionManager;
    this._features = {};
    this._xrSessionManager.onXRSessionInit.add(() => {
      this.getEnabledFeatures().forEach((featureName) => {
        const feature = this._features[featureName];
        if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) {
          this.attachFeature(featureName);
        }
      });
    });
    this._xrSessionManager.onXRSessionEnded.add(() => {
      this.getEnabledFeatures().forEach((featureName) => {
        const feature = this._features[featureName];
        if (feature.enabled && feature.featureImplementation.attached) {
          this.detachFeature(featureName);
        }
      });
    });
  }
  static AddWebXRFeature(featureName, constructorFunction, version = 1, stable = false) {
    this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version };
    if (version > this._AvailableFeatures[featureName].latest) {
      this._AvailableFeatures[featureName].latest = version;
    }
    if (stable) {
      this._AvailableFeatures[featureName].stable = version;
    }
    this._AvailableFeatures[featureName][version] = constructorFunction;
  }
  static ConstructFeature(featureName, version = 1, xrSessionManager, options) {
    const constructorFunction = this._AvailableFeatures[featureName][version];
    if (!constructorFunction) {
      throw new Error("feature not found");
    }
    return constructorFunction(xrSessionManager, options);
  }
  static GetAvailableFeatures() {
    return Object.keys(this._AvailableFeatures);
  }
  static GetAvailableVersions(featureName) {
    return Object.keys(this._AvailableFeatures[featureName]);
  }
  static GetLatestVersionOfFeature(featureName) {
    return this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest || -1;
  }
  static GetStableVersionOfFeature(featureName) {
    return this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable || -1;
  }
  attachFeature(featureName) {
    const feature = this._features[featureName];
    if (feature && feature.enabled && !feature.featureImplementation.attached) {
      const attached = feature.featureImplementation.attach();
      if (!attached) {
        Tools.Warn(`Feature ${featureName} failed to attach`);
      }
    }
  }
  detachFeature(featureName) {
    const feature = this._features[featureName];
    if (feature && feature.featureImplementation.attached) {
      const detached = feature.featureImplementation.detach();
      if (!detached) {
        Tools.Warn(`Feature ${featureName} failed to detach`);
      }
    }
  }
  disableFeature(featureName) {
    const name18 = typeof featureName === "string" ? featureName : featureName.Name;
    const feature = this._features[name18];
    if (feature && feature.enabled) {
      feature.enabled = false;
      this.detachFeature(name18);
      feature.featureImplementation.dispose();
      delete this._features[name18];
      return true;
    }
    return false;
  }
  dispose() {
    this.getEnabledFeatures().forEach((feature) => {
      this.disableFeature(feature);
    });
  }
  enableFeature(featureName, version = "latest", moduleOptions = {}, attachIfPossible = true, required = true) {
    const name18 = typeof featureName === "string" ? featureName : featureName.Name;
    let versionToLoad = 0;
    if (typeof version === "string") {
      if (!version) {
        throw new Error(`Error in provided version - ${name18} (${version})`);
      }
      if (version === "stable") {
        versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name18);
      } else if (version === "latest") {
        versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name18);
      } else {
        versionToLoad = +version;
      }
      if (versionToLoad === -1 || isNaN(versionToLoad)) {
        throw new Error(`feature not found - ${name18} (${version})`);
      }
    } else {
      versionToLoad = version;
    }
    const conflictingFeature = WebXRFeaturesManager._ConflictingFeatures[name18];
    if (conflictingFeature !== undefined && this.getEnabledFeatures().indexOf(conflictingFeature) !== -1) {
      throw new Error(`Feature ${name18} cannot be enabled while ${conflictingFeature} is enabled.`);
    }
    const feature = this._features[name18];
    const constructFunction = WebXRFeaturesManager.ConstructFeature(name18, versionToLoad, this._xrSessionManager, moduleOptions);
    if (!constructFunction) {
      throw new Error(`feature not found - ${name18}`);
    }
    if (feature) {
      this.disableFeature(name18);
    }
    const constructed = constructFunction();
    if (constructed.dependsOn) {
      const dependentsFound = constructed.dependsOn.every((featureName2) => !!this._features[featureName2]);
      if (!dependentsFound) {
        throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(", ")}`);
      }
    }
    if (constructed.isCompatible()) {
      this._features[name18] = {
        featureImplementation: constructed,
        enabled: true,
        version: versionToLoad,
        required
      };
      if (attachIfPossible) {
        if (this._xrSessionManager.session && !this._features[name18].featureImplementation.attached) {
          this.attachFeature(name18);
        }
      } else {
        this._features[name18].featureImplementation.disableAutoAttach = true;
      }
      return this._features[name18].featureImplementation;
    } else {
      if (required) {
        throw new Error("required feature not compatible");
      } else {
        Tools.Warn(`Feature ${name18} not compatible with the current environment/browser and was not enabled.`);
        return constructed;
      }
    }
  }
  getEnabledFeature(featureName) {
    return this._features[featureName] && this._features[featureName].featureImplementation;
  }
  getEnabledFeatures() {
    return Object.keys(this._features);
  }
  async _extendXRSessionInitObject(xrSessionInit) {
    const enabledFeatures = this.getEnabledFeatures();
    for (const featureName of enabledFeatures) {
      const feature = this._features[featureName];
      const nativeName = feature.featureImplementation.xrNativeFeatureName;
      if (nativeName) {
        if (feature.required) {
          xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || [];
          if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) {
            xrSessionInit.requiredFeatures.push(nativeName);
          }
        } else {
          xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || [];
          if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) {
            xrSessionInit.optionalFeatures.push(nativeName);
          }
        }
      }
      if (feature.featureImplementation.getXRSessionInitExtension) {
        const extended = await feature.featureImplementation.getXRSessionInitExtension();
        xrSessionInit = {
          ...xrSessionInit,
          ...extended
        };
      }
    }
    return xrSessionInit;
  }
}
WebXRFeaturesManager._AvailableFeatures = {};
WebXRFeaturesManager._ConflictingFeatures = {
  [WebXRFeatureName.TELEPORTATION]: WebXRFeatureName.MOVEMENT,
  [WebXRFeatureName.MOVEMENT]: WebXRFeatureName.TELEPORTATION
};

// node_modules/@babylonjs/core/Behaviors/Meshes/handConstraintBehavior.js
init_math_vector();
init_tools();
var HandConstraintZone;
(function(HandConstraintZone2) {
  HandConstraintZone2[HandConstraintZone2["ABOVE_FINGER_TIPS"] = 0] = "ABOVE_FINGER_TIPS";
  HandConstraintZone2[HandConstraintZone2["RADIAL_SIDE"] = 1] = "RADIAL_SIDE";
  HandConstraintZone2[HandConstraintZone2["ULNAR_SIDE"] = 2] = "ULNAR_SIDE";
  HandConstraintZone2[HandConstraintZone2["BELOW_WRIST"] = 3] = "BELOW_WRIST";
})(HandConstraintZone || (HandConstraintZone = {}));
var HandConstraintOrientation;
(function(HandConstraintOrientation2) {
  HandConstraintOrientation2[HandConstraintOrientation2["LOOK_AT_CAMERA"] = 0] = "LOOK_AT_CAMERA";
  HandConstraintOrientation2[HandConstraintOrientation2["HAND_ROTATION"] = 1] = "HAND_ROTATION";
})(HandConstraintOrientation || (HandConstraintOrientation = {}));
var HandConstraintVisibility;
(function(HandConstraintVisibility2) {
  HandConstraintVisibility2[HandConstraintVisibility2["ALWAYS_VISIBLE"] = 0] = "ALWAYS_VISIBLE";
  HandConstraintVisibility2[HandConstraintVisibility2["PALM_UP"] = 1] = "PALM_UP";
  HandConstraintVisibility2[HandConstraintVisibility2["GAZE_FOCUS"] = 2] = "GAZE_FOCUS";
  HandConstraintVisibility2[HandConstraintVisibility2["PALM_AND_GAZE"] = 3] = "PALM_AND_GAZE";
})(HandConstraintVisibility || (HandConstraintVisibility = {}));
// node_modules/@babylonjs/core/Bones/index.js
init_bone();

// node_modules/@babylonjs/core/Bones/boneIKController.js
init_math_vector();
init_logger();

class BoneIKController {
  get maxAngle() {
    return this._maxAngle;
  }
  set maxAngle(value) {
    this._setMaxAngle(value);
  }
  constructor(mesh, bone, options) {
    this.targetPosition = Vector3.Zero();
    this.poleTargetPosition = Vector3.Zero();
    this.poleTargetLocalOffset = Vector3.Zero();
    this.poleAngle = 0;
    this.slerpAmount = 1;
    this._bone1Quat = Quaternion.Identity();
    this._bone1Mat = Matrix.Identity();
    this._bone2Ang = Math.PI;
    this._maxAngle = Math.PI;
    this._rightHandedSystem = false;
    this._bendAxis = Vector3.Right();
    this._slerping = false;
    this._adjustRoll = 0;
    this._notEnoughInformation = false;
    this._bone2 = bone;
    const bone1 = bone.getParent();
    if (!bone1) {
      this._notEnoughInformation = true;
      Logger.Error("BoneIKController: bone must have a parent for IK to work.");
      return;
    }
    this._bone1 = bone1;
    if (this._bone2.children.length === 0 && !this._bone2.length) {
      this._notEnoughInformation = true;
      Logger.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");
      return;
    }
    this.mesh = mesh;
    bone.getSkeleton().computeAbsoluteMatrices();
    const bonePos = bone.getPosition();
    if (bone.getAbsoluteMatrix().determinant() > 0) {
      this._rightHandedSystem = true;
      this._bendAxis.x = 0;
      this._bendAxis.y = 0;
      this._bendAxis.z = -1;
      if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
        this._adjustRoll = Math.PI * 0.5;
        this._bendAxis.z = 1;
      }
    }
    if (this._bone1.length && this._bone2.length) {
      const boneScale1 = this._bone1.getScale();
      const boneScale2 = this._bone2.getScale();
      this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
      this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
    } else if (this._bone2.children[0]) {
      mesh.computeWorldMatrix(true);
      const pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
      const pos2 = this._bone2.getAbsolutePosition(mesh);
      const pos3 = this._bone1.getAbsolutePosition(mesh);
      this._bone2Length = Vector3.Distance(pos1, pos2);
      this._bone1Length = Vector3.Distance(pos2, pos3);
    } else {
      mesh.computeWorldMatrix(true);
      const boneScale2 = this._bone2.getScale();
      this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
      const pos2 = this._bone2.getAbsolutePosition(mesh);
      const pos3 = this._bone1.getAbsolutePosition(mesh);
      this._bone1Length = Vector3.Distance(pos2, pos3);
    }
    this._bone1.getRotationMatrixToRef(1, mesh, this._bone1Mat);
    this.maxAngle = Math.PI;
    if (options) {
      if (options.targetMesh) {
        this.targetMesh = options.targetMesh;
        this.targetMesh.computeWorldMatrix(true);
      }
      if (options.poleTargetMesh) {
        this.poleTargetMesh = options.poleTargetMesh;
        this.poleTargetMesh.computeWorldMatrix(true);
      } else if (options.poleTargetBone) {
        this.poleTargetBone = options.poleTargetBone;
      } else if (this._bone1.getParent()) {
        this.poleTargetBone = this._bone1.getParent();
      }
      if (options.poleTargetLocalOffset) {
        this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
      }
      if (options.poleAngle) {
        this.poleAngle = options.poleAngle;
      }
      if (options.bendAxis) {
        this._bendAxis.copyFrom(options.bendAxis);
      }
      if (options.maxAngle) {
        this.maxAngle = options.maxAngle;
      }
      if (options.slerpAmount) {
        this.slerpAmount = options.slerpAmount;
      }
    }
  }
  _setMaxAngle(ang) {
    if (ang < 0) {
      ang = 0;
    }
    if (ang > Math.PI || ang == undefined) {
      ang = Math.PI;
    }
    this._maxAngle = ang;
    const a = this._bone1Length;
    const b = this._bone2Length;
    this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  }
  update() {
    if (this._notEnoughInformation) {
      return;
    }
    const target = this.targetPosition;
    const poleTarget = this.poleTargetPosition;
    const mat1 = BoneIKController._TmpMats[0];
    const mat2 = BoneIKController._TmpMats[1];
    if (this.targetMesh) {
      target.copyFrom(this.targetMesh.getAbsolutePosition());
    }
    if (this.poleTargetBone) {
      this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
    } else if (this.poleTargetMesh) {
      Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
    }
    const bonePos = BoneIKController._TmpVecs[0];
    const zaxis = BoneIKController._TmpVecs[1];
    const xaxis = BoneIKController._TmpVecs[2];
    const yaxis = BoneIKController._TmpVecs[3];
    const upAxis = BoneIKController._TmpVecs[4];
    const tmpQuat = BoneIKController._TmpQuat;
    this._bone1.getAbsolutePositionToRef(this.mesh, bonePos);
    poleTarget.subtractToRef(bonePos, upAxis);
    if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
      upAxis.y = 1;
    } else {
      upAxis.normalize();
    }
    target.subtractToRef(bonePos, yaxis);
    yaxis.normalize();
    Vector3.CrossToRef(yaxis, upAxis, zaxis);
    zaxis.normalize();
    Vector3.CrossToRef(yaxis, zaxis, xaxis);
    xaxis.normalize();
    Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
    const a = this._bone1Length;
    const b = this._bone2Length;
    let c = Vector3.Distance(bonePos, target);
    if (this._maxReach > 0) {
      c = Math.min(this._maxReach, c);
    }
    let acosa = (b * b + c * c - a * a) / (2 * b * c);
    let acosb = (c * c + a * a - b * b) / (2 * c * a);
    if (acosa > 1) {
      acosa = 1;
    }
    if (acosb > 1) {
      acosb = 1;
    }
    if (acosa < -1) {
      acosa = -1;
    }
    if (acosb < -1) {
      acosb = -1;
    }
    const angA = Math.acos(acosa);
    const angB = Math.acos(acosb);
    let angC = -angA - angB;
    if (this._rightHandedSystem) {
      Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
      mat2.multiplyToRef(mat1, mat1);
      Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
      mat2.multiplyToRef(mat1, mat1);
    } else {
      const _tmpVec = BoneIKController._TmpVecs[5];
      _tmpVec.copyFrom(this._bendAxis);
      _tmpVec.x *= -1;
      Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
      mat2.multiplyToRef(mat1, mat1);
    }
    if (this.poleAngle) {
      Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
      mat1.multiplyToRef(mat2, mat1);
    }
    if (this._bone1) {
      if (this.slerpAmount < 1) {
        if (!this._slerping) {
          Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
        }
        Quaternion.FromRotationMatrixToRef(mat1, tmpQuat);
        Quaternion.SlerpToRef(this._bone1Quat, tmpQuat, this.slerpAmount, this._bone1Quat);
        angC = this._bone2Ang * (1 - this.slerpAmount) + angC * this.slerpAmount;
        this._bone1.setRotationQuaternion(this._bone1Quat, 1, this.mesh);
        this._slerping = true;
      } else {
        this._bone1.setRotationMatrix(mat1, 1, this.mesh);
        this._bone1Mat.copyFrom(mat1);
        this._slerping = false;
      }
      this._updateLinkedTransformRotation(this._bone1);
    }
    this._bone2.setAxisAngle(this._bendAxis, angC, 0);
    this._updateLinkedTransformRotation(this._bone2);
    this._bone2Ang = angC;
  }
  _updateLinkedTransformRotation(bone) {
    if (bone._linkedTransformNode) {
      if (!bone._linkedTransformNode.rotationQuaternion) {
        bone._linkedTransformNode.rotationQuaternion = new Quaternion;
      }
      bone.getRotationQuaternionToRef(0, null, bone._linkedTransformNode.rotationQuaternion);
    }
  }
}
BoneIKController._TmpVecs = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
BoneIKController._TmpQuat = Quaternion.Identity();
BoneIKController._TmpMats = [Matrix.Identity(), Matrix.Identity()];
// node_modules/@babylonjs/core/Bones/boneLookController.js
init_arrayTools();
init_math_vector();
init_math_axis();

class BoneLookController {
  get minYaw() {
    return this._minYaw;
  }
  set minYaw(value) {
    this._minYaw = value;
    this._minYawSin = Math.sin(value);
    this._minYawCos = Math.cos(value);
    if (this._maxYaw != null) {
      this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;
      this._yawRange = this._maxYaw - this._minYaw;
    }
  }
  get maxYaw() {
    return this._maxYaw;
  }
  set maxYaw(value) {
    this._maxYaw = value;
    this._maxYawSin = Math.sin(value);
    this._maxYawCos = Math.cos(value);
    if (this._minYaw != null) {
      this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;
      this._yawRange = this._maxYaw - this._minYaw;
    }
  }
  get minPitch() {
    return this._minPitch;
  }
  set minPitch(value) {
    this._minPitch = value;
    this._minPitchTan = Math.tan(value);
  }
  get maxPitch() {
    return this._maxPitch;
  }
  set maxPitch(value) {
    this._maxPitch = value;
    this._maxPitchTan = Math.tan(value);
  }
  constructor(mesh, bone, target, options) {
    this.upAxis = Vector3.Up();
    this.upAxisSpace = 0;
    this.adjustYaw = 0;
    this.adjustPitch = 0;
    this.adjustRoll = 0;
    this.slerpAmount = 1;
    this._boneQuat = Quaternion.Identity();
    this._slerping = false;
    this._firstFrameSkipped = false;
    this._fowardAxis = Vector3.Forward();
    this.useAbsoluteValueForYaw = false;
    this.mesh = mesh;
    this.bone = bone;
    this.target = target;
    if (options) {
      if (options.adjustYaw) {
        this.adjustYaw = options.adjustYaw;
      }
      if (options.adjustPitch) {
        this.adjustPitch = options.adjustPitch;
      }
      if (options.adjustRoll) {
        this.adjustRoll = options.adjustRoll;
      }
      if (options.maxYaw != null) {
        this.maxYaw = options.maxYaw;
      } else {
        this.maxYaw = Math.PI;
      }
      if (options.minYaw != null) {
        this.minYaw = options.minYaw;
      } else {
        this.minYaw = -Math.PI;
      }
      if (options.maxPitch != null) {
        this.maxPitch = options.maxPitch;
      } else {
        this.maxPitch = Math.PI;
      }
      if (options.minPitch != null) {
        this.minPitch = options.minPitch;
      } else {
        this.minPitch = -Math.PI;
      }
      if (options.slerpAmount != null) {
        this.slerpAmount = options.slerpAmount;
      }
      if (options.upAxis != null) {
        this.upAxis = options.upAxis;
      }
      if (options.upAxisSpace != null) {
        this.upAxisSpace = options.upAxisSpace;
      }
      if (options.yawAxis != null || options.pitchAxis != null) {
        let newYawAxis = Axis.Y;
        let newPitchAxis = Axis.X;
        if (options.yawAxis != null) {
          newYawAxis = options.yawAxis.clone();
          newYawAxis.normalize();
        }
        if (options.pitchAxis != null) {
          newPitchAxis = options.pitchAxis.clone();
          newPitchAxis.normalize();
        }
        const newRollAxis = Vector3.Cross(newPitchAxis, newYawAxis);
        this._transformYawPitch = Matrix.Identity();
        Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
        this._transformYawPitchInv = this._transformYawPitch.clone();
        this._transformYawPitch.invert();
      }
      if (options.useAbsoluteValueForYaw !== undefined) {
        this.useAbsoluteValueForYaw = options.useAbsoluteValueForYaw;
      }
    }
    if (!bone.getParent() && this.upAxisSpace == 2) {
      this.upAxisSpace = 0;
    }
  }
  update() {
    if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
      this._firstFrameSkipped = true;
      return;
    }
    const bone = this.bone;
    const bonePos = BoneLookController._TmpVecs[0];
    bone.getAbsolutePositionToRef(this.mesh, bonePos);
    let target = this.target;
    const _tmpMat1 = BoneLookController._TmpMats[0];
    const _tmpMat2 = BoneLookController._TmpMats[1];
    const mesh = this.mesh;
    const parentBone = bone.getParent();
    const upAxis = BoneLookController._TmpVecs[1];
    upAxis.copyFrom(this.upAxis);
    if (this.upAxisSpace == 2 && parentBone) {
      if (this._transformYawPitch) {
        Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
      }
      parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
    } else if (this.upAxisSpace == 0) {
      mesh.getDirectionToRef(upAxis, upAxis);
      if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
        upAxis.normalize();
      }
    }
    let checkYaw = false;
    let checkPitch = false;
    if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
      checkYaw = true;
    }
    if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
      checkPitch = true;
    }
    if (checkYaw || checkPitch) {
      const spaceMat = BoneLookController._TmpMats[2];
      const spaceMatInv = BoneLookController._TmpMats[3];
      if (this.upAxisSpace == 2 && upAxis.y == 1 && parentBone) {
        parentBone.getRotationMatrixToRef(1, this.mesh, spaceMat);
      } else if (this.upAxisSpace == 0 && upAxis.y == 1 && !parentBone) {
        spaceMat.copyFrom(mesh.getWorldMatrix());
      } else {
        let forwardAxis = BoneLookController._TmpVecs[2];
        forwardAxis.copyFrom(this._fowardAxis);
        if (this._transformYawPitch) {
          Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
        }
        if (parentBone) {
          parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
        } else {
          mesh.getDirectionToRef(forwardAxis, forwardAxis);
        }
        const rightAxis = Vector3.Cross(upAxis, forwardAxis);
        rightAxis.normalize();
        forwardAxis = Vector3.Cross(rightAxis, upAxis);
        Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
      }
      spaceMat.invertToRef(spaceMatInv);
      let xzlen = null;
      if (checkPitch) {
        const localTarget = BoneLookController._TmpVecs[3];
        target.subtractToRef(bonePos, localTarget);
        Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
        xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
        const pitch = Math.atan2(localTarget.y, xzlen);
        let newPitch = pitch;
        if (pitch > this._maxPitch) {
          localTarget.y = this._maxPitchTan * xzlen;
          newPitch = this._maxPitch;
        } else if (pitch < this._minPitch) {
          localTarget.y = this._minPitchTan * xzlen;
          newPitch = this._minPitch;
        }
        if (pitch != newPitch) {
          Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
          localTarget.addInPlace(bonePos);
          target = localTarget;
        }
      }
      if (checkYaw) {
        const localTarget = BoneLookController._TmpVecs[4];
        target.subtractToRef(bonePos, localTarget);
        Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
        const yaw = Math.atan2(localTarget.x, localTarget.z);
        const yawCheck = this.useAbsoluteValueForYaw ? Math.abs(yaw) : yaw;
        let newYaw = yaw;
        if (yawCheck > this._maxYaw || yawCheck < this._minYaw) {
          if (xzlen == null) {
            xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
          }
          if (this._yawRange > Math.PI) {
            if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
              localTarget.z = this._maxYawCos * xzlen;
              localTarget.x = this._maxYawSin * xzlen;
              newYaw = this._maxYaw;
            } else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
              localTarget.z = this._minYawCos * xzlen;
              localTarget.x = this._minYawSin * xzlen;
              newYaw = this._minYaw;
            }
          } else {
            if (yawCheck > this._maxYaw) {
              localTarget.z = this._maxYawCos * xzlen;
              localTarget.x = this._maxYawSin * xzlen;
              if (yaw < 0 && this.useAbsoluteValueForYaw) {
                localTarget.x *= -1;
              }
              newYaw = this._maxYaw;
            } else if (yawCheck < this._minYaw) {
              localTarget.z = this._minYawCos * xzlen;
              localTarget.x = this._minYawSin * xzlen;
              if (yaw < 0 && this.useAbsoluteValueForYaw) {
                localTarget.x *= -1;
              }
              newYaw = this._minYaw;
            }
          }
        }
        if (this._slerping && this._yawRange > Math.PI) {
          const boneFwd = BoneLookController._TmpVecs[8];
          boneFwd.copyFrom(Axis.Z);
          if (this._transformYawPitch) {
            Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
          }
          const boneRotMat = BoneLookController._TmpMats[4];
          this._boneQuat.toRotationMatrix(boneRotMat);
          this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
          Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
          Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
          const boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
          const angBtwTar = this._getAngleBetween(boneYaw, yaw);
          const angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
          if (angBtwTar > angBtwMidYaw) {
            if (xzlen == null) {
              xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
            }
            const angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
            const angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
            if (angBtwMin < angBtwMax) {
              newYaw = boneYaw + Math.PI * 0.75;
              localTarget.z = Math.cos(newYaw) * xzlen;
              localTarget.x = Math.sin(newYaw) * xzlen;
            } else {
              newYaw = boneYaw - Math.PI * 0.75;
              localTarget.z = Math.cos(newYaw) * xzlen;
              localTarget.x = Math.sin(newYaw) * xzlen;
            }
          }
        }
        if (yaw != newYaw) {
          Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
          localTarget.addInPlace(bonePos);
          target = localTarget;
        }
      }
    }
    const zaxis = BoneLookController._TmpVecs[5];
    const xaxis = BoneLookController._TmpVecs[6];
    const yaxis = BoneLookController._TmpVecs[7];
    const tmpQuat = BoneLookController._TmpQuat;
    const boneScaling = BoneLookController._TmpVecs[9];
    target.subtractToRef(bonePos, zaxis);
    zaxis.normalize();
    Vector3.CrossToRef(upAxis, zaxis, xaxis);
    xaxis.normalize();
    Vector3.CrossToRef(zaxis, xaxis, yaxis);
    yaxis.normalize();
    Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
    if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
      return;
    }
    if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
      return;
    }
    if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
      return;
    }
    if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
      Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
      _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
    }
    boneScaling.copyFrom(this.bone.getScale());
    if (this.slerpAmount < 1) {
      if (!this._slerping) {
        this.bone.getRotationQuaternionToRef(1, this.mesh, this._boneQuat);
      }
      if (this._transformYawPitch) {
        this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
      }
      Quaternion.FromRotationMatrixToRef(_tmpMat1, tmpQuat);
      Quaternion.SlerpToRef(this._boneQuat, tmpQuat, this.slerpAmount, this._boneQuat);
      this.bone.setRotationQuaternion(this._boneQuat, 1, this.mesh);
      this._slerping = true;
    } else {
      if (this._transformYawPitch) {
        this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
      }
      this.bone.setRotationMatrix(_tmpMat1, 1, this.mesh);
      this._slerping = false;
    }
    this.bone.setScale(boneScaling);
    this._updateLinkedTransformRotation();
  }
  _getAngleDiff(ang1, ang2) {
    let angDiff = ang2 - ang1;
    angDiff %= Math.PI * 2;
    if (angDiff > Math.PI) {
      angDiff -= Math.PI * 2;
    } else if (angDiff < -Math.PI) {
      angDiff += Math.PI * 2;
    }
    return angDiff;
  }
  _getAngleBetween(ang1, ang2) {
    ang1 %= 2 * Math.PI;
    ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;
    ang2 %= 2 * Math.PI;
    ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;
    let ab = 0;
    if (ang1 < ang2) {
      ab = ang2 - ang1;
    } else {
      ab = ang1 - ang2;
    }
    if (ab > Math.PI) {
      ab = Math.PI * 2 - ab;
    }
    return ab;
  }
  _isAngleBetween(ang, ang1, ang2) {
    ang %= 2 * Math.PI;
    ang = ang < 0 ? ang + 2 * Math.PI : ang;
    ang1 %= 2 * Math.PI;
    ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;
    ang2 %= 2 * Math.PI;
    ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;
    if (ang1 < ang2) {
      if (ang > ang1 && ang < ang2) {
        return true;
      }
    } else {
      if (ang > ang2 && ang < ang1) {
        return true;
      }
    }
    return false;
  }
  _updateLinkedTransformRotation() {
    const bone = this.bone;
    if (bone._linkedTransformNode) {
      if (!bone._linkedTransformNode.rotationQuaternion) {
        bone._linkedTransformNode.rotationQuaternion = new Quaternion;
      }
      bone.getRotationQuaternionToRef(0, null, bone._linkedTransformNode.rotationQuaternion);
    }
  }
}
BoneLookController._TmpVecs = BuildArray(10, Vector3.Zero);
BoneLookController._TmpQuat = Quaternion.Identity();
BoneLookController._TmpMats = BuildArray(5, Matrix.Identity);
// node_modules/@babylonjs/core/Buffers/index.js
init_buffer();
init_bufferUtils();
init_dataBuffer();

// node_modules/@babylonjs/core/Buffers/buffer.align.js
init_buffer();
var isLittleEndian = (() => {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  return !!((view[0] = 1) & array[0]);
})();
Object.defineProperty(VertexBuffer.prototype, "effectiveByteStride", {
  get: function() {
    return this._alignedBuffer && this._alignedBuffer.byteStride || this.byteStride;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(VertexBuffer.prototype, "effectiveByteOffset", {
  get: function() {
    return this._alignedBuffer ? 0 : this.byteOffset;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(VertexBuffer.prototype, "effectiveBuffer", {
  get: function() {
    return this._alignedBuffer && this._alignedBuffer.getBuffer() || this._buffer.getBuffer();
  },
  enumerable: true,
  configurable: true
});
VertexBuffer.prototype._rebuild = function() {
  this._buffer?._rebuild();
  this._alignedBuffer?._rebuild();
};
VertexBuffer.prototype.dispose = function() {
  if (this._ownsBuffer) {
    this._buffer.dispose();
  }
  this._alignedBuffer?.dispose();
  this._alignedBuffer = undefined;
  this._isDisposed = true;
};
VertexBuffer.prototype.getWrapperBuffer = function() {
  return this._alignedBuffer || this._buffer;
};
VertexBuffer.prototype._alignBuffer = function() {
  const data = this._buffer.getData();
  if (!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes || this.byteStride % 4 === 0 && this.byteOffset % 4 === 0 || !data) {
    return;
  }
  const typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  const alignedByteStride = this.byteStride + 3 & ~3;
  const alignedSize = alignedByteStride / typeByteLength;
  const totalVertices = this._maxVerticesCount;
  const totalByteLength = totalVertices * alignedByteStride;
  const totalLength = totalByteLength / typeByteLength;
  let sourceData;
  if (Array.isArray(data)) {
    const sourceDataAsFloat = new Float32Array(data);
    sourceData = new DataView(sourceDataAsFloat.buffer, sourceDataAsFloat.byteOffset, sourceDataAsFloat.byteLength);
  } else if (data instanceof ArrayBuffer) {
    sourceData = new DataView(data, 0, data.byteLength);
  } else {
    sourceData = new DataView(data.buffer, data.byteOffset, data.byteLength);
  }
  let alignedData;
  if (this.type === VertexBuffer.BYTE) {
    alignedData = new Int8Array(totalLength);
  } else if (this.type === VertexBuffer.UNSIGNED_BYTE) {
    alignedData = new Uint8Array(totalLength);
  } else if (this.type === VertexBuffer.SHORT) {
    alignedData = new Int16Array(totalLength);
  } else if (this.type === VertexBuffer.UNSIGNED_SHORT) {
    alignedData = new Uint16Array(totalLength);
  } else if (this.type === VertexBuffer.INT) {
    alignedData = new Int32Array(totalLength);
  } else if (this.type === VertexBuffer.UNSIGNED_INT) {
    alignedData = new Uint32Array(totalLength);
  } else {
    alignedData = new Float32Array(totalLength);
  }
  const numComponents = this.getSize();
  let sourceOffset = this.byteOffset;
  for (let i = 0;i < totalVertices; ++i) {
    for (let j = 0;j < numComponents; ++j) {
      switch (this.type) {
        case VertexBuffer.BYTE:
          alignedData[i * alignedSize + j] = sourceData.getInt8(sourceOffset + j);
          break;
        case VertexBuffer.UNSIGNED_BYTE:
          alignedData[i * alignedSize + j] = sourceData.getUint8(sourceOffset + j);
          break;
        case VertexBuffer.SHORT:
          alignedData[i * alignedSize + j] = sourceData.getInt16(sourceOffset + j * 2, isLittleEndian);
          break;
        case VertexBuffer.UNSIGNED_SHORT:
          alignedData[i * alignedSize + j] = sourceData.getUint16(sourceOffset + j * 2, isLittleEndian);
          break;
        case VertexBuffer.INT:
          alignedData[i * alignedSize + j] = sourceData.getInt32(sourceOffset + j * 4, isLittleEndian);
          break;
        case VertexBuffer.UNSIGNED_INT:
          alignedData[i * alignedSize + j] = sourceData.getUint32(sourceOffset + j * 4, isLittleEndian);
          break;
        case VertexBuffer.FLOAT:
          alignedData[i * alignedSize + j] = sourceData.getFloat32(sourceOffset + j * 4, isLittleEndian);
          break;
      }
    }
    sourceOffset += this.byteStride;
  }
  this._alignedBuffer?.dispose();
  this._alignedBuffer = new Buffer2(this.engine, alignedData, false, alignedByteStride, false, this.getIsInstanced(), true, this.instanceDivisor, (this._label ?? "VertexBuffer") + "_aligned");
};
// node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraMouseWheelInput.js
init_tslib_es6();
init_decorators();
init_observable();
init_pointerEvents();
init_deviceInputEvents();
init_tools();

class BaseCameraMouseWheelInput {
  constructor() {
    this.wheelPrecisionX = 3;
    this.wheelPrecisionY = 3;
    this.wheelPrecisionZ = 3;
    this.onChangedObservable = new Observable;
    this._wheelDeltaX = 0;
    this._wheelDeltaY = 0;
    this._wheelDeltaZ = 0;
    this._ffMultiplier = 12;
    this._normalize = 120;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this._wheel = (pointer) => {
      if (pointer.type !== PointerEventTypes.POINTERWHEEL) {
        return;
      }
      const event = pointer.event;
      const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1;
      this._wheelDeltaX += this.wheelPrecisionX * platformScale * event.deltaX / this._normalize;
      this._wheelDeltaY -= this.wheelPrecisionY * platformScale * event.deltaY / this._normalize;
      this._wheelDeltaZ += this.wheelPrecisionZ * platformScale * event.deltaZ / this._normalize;
      if (event.preventDefault) {
        if (!noPreventDefault) {
          event.preventDefault();
        }
      }
    };
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);
  }
  detachControl() {
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      this._observer = null;
      this._wheel = null;
    }
    if (this.onChangedObservable) {
      this.onChangedObservable.clear();
    }
  }
  checkInputs() {
    this.onChangedObservable.notifyObservers({
      wheelDeltaX: this._wheelDeltaX,
      wheelDeltaY: this._wheelDeltaY,
      wheelDeltaZ: this._wheelDeltaZ
    });
    this._wheelDeltaX = 0;
    this._wheelDeltaY = 0;
    this._wheelDeltaZ = 0;
  }
  getClassName() {
    return "BaseCameraMouseWheelInput";
  }
  getSimpleName() {
    return "mousewheel";
  }
}
__decorate([
  serialize()
], BaseCameraMouseWheelInput.prototype, "wheelPrecisionX", undefined);
__decorate([
  serialize()
], BaseCameraMouseWheelInput.prototype, "wheelPrecisionY", undefined);
__decorate([
  serialize()
], BaseCameraMouseWheelInput.prototype, "wheelPrecisionZ", undefined);
// node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraPointersInput.js
init_tslib_es6();
init_decorators();
init_tools();
init_pointerEvents();

class BaseCameraPointersInput {
  constructor() {
    this._currentMousePointerIdDown = -1;
    this.buttons = [0, 1, 2];
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    const engine = this.camera.getEngine();
    const element = engine.getInputElement();
    let previousPinchSquaredDistance = 0;
    let previousMultiTouchPanPosition = null;
    this._pointA = null;
    this._pointB = null;
    this._altKey = false;
    this._ctrlKey = false;
    this._metaKey = false;
    this._shiftKey = false;
    this._buttonsPressed = 0;
    this._pointerInput = (p) => {
      const evt = p.event;
      const isTouch = evt.pointerType === "touch";
      if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {
        return;
      }
      const srcElement = evt.target;
      this._altKey = evt.altKey;
      this._ctrlKey = evt.ctrlKey;
      this._metaKey = evt.metaKey;
      this._shiftKey = evt.shiftKey;
      this._buttonsPressed = evt.buttons;
      if (engine.isPointerLock) {
        const offsetX = evt.movementX;
        const offsetY = evt.movementY;
        this.onTouch(null, offsetX, offsetY);
        this._pointA = null;
        this._pointB = null;
      } else if (p.type !== PointerEventTypes.POINTERDOWN && p.type !== PointerEventTypes.POINTERDOUBLETAP && isTouch && this._pointA?.pointerId !== evt.pointerId && this._pointB?.pointerId !== evt.pointerId) {
        return;
      } else if (p.type === PointerEventTypes.POINTERDOWN && (this._currentMousePointerIdDown === -1 || isTouch)) {
        try {
          srcElement?.setPointerCapture(evt.pointerId);
        } catch (e) {}
        if (this._pointA === null) {
          this._pointA = {
            x: evt.clientX,
            y: evt.clientY,
            pointerId: evt.pointerId,
            type: evt.pointerType
          };
        } else if (this._pointB === null) {
          this._pointB = {
            x: evt.clientX,
            y: evt.clientY,
            pointerId: evt.pointerId,
            type: evt.pointerType
          };
        } else {
          return;
        }
        if (this._currentMousePointerIdDown === -1 && !isTouch) {
          this._currentMousePointerIdDown = evt.pointerId;
        }
        this.onButtonDown(evt);
        if (!noPreventDefault) {
          evt.preventDefault();
          element && element.focus();
        }
      } else if (p.type === PointerEventTypes.POINTERDOUBLETAP) {
        this.onDoubleTap(evt.pointerType);
      } else if (p.type === PointerEventTypes.POINTERUP && (this._currentMousePointerIdDown === evt.pointerId || isTouch)) {
        try {
          srcElement?.releasePointerCapture(evt.pointerId);
        } catch (e) {}
        if (!isTouch) {
          this._pointB = null;
        }
        if (engine._badOS) {
          this._pointA = this._pointB = null;
        } else {
          if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) {
            this._pointA = this._pointB;
            this._pointB = null;
          } else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) {
            this._pointB = null;
          } else {
            this._pointA = this._pointB = null;
          }
        }
        if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) {
          this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, previousMultiTouchPanPosition, null);
          previousPinchSquaredDistance = 0;
          previousMultiTouchPanPosition = null;
        }
        this._currentMousePointerIdDown = -1;
        this.onButtonUp(evt);
        if (!noPreventDefault) {
          evt.preventDefault();
        }
      } else if (p.type === PointerEventTypes.POINTERMOVE) {
        if (!noPreventDefault) {
          evt.preventDefault();
        }
        if (this._pointA && this._pointB === null) {
          const offsetX = evt.clientX - this._pointA.x;
          const offsetY = evt.clientY - this._pointA.y;
          this._pointA.x = evt.clientX;
          this._pointA.y = evt.clientY;
          this.onTouch(this._pointA, offsetX, offsetY);
        } else if (this._pointA && this._pointB) {
          const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB;
          ed.x = evt.clientX;
          ed.y = evt.clientY;
          const distX = this._pointA.x - this._pointB.x;
          const distY = this._pointA.y - this._pointB.y;
          const pinchSquaredDistance = distX * distX + distY * distY;
          const multiTouchPanPosition = {
            x: (this._pointA.x + this._pointB.x) / 2,
            y: (this._pointA.y + this._pointB.y) / 2,
            pointerId: evt.pointerId,
            type: p.type
          };
          this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition);
          previousMultiTouchPanPosition = multiTouchPanPosition;
          previousPinchSquaredDistance = pinchSquaredDistance;
        }
      }
    };
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP);
    this._onLostFocus = () => {
      this._pointA = this._pointB = null;
      previousPinchSquaredDistance = 0;
      previousMultiTouchPanPosition = null;
      this.onLostFocus();
    };
    this._contextMenuBind = (evt) => this.onContextMenu(evt);
    element && element.addEventListener("contextmenu", this._contextMenuBind, false);
    const hostWindow = this.camera.getScene().getEngine().getHostWindow();
    if (hostWindow) {
      Tools.RegisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]);
    }
  }
  detachControl() {
    if (this._onLostFocus) {
      const hostWindow = this.camera.getScene().getEngine().getHostWindow();
      if (hostWindow) {
        Tools.UnregisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]);
      }
    }
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      this._observer = null;
      if (this._contextMenuBind) {
        const inputElement = this.camera.getScene().getEngine().getInputElement();
        inputElement && inputElement.removeEventListener("contextmenu", this._contextMenuBind);
      }
      this._onLostFocus = null;
    }
    this._altKey = false;
    this._ctrlKey = false;
    this._metaKey = false;
    this._shiftKey = false;
    this._buttonsPressed = 0;
    this._currentMousePointerIdDown = -1;
  }
  getClassName() {
    return "BaseCameraPointersInput";
  }
  getSimpleName() {
    return "pointers";
  }
  onDoubleTap(type) {}
  onTouch(point, offsetX, offsetY) {}
  onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {}
  onContextMenu(evt) {
    evt.preventDefault();
  }
  onButtonDown(_evt) {}
  onButtonUp(_evt) {}
  onLostFocus() {}
}
__decorate([
  serialize()
], BaseCameraPointersInput.prototype, "buttons", undefined);
// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraGamepadInput.js
init_tslib_es6();
init_decorators();

// node_modules/@babylonjs/core/Cameras/cameraInputsManager.js
init_logger();
init_decorators_serialization();
var CameraInputTypes = {};

class CameraInputsManager {
  constructor(camera) {
    this.attachedToElement = false;
    this.attached = {};
    this.camera = camera;
    this.checkInputs = () => {};
  }
  add(input) {
    const type = input.getSimpleName();
    if (this.attached[type]) {
      Logger.Warn("camera input of type " + type + " already exists on camera");
      return;
    }
    this.attached[type] = input;
    input.camera = this.camera;
    if (input.checkInputs) {
      this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
    }
    if (this.attachedToElement) {
      input.attachControl(this.noPreventDefault);
    }
  }
  remove(inputToRemove) {
    for (const cam in this.attached) {
      const input = this.attached[cam];
      if (input === inputToRemove) {
        input.detachControl();
        input.camera = null;
        delete this.attached[cam];
        this.rebuildInputCheck();
        return;
      }
    }
  }
  removeByType(inputType) {
    for (const cam in this.attached) {
      const input = this.attached[cam];
      if (input.getClassName() === inputType) {
        input.detachControl();
        input.camera = null;
        delete this.attached[cam];
        this.rebuildInputCheck();
      }
    }
  }
  _addCheckInputs(fn) {
    const current = this.checkInputs;
    return () => {
      current();
      fn();
    };
  }
  attachInput(input) {
    if (this.attachedToElement) {
      input.attachControl(this.noPreventDefault);
    }
  }
  attachElement(noPreventDefault = false) {
    if (this.attachedToElement) {
      return;
    }
    noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
    this.attachedToElement = true;
    this.noPreventDefault = noPreventDefault;
    for (const cam in this.attached) {
      this.attached[cam].attachControl(noPreventDefault);
    }
  }
  detachElement(disconnect = false) {
    for (const cam in this.attached) {
      this.attached[cam].detachControl();
      if (disconnect) {
        this.attached[cam].camera = null;
      }
    }
    this.attachedToElement = false;
  }
  rebuildInputCheck() {
    this.checkInputs = () => {};
    for (const cam in this.attached) {
      const input = this.attached[cam];
      if (input.checkInputs) {
        this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
      }
    }
  }
  clear() {
    if (this.attachedToElement) {
      this.detachElement(true);
    }
    this.attached = {};
    this.attachedToElement = false;
    this.checkInputs = () => {};
  }
  serialize(serializedCamera) {
    const inputs = {};
    for (const cam in this.attached) {
      const input = this.attached[cam];
      const res = SerializationHelper.Serialize(input);
      inputs[input.getClassName()] = res;
    }
    serializedCamera.inputsmgr = inputs;
  }
  parse(parsedCamera) {
    const parsedInputs = parsedCamera.inputsmgr;
    if (parsedInputs) {
      this.clear();
      for (const n in parsedInputs) {
        const construct = CameraInputTypes[n];
        if (construct) {
          const parsedinput = parsedInputs[n];
          const input = SerializationHelper.Parse(() => {
            return new construct;
          }, parsedinput, null);
          this.add(input);
        }
      }
    } else {
      for (const n in this.attached) {
        const construct = CameraInputTypes[this.attached[n].getClassName()];
        if (construct) {
          const input = SerializationHelper.Parse(() => {
            return new construct;
          }, parsedCamera, null);
          this.remove(this.attached[n]);
          this.add(input);
        }
      }
    }
  }
}

// node_modules/@babylonjs/core/Gamepads/gamepad.js
init_observable();
class Gamepad {
  get isConnected() {
    return this._isConnected;
  }
  constructor(id, index, browserGamepad, leftStickX = 0, leftStickY = 1, rightStickX = 2, rightStickY = 3) {
    this.id = id;
    this.index = index;
    this.browserGamepad = browserGamepad;
    this._leftStick = { x: 0, y: 0 };
    this._rightStick = { x: 0, y: 0 };
    this._isConnected = true;
    this._invertLeftStickY = false;
    this.type = Gamepad.GAMEPAD;
    this._leftStickAxisX = leftStickX;
    this._leftStickAxisY = leftStickY;
    this._rightStickAxisX = rightStickX;
    this._rightStickAxisY = rightStickY;
    if (this.browserGamepad.axes.length >= 2) {
      this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
    }
    if (this.browserGamepad.axes.length >= 4) {
      this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
    }
  }
  onleftstickchanged(callback) {
    this._onleftstickchanged = callback;
  }
  onrightstickchanged(callback) {
    this._onrightstickchanged = callback;
  }
  get leftStick() {
    return this._leftStick;
  }
  set leftStick(newValues) {
    if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
      this._onleftstickchanged(newValues);
    }
    this._leftStick = newValues;
  }
  get rightStick() {
    return this._rightStick;
  }
  set rightStick(newValues) {
    if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
      this._onrightstickchanged(newValues);
    }
    this._rightStick = newValues;
  }
  update() {
    if (this._leftStick) {
      this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
      if (this._invertLeftStickY) {
        this.leftStick.y *= -1;
      }
    }
    if (this._rightStick) {
      this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
    }
  }
  dispose() {}
}
Gamepad.GAMEPAD = 0;
Gamepad.GENERIC = 1;
Gamepad.XBOX = 2;
Gamepad.POSE_ENABLED = 3;
Gamepad.DUALSHOCK = 4;

class GenericPad extends Gamepad {
  onbuttondown(callback) {
    this._onbuttondown = callback;
  }
  onbuttonup(callback) {
    this._onbuttonup = callback;
  }
  constructor(id, index, browserGamepad) {
    super(id, index, browserGamepad);
    this.onButtonDownObservable = new Observable;
    this.onButtonUpObservable = new Observable;
    this.type = Gamepad.GENERIC;
    this._buttons = new Array(browserGamepad.buttons.length);
  }
  _setButtonValue(newValue, currentValue, buttonIndex) {
    if (newValue !== currentValue) {
      if (newValue === 1) {
        if (this._onbuttondown) {
          this._onbuttondown(buttonIndex);
        }
        this.onButtonDownObservable.notifyObservers(buttonIndex);
      }
      if (newValue === 0) {
        if (this._onbuttonup) {
          this._onbuttonup(buttonIndex);
        }
        this.onButtonUpObservable.notifyObservers(buttonIndex);
      }
    }
    return newValue;
  }
  update() {
    super.update();
    for (let index = 0;index < this._buttons.length; index++) {
      this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
    }
  }
  dispose() {
    super.dispose();
    this.onButtonDownObservable.clear();
    this.onButtonUpObservable.clear();
  }
}

// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraGamepadInput.js
class ArcRotateCameraGamepadInput {
  constructor() {
    this.gamepadRotationSensibility = 80;
    this.gamepadMoveSensibility = 40;
    this._yAxisScale = 1;
  }
  get invertYAxis() {
    return this._yAxisScale !== 1;
  }
  set invertYAxis(value) {
    this._yAxisScale = value ? -1 : 1;
  }
  attachControl() {
    const manager = this.camera.getScene().gamepadManager;
    this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {
      if (gamepad.type !== Gamepad.POSE_ENABLED) {
        if (!this.gamepad || gamepad.type === Gamepad.XBOX) {
          this.gamepad = gamepad;
        }
      }
    });
    this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {
      if (this.gamepad === gamepad) {
        this.gamepad = null;
      }
    });
    this.gamepad = manager.getGamepadByType(Gamepad.XBOX);
    if (!this.gamepad && manager.gamepads.length) {
      this.gamepad = manager.gamepads[0];
    }
  }
  detachControl() {
    this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
    this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
    this.gamepad = null;
  }
  checkInputs() {
    if (this.gamepad) {
      const camera = this.camera;
      const rsValues = this.gamepad.rightStick;
      if (rsValues) {
        if (rsValues.x != 0) {
          const normalizedRX = rsValues.x / this.gamepadRotationSensibility;
          if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
            camera.inertialAlphaOffset += normalizedRX;
          }
        }
        if (rsValues.y != 0) {
          const normalizedRY = rsValues.y / this.gamepadRotationSensibility * this._yAxisScale;
          if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
            camera.inertialBetaOffset += normalizedRY;
          }
        }
      }
      const lsValues = this.gamepad.leftStick;
      if (lsValues && lsValues.y != 0) {
        const normalizedLY = lsValues.y / this.gamepadMoveSensibility;
        if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
          this.camera.inertialRadiusOffset -= normalizedLY;
        }
      }
    }
  }
  getClassName() {
    return "ArcRotateCameraGamepadInput";
  }
  getSimpleName() {
    return "gamepad";
  }
}
__decorate([
  serialize()
], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", undefined);
__decorate([
  serialize()
], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", undefined);
CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js
init_tslib_es6();
init_decorators();
init_keyboardEvents();
init_tools();

class ArcRotateCameraKeyboardMoveInput {
  constructor() {
    this.keysUp = [38];
    this.keysDown = [40];
    this.keysLeft = [37];
    this.keysRight = [39];
    this.keysReset = [220];
    this.panningSensibility = 50;
    this.zoomingSensibility = 25;
    this.useAltToZoom = true;
    this.angularSpeed = 0.01;
    this._keys = new Array;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    if (this._onCanvasBlurObserver) {
      return;
    }
    this._scene = this.camera.getScene();
    this._engine = this._scene.getEngine();
    this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
      this._keys.length = 0;
    });
    this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
      const evt = info.event;
      if (!evt.metaKey) {
        if (info.type === KeyboardEventTypes.KEYDOWN) {
          this._ctrlPressed = evt.ctrlKey;
          this._altPressed = evt.altKey;
          if (this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1 || this.keysReset.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index === -1) {
              this._keys.push(evt.keyCode);
            }
            if (evt.preventDefault) {
              if (!noPreventDefault) {
                evt.preventDefault();
              }
            }
          }
        } else {
          if (this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1 || this.keysReset.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index >= 0) {
              this._keys.splice(index, 1);
            }
            if (evt.preventDefault) {
              if (!noPreventDefault) {
                evt.preventDefault();
              }
            }
          }
        }
      }
    });
  }
  detachControl() {
    if (this._scene) {
      if (this._onKeyboardObserver) {
        this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
      }
      if (this._onCanvasBlurObserver) {
        this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
      }
      this._onKeyboardObserver = null;
      this._onCanvasBlurObserver = null;
    }
    this._keys.length = 0;
  }
  checkInputs() {
    if (this._onKeyboardObserver) {
      const camera = this.camera;
      for (let index = 0;index < this._keys.length; index++) {
        const keyCode = this._keys[index];
        if (this.keysLeft.indexOf(keyCode) !== -1) {
          if (this._ctrlPressed && this.camera._useCtrlForPanning) {
            camera.inertialPanningX -= 1 / this.panningSensibility;
          } else {
            camera.inertialAlphaOffset -= this.angularSpeed;
          }
        } else if (this.keysUp.indexOf(keyCode) !== -1) {
          if (this._ctrlPressed && this.camera._useCtrlForPanning) {
            camera.inertialPanningY += 1 / this.panningSensibility;
          } else if (this._altPressed && this.useAltToZoom) {
            camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
          } else {
            camera.inertialBetaOffset -= this.angularSpeed;
          }
        } else if (this.keysRight.indexOf(keyCode) !== -1) {
          if (this._ctrlPressed && this.camera._useCtrlForPanning) {
            camera.inertialPanningX += 1 / this.panningSensibility;
          } else {
            camera.inertialAlphaOffset += this.angularSpeed;
          }
        } else if (this.keysDown.indexOf(keyCode) !== -1) {
          if (this._ctrlPressed && this.camera._useCtrlForPanning) {
            camera.inertialPanningY -= 1 / this.panningSensibility;
          } else if (this._altPressed && this.useAltToZoom) {
            camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
          } else {
            camera.inertialBetaOffset += this.angularSpeed;
          }
        } else if (this.keysReset.indexOf(keyCode) !== -1) {
          if (camera.useInputToRestoreState) {
            camera.restoreState();
          }
        }
      }
    }
  }
  getClassName() {
    return "ArcRotateCameraKeyboardMoveInput";
  }
  getSimpleName() {
    return "keyboard";
  }
}
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", undefined);
__decorate([
  serialize()
], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", undefined);
CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraMouseWheelInput.js
init_tslib_es6();
init_decorators();
init_pointerEvents();
init_math_plane();
init_math_vector();
init_math_constants();
init_deviceInputEvents();
init_tools();
var ffMultiplier = 40;

class ArcRotateCameraMouseWheelInput {
  constructor() {
    this.wheelPrecision = 3;
    this.zoomToMouseLocation = false;
    this.wheelDeltaPercentage = 0;
    this.customComputeDeltaFromMouseWheel = null;
    this._viewOffset = new Vector3(0, 0, 0);
    this._globalOffset = new Vector3(0, 0, 0);
    this._inertialPanning = Vector3.Zero();
  }
  _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) {
    let delta = 0;
    const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius;
    if (mouseWheelDelta > 0) {
      delta = wheelDelta / (1 + this.wheelDeltaPercentage);
    } else {
      delta = wheelDelta * (1 + this.wheelDeltaPercentage);
    }
    return delta;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this._wheel = (p) => {
      if (p.type !== PointerEventTypes.POINTERWHEEL) {
        return;
      }
      const event = p.event;
      let delta = 0;
      const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1;
      const wheelDelta = -(event.deltaY * platformScale);
      if (this.customComputeDeltaFromMouseWheel) {
        delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event);
      } else {
        if (this.wheelDeltaPercentage) {
          delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius);
          if (delta > 0) {
            let estimatedTargetRadius = this.camera.radius;
            let targetInertia = this.camera.inertialRadiusOffset + delta;
            for (let i = 0;i < 20 && Math.abs(targetInertia) > 0.001; i++) {
              estimatedTargetRadius -= targetInertia;
              targetInertia *= this.camera.inertia;
            }
            estimatedTargetRadius = Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE);
            delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius);
          }
        } else {
          delta = wheelDelta / (this.wheelPrecision * 40);
        }
      }
      if (delta) {
        if (this.zoomToMouseLocation) {
          if (!this._hitPlane) {
            this._updateHitPlane();
          }
          this._zoomToMouse(delta);
        } else {
          this.camera.inertialRadiusOffset += delta;
        }
      }
      if (event.preventDefault) {
        if (!noPreventDefault) {
          event.preventDefault();
        }
      }
    };
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);
    if (this.zoomToMouseLocation) {
      this._inertialPanning.setAll(0);
    }
  }
  detachControl() {
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      this._observer = null;
      this._wheel = null;
    }
  }
  checkInputs() {
    if (!this.zoomToMouseLocation) {
      return;
    }
    const camera = this.camera;
    const motion = 0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset;
    if (motion) {
      this._updateHitPlane();
      camera.target.addInPlace(this._inertialPanning);
      this._inertialPanning.scaleInPlace(camera.inertia);
      this._zeroIfClose(this._inertialPanning);
    }
  }
  getClassName() {
    return "ArcRotateCameraMouseWheelInput";
  }
  getSimpleName() {
    return "mousewheel";
  }
  _updateHitPlane() {
    const camera = this.camera;
    const direction = camera.target.subtract(camera.position);
    this._hitPlane = Plane.FromPositionAndNormal(camera.target, direction);
  }
  _getPosition() {
    const camera = this.camera;
    const scene = camera.getScene();
    const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, Matrix.Identity(), camera, false);
    if (camera.targetScreenOffset.x !== 0 || camera.targetScreenOffset.y !== 0) {
      this._viewOffset.set(camera.targetScreenOffset.x, camera.targetScreenOffset.y, 0);
      camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
      this._globalOffset = Vector3.TransformNormal(this._viewOffset, camera._cameraTransformMatrix);
      ray.origin.addInPlace(this._globalOffset);
    }
    let distance = 0;
    if (this._hitPlane) {
      distance = ray.intersectsPlane(this._hitPlane) ?? 0;
    }
    return ray.origin.addInPlace(ray.direction.scaleInPlace(distance));
  }
  _zoomToMouse(delta) {
    const camera = this.camera;
    const inertiaComp = 1 - camera.inertia;
    if (camera.lowerRadiusLimit) {
      const lowerLimit = camera.lowerRadiusLimit ?? 0;
      if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) {
        delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset;
      }
    }
    if (camera.upperRadiusLimit) {
      const upperLimit = camera.upperRadiusLimit ?? 0;
      if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) {
        delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset;
      }
    }
    const zoomDistance = delta / inertiaComp;
    const ratio = zoomDistance / camera.radius;
    const vec = this._getPosition();
    const directionToZoomLocation = TmpVectors.Vector3[6];
    vec.subtractToRef(camera.target, directionToZoomLocation);
    directionToZoomLocation.scaleInPlace(ratio);
    directionToZoomLocation.scaleInPlace(inertiaComp);
    this._inertialPanning.addInPlace(directionToZoomLocation);
    camera.inertialRadiusOffset += delta;
  }
  _zeroIfClose(vec) {
    if (Math.abs(vec.x) < Epsilon) {
      vec.x = 0;
    }
    if (Math.abs(vec.y) < Epsilon) {
      vec.y = 0;
    }
    if (Math.abs(vec.z) < Epsilon) {
      vec.z = 0;
    }
  }
}
__decorate([
  serialize()
], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", undefined);
__decorate([
  serialize()
], ArcRotateCameraMouseWheelInput.prototype, "zoomToMouseLocation", undefined);
__decorate([
  serialize()
], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", undefined);
CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraPointersInput.js
init_tslib_es6();
init_decorators();
class ArcRotateCameraPointersInput extends BaseCameraPointersInput {
  constructor() {
    super(...arguments);
    this.buttons = [0, 1, 2];
    this.angularSensibilityX = 1000;
    this.angularSensibilityY = 1000;
    this.pinchPrecision = 12;
    this.pinchDeltaPercentage = 0;
    this.useNaturalPinchZoom = false;
    this.pinchZoom = true;
    this.panningSensibility = 1000;
    this.multiTouchPanning = true;
    this.multiTouchPanAndZoom = true;
    this.pinchInwards = true;
    this._isPanClick = false;
    this._twoFingerActivityCount = 0;
    this._isPinching = false;
  }
  getClassName() {
    return "ArcRotateCameraPointersInput";
  }
  _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) {
    if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) {
      const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x;
      const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y;
      this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility;
      this.camera.inertialPanningY += moveDeltaY / this.panningSensibility;
    }
  }
  _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) {
    const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch;
    if (this.useNaturalPinchZoom) {
      this.camera.radius = radius * Math.sqrt(previousPinchSquaredDistance) / Math.sqrt(pinchSquaredDistance);
    } else if (this.pinchDeltaPercentage) {
      this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage;
    } else {
      this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY) / 2);
    }
  }
  onTouch(point, offsetX, offsetY) {
    if (this.panningSensibility !== 0 && (this._ctrlKey && this.camera._useCtrlForPanning || this._isPanClick)) {
      this.camera.inertialPanningX += -offsetX / this.panningSensibility;
      this.camera.inertialPanningY += offsetY / this.panningSensibility;
    } else {
      this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX;
      this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY;
    }
  }
  onDoubleTap() {
    if (this.camera.useInputToRestoreState) {
      this.camera.restoreState();
    }
  }
  onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {
    if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {
      return;
    }
    if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {
      return;
    }
    if (this.multiTouchPanAndZoom) {
      this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
      this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
    } else if (this.multiTouchPanning && this.pinchZoom) {
      this._twoFingerActivityCount++;
      if (this._isPinching || this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance) {
        this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
        this._isPinching = true;
      } else {
        this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
      }
    } else if (this.multiTouchPanning) {
      this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);
    } else if (this.pinchZoom) {
      this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);
    }
  }
  onButtonDown(evt) {
    this._isPanClick = evt.button === this.camera._panningMouseButton;
  }
  onButtonUp(_evt) {
    this._twoFingerActivityCount = 0;
    this._isPinching = false;
  }
  onLostFocus() {
    this._isPanClick = false;
    this._twoFingerActivityCount = 0;
    this._isPinching = false;
  }
}
ArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001;
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "buttons", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "pinchPrecision", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "useNaturalPinchZoom", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "pinchZoom", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "panningSensibility", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", undefined);
__decorate([
  serialize()
], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", undefined);
CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
// node_modules/@babylonjs/core/Cameras/arcRotateCameraInputsManager.js
class ArcRotateCameraInputsManager extends CameraInputsManager {
  constructor(camera) {
    super(camera);
  }
  addMouseWheel() {
    this.add(new ArcRotateCameraMouseWheelInput);
    return this;
  }
  addPointers() {
    this.add(new ArcRotateCameraPointersInput);
    return this;
  }
  addKeyboard() {
    this.add(new ArcRotateCameraKeyboardMoveInput);
    return this;
  }
}

// node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.js
init_tools();
ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function() {
  this.add(new ArcRotateCameraVRDeviceOrientationInput);
  return this;
};

class ArcRotateCameraVRDeviceOrientationInput {
  constructor() {
    this.alphaCorrection = 1;
    this.gammaCorrection = 1;
    this._alpha = 0;
    this._gamma = 0;
    this._dirty = false;
    this._deviceOrientationHandler = (evt) => this._onOrientationEvent(evt);
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this.camera.attachControl(noPreventDefault);
    const hostWindow = this.camera.getScene().getEngine().getHostWindow();
    if (hostWindow) {
      if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") {
        DeviceOrientationEvent.requestPermission().then((response) => {
          if (response === "granted") {
            hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler);
          } else {
            Tools.Warn("Permission not granted.");
          }
        }).catch((error) => {
          Tools.Error(error);
        });
      } else {
        hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler);
      }
    }
  }
  _onOrientationEvent(evt) {
    if (evt.alpha !== null) {
      this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
    }
    if (evt.gamma !== null) {
      this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
    }
    this._dirty = true;
  }
  checkInputs() {
    if (this._dirty) {
      this._dirty = false;
      if (this._gamma < 0) {
        this._gamma = 180 + this._gamma;
      }
      this.camera.alpha = -this._alpha / 180 * Math.PI % Math.PI * 2;
      this.camera.beta = this._gamma / 180 * Math.PI;
    }
  }
  detachControl() {
    window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  }
  getClassName() {
    return "ArcRotateCameraVRDeviceOrientationInput";
  }
  getSimpleName() {
    return "VRDeviceOrientation";
  }
}
CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
// node_modules/@babylonjs/core/Cameras/Inputs/flyCameraKeyboardInput.js
init_tslib_es6();
init_decorators();
init_keyboardEvents();
init_math_vector();
init_tools();

class FlyCameraKeyboardInput {
  constructor() {
    this.keysForward = [87];
    this.keysBackward = [83];
    this.keysUp = [69];
    this.keysDown = [81];
    this.keysRight = [68];
    this.keysLeft = [65];
    this._keys = new Array;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    if (this._onCanvasBlurObserver) {
      return;
    }
    this._scene = this.camera.getScene();
    this._engine = this._scene.getEngine();
    this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
      this._keys.length = 0;
    });
    this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
      const evt = info.event;
      if (info.type === KeyboardEventTypes.KEYDOWN) {
        if (this.keysForward.indexOf(evt.keyCode) !== -1 || this.keysBackward.indexOf(evt.keyCode) !== -1 || this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1) {
          const index = this._keys.indexOf(evt.keyCode);
          if (index === -1) {
            this._keys.push(evt.keyCode);
          }
          if (!noPreventDefault) {
            evt.preventDefault();
          }
        }
      } else {
        if (this.keysForward.indexOf(evt.keyCode) !== -1 || this.keysBackward.indexOf(evt.keyCode) !== -1 || this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1) {
          const index = this._keys.indexOf(evt.keyCode);
          if (index >= 0) {
            this._keys.splice(index, 1);
          }
          if (!noPreventDefault) {
            evt.preventDefault();
          }
        }
      }
    });
  }
  detachControl() {
    if (this._scene) {
      if (this._onKeyboardObserver) {
        this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
      }
      if (this._onCanvasBlurObserver) {
        this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
      }
      this._onKeyboardObserver = null;
      this._onCanvasBlurObserver = null;
    }
    this._keys.length = 0;
  }
  getClassName() {
    return "FlyCameraKeyboardInput";
  }
  _onLostFocus() {
    this._keys.length = 0;
  }
  getSimpleName() {
    return "keyboard";
  }
  checkInputs() {
    if (this._onKeyboardObserver) {
      const camera = this.camera;
      for (let index = 0;index < this._keys.length; index++) {
        const keyCode = this._keys[index];
        const speed = camera._computeLocalCameraSpeed();
        if (this.keysForward.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, speed);
        } else if (this.keysBackward.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, -speed);
        } else if (this.keysUp.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, speed, 0);
        } else if (this.keysDown.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, -speed, 0);
        } else if (this.keysRight.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(speed, 0, 0);
        } else if (this.keysLeft.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(-speed, 0, 0);
        }
        if (camera.getScene().useRightHandedSystem) {
          camera._localDirection.z *= -1;
        }
        camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
        Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
        camera.cameraDirection.addInPlace(camera._transformedDirection);
      }
    }
  }
}
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysForward", undefined);
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysBackward", undefined);
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysUp", undefined);
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysDown", undefined);
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysRight", undefined);
__decorate([
  serialize()
], FlyCameraKeyboardInput.prototype, "keysLeft", undefined);
CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
// node_modules/@babylonjs/core/Cameras/Inputs/flyCameraMouseInput.js
init_tslib_es6();
init_decorators();
init_pointerEvents();
init_math_vector();
init_math_axis();
init_tools();

class FlyCameraMouseInput {
  constructor() {
    this.buttons = [0, 1, 2];
    this.buttonsYaw = [-1, 0, 1];
    this.buttonsPitch = [-1, 0, 1];
    this.buttonsRoll = [2];
    this.activeButton = -1;
    this.angularSensibility = 1000;
    this._previousPosition = null;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this._noPreventDefault = noPreventDefault;
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver((p) => {
      this._pointerInput(p);
    }, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);
    this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(() => {
      if (this.camera.rollCorrect) {
        this.camera.restoreRoll(this.camera.rollCorrect);
      }
    });
  }
  detachControl() {
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
      this._observer = null;
      this._rollObserver = null;
      this._previousPosition = null;
      this._noPreventDefault = undefined;
    }
  }
  getClassName() {
    return "FlyCameraMouseInput";
  }
  getSimpleName() {
    return "mouse";
  }
  _pointerInput(p) {
    const e = p.event;
    const camera = this.camera;
    const engine = camera.getEngine();
    if (!this.touchEnabled && e.pointerType === "touch") {
      return;
    }
    if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
      return;
    }
    const srcElement = e.target;
    if (p.type === PointerEventTypes.POINTERDOWN) {
      try {
        srcElement?.setPointerCapture(e.pointerId);
      } catch (e2) {}
      this._previousPosition = {
        x: e.clientX,
        y: e.clientY
      };
      this.activeButton = e.button;
      if (!this._noPreventDefault) {
        e.preventDefault();
      }
      if (engine.isPointerLock) {
        this._onMouseMove(p.event);
      }
    } else if (p.type === PointerEventTypes.POINTERUP) {
      try {
        srcElement?.releasePointerCapture(e.pointerId);
      } catch (e2) {}
      this.activeButton = -1;
      this._previousPosition = null;
      if (!this._noPreventDefault) {
        e.preventDefault();
      }
    } else if (p.type === PointerEventTypes.POINTERMOVE) {
      if (!this._previousPosition) {
        if (engine.isPointerLock) {
          this._onMouseMove(p.event);
        }
        return;
      }
      const offsetX = e.clientX - this._previousPosition.x;
      const offsetY = e.clientY - this._previousPosition.y;
      this._rotateCamera(offsetX, offsetY);
      this._previousPosition = {
        x: e.clientX,
        y: e.clientY
      };
      if (!this._noPreventDefault) {
        e.preventDefault();
      }
    }
  }
  _onMouseMove(e) {
    const camera = this.camera;
    const engine = camera.getEngine();
    if (!engine.isPointerLock) {
      return;
    }
    const offsetX = e.movementX;
    const offsetY = e.movementY;
    this._rotateCamera(offsetX, offsetY);
    this._previousPosition = null;
    if (!this._noPreventDefault) {
      e.preventDefault();
    }
  }
  _rotateCamera(offsetX, offsetY) {
    const camera = this.camera;
    const handednessMultiplier = camera._calculateHandednessMultiplier();
    offsetX *= handednessMultiplier;
    const x = offsetX / this.angularSensibility;
    const y = offsetY / this.angularSensibility;
    const currentRotation = Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
    let rotationChange;
    if (this.buttonsPitch.some((v) => {
      return v === this.activeButton;
    })) {
      rotationChange = Quaternion.RotationAxis(Axis.X, y);
      currentRotation.multiplyInPlace(rotationChange);
    }
    if (this.buttonsYaw.some((v) => {
      return v === this.activeButton;
    })) {
      rotationChange = Quaternion.RotationAxis(Axis.Y, x);
      currentRotation.multiplyInPlace(rotationChange);
      const limit = camera.bankedTurnLimit + camera._trackRoll;
      if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
        const bankingDelta = camera.bankedTurnMultiplier * -x;
        rotationChange = Quaternion.RotationAxis(Axis.Z, bankingDelta);
        currentRotation.multiplyInPlace(rotationChange);
      }
    }
    if (this.buttonsRoll.some((v) => {
      return v === this.activeButton;
    })) {
      rotationChange = Quaternion.RotationAxis(Axis.Z, -x);
      camera._trackRoll -= x;
      currentRotation.multiplyInPlace(rotationChange);
    }
    currentRotation.toEulerAnglesToRef(camera.rotation);
  }
}
__decorate([
  serialize()
], FlyCameraMouseInput.prototype, "buttons", undefined);
__decorate([
  serialize()
], FlyCameraMouseInput.prototype, "angularSensibility", undefined);
CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
// node_modules/@babylonjs/core/Cameras/Inputs/followCameraKeyboardMoveInput.js
init_tslib_es6();
init_decorators();
init_keyboardEvents();
init_tools();

class FollowCameraKeyboardMoveInput {
  constructor() {
    this.keysHeightOffsetIncr = [38];
    this.keysHeightOffsetDecr = [40];
    this.keysHeightOffsetModifierAlt = false;
    this.keysHeightOffsetModifierCtrl = false;
    this.keysHeightOffsetModifierShift = false;
    this.keysRotationOffsetIncr = [37];
    this.keysRotationOffsetDecr = [39];
    this.keysRotationOffsetModifierAlt = false;
    this.keysRotationOffsetModifierCtrl = false;
    this.keysRotationOffsetModifierShift = false;
    this.keysRadiusIncr = [40];
    this.keysRadiusDecr = [38];
    this.keysRadiusModifierAlt = true;
    this.keysRadiusModifierCtrl = false;
    this.keysRadiusModifierShift = false;
    this.heightSensibility = 1;
    this.rotationSensibility = 1;
    this.radiusSensibility = 1;
    this._keys = new Array;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    if (this._onCanvasBlurObserver) {
      return;
    }
    this._scene = this.camera.getScene();
    this._engine = this._scene.getEngine();
    this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
      this._keys.length = 0;
    });
    this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
      const evt = info.event;
      if (!evt.metaKey) {
        if (info.type === KeyboardEventTypes.KEYDOWN) {
          this._ctrlPressed = evt.ctrlKey;
          this._altPressed = evt.altKey;
          this._shiftPressed = evt.shiftKey;
          if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index === -1) {
              this._keys.push(evt.keyCode);
            }
            if (evt.preventDefault) {
              if (!noPreventDefault) {
                evt.preventDefault();
              }
            }
          }
        } else {
          if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index >= 0) {
              this._keys.splice(index, 1);
            }
            if (evt.preventDefault) {
              if (!noPreventDefault) {
                evt.preventDefault();
              }
            }
          }
        }
      }
    });
  }
  detachControl() {
    if (this._scene) {
      if (this._onKeyboardObserver) {
        this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
      }
      if (this._onCanvasBlurObserver) {
        this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
      }
      this._onKeyboardObserver = null;
      this._onCanvasBlurObserver = null;
    }
    this._keys.length = 0;
  }
  checkInputs() {
    if (this._onKeyboardObserver) {
      this._keys.forEach((keyCode) => {
        if (this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {
          this.camera.heightOffset += this.heightSensibility;
        } else if (this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {
          this.camera.heightOffset -= this.heightSensibility;
        } else if (this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {
          this.camera.rotationOffset += this.rotationSensibility;
          this.camera.rotationOffset %= 360;
        } else if (this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {
          this.camera.rotationOffset -= this.rotationSensibility;
          this.camera.rotationOffset %= 360;
        } else if (this.keysRadiusIncr.indexOf(keyCode) !== -1 && this._modifierRadius()) {
          this.camera.radius += this.radiusSensibility;
        } else if (this.keysRadiusDecr.indexOf(keyCode) !== -1 && this._modifierRadius()) {
          this.camera.radius -= this.radiusSensibility;
        }
      });
    }
  }
  getClassName() {
    return "FollowCameraKeyboardMoveInput";
  }
  getSimpleName() {
    return "keyboard";
  }
  _modifierHeightOffset() {
    return this.keysHeightOffsetModifierAlt === this._altPressed && this.keysHeightOffsetModifierCtrl === this._ctrlPressed && this.keysHeightOffsetModifierShift === this._shiftPressed;
  }
  _modifierRotationOffset() {
    return this.keysRotationOffsetModifierAlt === this._altPressed && this.keysRotationOffsetModifierCtrl === this._ctrlPressed && this.keysRotationOffsetModifierShift === this._shiftPressed;
  }
  _modifierRadius() {
    return this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed;
  }
}
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", undefined);
__decorate([
  serialize()
], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", undefined);
CameraInputTypes["FollowCameraKeyboardMoveInput"] = FollowCameraKeyboardMoveInput;
// node_modules/@babylonjs/core/Cameras/Inputs/followCameraMouseWheelInput.js
init_tslib_es6();
init_decorators();
init_pointerEvents();
init_tools();
init_logger();

class FollowCameraMouseWheelInput {
  constructor() {
    this.axisControlRadius = true;
    this.axisControlHeight = false;
    this.axisControlRotation = false;
    this.wheelPrecision = 3;
    this.wheelDeltaPercentage = 0;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this._wheel = (p) => {
      if (p.type !== PointerEventTypes.POINTERWHEEL) {
        return;
      }
      const event = p.event;
      let delta = 0;
      const wheelDelta = Math.max(-1, Math.min(1, event.deltaY));
      if (this.wheelDeltaPercentage) {
        if (+this.axisControlRadius + +this.axisControlHeight + +this.axisControlRotation) {
          Logger.Warn("wheelDeltaPercentage only usable when mouse wheel " + "controls ONE axis. " + "Currently enabled: " + "axisControlRadius: " + this.axisControlRadius + ", axisControlHeightOffset: " + this.axisControlHeight + ", axisControlRotationOffset: " + this.axisControlRotation);
        }
        if (this.axisControlRadius) {
          delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.radius;
        } else if (this.axisControlHeight) {
          delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.heightOffset;
        } else if (this.axisControlRotation) {
          delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.rotationOffset;
        }
      } else {
        delta = wheelDelta * this.wheelPrecision;
      }
      if (delta) {
        if (this.axisControlRadius) {
          this.camera.radius += delta;
        } else if (this.axisControlHeight) {
          this.camera.heightOffset -= delta;
        } else if (this.axisControlRotation) {
          this.camera.rotationOffset -= delta;
        }
      }
      if (event.preventDefault) {
        if (!noPreventDefault) {
          event.preventDefault();
        }
      }
    };
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);
  }
  detachControl() {
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      this._observer = null;
      this._wheel = null;
    }
  }
  getClassName() {
    return "ArcRotateCameraMouseWheelInput";
  }
  getSimpleName() {
    return "mousewheel";
  }
}
__decorate([
  serialize()
], FollowCameraMouseWheelInput.prototype, "axisControlRadius", undefined);
__decorate([
  serialize()
], FollowCameraMouseWheelInput.prototype, "axisControlHeight", undefined);
__decorate([
  serialize()
], FollowCameraMouseWheelInput.prototype, "axisControlRotation", undefined);
__decorate([
  serialize()
], FollowCameraMouseWheelInput.prototype, "wheelPrecision", undefined);
__decorate([
  serialize()
], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", undefined);
CameraInputTypes["FollowCameraMouseWheelInput"] = FollowCameraMouseWheelInput;
// node_modules/@babylonjs/core/Cameras/Inputs/followCameraPointersInput.js
init_tslib_es6();
init_decorators();
init_logger();

class FollowCameraPointersInput extends BaseCameraPointersInput {
  constructor() {
    super(...arguments);
    this.angularSensibilityX = 1;
    this.angularSensibilityY = 1;
    this.pinchPrecision = 1e4;
    this.pinchDeltaPercentage = 0;
    this.axisXControlRadius = false;
    this.axisXControlHeight = false;
    this.axisXControlRotation = true;
    this.axisYControlRadius = false;
    this.axisYControlHeight = true;
    this.axisYControlRotation = false;
    this.axisPinchControlRadius = true;
    this.axisPinchControlHeight = false;
    this.axisPinchControlRotation = false;
    this.warningEnable = true;
    this._warningCounter = 0;
  }
  getClassName() {
    return "FollowCameraPointersInput";
  }
  onTouch(pointA, offsetX, offsetY) {
    this._warning();
    if (this.axisXControlRotation) {
      this.camera.rotationOffset += offsetX / this.angularSensibilityX;
    } else if (this.axisYControlRotation) {
      this.camera.rotationOffset += offsetY / this.angularSensibilityX;
    }
    if (this.axisXControlHeight) {
      this.camera.heightOffset += offsetX / this.angularSensibilityY;
    } else if (this.axisYControlHeight) {
      this.camera.heightOffset += offsetY / this.angularSensibilityY;
    }
    if (this.axisXControlRadius) {
      this.camera.radius -= offsetX / this.angularSensibilityY;
    } else if (this.axisYControlRadius) {
      this.camera.radius -= offsetY / this.angularSensibilityY;
    }
  }
  onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {
    if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {
      return;
    }
    if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {
      return;
    }
    let pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY) / 2);
    if (this.pinchDeltaPercentage) {
      pinchDelta *= 0.01 * this.pinchDeltaPercentage;
      if (this.axisPinchControlRotation) {
        this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset;
      }
      if (this.axisPinchControlHeight) {
        this.camera.heightOffset += pinchDelta * this.camera.heightOffset;
      }
      if (this.axisPinchControlRadius) {
        this.camera.radius -= pinchDelta * this.camera.radius;
      }
    } else {
      if (this.axisPinchControlRotation) {
        this.camera.rotationOffset += pinchDelta;
      }
      if (this.axisPinchControlHeight) {
        this.camera.heightOffset += pinchDelta;
      }
      if (this.axisPinchControlRadius) {
        this.camera.radius -= pinchDelta;
      }
    }
  }
  _warning() {
    if (!this.warningEnable || this._warningCounter++ % 100 !== 0) {
      return;
    }
    const warn = "It probably only makes sense to control ONE camera " + "property with each pointer axis. Set 'warningEnable = false' " + "if you are sure. Currently enabled: ";
    if (+this.axisXControlRotation + +this.axisXControlHeight + +this.axisXControlRadius <= 1) {
      Logger.Warn(warn + "axisXControlRotation: " + this.axisXControlRotation + ", axisXControlHeight: " + this.axisXControlHeight + ", axisXControlRadius: " + this.axisXControlRadius);
    }
    if (+this.axisYControlRotation + +this.axisYControlHeight + +this.axisYControlRadius <= 1) {
      Logger.Warn(warn + "axisYControlRotation: " + this.axisYControlRotation + ", axisYControlHeight: " + this.axisYControlHeight + ", axisYControlRadius: " + this.axisYControlRadius);
    }
    if (+this.axisPinchControlRotation + +this.axisPinchControlHeight + +this.axisPinchControlRadius <= 1) {
      Logger.Warn(warn + "axisPinchControlRotation: " + this.axisPinchControlRotation + ", axisPinchControlHeight: " + this.axisPinchControlHeight + ", axisPinchControlRadius: " + this.axisPinchControlRadius);
    }
  }
}
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "angularSensibilityX", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "angularSensibilityY", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "pinchPrecision", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisXControlRadius", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisXControlHeight", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisXControlRotation", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisYControlRadius", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisYControlHeight", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisYControlRotation", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisPinchControlRadius", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisPinchControlHeight", undefined);
__decorate([
  serialize()
], FollowCameraPointersInput.prototype, "axisPinchControlRotation", undefined);
CameraInputTypes["FollowCameraPointersInput"] = FollowCameraPointersInput;
// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraDeviceOrientationInput.js
init_math_vector();
init_tools();

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraKeyboardMoveInput.js
init_tslib_es6();
init_decorators();
init_keyboardEvents();
init_math_vector();
init_tools();

class FreeCameraKeyboardMoveInput {
  constructor() {
    this.keysUp = [38];
    this.keysUpward = [33];
    this.keysDown = [40];
    this.keysDownward = [34];
    this.keysLeft = [37];
    this.keysRight = [39];
    this.rotationSpeed = 0.5;
    this.keysRotateLeft = [];
    this.keysRotateRight = [];
    this.keysRotateUp = [];
    this.keysRotateDown = [];
    this._keys = new Array;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    if (this._onCanvasBlurObserver) {
      return;
    }
    this._scene = this.camera.getScene();
    this._engine = this._scene.getEngine();
    this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {
      this._keys.length = 0;
    });
    this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {
      const evt = info.event;
      if (!evt.metaKey) {
        if (info.type === KeyboardEventTypes.KEYDOWN) {
          if (this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1 || this.keysUpward.indexOf(evt.keyCode) !== -1 || this.keysDownward.indexOf(evt.keyCode) !== -1 || this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || this.keysRotateRight.indexOf(evt.keyCode) !== -1 || this.keysRotateUp.indexOf(evt.keyCode) !== -1 || this.keysRotateDown.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index === -1) {
              this._keys.push(evt.keyCode);
            }
            if (!noPreventDefault) {
              evt.preventDefault();
            }
          }
        } else {
          if (this.keysUp.indexOf(evt.keyCode) !== -1 || this.keysDown.indexOf(evt.keyCode) !== -1 || this.keysLeft.indexOf(evt.keyCode) !== -1 || this.keysRight.indexOf(evt.keyCode) !== -1 || this.keysUpward.indexOf(evt.keyCode) !== -1 || this.keysDownward.indexOf(evt.keyCode) !== -1 || this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || this.keysRotateRight.indexOf(evt.keyCode) !== -1 || this.keysRotateUp.indexOf(evt.keyCode) !== -1 || this.keysRotateDown.indexOf(evt.keyCode) !== -1) {
            const index = this._keys.indexOf(evt.keyCode);
            if (index >= 0) {
              this._keys.splice(index, 1);
            }
            if (!noPreventDefault) {
              evt.preventDefault();
            }
          }
        }
      }
    });
  }
  detachControl() {
    if (this._scene) {
      if (this._onKeyboardObserver) {
        this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
      }
      if (this._onCanvasBlurObserver) {
        this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
      }
      this._onKeyboardObserver = null;
      this._onCanvasBlurObserver = null;
    }
    this._keys.length = 0;
  }
  checkInputs() {
    if (this._onKeyboardObserver) {
      const camera = this.camera;
      for (let index = 0;index < this._keys.length; index++) {
        const keyCode = this._keys[index];
        const speed = camera._computeLocalCameraSpeed();
        if (this.keysLeft.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(-speed, 0, 0);
        } else if (this.keysUp.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, speed);
        } else if (this.keysRight.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(speed, 0, 0);
        } else if (this.keysDown.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, -speed);
        } else if (this.keysUpward.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, speed, 0);
        } else if (this.keysDownward.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, -speed, 0);
        } else if (this.keysRotateLeft.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, 0);
          camera.cameraRotation.y -= this._getLocalRotation();
        } else if (this.keysRotateRight.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, 0);
          camera.cameraRotation.y += this._getLocalRotation();
        } else if (this.keysRotateUp.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, 0);
          camera.cameraRotation.x -= this._getLocalRotation();
        } else if (this.keysRotateDown.indexOf(keyCode) !== -1) {
          camera._localDirection.copyFromFloats(0, 0, 0);
          camera.cameraRotation.x += this._getLocalRotation();
        }
        if (camera.getScene().useRightHandedSystem) {
          camera._localDirection.z *= -1;
        }
        camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
        Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
        camera.cameraDirection.addInPlace(camera._transformedDirection);
      }
    }
  }
  getClassName() {
    return "FreeCameraKeyboardMoveInput";
  }
  _onLostFocus() {
    this._keys.length = 0;
  }
  getSimpleName() {
    return "keyboard";
  }
  _getLocalRotation() {
    const handednessMultiplier = this.camera._calculateHandednessMultiplier();
    const rotation = this.rotationSpeed * this._engine.getDeltaTime() / 1000 * handednessMultiplier;
    return rotation;
  }
}
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysUp", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysUpward", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysDown", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysDownward", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysLeft", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRight", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "rotationSpeed", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRotateLeft", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRotateRight", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRotateUp", undefined);
__decorate([
  serialize()
], FreeCameraKeyboardMoveInput.prototype, "keysRotateDown", undefined);
CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseInput.js
init_tslib_es6();
init_observable();
init_decorators();
init_pointerEvents();
init_tools();

class FreeCameraMouseInput {
  constructor(touchEnabled = true) {
    this.touchEnabled = touchEnabled;
    this.buttons = [0, 1, 2];
    this.angularSensibility = 2000;
    this._previousPosition = null;
    this.onPointerMovedObservable = new Observable;
    this._allowCameraRotation = true;
    this._currentActiveButton = -1;
    this._activePointerId = -1;
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    const engine = this.camera.getEngine();
    const element = engine.getInputElement();
    if (!this._pointerInput) {
      this._pointerInput = (p) => {
        const evt = p.event;
        const isTouch = evt.pointerType === "touch";
        if (!this.touchEnabled && isTouch) {
          return;
        }
        if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {
          return;
        }
        const srcElement = evt.target;
        if (p.type === PointerEventTypes.POINTERDOWN) {
          if (isTouch && this._activePointerId !== -1 || !isTouch && this._currentActiveButton !== -1) {
            return;
          }
          this._activePointerId = evt.pointerId;
          try {
            srcElement?.setPointerCapture(evt.pointerId);
          } catch (e) {}
          if (this._currentActiveButton === -1) {
            this._currentActiveButton = evt.button;
          }
          this._previousPosition = {
            x: evt.clientX,
            y: evt.clientY
          };
          if (!noPreventDefault) {
            evt.preventDefault();
            element && element.focus();
          }
          if (engine.isPointerLock && this._onMouseMove) {
            this._onMouseMove(p.event);
          }
        } else if (p.type === PointerEventTypes.POINTERUP) {
          if (isTouch && this._activePointerId !== evt.pointerId || !isTouch && this._currentActiveButton !== evt.button) {
            return;
          }
          try {
            srcElement?.releasePointerCapture(evt.pointerId);
          } catch (e) {}
          this._currentActiveButton = -1;
          this._previousPosition = null;
          if (!noPreventDefault) {
            evt.preventDefault();
          }
          this._activePointerId = -1;
        } else if (p.type === PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) {
          if (engine.isPointerLock && this._onMouseMove) {
            this._onMouseMove(p.event);
          } else if (this._previousPosition) {
            const handednessMultiplier = this.camera._calculateHandednessMultiplier();
            const offsetX = (evt.clientX - this._previousPosition.x) * handednessMultiplier;
            const offsetY = evt.clientY - this._previousPosition.y;
            if (this._allowCameraRotation) {
              this.camera.cameraRotation.y += offsetX / this.angularSensibility;
              this.camera.cameraRotation.x += offsetY / this.angularSensibility;
            }
            this.onPointerMovedObservable.notifyObservers({ offsetX, offsetY });
            this._previousPosition = {
              x: evt.clientX,
              y: evt.clientY
            };
            if (!noPreventDefault) {
              evt.preventDefault();
            }
          }
        }
      };
    }
    this._onMouseMove = (evt) => {
      if (!engine.isPointerLock) {
        return;
      }
      const handednessMultiplier = this.camera._calculateHandednessMultiplier();
      const offsetX = evt.movementX * handednessMultiplier;
      this.camera.cameraRotation.y += offsetX / this.angularSensibility;
      const offsetY = evt.movementY;
      this.camera.cameraRotation.x += offsetY / this.angularSensibility;
      this._previousPosition = null;
      if (!noPreventDefault) {
        evt.preventDefault();
      }
    };
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);
    if (element) {
      this._contextMenuBind = (evt) => this.onContextMenu(evt);
      element.addEventListener("contextmenu", this._contextMenuBind, false);
    }
  }
  onContextMenu(evt) {
    evt.preventDefault();
  }
  detachControl() {
    if (this._observer) {
      this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
      if (this._contextMenuBind) {
        const engine = this.camera.getEngine();
        const element = engine.getInputElement();
        element && element.removeEventListener("contextmenu", this._contextMenuBind);
      }
      if (this.onPointerMovedObservable) {
        this.onPointerMovedObservable.clear();
      }
      this._observer = null;
      this._onMouseMove = null;
      this._previousPosition = null;
    }
    this._activePointerId = -1;
    this._currentActiveButton = -1;
  }
  getClassName() {
    return "FreeCameraMouseInput";
  }
  getSimpleName() {
    return "mouse";
  }
}
__decorate([
  serialize()
], FreeCameraMouseInput.prototype, "buttons", undefined);
__decorate([
  serialize()
], FreeCameraMouseInput.prototype, "angularSensibility", undefined);
CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseWheelInput.js
init_tslib_es6();
init_decorators();
init_math_vector();
var _CameraProperty;
(function(_CameraProperty2) {
  _CameraProperty2[_CameraProperty2["MoveRelative"] = 0] = "MoveRelative";
  _CameraProperty2[_CameraProperty2["RotateRelative"] = 1] = "RotateRelative";
  _CameraProperty2[_CameraProperty2["MoveScene"] = 2] = "MoveScene";
})(_CameraProperty || (_CameraProperty = {}));

class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput {
  constructor() {
    super(...arguments);
    this._moveRelative = Vector3.Zero();
    this._rotateRelative = Vector3.Zero();
    this._moveScene = Vector3.Zero();
    this._wheelXAction = _CameraProperty.MoveRelative;
    this._wheelXActionCoordinate = 0;
    this._wheelYAction = _CameraProperty.MoveRelative;
    this._wheelYActionCoordinate = 2;
    this._wheelZAction = null;
    this._wheelZActionCoordinate = null;
  }
  getClassName() {
    return "FreeCameraMouseWheelInput";
  }
  set wheelXMoveRelative(axis) {
    if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) {
      return;
    }
    this._wheelXAction = _CameraProperty.MoveRelative;
    this._wheelXActionCoordinate = axis;
  }
  get wheelXMoveRelative() {
    if (this._wheelXAction !== _CameraProperty.MoveRelative) {
      return null;
    }
    return this._wheelXActionCoordinate;
  }
  set wheelYMoveRelative(axis) {
    if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) {
      return;
    }
    this._wheelYAction = _CameraProperty.MoveRelative;
    this._wheelYActionCoordinate = axis;
  }
  get wheelYMoveRelative() {
    if (this._wheelYAction !== _CameraProperty.MoveRelative) {
      return null;
    }
    return this._wheelYActionCoordinate;
  }
  set wheelZMoveRelative(axis) {
    if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) {
      return;
    }
    this._wheelZAction = _CameraProperty.MoveRelative;
    this._wheelZActionCoordinate = axis;
  }
  get wheelZMoveRelative() {
    if (this._wheelZAction !== _CameraProperty.MoveRelative) {
      return null;
    }
    return this._wheelZActionCoordinate;
  }
  set wheelXRotateRelative(axis) {
    if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) {
      return;
    }
    this._wheelXAction = _CameraProperty.RotateRelative;
    this._wheelXActionCoordinate = axis;
  }
  get wheelXRotateRelative() {
    if (this._wheelXAction !== _CameraProperty.RotateRelative) {
      return null;
    }
    return this._wheelXActionCoordinate;
  }
  set wheelYRotateRelative(axis) {
    if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) {
      return;
    }
    this._wheelYAction = _CameraProperty.RotateRelative;
    this._wheelYActionCoordinate = axis;
  }
  get wheelYRotateRelative() {
    if (this._wheelYAction !== _CameraProperty.RotateRelative) {
      return null;
    }
    return this._wheelYActionCoordinate;
  }
  set wheelZRotateRelative(axis) {
    if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) {
      return;
    }
    this._wheelZAction = _CameraProperty.RotateRelative;
    this._wheelZActionCoordinate = axis;
  }
  get wheelZRotateRelative() {
    if (this._wheelZAction !== _CameraProperty.RotateRelative) {
      return null;
    }
    return this._wheelZActionCoordinate;
  }
  set wheelXMoveScene(axis) {
    if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) {
      return;
    }
    this._wheelXAction = _CameraProperty.MoveScene;
    this._wheelXActionCoordinate = axis;
  }
  get wheelXMoveScene() {
    if (this._wheelXAction !== _CameraProperty.MoveScene) {
      return null;
    }
    return this._wheelXActionCoordinate;
  }
  set wheelYMoveScene(axis) {
    if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) {
      return;
    }
    this._wheelYAction = _CameraProperty.MoveScene;
    this._wheelYActionCoordinate = axis;
  }
  get wheelYMoveScene() {
    if (this._wheelYAction !== _CameraProperty.MoveScene) {
      return null;
    }
    return this._wheelYActionCoordinate;
  }
  set wheelZMoveScene(axis) {
    if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) {
      return;
    }
    this._wheelZAction = _CameraProperty.MoveScene;
    this._wheelZActionCoordinate = axis;
  }
  get wheelZMoveScene() {
    if (this._wheelZAction !== _CameraProperty.MoveScene) {
      return null;
    }
    return this._wheelZActionCoordinate;
  }
  checkInputs() {
    if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) {
      return;
    }
    this._moveRelative.setAll(0);
    this._rotateRelative.setAll(0);
    this._moveScene.setAll(0);
    this._updateCamera();
    if (this.camera.getScene().useRightHandedSystem) {
      this._moveRelative.z *= -1;
    }
    const cameraTransformMatrix = Matrix.Zero();
    this.camera.getViewMatrix().invertToRef(cameraTransformMatrix);
    const transformedDirection = Vector3.Zero();
    Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection);
    this.camera.cameraRotation.x += this._rotateRelative.x / 200;
    this.camera.cameraRotation.y += this._rotateRelative.y / 200;
    this.camera.cameraDirection.addInPlace(transformedDirection);
    this.camera.cameraDirection.addInPlace(this._moveScene);
    super.checkInputs();
  }
  _updateCamera() {
    this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate);
    this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate);
    this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate);
  }
  _updateCameraProperty(value, cameraProperty, coordinate) {
    if (value === 0) {
      return;
    }
    if (cameraProperty === null || coordinate === null) {
      return;
    }
    let action2 = null;
    switch (cameraProperty) {
      case _CameraProperty.MoveRelative:
        action2 = this._moveRelative;
        break;
      case _CameraProperty.RotateRelative:
        action2 = this._rotateRelative;
        break;
      case _CameraProperty.MoveScene:
        action2 = this._moveScene;
        break;
    }
    switch (coordinate) {
      case 0:
        action2.set(value, 0, 0);
        break;
      case 1:
        action2.set(0, value, 0);
        break;
      case 2:
        action2.set(0, 0, value);
        break;
    }
  }
}
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelXMoveRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelYMoveRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelZMoveRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelXRotateRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelYRotateRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelZRotateRelative", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelXMoveScene", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelYMoveScene", null);
__decorate([
  serialize()
], FreeCameraMouseWheelInput.prototype, "wheelZMoveScene", null);
CameraInputTypes["FreeCameraMouseWheelInput"] = FreeCameraMouseWheelInput;

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraTouchInput.js
init_tslib_es6();
init_decorators();
init_pointerEvents();
init_math_vector();
init_tools();

class FreeCameraTouchInput {
  constructor(allowMouse = false) {
    this.allowMouse = allowMouse;
    this.touchAngularSensibility = 200000;
    this.touchMoveSensibility = 250;
    this.singleFingerRotate = false;
    this._offsetX = null;
    this._offsetY = null;
    this._pointerPressed = new Array;
    this._isSafari = Tools.IsSafari();
  }
  attachControl(noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    let previousPosition = null;
    if (this._pointerInput === undefined) {
      this._onLostFocus = () => {
        this._offsetX = null;
        this._offsetY = null;
      };
      this._pointerInput = (p) => {
        const evt = p.event;
        const isMouseEvent = evt.pointerType === "mouse" || this._isSafari && typeof evt.pointerType === "undefined";
        if (!this.allowMouse && isMouseEvent) {
          return;
        }
        if (p.type === PointerEventTypes.POINTERDOWN) {
          if (!noPreventDefault) {
            evt.preventDefault();
          }
          this._pointerPressed.push(evt.pointerId);
          if (this._pointerPressed.length !== 1) {
            return;
          }
          previousPosition = {
            x: evt.clientX,
            y: evt.clientY
          };
        } else if (p.type === PointerEventTypes.POINTERUP) {
          if (!noPreventDefault) {
            evt.preventDefault();
          }
          const index = this._pointerPressed.indexOf(evt.pointerId);
          if (index === -1) {
            return;
          }
          this._pointerPressed.splice(index, 1);
          if (index != 0) {
            return;
          }
          previousPosition = null;
          this._offsetX = null;
          this._offsetY = null;
        } else if (p.type === PointerEventTypes.POINTERMOVE) {
          if (!noPreventDefault) {
            evt.preventDefault();
          }
          if (!previousPosition) {
            return;
          }
          const index = this._pointerPressed.indexOf(evt.pointerId);
          if (index != 0) {
            return;
          }
          this._offsetX = evt.clientX - previousPosition.x;
          this._offsetY = -(evt.clientY - previousPosition.y);
        }
      };
    }
    this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);
    if (this._onLostFocus) {
      const engine = this.camera.getEngine();
      const element = engine.getInputElement();
      element && element.addEventListener("blur", this._onLostFocus);
    }
  }
  detachControl() {
    if (this._pointerInput) {
      if (this._observer) {
        this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);
        this._observer = null;
      }
      if (this._onLostFocus) {
        const engine = this.camera.getEngine();
        const element = engine.getInputElement();
        element && element.removeEventListener("blur", this._onLostFocus);
        this._onLostFocus = null;
      }
      this._pointerPressed.length = 0;
      this._offsetX = null;
      this._offsetY = null;
    }
  }
  checkInputs() {
    if (this._offsetX === null || this._offsetY === null) {
      return;
    }
    if (this._offsetX === 0 && this._offsetY === 0) {
      return;
    }
    const camera = this.camera;
    const handednessMultiplier = camera._calculateHandednessMultiplier();
    camera.cameraRotation.y = handednessMultiplier * this._offsetX / this.touchAngularSensibility;
    const rotateCamera = this.singleFingerRotate && this._pointerPressed.length === 1 || !this.singleFingerRotate && this._pointerPressed.length > 1;
    if (rotateCamera) {
      camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;
    } else {
      const speed = camera._computeLocalCameraSpeed();
      const direction = new Vector3(0, 0, this.touchMoveSensibility !== 0 ? speed * this._offsetY / this.touchMoveSensibility : 0);
      Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
      camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
    }
  }
  getClassName() {
    return "FreeCameraTouchInput";
  }
  getSimpleName() {
    return "touch";
  }
}
__decorate([
  serialize()
], FreeCameraTouchInput.prototype, "touchAngularSensibility", undefined);
__decorate([
  serialize()
], FreeCameraTouchInput.prototype, "touchMoveSensibility", undefined);
CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;

// node_modules/@babylonjs/core/Cameras/freeCameraInputsManager.js
class FreeCameraInputsManager extends CameraInputsManager {
  constructor(camera) {
    super(camera);
    this._mouseInput = null;
    this._mouseWheelInput = null;
  }
  addKeyboard() {
    this.add(new FreeCameraKeyboardMoveInput);
    return this;
  }
  addMouse(touchEnabled = true) {
    if (!this._mouseInput) {
      this._mouseInput = new FreeCameraMouseInput(touchEnabled);
      this.add(this._mouseInput);
    }
    return this;
  }
  removeMouse() {
    if (this._mouseInput) {
      this.remove(this._mouseInput);
    }
    return this;
  }
  addMouseWheel() {
    if (!this._mouseWheelInput) {
      this._mouseWheelInput = new FreeCameraMouseWheelInput;
      this.add(this._mouseWheelInput);
    }
    return this;
  }
  removeMouseWheel() {
    if (this._mouseWheelInput) {
      this.remove(this._mouseWheelInput);
    }
    return this;
  }
  addTouch() {
    this.add(new FreeCameraTouchInput);
    return this;
  }
  clear() {
    super.clear();
    this._mouseInput = null;
  }
}

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraDeviceOrientationInput.js
init_observable();
FreeCameraInputsManager.prototype.addDeviceOrientation = function(smoothFactor) {
  if (!this._deviceOrientationInput) {
    this._deviceOrientationInput = new FreeCameraDeviceOrientationInput;
    if (smoothFactor) {
      this._deviceOrientationInput.smoothFactor = smoothFactor;
    }
    this.add(this._deviceOrientationInput);
  }
  return this;
};

class FreeCameraDeviceOrientationInput {
  static WaitForOrientationChangeAsync(timeout) {
    return new Promise((res, rej) => {
      let gotValue = false;
      const eventHandler = () => {
        window.removeEventListener("deviceorientation", eventHandler);
        gotValue = true;
        res();
      };
      if (timeout) {
        setTimeout(() => {
          if (!gotValue) {
            window.removeEventListener("deviceorientation", eventHandler);
            rej("WaitForOrientationChangeAsync timed out");
          }
        }, timeout);
      }
      if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") {
        DeviceOrientationEvent.requestPermission().then((response) => {
          if (response == "granted") {
            window.addEventListener("deviceorientation", eventHandler);
          } else {
            Tools.Warn("Permission not granted.");
          }
        }).catch((error) => {
          Tools.Error(error);
        });
      } else {
        window.addEventListener("deviceorientation", eventHandler);
      }
    });
  }
  constructor() {
    this._screenOrientationAngle = 0;
    this._screenQuaternion = new Quaternion;
    this._alpha = 0;
    this._beta = 0;
    this._gamma = 0;
    this.smoothFactor = 0;
    this._onDeviceOrientationChangedObservable = new Observable;
    this._orientationChanged = () => {
      this._screenOrientationAngle = window.orientation !== undefined ? +window.orientation : window.screen.orientation && window.screen.orientation["angle"] ? window.screen.orientation.angle : 0;
      this._screenOrientationAngle = -Tools.ToRadians(this._screenOrientationAngle / 2);
      this._screenQuaternion.copyFromFloats(0, Math.sin(this._screenOrientationAngle), 0, Math.cos(this._screenOrientationAngle));
    };
    this._deviceOrientation = (evt) => {
      if (this.smoothFactor) {
        this._alpha = evt.alpha !== null ? Tools.SmoothAngleChange(this._alpha, evt.alpha, this.smoothFactor) : 0;
        this._beta = evt.beta !== null ? Tools.SmoothAngleChange(this._beta, evt.beta, this.smoothFactor) : 0;
        this._gamma = evt.gamma !== null ? Tools.SmoothAngleChange(this._gamma, evt.gamma, this.smoothFactor) : 0;
      } else {
        this._alpha = evt.alpha !== null ? evt.alpha : 0;
        this._beta = evt.beta !== null ? evt.beta : 0;
        this._gamma = evt.gamma !== null ? evt.gamma : 0;
      }
      if (evt.alpha !== null) {
        this._onDeviceOrientationChangedObservable.notifyObservers();
      }
    };
    this._constantTransform = new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
    this._orientationChanged();
  }
  get camera() {
    return this._camera;
  }
  set camera(camera) {
    this._camera = camera;
    if (this._camera != null && !this._camera.rotationQuaternion) {
      this._camera.rotationQuaternion = new Quaternion;
    }
    if (this._camera) {
      this._camera.onDisposeObservable.add(() => {
        this._onDeviceOrientationChangedObservable.clear();
      });
    }
  }
  attachControl() {
    const hostWindow = this.camera.getScene().getEngine().getHostWindow();
    if (hostWindow) {
      const eventHandler = () => {
        hostWindow.addEventListener("orientationchange", this._orientationChanged);
        hostWindow.addEventListener("deviceorientation", this._deviceOrientation);
        this._orientationChanged();
      };
      if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") {
        DeviceOrientationEvent.requestPermission().then((response) => {
          if (response === "granted") {
            eventHandler();
          } else {
            Tools.Warn("Permission not granted.");
          }
        }).catch((error) => {
          Tools.Error(error);
        });
      } else {
        eventHandler();
      }
    }
  }
  detachControl() {
    window.removeEventListener("orientationchange", this._orientationChanged);
    window.removeEventListener("deviceorientation", this._deviceOrientation);
    this._alpha = 0;
  }
  checkInputs() {
    if (!this._alpha) {
      return;
    }
    Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha), Tools.ToRadians(this._beta), -Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
    this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
    this._camera.rotationQuaternion.multiplyInPlace(this._constantTransform);
    if (this._camera.getScene().useRightHandedSystem) {
      this._camera.rotationQuaternion.y *= -1;
    } else {
      this._camera.rotationQuaternion.z *= -1;
    }
    this._camera.rotationQuaternion.w *= -1;
  }
  getClassName() {
    return "FreeCameraDeviceOrientationInput";
  }
  getSimpleName() {
    return "deviceOrientation";
  }
}
CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraGamepadInput.js
init_tslib_es6();
init_decorators();
init_math_vector();
class FreeCameraGamepadInput {
  constructor() {
    this.gamepadAngularSensibility = 200;
    this.gamepadMoveSensibility = 40;
    this.deadzoneDelta = 0.1;
    this._yAxisScale = 1;
    this._cameraTransform = Matrix.Identity();
    this._deltaTransform = Vector3.Zero();
    this._vector3 = Vector3.Zero();
    this._vector2 = Vector2.Zero();
  }
  get invertYAxis() {
    return this._yAxisScale !== 1;
  }
  set invertYAxis(value) {
    this._yAxisScale = value ? -1 : 1;
  }
  attachControl() {
    const manager = this.camera.getScene().gamepadManager;
    this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {
      if (gamepad.type !== Gamepad.POSE_ENABLED) {
        if (!this.gamepad || gamepad.type === Gamepad.XBOX) {
          this.gamepad = gamepad;
        }
      }
    });
    this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {
      if (this.gamepad === gamepad) {
        this.gamepad = null;
      }
    });
    this.gamepad = manager.getGamepadByType(Gamepad.XBOX);
    if (!this.gamepad && manager.gamepads.length) {
      this.gamepad = manager.gamepads[0];
    }
  }
  detachControl() {
    this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
    this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
    this.gamepad = null;
  }
  checkInputs() {
    if (this.gamepad && this.gamepad.leftStick) {
      const camera = this.camera;
      const lsValues = this.gamepad.leftStick;
      if (this.gamepadMoveSensibility !== 0) {
        lsValues.x = Math.abs(lsValues.x) > this.deadzoneDelta ? lsValues.x / this.gamepadMoveSensibility : 0;
        lsValues.y = Math.abs(lsValues.y) > this.deadzoneDelta ? lsValues.y / this.gamepadMoveSensibility : 0;
      }
      let rsValues = this.gamepad.rightStick;
      if (rsValues && this.gamepadAngularSensibility !== 0) {
        rsValues.x = Math.abs(rsValues.x) > this.deadzoneDelta ? rsValues.x / this.gamepadAngularSensibility : 0;
        rsValues.y = (Math.abs(rsValues.y) > this.deadzoneDelta ? rsValues.y / this.gamepadAngularSensibility : 0) * this._yAxisScale;
      } else {
        rsValues = { x: 0, y: 0 };
      }
      if (!camera.rotationQuaternion) {
        Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
      } else {
        camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
      }
      const speed = camera._computeLocalCameraSpeed() * 50;
      this._vector3.copyFromFloats(lsValues.x * speed, 0, -lsValues.y * speed);
      Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
      camera.cameraDirection.addInPlace(this._deltaTransform);
      this._vector2.copyFromFloats(rsValues.y, rsValues.x);
      camera.cameraRotation.addInPlace(this._vector2);
    }
  }
  getClassName() {
    return "FreeCameraGamepadInput";
  }
  getSimpleName() {
    return "gamepad";
  }
}
__decorate([
  serialize()
], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", undefined);
__decorate([
  serialize()
], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", undefined);
CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
// node_modules/@babylonjs/core/Misc/virtualJoystick.js
init_math_vector();
var JoystickAxis;
(function(JoystickAxis2) {
  JoystickAxis2[JoystickAxis2["X"] = 0] = "X";
  JoystickAxis2[JoystickAxis2["Y"] = 1] = "Y";
  JoystickAxis2[JoystickAxis2["Z"] = 2] = "Z";
})(JoystickAxis || (JoystickAxis = {}));

class VirtualJoystick {
  static _GetDefaultOptions() {
    return {
      puckSize: 40,
      containerSize: 60,
      color: "cyan",
      puckImage: undefined,
      containerImage: undefined,
      position: undefined,
      alwaysVisible: false,
      limitToContainer: false
    };
  }
  constructor(leftJoystick, customizations) {
    this._released = false;
    const options = {
      ...VirtualJoystick._GetDefaultOptions(),
      ...customizations
    };
    if (leftJoystick) {
      this._leftJoystick = true;
    } else {
      this._leftJoystick = false;
    }
    VirtualJoystick._GlobalJoystickIndex++;
    this._axisTargetedByLeftAndRight = 0;
    this._axisTargetedByUpAndDown = 1;
    this.reverseLeftRight = false;
    this.reverseUpDown = false;
    this._touches = new StringDictionary;
    this.deltaPosition = Vector3.Zero();
    this._joystickSensibility = 25;
    this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
    this._onResize = () => {
      VirtualJoystick._VJCanvasWidth = window.innerWidth;
      VirtualJoystick._VJCanvasHeight = window.innerHeight;
      if (VirtualJoystick.Canvas) {
        VirtualJoystick.Canvas.width = VirtualJoystick._VJCanvasWidth;
        VirtualJoystick.Canvas.height = VirtualJoystick._VJCanvasHeight;
      }
      VirtualJoystick._HalfWidth = VirtualJoystick._VJCanvasWidth / 2;
    };
    if (!VirtualJoystick.Canvas) {
      window.addEventListener("resize", this._onResize, false);
      VirtualJoystick.Canvas = document.createElement("canvas");
      VirtualJoystick._VJCanvasWidth = window.innerWidth;
      VirtualJoystick._VJCanvasHeight = window.innerHeight;
      VirtualJoystick.Canvas.width = window.innerWidth;
      VirtualJoystick.Canvas.height = window.innerHeight;
      VirtualJoystick.Canvas.style.width = "100%";
      VirtualJoystick.Canvas.style.height = "100%";
      VirtualJoystick.Canvas.style.position = "absolute";
      VirtualJoystick.Canvas.style.backgroundColor = "transparent";
      VirtualJoystick.Canvas.style.top = "0px";
      VirtualJoystick.Canvas.style.left = "0px";
      VirtualJoystick.Canvas.style.zIndex = "5";
      VirtualJoystick.Canvas.style.touchAction = "none";
      VirtualJoystick.Canvas.setAttribute("touch-action", "none");
      const context = VirtualJoystick.Canvas.getContext("2d");
      if (!context) {
        throw new Error("Unable to create canvas for virtual joystick");
      }
      VirtualJoystick._VJCanvasContext = context;
      VirtualJoystick._VJCanvasContext.strokeStyle = "#ffffff";
      VirtualJoystick._VJCanvasContext.lineWidth = 2;
      document.body.appendChild(VirtualJoystick.Canvas);
    }
    VirtualJoystick._HalfWidth = VirtualJoystick.Canvas.width / 2;
    this.pressed = false;
    this.limitToContainer = options.limitToContainer;
    this._joystickColor = options.color;
    this.containerSize = options.containerSize;
    this.puckSize = options.puckSize;
    if (options.position) {
      this.setPosition(options.position.x, options.position.y);
    }
    if (options.puckImage) {
      this.setPuckImage(options.puckImage);
    }
    if (options.containerImage) {
      this.setContainerImage(options.containerImage);
    }
    if (options.alwaysVisible) {
      VirtualJoystick._AlwaysVisibleSticks++;
    }
    this.alwaysVisible = options.alwaysVisible;
    this._joystickPointerId = -1;
    this._joystickPointerPos = new Vector2(0, 0);
    this._joystickPreviousPointerPos = new Vector2(0, 0);
    this._joystickPointerStartPos = new Vector2(0, 0);
    this._deltaJoystickVector = new Vector2(0, 0);
    this._onPointerDownHandlerRef = (evt) => {
      this._onPointerDown(evt);
    };
    this._onPointerMoveHandlerRef = (evt) => {
      this._onPointerMove(evt);
    };
    this._onPointerUpHandlerRef = (evt) => {
      this._onPointerUp(evt);
    };
    VirtualJoystick.Canvas.addEventListener("pointerdown", this._onPointerDownHandlerRef, false);
    VirtualJoystick.Canvas.addEventListener("pointermove", this._onPointerMoveHandlerRef, false);
    VirtualJoystick.Canvas.addEventListener("pointerup", this._onPointerUpHandlerRef, false);
    VirtualJoystick.Canvas.addEventListener("pointerout", this._onPointerUpHandlerRef, false);
    VirtualJoystick.Canvas.addEventListener("pointercancel", this._onPointerUpHandlerRef, false);
    VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => {
      evt.preventDefault();
    }, false);
    requestAnimationFrame(() => {
      this._drawVirtualJoystick();
    });
  }
  setJoystickSensibility(newJoystickSensibility) {
    this._joystickSensibility = newJoystickSensibility;
    this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  }
  _onPointerDown(e) {
    let positionOnScreenCondition;
    e.preventDefault();
    if (this._leftJoystick === true) {
      positionOnScreenCondition = e.clientX < VirtualJoystick._HalfWidth;
    } else {
      positionOnScreenCondition = e.clientX > VirtualJoystick._HalfWidth;
    }
    if (positionOnScreenCondition && this._joystickPointerId < 0) {
      this._joystickPointerId = e.pointerId;
      if (this._joystickPosition) {
        this._joystickPointerStartPos = this._joystickPosition.clone();
        this._joystickPointerPos = this._joystickPosition.clone();
        this._joystickPreviousPointerPos = this._joystickPosition.clone();
        this._onPointerMove(e);
      } else {
        this._joystickPointerStartPos.x = e.clientX;
        this._joystickPointerStartPos.y = e.clientY;
        this._joystickPointerPos = this._joystickPointerStartPos.clone();
        this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
      }
      this._deltaJoystickVector.x = 0;
      this._deltaJoystickVector.y = 0;
      this.pressed = true;
      this._touches.add(e.pointerId.toString(), e);
    } else {
      if (VirtualJoystick._GlobalJoystickIndex < 2 && this._action) {
        this._action();
        this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
      }
    }
  }
  _onPointerMove(e) {
    if (this._joystickPointerId == e.pointerId) {
      if (this.limitToContainer) {
        const vector = new Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y);
        const distance = vector.length();
        if (distance > this.containerSize) {
          vector.scaleInPlace(this.containerSize / distance);
        }
        this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x;
        this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y;
      } else {
        this._joystickPointerPos.x = e.clientX;
        this._joystickPointerPos.y = e.clientY;
      }
      this._deltaJoystickVector = this._joystickPointerPos.clone();
      this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
      if (0 < VirtualJoystick._AlwaysVisibleSticks) {
        if (this._leftJoystick) {
          this._joystickPointerPos.x = Math.min(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);
        } else {
          this._joystickPointerPos.x = Math.max(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);
        }
      }
      const directionLeftRight = this.reverseLeftRight ? -1 : 1;
      const deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
      switch (this._axisTargetedByLeftAndRight) {
        case 0:
          this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
          break;
        case 1:
          this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
          break;
        case 2:
          this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
          break;
      }
      const directionUpDown = this.reverseUpDown ? 1 : -1;
      const deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
      switch (this._axisTargetedByUpAndDown) {
        case 0:
          this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
          break;
        case 1:
          this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
          break;
        case 2:
          this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
          break;
      }
    } else {
      const data = this._touches.get(e.pointerId.toString());
      if (data) {
        data.x = e.clientX;
        data.y = e.clientY;
      }
    }
  }
  _onPointerUp(e) {
    if (this._joystickPointerId == e.pointerId) {
      this._clearPreviousDraw();
      this._joystickPointerId = -1;
      this.pressed = false;
    } else {
      const touch = this._touches.get(e.pointerId.toString());
      if (touch) {
        VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
      }
    }
    this._deltaJoystickVector.x = 0;
    this._deltaJoystickVector.y = 0;
    this._touches.remove(e.pointerId.toString());
  }
  setJoystickColor(newColor) {
    this._joystickColor = newColor;
  }
  set containerSize(newSize) {
    this._joystickContainerSize = newSize;
    this._clearContainerSize = ~~(this._joystickContainerSize * 2.1);
    this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2);
  }
  get containerSize() {
    return this._joystickContainerSize;
  }
  set puckSize(newSize) {
    this._joystickPuckSize = newSize;
    this._clearPuckSize = ~~(this._joystickPuckSize * 2.1);
    this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2);
  }
  get puckSize() {
    return this._joystickPuckSize;
  }
  clearPosition() {
    this.alwaysVisible = false;
    this._joystickPosition = null;
  }
  set alwaysVisible(value) {
    if (this._alwaysVisible === value) {
      return;
    }
    if (value && this._joystickPosition) {
      VirtualJoystick._AlwaysVisibleSticks++;
      this._alwaysVisible = true;
    } else {
      VirtualJoystick._AlwaysVisibleSticks--;
      this._alwaysVisible = false;
    }
  }
  get alwaysVisible() {
    return this._alwaysVisible;
  }
  setPosition(x, y) {
    if (this._joystickPointerStartPos) {
      this._clearPreviousDraw();
    }
    this._joystickPosition = new Vector2(x, y);
  }
  setActionOnTouch(action2) {
    this._action = action2;
  }
  setAxisForLeftRight(axis) {
    switch (axis) {
      case 0:
      case 1:
      case 2:
        this._axisTargetedByLeftAndRight = axis;
        break;
      default:
        this._axisTargetedByLeftAndRight = 0;
        break;
    }
  }
  setAxisForUpDown(axis) {
    switch (axis) {
      case 0:
      case 1:
      case 2:
        this._axisTargetedByUpAndDown = axis;
        break;
      default:
        this._axisTargetedByUpAndDown = 1;
        break;
    }
  }
  _clearPreviousDraw() {
    const jp = this._joystickPosition || this._joystickPointerStartPos;
    VirtualJoystick._VJCanvasContext.clearRect(jp.x - this._clearContainerSizeOffset, jp.y - this._clearContainerSizeOffset, this._clearContainerSize, this._clearContainerSize);
    VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset - 1, this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset - 1, this._clearPuckSize + 2, this._clearPuckSize + 2);
  }
  setContainerImage(urlPath) {
    const image = new Image;
    image.src = urlPath;
    image.onload = () => this._containerImage = image;
  }
  setPuckImage(urlPath) {
    const image = new Image;
    image.src = urlPath;
    image.onload = () => this._puckImage = image;
  }
  _drawContainer() {
    const jp = this._joystickPosition || this._joystickPointerStartPos;
    this._clearPreviousDraw();
    if (this._containerImage) {
      VirtualJoystick._VJCanvasContext.drawImage(this._containerImage, jp.x - this.containerSize, jp.y - this.containerSize, this.containerSize * 2, this.containerSize * 2);
    } else {
      VirtualJoystick._VJCanvasContext.beginPath();
      VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;
      VirtualJoystick._VJCanvasContext.lineWidth = 2;
      VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true);
      VirtualJoystick._VJCanvasContext.stroke();
      VirtualJoystick._VJCanvasContext.closePath();
      VirtualJoystick._VJCanvasContext.beginPath();
      VirtualJoystick._VJCanvasContext.lineWidth = 6;
      VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;
      VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true);
      VirtualJoystick._VJCanvasContext.stroke();
      VirtualJoystick._VJCanvasContext.closePath();
    }
  }
  _drawPuck() {
    if (this._puckImage) {
      VirtualJoystick._VJCanvasContext.drawImage(this._puckImage, this._joystickPointerPos.x - this.puckSize, this._joystickPointerPos.y - this.puckSize, this.puckSize * 2, this.puckSize * 2);
    } else {
      VirtualJoystick._VJCanvasContext.beginPath();
      VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;
      VirtualJoystick._VJCanvasContext.lineWidth = 2;
      VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true);
      VirtualJoystick._VJCanvasContext.stroke();
      VirtualJoystick._VJCanvasContext.closePath();
    }
  }
  _drawVirtualJoystick() {
    if (this._released) {
      return;
    }
    if (this.alwaysVisible) {
      this._drawContainer();
    }
    if (this.pressed) {
      this._touches.forEach((key, touch) => {
        if (touch.pointerId === this._joystickPointerId) {
          if (!this.alwaysVisible) {
            this._drawContainer();
          }
          this._drawPuck();
          this._joystickPreviousPointerPos = this._joystickPointerPos.clone();
        } else {
          VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
          VirtualJoystick._VJCanvasContext.beginPath();
          VirtualJoystick._VJCanvasContext.fillStyle = "white";
          VirtualJoystick._VJCanvasContext.beginPath();
          VirtualJoystick._VJCanvasContext.strokeStyle = "red";
          VirtualJoystick._VJCanvasContext.lineWidth = 6;
          VirtualJoystick._VJCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
          VirtualJoystick._VJCanvasContext.stroke();
          VirtualJoystick._VJCanvasContext.closePath();
          touch.prevX = touch.x;
          touch.prevY = touch.y;
        }
      });
    }
    requestAnimationFrame(() => {
      this._drawVirtualJoystick();
    });
  }
  releaseCanvas() {
    if (VirtualJoystick.Canvas) {
      VirtualJoystick.Canvas.removeEventListener("pointerdown", this._onPointerDownHandlerRef);
      VirtualJoystick.Canvas.removeEventListener("pointermove", this._onPointerMoveHandlerRef);
      VirtualJoystick.Canvas.removeEventListener("pointerup", this._onPointerUpHandlerRef);
      VirtualJoystick.Canvas.removeEventListener("pointerout", this._onPointerUpHandlerRef);
      VirtualJoystick.Canvas.removeEventListener("pointercancel", this._onPointerUpHandlerRef);
      window.removeEventListener("resize", this._onResize);
      document.body.removeChild(VirtualJoystick.Canvas);
      VirtualJoystick.Canvas = null;
    }
    this._released = true;
  }
}
VirtualJoystick._GlobalJoystickIndex = 0;
VirtualJoystick._AlwaysVisibleSticks = 0;

// node_modules/@babylonjs/core/Cameras/Inputs/freeCameraVirtualJoystickInput.js
init_math_vector();
FreeCameraInputsManager.prototype.addVirtualJoystick = function() {
  this.add(new FreeCameraVirtualJoystickInput);
  return this;
};

class FreeCameraVirtualJoystickInput {
  getLeftJoystick() {
    return this._leftjoystick;
  }
  getRightJoystick() {
    return this._rightjoystick;
  }
  checkInputs() {
    if (this._leftjoystick) {
      const camera = this.camera;
      const speed = camera._computeLocalCameraSpeed() * 50;
      const cameraTransform = Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
      const deltaTransform = Vector3.TransformCoordinates(new Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
      camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
      camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
      if (!this._leftjoystick.pressed) {
        this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
      }
      if (!this._rightjoystick.pressed) {
        this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
      }
    }
  }
  attachControl() {
    this._leftjoystick = new VirtualJoystick(true);
    this._leftjoystick.setAxisForUpDown(2);
    this._leftjoystick.setAxisForLeftRight(0);
    this._leftjoystick.setJoystickSensibility(0.15);
    this._rightjoystick = new VirtualJoystick(false);
    this._rightjoystick.setAxisForUpDown(0);
    this._rightjoystick.setAxisForLeftRight(1);
    this._rightjoystick.reverseUpDown = true;
    this._rightjoystick.setJoystickSensibility(0.05);
    this._rightjoystick.setJoystickColor("yellow");
  }
  detachControl() {
    this._leftjoystick.releaseCanvas();
    this._rightjoystick.releaseCanvas();
  }
  getClassName() {
    return "FreeCameraVirtualJoystickInput";
  }
  getSimpleName() {
    return "virtualJoystick";
  }
}
CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
// node_modules/@babylonjs/core/Cameras/targetCamera.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_math_constants();
init_math_axis();
init_node();
Node2.AddNodeConstructor("TargetCamera", (name18, scene) => {
  return () => new TargetCamera(name18, Vector3.Zero(), scene);
});

class TargetCamera extends Camera {
  constructor(name18, position, scene, setActiveOnSceneIfNoneActive = true) {
    super(name18, position, scene, setActiveOnSceneIfNoneActive);
    this._tmpUpVector = Vector3.Zero();
    this._tmpTargetVector = Vector3.Zero();
    this.cameraDirection = new Vector3(0, 0, 0);
    this.cameraRotation = new Vector2(0, 0);
    this.ignoreParentScaling = false;
    this.updateUpVectorFromRotation = false;
    this._tmpQuaternion = new Quaternion;
    this.rotation = new Vector3(0, 0, 0);
    this.speed = 2;
    this.noRotationConstraint = false;
    this.invertRotation = false;
    this.inverseRotationSpeed = 0.2;
    this.lockedTarget = null;
    this._currentTarget = Vector3.Zero();
    this._initialFocalDistance = 1;
    this._viewMatrix = Matrix.Zero();
    this._camMatrix = Matrix.Zero();
    this._cameraTransformMatrix = Matrix.Zero();
    this._cameraRotationMatrix = Matrix.Zero();
    this._referencePoint = new Vector3(0, 0, 1);
    this._transformedReferencePoint = Vector3.Zero();
    this._deferredPositionUpdate = new Vector3;
    this._deferredRotationQuaternionUpdate = new Quaternion;
    this._deferredRotationUpdate = new Vector3;
    this._deferredUpdated = false;
    this._deferOnly = false;
    this._defaultUp = Vector3.Up();
    this._cachedRotationZ = 0;
    this._cachedQuaternionRotationZ = 0;
  }
  getFrontPosition(distance) {
    this.getWorldMatrix();
    const worldForward = TmpVectors.Vector3[0];
    const localForward = TmpVectors.Vector3[1];
    localForward.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
    this.getDirectionToRef(localForward, worldForward);
    worldForward.scaleInPlace(distance);
    return this.globalPosition.add(worldForward);
  }
  _getLockedTargetPosition() {
    if (!this.lockedTarget) {
      return null;
    }
    if (this.lockedTarget.absolutePosition) {
      const lockedTarget = this.lockedTarget;
      const m = lockedTarget.computeWorldMatrix();
      m.getTranslationToRef(lockedTarget.absolutePosition);
    }
    return this.lockedTarget.absolutePosition || this.lockedTarget;
  }
  storeState() {
    this._storedPosition = this.position.clone();
    this._storedRotation = this.rotation.clone();
    if (this.rotationQuaternion) {
      this._storedRotationQuaternion = this.rotationQuaternion.clone();
    }
    return super.storeState();
  }
  _restoreStateValues() {
    if (!super._restoreStateValues()) {
      return false;
    }
    this.position = this._storedPosition.clone();
    this.rotation = this._storedRotation.clone();
    if (this.rotationQuaternion) {
      this.rotationQuaternion = this._storedRotationQuaternion.clone();
    }
    this.cameraDirection.copyFromFloats(0, 0, 0);
    this.cameraRotation.copyFromFloats(0, 0);
    return true;
  }
  _initCache() {
    super._initCache();
    this._cache.lockedTarget = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cache.rotation = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  }
  _updateCache(ignoreParentClass) {
    if (!ignoreParentClass) {
      super._updateCache();
    }
    const lockedTargetPosition = this._getLockedTargetPosition();
    if (!lockedTargetPosition) {
      this._cache.lockedTarget = null;
    } else {
      if (!this._cache.lockedTarget) {
        this._cache.lockedTarget = lockedTargetPosition.clone();
      } else {
        this._cache.lockedTarget.copyFrom(lockedTargetPosition);
      }
    }
    this._cache.rotation.copyFrom(this.rotation);
    if (this.rotationQuaternion) {
      this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
    }
  }
  _isSynchronizedViewMatrix() {
    if (!super._isSynchronizedViewMatrix()) {
      return false;
    }
    const lockedTargetPosition = this._getLockedTargetPosition();
    return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  }
  _computeLocalCameraSpeed() {
    const engine = this.getEngine();
    return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100));
  }
  setTarget(target) {
    this.upVector.normalize();
    this._initialFocalDistance = target.subtract(this.position).length();
    if (this.position.z === target.z) {
      this.position.z += Epsilon;
    }
    this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance);
    Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
    this._camMatrix.invert();
    this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
    const vDir = target.subtract(this.position);
    if (vDir.x >= 0) {
      this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2;
    } else {
      this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2;
    }
    this.rotation.z = 0;
    if (isNaN(this.rotation.x)) {
      this.rotation.x = 0;
    }
    if (isNaN(this.rotation.y)) {
      this.rotation.y = 0;
    }
    if (isNaN(this.rotation.z)) {
      this.rotation.z = 0;
    }
    if (this.rotationQuaternion) {
      Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
    }
  }
  get target() {
    return this.getTarget();
  }
  set target(value) {
    this.setTarget(value);
  }
  getTarget() {
    return this._currentTarget;
  }
  _decideIfNeedsToMove() {
    return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  }
  _updatePosition() {
    if (this.parent) {
      this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]);
      Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]);
      this._deferredPositionUpdate.addInPlace(TmpVectors.Vector3[0]);
      if (!this._deferOnly) {
        this.position.copyFrom(this._deferredPositionUpdate);
      } else {
        this._deferredUpdated = true;
      }
      return;
    }
    this._deferredPositionUpdate.addInPlace(this.cameraDirection);
    if (!this._deferOnly) {
      this.position.copyFrom(this._deferredPositionUpdate);
    } else {
      this._deferredUpdated = true;
    }
  }
  _checkInputs() {
    const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1;
    const needToMove = this._decideIfNeedsToMove();
    const needToRotate = this.cameraRotation.x || this.cameraRotation.y;
    this._deferredUpdated = false;
    this._deferredRotationUpdate.copyFrom(this.rotation);
    this._deferredPositionUpdate.copyFrom(this.position);
    if (this.rotationQuaternion) {
      this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion);
    }
    if (needToMove) {
      this._updatePosition();
    }
    if (needToRotate) {
      if (this.rotationQuaternion) {
        this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate);
      }
      this._deferredRotationUpdate.x += this.cameraRotation.x * directionMultiplier;
      this._deferredRotationUpdate.y += this.cameraRotation.y * directionMultiplier;
      if (!this.noRotationConstraint) {
        const limit = 1.570796;
        if (this._deferredRotationUpdate.x > limit) {
          this._deferredRotationUpdate.x = limit;
        }
        if (this._deferredRotationUpdate.x < -limit) {
          this._deferredRotationUpdate.x = -limit;
        }
      }
      if (!this._deferOnly) {
        this.rotation.copyFrom(this._deferredRotationUpdate);
      } else {
        this._deferredUpdated = true;
      }
      if (this.rotationQuaternion) {
        const len = this._deferredRotationUpdate.lengthSquared();
        if (len) {
          Quaternion.RotationYawPitchRollToRef(this._deferredRotationUpdate.y, this._deferredRotationUpdate.x, this._deferredRotationUpdate.z, this._deferredRotationQuaternionUpdate);
          if (!this._deferOnly) {
            this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate);
          } else {
            this._deferredUpdated = true;
          }
        }
      }
    }
    if (needToMove) {
      if (Math.abs(this.cameraDirection.x) < this.speed * Epsilon) {
        this.cameraDirection.x = 0;
      }
      if (Math.abs(this.cameraDirection.y) < this.speed * Epsilon) {
        this.cameraDirection.y = 0;
      }
      if (Math.abs(this.cameraDirection.z) < this.speed * Epsilon) {
        this.cameraDirection.z = 0;
      }
      this.cameraDirection.scaleInPlace(this.inertia);
    }
    if (needToRotate) {
      if (Math.abs(this.cameraRotation.x) < this.speed * Epsilon) {
        this.cameraRotation.x = 0;
      }
      if (Math.abs(this.cameraRotation.y) < this.speed * Epsilon) {
        this.cameraRotation.y = 0;
      }
      this.cameraRotation.scaleInPlace(this.inertia);
    }
    super._checkInputs();
  }
  _updateCameraRotationMatrix() {
    if (this.rotationQuaternion) {
      this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
    } else {
      Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
    }
  }
  _rotateUpVectorWithCameraRotationMatrix() {
    Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
    return this;
  }
  _getViewMatrix() {
    if (this.lockedTarget) {
      this.setTarget(this._getLockedTargetPosition());
    }
    this._updateCameraRotationMatrix();
    if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
      this._rotateUpVectorWithCameraRotationMatrix();
      this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
    } else if (this._cachedRotationZ !== this.rotation.z) {
      this._rotateUpVectorWithCameraRotationMatrix();
      this._cachedRotationZ = this.rotation.z;
    }
    Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
    this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
    if (this.updateUpVectorFromRotation) {
      if (this.rotationQuaternion) {
        Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);
      } else {
        Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);
        Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
      }
    }
    this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
    return this._viewMatrix;
  }
  _computeViewMatrix(position, target, up) {
    if (this.ignoreParentScaling) {
      if (this.parent) {
        const parentWorldMatrix = this.parent.getWorldMatrix();
        Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
        Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector);
        Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector);
        this._markSyncedWithParent();
      } else {
        this._globalPosition.copyFrom(position);
        this._tmpTargetVector.copyFrom(target);
        this._tmpUpVector.copyFrom(up);
      }
      if (this.getScene().useRightHandedSystem) {
        Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
      } else {
        Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
      }
      return;
    }
    if (this.getScene().useRightHandedSystem) {
      Matrix.LookAtRHToRef(position, target, up, this._viewMatrix);
    } else {
      Matrix.LookAtLHToRef(position, target, up, this._viewMatrix);
    }
    if (this.parent) {
      const parentWorldMatrix = this.parent.getWorldMatrix();
      this._viewMatrix.invert();
      this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix);
      this._viewMatrix.getTranslationToRef(this._globalPosition);
      this._viewMatrix.invert();
      this._markSyncedWithParent();
    } else {
      this._globalPosition.copyFrom(position);
    }
  }
  createRigCamera(name18, cameraIndex) {
    if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
      const rigCamera = new TargetCamera(name18, this.position.clone(), this.getScene());
      rigCamera.isRigCamera = true;
      rigCamera.rigParent = this;
      if (this.cameraRigMode === Camera.RIG_MODE_VR) {
        if (!this.rotationQuaternion) {
          this.rotationQuaternion = new Quaternion;
        }
        rigCamera._cameraRigParams = {};
        rigCamera.rotationQuaternion = new Quaternion;
      }
      rigCamera.mode = this.mode;
      rigCamera.orthoLeft = this.orthoLeft;
      rigCamera.orthoRight = this.orthoRight;
      rigCamera.orthoTop = this.orthoTop;
      rigCamera.orthoBottom = this.orthoBottom;
      return rigCamera;
    }
    return null;
  }
  _updateRigCameras() {
    const camLeft = this._rigCameras[0];
    const camRight = this._rigCameras[1];
    this.computeWorldMatrix();
    switch (this.cameraRigMode) {
      case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
      case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
      case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: {
        const leftSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1;
        const rightSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;
        this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);
        this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);
        break;
      }
      case Camera.RIG_MODE_VR:
        if (camLeft.rotationQuaternion) {
          camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
          camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
        } else {
          camLeft.rotation.copyFrom(this.rotation);
          camRight.rotation.copyFrom(this.rotation);
        }
        camLeft.position.copyFrom(this.position);
        camRight.position.copyFrom(this.position);
        break;
    }
    super._updateRigCameras();
  }
  _getRigCamPositionAndTarget(halfSpace, rigCamera) {
    const target = this.getTarget();
    target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);
    TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
    const newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);
    Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);
    TargetCamera._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix);
    Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);
    TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);
    Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);
    rigCamera.setTarget(newFocalTarget);
  }
  getClassName() {
    return "TargetCamera";
  }
}
TargetCamera._RigCamTransformMatrix = new Matrix;
TargetCamera._TargetTransformMatrix = new Matrix;
TargetCamera._TargetFocalPoint = new Vector3;
__decorate([
  serialize()
], TargetCamera.prototype, "ignoreParentScaling", undefined);
__decorate([
  serialize()
], TargetCamera.prototype, "updateUpVectorFromRotation", undefined);
__decorate([
  serializeAsVector3()
], TargetCamera.prototype, "rotation", undefined);
__decorate([
  serialize()
], TargetCamera.prototype, "speed", undefined);
__decorate([
  serializeAsMeshReference("lockedTargetId")
], TargetCamera.prototype, "lockedTarget", undefined);
// node_modules/@babylonjs/core/Cameras/freeCamera.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_tools();
init_typeStore();
init_abstractEngine();

class FreeCamera extends TargetCamera {
  get angularSensibility() {
    const mouse = this.inputs.attached["mouse"];
    if (mouse) {
      return mouse.angularSensibility;
    }
    return 0;
  }
  set angularSensibility(value) {
    const mouse = this.inputs.attached["mouse"];
    if (mouse) {
      mouse.angularSensibility = value;
    }
  }
  get keysUp() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysUp;
    }
    return [];
  }
  set keysUp(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysUp = value;
    }
  }
  get keysUpward() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysUpward;
    }
    return [];
  }
  set keysUpward(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysUpward = value;
    }
  }
  get keysDown() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysDown;
    }
    return [];
  }
  set keysDown(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysDown = value;
    }
  }
  get keysDownward() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysDownward;
    }
    return [];
  }
  set keysDownward(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysDownward = value;
    }
  }
  get keysLeft() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysLeft;
    }
    return [];
  }
  set keysLeft(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysLeft = value;
    }
  }
  get keysRight() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRight;
    }
    return [];
  }
  set keysRight(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRight = value;
    }
  }
  get keysRotateLeft() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRotateLeft;
    }
    return [];
  }
  set keysRotateLeft(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRotateLeft = value;
    }
  }
  get keysRotateRight() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRotateRight;
    }
    return [];
  }
  set keysRotateRight(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRotateRight = value;
    }
  }
  get keysRotateUp() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRotateUp;
    }
    return [];
  }
  set keysRotateUp(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRotateUp = value;
    }
  }
  get keysRotateDown() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRotateDown;
    }
    return [];
  }
  set keysRotateDown(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRotateDown = value;
    }
  }
  constructor(name18, position, scene, setActiveOnSceneIfNoneActive = true) {
    super(name18, position, scene, setActiveOnSceneIfNoneActive);
    this.ellipsoid = new Vector3(0.5, 1, 0.5);
    this.ellipsoidOffset = new Vector3(0, 0, 0);
    this.checkCollisions = false;
    this.applyGravity = false;
    this._needMoveForGravity = false;
    this._oldPosition = Vector3.Zero();
    this._diffPosition = Vector3.Zero();
    this._newPosition = Vector3.Zero();
    this._collisionMask = -1;
    this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
      this._newPosition.copyFrom(newPosition);
      this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
      if (this._diffPosition.length() > AbstractEngine.CollisionsEpsilon) {
        this.position.addToRef(this._diffPosition, this._deferredPositionUpdate);
        if (!this._deferOnly) {
          this.position.copyFrom(this._deferredPositionUpdate);
        } else {
          this._deferredUpdated = true;
        }
        if (this.onCollide && collidedMesh) {
          this.onCollide(collidedMesh);
        }
      }
    };
    this.inputs = new FreeCameraInputsManager(this);
    this.inputs.addKeyboard().addMouse();
  }
  attachControl(ignored, noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this.inputs.attachElement(noPreventDefault);
  }
  detachControl() {
    this.inputs.detachElement();
    this.cameraDirection = new Vector3(0, 0, 0);
    this.cameraRotation = new Vector2(0, 0);
  }
  get collisionMask() {
    return this._collisionMask;
  }
  set collisionMask(mask) {
    this._collisionMask = !isNaN(mask) ? mask : -1;
  }
  _collideWithWorld(displacement) {
    let globalPosition;
    if (this.parent) {
      globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
    } else {
      globalPosition = this.position;
    }
    globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
    this._oldPosition.addInPlace(this.ellipsoidOffset);
    const coordinator = this.getScene().collisionCoordinator;
    if (!this._collider) {
      this._collider = coordinator.createCollider();
    }
    this._collider._radius = this.ellipsoid;
    this._collider.collisionMask = this._collisionMask;
    let actualDisplacement = displacement;
    if (this.applyGravity) {
      actualDisplacement = displacement.add(this.getScene().gravity);
    }
    coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  }
  _checkInputs() {
    if (!this._localDirection) {
      this._localDirection = Vector3.Zero();
      this._transformedDirection = Vector3.Zero();
    }
    this.inputs.checkInputs();
    super._checkInputs();
  }
  set needMoveForGravity(value) {
    this._needMoveForGravity = value;
  }
  get needMoveForGravity() {
    return this._needMoveForGravity;
  }
  _decideIfNeedsToMove() {
    return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  }
  _updatePosition() {
    if (this.checkCollisions && this.getScene().collisionsEnabled) {
      this._collideWithWorld(this.cameraDirection);
    } else {
      super._updatePosition();
    }
  }
  dispose() {
    this.inputs.clear();
    super.dispose();
  }
  getClassName() {
    return "FreeCamera";
  }
}
__decorate([
  serializeAsVector3()
], FreeCamera.prototype, "ellipsoid", undefined);
__decorate([
  serializeAsVector3()
], FreeCamera.prototype, "ellipsoidOffset", undefined);
__decorate([
  serialize()
], FreeCamera.prototype, "checkCollisions", undefined);
__decorate([
  serialize()
], FreeCamera.prototype, "applyGravity", undefined);
RegisterClass("BABYLON.FreeCamera", FreeCamera);
// node_modules/@babylonjs/core/Cameras/touchCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("TouchCamera", (name18, scene) => {
  return () => new TouchCamera(name18, Vector3.Zero(), scene);
});

class TouchCamera extends FreeCamera {
  get touchAngularSensibility() {
    const touch = this.inputs.attached["touch"];
    if (touch) {
      return touch.touchAngularSensibility;
    }
    return 0;
  }
  set touchAngularSensibility(value) {
    const touch = this.inputs.attached["touch"];
    if (touch) {
      touch.touchAngularSensibility = value;
    }
  }
  get touchMoveSensibility() {
    const touch = this.inputs.attached["touch"];
    if (touch) {
      return touch.touchMoveSensibility;
    }
    return 0;
  }
  set touchMoveSensibility(value) {
    const touch = this.inputs.attached["touch"];
    if (touch) {
      touch.touchMoveSensibility = value;
    }
  }
  constructor(name18, position, scene) {
    super(name18, position, scene);
    this.inputs.addTouch();
    this._setupInputs();
  }
  getClassName() {
    return "TouchCamera";
  }
  _setupInputs() {
    const touch = this.inputs.attached["touch"];
    const mouse = this.inputs.attached["mouse"];
    if (mouse) {
      mouse.touchEnabled = !touch;
    } else {
      touch.allowMouse = !mouse;
    }
  }
}
// node_modules/@babylonjs/core/Cameras/arcRotateCamera.js
init_tslib_es6();
init_decorators();
init_observable();
init_math_vector();
init_node();
init_math_constants();
init_tools();
init_typeStore();
Node2.AddNodeConstructor("ArcRotateCamera", (name18, scene) => {
  return () => new ArcRotateCamera(name18, 0, 0, 1, Vector3.Zero(), scene);
});
function ComputeAlpha(offset) {
  let alpha = Math.PI / 2;
  if (!(offset.x === 0 && offset.z === 0)) {
    alpha = Math.acos(offset.x / Math.sqrt(Math.pow(offset.x, 2) + Math.pow(offset.z, 2)));
  }
  if (offset.z < 0) {
    alpha = 2 * Math.PI - alpha;
  }
  return alpha;
}
function ComputeBeta(verticalOffset, radius) {
  return Math.acos(verticalOffset / radius);
}

class ArcRotateCamera extends TargetCamera {
  get target() {
    return this._target;
  }
  set target(value) {
    this.setTarget(value);
  }
  get targetHost() {
    return this._targetHost;
  }
  set targetHost(value) {
    if (value) {
      this.setTarget(value);
    }
  }
  getTarget() {
    return this.target;
  }
  get position() {
    return this._position;
  }
  set position(newPosition) {
    this.setPosition(newPosition);
  }
  set upVector(vec) {
    if (!this._upToYMatrix) {
      this._yToUpMatrix = new Matrix;
      this._upToYMatrix = new Matrix;
      this._upVector = Vector3.Zero();
    }
    vec.normalize();
    this._upVector.copyFrom(vec);
    this.setMatUp();
  }
  get upVector() {
    return this._upVector;
  }
  setMatUp() {
    Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._yToUpMatrix);
    Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix);
  }
  get angularSensibilityX() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.angularSensibilityX;
    }
    return 0;
  }
  set angularSensibilityX(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.angularSensibilityX = value;
    }
  }
  get angularSensibilityY() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.angularSensibilityY;
    }
    return 0;
  }
  set angularSensibilityY(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.angularSensibilityY = value;
    }
  }
  get pinchPrecision() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.pinchPrecision;
    }
    return 0;
  }
  set pinchPrecision(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.pinchPrecision = value;
    }
  }
  get pinchDeltaPercentage() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.pinchDeltaPercentage;
    }
    return 0;
  }
  set pinchDeltaPercentage(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.pinchDeltaPercentage = value;
    }
  }
  get useNaturalPinchZoom() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.useNaturalPinchZoom;
    }
    return false;
  }
  set useNaturalPinchZoom(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.useNaturalPinchZoom = value;
    }
  }
  get panningSensibility() {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      return pointers.panningSensibility;
    }
    return 0;
  }
  set panningSensibility(value) {
    const pointers = this.inputs.attached["pointers"];
    if (pointers) {
      pointers.panningSensibility = value;
    }
  }
  get keysUp() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysUp;
    }
    return [];
  }
  set keysUp(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysUp = value;
    }
  }
  get keysDown() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysDown;
    }
    return [];
  }
  set keysDown(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysDown = value;
    }
  }
  get keysLeft() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysLeft;
    }
    return [];
  }
  set keysLeft(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysLeft = value;
    }
  }
  get keysRight() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRight;
    }
    return [];
  }
  set keysRight(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRight = value;
    }
  }
  get wheelPrecision() {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      return mousewheel.wheelPrecision;
    }
    return 0;
  }
  set wheelPrecision(value) {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      mousewheel.wheelPrecision = value;
    }
  }
  get zoomToMouseLocation() {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      return mousewheel.zoomToMouseLocation;
    }
    return false;
  }
  set zoomToMouseLocation(value) {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      mousewheel.zoomToMouseLocation = value;
    }
  }
  get wheelDeltaPercentage() {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      return mousewheel.wheelDeltaPercentage;
    }
    return 0;
  }
  set wheelDeltaPercentage(value) {
    const mousewheel = this.inputs.attached["mousewheel"];
    if (mousewheel) {
      mousewheel.wheelDeltaPercentage = value;
    }
  }
  get bouncingBehavior() {
    return this._bouncingBehavior;
  }
  get useBouncingBehavior() {
    return this._bouncingBehavior != null;
  }
  set useBouncingBehavior(value) {
    if (value === this.useBouncingBehavior) {
      return;
    }
    if (value) {
      this._bouncingBehavior = new BouncingBehavior;
      this.addBehavior(this._bouncingBehavior);
    } else if (this._bouncingBehavior) {
      this.removeBehavior(this._bouncingBehavior);
      this._bouncingBehavior = null;
    }
  }
  get framingBehavior() {
    return this._framingBehavior;
  }
  get useFramingBehavior() {
    return this._framingBehavior != null;
  }
  set useFramingBehavior(value) {
    if (value === this.useFramingBehavior) {
      return;
    }
    if (value) {
      this._framingBehavior = new FramingBehavior;
      this.addBehavior(this._framingBehavior);
    } else if (this._framingBehavior) {
      this.removeBehavior(this._framingBehavior);
      this._framingBehavior = null;
    }
  }
  get autoRotationBehavior() {
    return this._autoRotationBehavior;
  }
  get useAutoRotationBehavior() {
    return this._autoRotationBehavior != null;
  }
  set useAutoRotationBehavior(value) {
    if (value === this.useAutoRotationBehavior) {
      return;
    }
    if (value) {
      this._autoRotationBehavior = new AutoRotationBehavior;
      this.addBehavior(this._autoRotationBehavior);
    } else if (this._autoRotationBehavior) {
      this.removeBehavior(this._autoRotationBehavior);
      this._autoRotationBehavior = null;
    }
  }
  constructor(name18, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) {
    super(name18, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive);
    this.inertialAlphaOffset = 0;
    this.inertialBetaOffset = 0;
    this.inertialRadiusOffset = 0;
    this.lowerAlphaLimit = null;
    this.upperAlphaLimit = null;
    this.lowerBetaLimit = 0.01;
    this.upperBetaLimit = Math.PI - 0.01;
    this.lowerRadiusLimit = null;
    this.upperRadiusLimit = null;
    this.lowerTargetYLimit = -Infinity;
    this.inertialPanningX = 0;
    this.inertialPanningY = 0;
    this.pinchToPanMaxDistance = 20;
    this.panningDistanceLimit = null;
    this.panningOriginTarget = Vector3.Zero();
    this.panningInertia = 0.9;
    this.zoomOnFactor = 1;
    this.targetScreenOffset = Vector2.Zero();
    this.allowUpsideDown = true;
    this.useInputToRestoreState = true;
    this.restoreStateInterpolationFactor = 0;
    this._currentInterpolationFactor = 0;
    this._viewMatrix = new Matrix;
    this.panningAxis = new Vector3(1, 1, 0);
    this._transformedDirection = new Vector3;
    this.mapPanning = false;
    this._progressiveRestore = false;
    this.onMeshTargetChangedObservable = new Observable;
    this.checkCollisions = false;
    this.collisionRadius = new Vector3(0.5, 0.5, 0.5);
    this._previousPosition = Vector3.Zero();
    this._collisionVelocity = Vector3.Zero();
    this._newPosition = Vector3.Zero();
    this._computationVector = Vector3.Zero();
    this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
      if (!collidedMesh) {
        this._previousPosition.copyFrom(this._position);
      } else {
        this.setPosition(newPosition);
        if (this.onCollide) {
          this.onCollide(collidedMesh);
        }
      }
      const cosa = Math.cos(this.alpha);
      const sina = Math.sin(this.alpha);
      const cosb = Math.cos(this.beta);
      let sinb = Math.sin(this.beta);
      if (sinb === 0) {
        sinb = 0.0001;
      }
      const target2 = this._getTargetPosition();
      this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
      target2.addToRef(this._computationVector, this._newPosition);
      this._position.copyFrom(this._newPosition);
      let up = this.upVector;
      if (this.allowUpsideDown && this.beta < 0) {
        up = up.clone();
        up = up.negate();
      }
      this._computeViewMatrix(this._position, target2, up);
      this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
      this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
      this._collisionTriggered = false;
    };
    this._target = Vector3.Zero();
    if (target) {
      this.setTarget(target);
    }
    this.alpha = alpha;
    this.beta = beta;
    this.radius = radius;
    this.getViewMatrix();
    this.inputs = new ArcRotateCameraInputsManager(this);
    this.inputs.addKeyboard().addMouseWheel().addPointers();
  }
  _initCache() {
    super._initCache();
    this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cache.alpha = undefined;
    this._cache.beta = undefined;
    this._cache.radius = undefined;
    this._cache.targetScreenOffset = Vector2.Zero();
  }
  _updateCache(ignoreParentClass) {
    if (!ignoreParentClass) {
      super._updateCache();
    }
    this._cache._target.copyFrom(this._getTargetPosition());
    this._cache.alpha = this.alpha;
    this._cache.beta = this.beta;
    this._cache.radius = this.radius;
    this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  }
  _getTargetPosition() {
    if (this._targetHost && this._targetHost.getAbsolutePosition) {
      const pos = this._targetHost.getAbsolutePosition();
      if (this._targetBoundingCenter) {
        pos.addToRef(this._targetBoundingCenter, this._target);
      } else {
        this._target.copyFrom(pos);
      }
    }
    const lockedTargetPosition = this._getLockedTargetPosition();
    if (lockedTargetPosition) {
      return lockedTargetPosition;
    }
    return this._target;
  }
  storeState() {
    this._storedAlpha = this._goalAlpha = this.alpha;
    this._storedBeta = this._goalBeta = this.beta;
    this._storedRadius = this._goalRadius = this.radius;
    this._storedTarget = this._goalTarget = this._getTargetPosition().clone();
    this._storedTargetScreenOffset = this._goalTargetScreenOffset = this.targetScreenOffset.clone();
    return super.storeState();
  }
  _restoreStateValues() {
    if (this.hasStateStored() && this.restoreStateInterpolationFactor > Epsilon && this.restoreStateInterpolationFactor < 1) {
      this.interpolateTo(this._storedAlpha, this._storedBeta, this._storedRadius, this._storedTarget, this._storedTargetScreenOffset, this.restoreStateInterpolationFactor);
      return true;
    }
    if (!super._restoreStateValues()) {
      return false;
    }
    this.setTarget(this._storedTarget.clone());
    this.alpha = this._storedAlpha;
    this.beta = this._storedBeta;
    this.radius = this._storedRadius;
    this.targetScreenOffset = this._storedTargetScreenOffset.clone();
    this.inertialAlphaOffset = 0;
    this.inertialBetaOffset = 0;
    this.inertialRadiusOffset = 0;
    this.inertialPanningX = 0;
    this.inertialPanningY = 0;
    return true;
  }
  interpolateTo(alpha = this.alpha, beta = this.beta, radius = this.radius, target = this.target, targetScreenOffset = this.targetScreenOffset, interpolationFactor) {
    this._progressiveRestore = true;
    this.inertialAlphaOffset = 0;
    this.inertialBetaOffset = 0;
    this.inertialRadiusOffset = 0;
    this.inertialPanningX = 0;
    this.inertialPanningY = 0;
    if (interpolationFactor != null) {
      this._currentInterpolationFactor = interpolationFactor;
    } else if (this.restoreStateInterpolationFactor !== 0) {
      this._currentInterpolationFactor = this.restoreStateInterpolationFactor;
    } else {
      this._currentInterpolationFactor = 0.1;
    }
    alpha = Clamp(alpha, this.lowerAlphaLimit ?? -Infinity, this.upperAlphaLimit ?? Infinity);
    beta = Clamp(beta, this.lowerBetaLimit ?? -Infinity, this.upperBetaLimit ?? Infinity);
    radius = Clamp(radius, this.lowerRadiusLimit ?? -Infinity, this.upperRadiusLimit ?? Infinity);
    target.y = Clamp(target.y, this.lowerTargetYLimit ?? -Infinity, Infinity);
    this._goalAlpha = alpha;
    this._goalBeta = beta;
    this._goalRadius = radius;
    this._goalTarget = target;
    this._goalTargetScreenOffset = targetScreenOffset;
  }
  _isSynchronizedViewMatrix() {
    if (!super._isSynchronizedViewMatrix()) {
      return false;
    }
    return this._cache._target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  }
  attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) {
    const args = arguments;
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(args);
    this._useCtrlForPanning = useCtrlForPanning;
    this._panningMouseButton = panningMouseButton;
    if (typeof args[0] === "boolean") {
      if (args.length > 1) {
        this._useCtrlForPanning = args[1];
      }
      if (args.length > 2) {
        this._panningMouseButton = args[2];
      }
    }
    this.inputs.attachElement(noPreventDefault);
    this._reset = () => {
      this.inertialAlphaOffset = 0;
      this.inertialBetaOffset = 0;
      this.inertialRadiusOffset = 0;
      this.inertialPanningX = 0;
      this.inertialPanningY = 0;
    };
  }
  detachControl() {
    this.inputs.detachElement();
    if (this._reset) {
      this._reset();
    }
  }
  _checkInputs() {
    if (this._collisionTriggered) {
      return;
    }
    this.inputs.checkInputs();
    if (this._progressiveRestore) {
      const dt = this._scene.getEngine().getDeltaTime() / 1000;
      const t = 1 - Math.pow(2, -dt / this._currentInterpolationFactor);
      this.setTarget(Vector3.Lerp(this.getTarget(), this._goalTarget, t));
      Quaternion.RotationAlphaBetaGammaToRef(this._goalAlpha, this._goalBeta, 0, TmpVectors.Quaternion[0]);
      Quaternion.RotationAlphaBetaGammaToRef(this.alpha, this.beta, 0, TmpVectors.Quaternion[1]);
      Quaternion.SlerpToRef(TmpVectors.Quaternion[1], TmpVectors.Quaternion[0], t, TmpVectors.Quaternion[2]);
      TmpVectors.Quaternion[2].normalize();
      TmpVectors.Quaternion[2].toAlphaBetaGammaToRef(TmpVectors.Vector3[0]);
      this.alpha = TmpVectors.Vector3[0].x;
      this.beta = TmpVectors.Vector3[0].y;
      this.radius += (this._goalRadius - this.radius) * t;
      Vector2.LerpToRef(this.targetScreenOffset, this._goalTargetScreenOffset, t, this.targetScreenOffset);
      if (Vector3.DistanceSquared(this.getTarget(), this._goalTarget) < Epsilon && TmpVectors.Quaternion[2].isApprox(TmpVectors.Quaternion[0]) && Math.pow(this._goalRadius - this.radius, 2) < Epsilon && Vector2.Distance(this.targetScreenOffset, this._goalTargetScreenOffset) < Epsilon || this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0 || this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
        this._progressiveRestore = false;
      }
    }
    if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
      const directionModifier = this.invertRotation ? -1 : 1;
      const handednessMultiplier = this._calculateHandednessMultiplier();
      let inertialAlphaOffset = this.inertialAlphaOffset * handednessMultiplier;
      if (this.beta < 0) {
        inertialAlphaOffset *= -1;
      }
      this.alpha += inertialAlphaOffset * directionModifier;
      this.beta += this.inertialBetaOffset * directionModifier;
      this.radius -= this.inertialRadiusOffset;
      this.inertialAlphaOffset *= this.inertia;
      this.inertialBetaOffset *= this.inertia;
      this.inertialRadiusOffset *= this.inertia;
      if (Math.abs(this.inertialAlphaOffset) < Epsilon) {
        this.inertialAlphaOffset = 0;
      }
      if (Math.abs(this.inertialBetaOffset) < Epsilon) {
        this.inertialBetaOffset = 0;
      }
      if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) {
        this.inertialRadiusOffset = 0;
      }
    }
    if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
      const localDirection = new Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
      this._viewMatrix.invertToRef(this._cameraTransformMatrix);
      localDirection.multiplyInPlace(this.panningAxis);
      Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection);
      if (this.mapPanning) {
        const up = this.upVector;
        const right = Vector3.CrossToRef(this._transformedDirection, up, this._transformedDirection);
        Vector3.CrossToRef(up, right, this._transformedDirection);
      } else if (!this.panningAxis.y) {
        this._transformedDirection.y = 0;
      }
      if (!this._targetHost) {
        if (this.panningDistanceLimit) {
          this._transformedDirection.addInPlace(this._target);
          const distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
          if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) {
            this._target.copyFrom(this._transformedDirection);
          }
        } else {
          if (this.parent) {
            const m = TmpVectors.Matrix[0];
            this.parent.getWorldMatrix().getRotationMatrixToRef(m);
            m.transposeToRef(m);
            Vector3.TransformCoordinatesToRef(this._transformedDirection, m, this._transformedDirection);
          }
          this._target.addInPlace(this._transformedDirection);
        }
      }
      this.inertialPanningX *= this.panningInertia;
      this.inertialPanningY *= this.panningInertia;
      if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) {
        this.inertialPanningX = 0;
      }
      if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) {
        this.inertialPanningY = 0;
      }
    }
    this._checkLimits();
    super._checkInputs();
  }
  _checkLimits() {
    if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
      if (this.allowUpsideDown && this.beta > Math.PI) {
        this.beta = this.beta - 2 * Math.PI;
      }
    } else {
      if (this.beta < this.lowerBetaLimit) {
        this.beta = this.lowerBetaLimit;
      }
    }
    if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
      if (this.allowUpsideDown && this.beta < -Math.PI) {
        this.beta = this.beta + 2 * Math.PI;
      }
    } else {
      if (this.beta > this.upperBetaLimit) {
        this.beta = this.upperBetaLimit;
      }
    }
    if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
      this.alpha = this.lowerAlphaLimit;
    }
    if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
      this.alpha = this.upperAlphaLimit;
    }
    if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
      this.radius = this.lowerRadiusLimit;
      this.inertialRadiusOffset = 0;
    }
    if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
      this.radius = this.upperRadiusLimit;
      this.inertialRadiusOffset = 0;
    }
    this.target.y = Math.max(this.target.y, this.lowerTargetYLimit);
  }
  rebuildAnglesAndRadius() {
    this._position.subtractToRef(this._getTargetPosition(), this._computationVector);
    if (this._upVector.x !== 0 || this._upVector.y !== 1 || this._upVector.z !== 0) {
      Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector);
    }
    this.radius = this._computationVector.length();
    if (this.radius === 0) {
      this.radius = 0.0001;
    }
    const previousAlpha = this.alpha;
    this.alpha = ComputeAlpha(this._computationVector);
    this.beta = ComputeBeta(this._computationVector.y, this.radius);
    const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2 * Math.PI));
    this.alpha += alphaCorrectionTurns * 2 * Math.PI;
    this._checkLimits();
  }
  setPosition(position) {
    if (this._position.equals(position)) {
      return;
    }
    this._position.copyFrom(position);
    this.rebuildAnglesAndRadius();
  }
  setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) {
    cloneAlphaBetaRadius = this.overrideCloneAlphaBetaRadius ?? cloneAlphaBetaRadius;
    if (target.computeWorldMatrix) {
      if (toBoundingCenter && target.getBoundingInfo) {
        this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
      } else {
        this._targetBoundingCenter = null;
      }
      target.computeWorldMatrix();
      this._targetHost = target;
      this._target = this._getTargetPosition();
      this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
    } else {
      const newTarget = target;
      const currentTarget = this._getTargetPosition();
      if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
        return;
      }
      this._targetHost = null;
      this._target = newTarget;
      this._targetBoundingCenter = null;
      this.onMeshTargetChangedObservable.notifyObservers(null);
    }
    if (!cloneAlphaBetaRadius) {
      this.rebuildAnglesAndRadius();
    }
  }
  _getViewMatrix() {
    const cosa = Math.cos(this.alpha);
    const sina = Math.sin(this.alpha);
    const cosb = Math.cos(this.beta);
    let sinb = Math.sin(this.beta);
    if (sinb === 0) {
      sinb = 0.0001;
    }
    if (this.radius === 0) {
      this.radius = 0.0001;
    }
    const target = this._getTargetPosition();
    this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
    if (this._upVector.x !== 0 || this._upVector.y !== 1 || this._upVector.z !== 0) {
      Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector);
    }
    target.addToRef(this._computationVector, this._newPosition);
    if (this.getScene().collisionsEnabled && this.checkCollisions) {
      const coordinator = this.getScene().collisionCoordinator;
      if (!this._collider) {
        this._collider = coordinator.createCollider();
      }
      this._collider._radius = this.collisionRadius;
      this._newPosition.subtractToRef(this._position, this._collisionVelocity);
      this._collisionTriggered = true;
      coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
    } else {
      this._position.copyFrom(this._newPosition);
      let up = this.upVector;
      if (this.allowUpsideDown && sinb < 0) {
        up = up.negate();
      }
      this._computeViewMatrix(this._position, target, up);
      this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
      this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
    }
    this._currentTarget = target;
    return this._viewMatrix;
  }
  zoomOn(meshes, doNotUpdateMaxZ = false) {
    meshes = meshes || this.getScene().meshes;
    const minMaxVector = Mesh.MinMax(meshes);
    let distance = this._calculateLowerRadiusFromModelBoundingSphere(minMaxVector.min, minMaxVector.max);
    distance = Math.max(Math.min(distance, this.upperRadiusLimit || Number.MAX_VALUE), this.lowerRadiusLimit || 0);
    this.radius = distance * this.zoomOnFactor;
    this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance }, doNotUpdateMaxZ);
  }
  focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) {
    let meshesOrMinMaxVector;
    let distance;
    if (meshesOrMinMaxVectorAndDistance.min === undefined) {
      const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
      meshesOrMinMaxVector = Mesh.MinMax(meshes);
      distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
    } else {
      const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
      meshesOrMinMaxVector = minMaxVectorAndDistance;
      distance = minMaxVectorAndDistance.distance;
    }
    this._target = Mesh.Center(meshesOrMinMaxVector);
    if (!doNotUpdateMaxZ) {
      this.maxZ = distance * 2;
    }
  }
  createRigCamera(name18, cameraIndex) {
    let alphaShift = 0;
    switch (this.cameraRigMode) {
      case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
      case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
      case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
      case Camera.RIG_MODE_VR:
        alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
        break;
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
        alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
        break;
    }
    const rigCam = new ArcRotateCamera(name18, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
    rigCam._cameraRigParams = {};
    rigCam.isRigCamera = true;
    rigCam.rigParent = this;
    rigCam.upVector = this.upVector;
    rigCam.mode = this.mode;
    rigCam.orthoLeft = this.orthoLeft;
    rigCam.orthoRight = this.orthoRight;
    rigCam.orthoBottom = this.orthoBottom;
    rigCam.orthoTop = this.orthoTop;
    return rigCam;
  }
  _updateRigCameras() {
    const camLeft = this._rigCameras[0];
    const camRight = this._rigCameras[1];
    camLeft.beta = camRight.beta = this.beta;
    switch (this.cameraRigMode) {
      case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
      case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
      case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
      case Camera.RIG_MODE_VR:
        camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
        camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
        break;
      case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
        camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
        camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
        break;
    }
    super._updateRigCameras();
  }
  _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld, radiusScale = 1) {
    const boxVectorGlobalDiagonal = Vector3.Distance(minimumWorld, maximumWorld);
    const engine = this.getScene().getEngine();
    const aspectRatio = engine.getAspectRatio(this);
    const frustumSlopeY = Math.tan(this.fov / 2);
    const frustumSlopeX = frustumSlopeY * aspectRatio;
    const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
    const radius = radiusWithoutFraming * radiusScale;
    const distanceForHorizontalFrustum = radius * Math.sqrt(1 + 1 / (frustumSlopeX * frustumSlopeX));
    const distanceForVerticalFrustum = radius * Math.sqrt(1 + 1 / (frustumSlopeY * frustumSlopeY));
    return Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  }
  dispose() {
    this.inputs.clear();
    super.dispose();
  }
  getClassName() {
    return "ArcRotateCamera";
  }
}
__decorate([
  serialize()
], ArcRotateCamera.prototype, "alpha", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "beta", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "radius", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "overrideCloneAlphaBetaRadius", undefined);
__decorate([
  serializeAsVector3("target")
], ArcRotateCamera.prototype, "_target", undefined);
__decorate([
  serializeAsMeshReference("targetHost")
], ArcRotateCamera.prototype, "_targetHost", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "inertialAlphaOffset", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "inertialBetaOffset", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "inertialRadiusOffset", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "lowerAlphaLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "upperAlphaLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "lowerBetaLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "upperBetaLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "lowerRadiusLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "upperRadiusLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "lowerTargetYLimit", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "inertialPanningX", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "inertialPanningY", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "pinchToPanMaxDistance", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "panningDistanceLimit", undefined);
__decorate([
  serializeAsVector3()
], ArcRotateCamera.prototype, "panningOriginTarget", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "panningInertia", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "zoomToMouseLocation", null);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "zoomOnFactor", undefined);
__decorate([
  serializeAsVector2()
], ArcRotateCamera.prototype, "targetScreenOffset", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "allowUpsideDown", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "useInputToRestoreState", undefined);
__decorate([
  serialize()
], ArcRotateCamera.prototype, "restoreStateInterpolationFactor", undefined);
RegisterClass("BABYLON.ArcRotateCamera", ArcRotateCamera);
// node_modules/@babylonjs/core/Cameras/deviceOrientationCamera.js
init_math_vector();
init_node();
init_math_axis();
Node2.AddNodeConstructor("DeviceOrientationCamera", (name18, scene) => {
  return () => new DeviceOrientationCamera(name18, Vector3.Zero(), scene);
});

class DeviceOrientationCamera extends FreeCamera {
  constructor(name18, position, scene) {
    super(name18, position, scene);
    this._tmpDragQuaternion = new Quaternion;
    this._disablePointerInputWhenUsingDeviceOrientation = true;
    this._dragFactor = 0;
    this._quaternionCache = new Quaternion;
    this.inputs.addDeviceOrientation();
    if (this.inputs._deviceOrientationInput) {
      this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(() => {
        if (this._disablePointerInputWhenUsingDeviceOrientation) {
          if (this.inputs._mouseInput) {
            this.inputs._mouseInput._allowCameraRotation = false;
            this.inputs._mouseInput.onPointerMovedObservable.add((e) => {
              if (this._dragFactor != 0) {
                if (!this._initialQuaternion) {
                  this._initialQuaternion = new Quaternion;
                }
                Quaternion.FromEulerAnglesToRef(0, e.offsetX * this._dragFactor, 0, this._tmpDragQuaternion);
                this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion, this._initialQuaternion);
              }
            });
          }
        }
      });
    }
  }
  get disablePointerInputWhenUsingDeviceOrientation() {
    return this._disablePointerInputWhenUsingDeviceOrientation;
  }
  set disablePointerInputWhenUsingDeviceOrientation(value) {
    this._disablePointerInputWhenUsingDeviceOrientation = value;
  }
  enableHorizontalDragging(dragFactor = 1 / 300) {
    this._dragFactor = dragFactor;
  }
  getClassName() {
    return "DeviceOrientationCamera";
  }
  _checkInputs() {
    super._checkInputs();
    this._quaternionCache.copyFrom(this.rotationQuaternion);
    if (this._initialQuaternion) {
      this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
    }
  }
  resetToCurrentRotation(axis = Axis.Y) {
    if (!this.rotationQuaternion) {
      return;
    }
    if (!this._initialQuaternion) {
      this._initialQuaternion = new Quaternion;
    }
    this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
    ["x", "y", "z"].forEach((axisName) => {
      if (!axis[axisName]) {
        this._initialQuaternion[axisName] = 0;
      } else {
        this._initialQuaternion[axisName] *= -1;
      }
    });
    this._initialQuaternion.normalize();
    this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  }
}
// node_modules/@babylonjs/core/Cameras/flyCamera.js
init_tslib_es6();
init_decorators();
init_math_vector();

// node_modules/@babylonjs/core/Cameras/flyCameraInputsManager.js
class FlyCameraInputsManager extends CameraInputsManager {
  constructor(camera) {
    super(camera);
  }
  addKeyboard() {
    this.add(new FlyCameraKeyboardInput);
    return this;
  }
  addMouse() {
    this.add(new FlyCameraMouseInput);
    return this;
  }
}

// node_modules/@babylonjs/core/Cameras/flyCamera.js
init_tools();
init_typeStore();
init_abstractEngine();

class FlyCamera extends TargetCamera {
  get angularSensibility() {
    const mouse = this.inputs.attached["mouse"];
    if (mouse) {
      return mouse.angularSensibility;
    }
    return 0;
  }
  set angularSensibility(value) {
    const mouse = this.inputs.attached["mouse"];
    if (mouse) {
      mouse.angularSensibility = value;
    }
  }
  get keysForward() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysForward;
    }
    return [];
  }
  set keysForward(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysForward = value;
    }
  }
  get keysBackward() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysBackward;
    }
    return [];
  }
  set keysBackward(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysBackward = value;
    }
  }
  get keysUp() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysUp;
    }
    return [];
  }
  set keysUp(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysUp = value;
    }
  }
  get keysDown() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysDown;
    }
    return [];
  }
  set keysDown(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysDown = value;
    }
  }
  get keysLeft() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysLeft;
    }
    return [];
  }
  set keysLeft(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysLeft = value;
    }
  }
  get keysRight() {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      return keyboard.keysRight;
    }
    return [];
  }
  set keysRight(value) {
    const keyboard = this.inputs.attached["keyboard"];
    if (keyboard) {
      keyboard.keysRight = value;
    }
  }
  constructor(name18, position, scene, setActiveOnSceneIfNoneActive = true) {
    super(name18, position, scene, setActiveOnSceneIfNoneActive);
    this.ellipsoid = new Vector3(1, 1, 1);
    this.ellipsoidOffset = new Vector3(0, 0, 0);
    this.checkCollisions = false;
    this.applyGravity = false;
    this.cameraDirection = Vector3.Zero();
    this._trackRoll = 0;
    this.rollCorrect = 100;
    this.bankedTurn = false;
    this.bankedTurnLimit = Math.PI / 2;
    this.bankedTurnMultiplier = 1;
    this._needMoveForGravity = false;
    this._oldPosition = Vector3.Zero();
    this._diffPosition = Vector3.Zero();
    this._newPosition = Vector3.Zero();
    this._collisionMask = -1;
    this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {
      const updatePosition = (newPos) => {
        this._newPosition.copyFrom(newPos);
        this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
        if (this._diffPosition.length() > AbstractEngine.CollisionsEpsilon) {
          this.position.addInPlace(this._diffPosition);
          if (this.onCollide && collidedMesh) {
            this.onCollide(collidedMesh);
          }
        }
      };
      updatePosition(newPosition);
    };
    this.inputs = new FlyCameraInputsManager(this);
    this.inputs.addKeyboard().addMouse();
  }
  attachControl(ignored, noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this.inputs.attachElement(noPreventDefault);
  }
  detachControl() {
    this.inputs.detachElement();
    this.cameraDirection = new Vector3(0, 0, 0);
  }
  get collisionMask() {
    return this._collisionMask;
  }
  set collisionMask(mask) {
    this._collisionMask = !isNaN(mask) ? mask : -1;
  }
  _collideWithWorld(displacement) {
    let globalPosition;
    if (this.parent) {
      globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
    } else {
      globalPosition = this.position;
    }
    globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
    this._oldPosition.addInPlace(this.ellipsoidOffset);
    const coordinator = this.getScene().collisionCoordinator;
    if (!this._collider) {
      this._collider = coordinator.createCollider();
    }
    this._collider._radius = this.ellipsoid;
    this._collider.collisionMask = this._collisionMask;
    let actualDisplacement = displacement;
    if (this.applyGravity) {
      actualDisplacement = displacement.add(this.getScene().gravity);
    }
    coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  }
  _checkInputs() {
    if (!this._localDirection) {
      this._localDirection = Vector3.Zero();
      this._transformedDirection = Vector3.Zero();
    }
    this.inputs.checkInputs();
    super._checkInputs();
  }
  set needMoveForGravity(value) {
    this._needMoveForGravity = value;
  }
  get needMoveForGravity() {
    return this._needMoveForGravity;
  }
  _decideIfNeedsToMove() {
    return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  }
  _updatePosition() {
    if (this.checkCollisions && this.getScene().collisionsEnabled) {
      this._collideWithWorld(this.cameraDirection);
    } else {
      super._updatePosition();
    }
  }
  restoreRoll(rate) {
    const limit = this._trackRoll;
    const z = this.rotation.z;
    const delta = limit - z;
    const minRad = 0.001;
    if (Math.abs(delta) >= minRad) {
      this.rotation.z += delta / rate;
      if (Math.abs(limit - this.rotation.z) <= minRad) {
        this.rotation.z = limit;
      }
    }
  }
  dispose() {
    this.inputs.clear();
    super.dispose();
  }
  getClassName() {
    return "FlyCamera";
  }
}
__decorate([
  serializeAsVector3()
], FlyCamera.prototype, "ellipsoid", undefined);
__decorate([
  serializeAsVector3()
], FlyCamera.prototype, "ellipsoidOffset", undefined);
__decorate([
  serialize()
], FlyCamera.prototype, "checkCollisions", undefined);
__decorate([
  serialize()
], FlyCamera.prototype, "applyGravity", undefined);
RegisterClass("BABYLON.FlyCamera", FlyCamera);
// node_modules/@babylonjs/core/Cameras/followCamera.js
init_tslib_es6();
init_decorators();
init_tools();
init_math_vector();
init_node();

// node_modules/@babylonjs/core/Cameras/followCameraInputsManager.js
init_logger();
class FollowCameraInputsManager extends CameraInputsManager {
  constructor(camera) {
    super(camera);
  }
  addKeyboard() {
    this.add(new FollowCameraKeyboardMoveInput);
    return this;
  }
  addMouseWheel() {
    this.add(new FollowCameraMouseWheelInput);
    return this;
  }
  addPointers() {
    this.add(new FollowCameraPointersInput);
    return this;
  }
  addVRDeviceOrientation() {
    Logger.Warn("DeviceOrientation support not yet implemented for FollowCamera.");
    return this;
  }
}

// node_modules/@babylonjs/core/Cameras/followCamera.js
init_typeStore();
Node2.AddNodeConstructor("FollowCamera", (name18, scene) => {
  return () => new FollowCamera(name18, Vector3.Zero(), scene);
});
Node2.AddNodeConstructor("ArcFollowCamera", (name18, scene) => {
  return () => new ArcFollowCamera(name18, 0, 0, 1, null, scene);
});

class FollowCamera extends TargetCamera {
  constructor(name18, position, scene, lockedTarget = null) {
    super(name18, position, scene);
    this.radius = 12;
    this.lowerRadiusLimit = null;
    this.upperRadiusLimit = null;
    this.rotationOffset = 0;
    this.lowerRotationOffsetLimit = null;
    this.upperRotationOffsetLimit = null;
    this.heightOffset = 4;
    this.lowerHeightOffsetLimit = null;
    this.upperHeightOffsetLimit = null;
    this.cameraAcceleration = 0.05;
    this.maxCameraSpeed = 20;
    this.lockedTarget = lockedTarget;
    this.inputs = new FollowCameraInputsManager(this);
    this.inputs.addKeyboard().addMouseWheel().addPointers();
  }
  _follow(cameraTarget) {
    if (!cameraTarget) {
      return;
    }
    const rotMatrix = TmpVectors.Matrix[0];
    cameraTarget.absoluteRotationQuaternion.toRotationMatrix(rotMatrix);
    const yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
    const radians = Tools.ToRadians(this.rotationOffset) + yRotation;
    const targetPosition = cameraTarget.getAbsolutePosition();
    const targetX = targetPosition.x + Math.sin(radians) * this.radius;
    const targetZ = targetPosition.z + Math.cos(radians) * this.radius;
    const dx = targetX - this.position.x;
    const dy = targetPosition.y + this.heightOffset - this.position.y;
    const dz = targetZ - this.position.z;
    let vx = dx * this.cameraAcceleration * 2;
    let vy = dy * this.cameraAcceleration;
    let vz = dz * this.cameraAcceleration * 2;
    if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
      vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
    }
    if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
      vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
    }
    if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
      vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
    }
    this.position = new Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
    this.setTarget(targetPosition);
  }
  attachControl(ignored, noPreventDefault) {
    noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);
    this.inputs.attachElement(noPreventDefault);
    this._reset = () => {};
  }
  detachControl() {
    this.inputs.detachElement();
    if (this._reset) {
      this._reset();
    }
  }
  _checkInputs() {
    this.inputs.checkInputs();
    this._checkLimits();
    super._checkInputs();
    if (this.lockedTarget) {
      this._follow(this.lockedTarget);
    }
  }
  _checkLimits() {
    if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
      this.radius = this.lowerRadiusLimit;
    }
    if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
      this.radius = this.upperRadiusLimit;
    }
    if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) {
      this.heightOffset = this.lowerHeightOffsetLimit;
    }
    if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) {
      this.heightOffset = this.upperHeightOffsetLimit;
    }
    if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) {
      this.rotationOffset = this.lowerRotationOffsetLimit;
    }
    if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) {
      this.rotationOffset = this.upperRotationOffsetLimit;
    }
  }
  getClassName() {
    return "FollowCamera";
  }
}
__decorate([
  serialize()
], FollowCamera.prototype, "radius", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "lowerRadiusLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "upperRadiusLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "rotationOffset", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "lowerRotationOffsetLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "upperRotationOffsetLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "heightOffset", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "lowerHeightOffsetLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "upperHeightOffsetLimit", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "cameraAcceleration", undefined);
__decorate([
  serialize()
], FollowCamera.prototype, "maxCameraSpeed", undefined);
__decorate([
  serializeAsMeshReference("lockedTargetId")
], FollowCamera.prototype, "lockedTarget", undefined);

class ArcFollowCamera extends TargetCamera {
  constructor(name18, alpha, beta, radius, target, scene) {
    super(name18, Vector3.Zero(), scene);
    this.alpha = alpha;
    this.beta = beta;
    this.radius = radius;
    this._cartesianCoordinates = Vector3.Zero();
    this.setMeshTarget(target);
  }
  setMeshTarget(target) {
    this._meshTarget = target;
    this._follow();
  }
  _follow() {
    if (!this._meshTarget) {
      return;
    }
    this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
    this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
    this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
    const targetPosition = this._meshTarget.getAbsolutePosition();
    this.position = targetPosition.add(this._cartesianCoordinates);
    this.setTarget(targetPosition);
  }
  _checkInputs() {
    super._checkInputs();
    this._follow();
  }
  getClassName() {
    return "ArcFollowCamera";
  }
}
RegisterClass("BABYLON.FollowCamera", FollowCamera);
RegisterClass("BABYLON.ArcFollowCamera", ArcFollowCamera);
// node_modules/@babylonjs/core/Cameras/universalCamera.js
init_node();
init_math_vector();

// node_modules/@babylonjs/core/Gamepads/gamepadSceneComponent.js
init_scene();
init_sceneComponent();

// node_modules/@babylonjs/core/Gamepads/gamepadManager.js
init_observable();
init_domManagement();

// node_modules/@babylonjs/core/Gamepads/xboxGamepad.js
init_observable();
var Xbox360Button;
(function(Xbox360Button2) {
  Xbox360Button2[Xbox360Button2["A"] = 0] = "A";
  Xbox360Button2[Xbox360Button2["B"] = 1] = "B";
  Xbox360Button2[Xbox360Button2["X"] = 2] = "X";
  Xbox360Button2[Xbox360Button2["Y"] = 3] = "Y";
  Xbox360Button2[Xbox360Button2["LB"] = 4] = "LB";
  Xbox360Button2[Xbox360Button2["RB"] = 5] = "RB";
  Xbox360Button2[Xbox360Button2["Back"] = 8] = "Back";
  Xbox360Button2[Xbox360Button2["Start"] = 9] = "Start";
  Xbox360Button2[Xbox360Button2["LeftStick"] = 10] = "LeftStick";
  Xbox360Button2[Xbox360Button2["RightStick"] = 11] = "RightStick";
})(Xbox360Button || (Xbox360Button = {}));
var Xbox360Dpad;
(function(Xbox360Dpad2) {
  Xbox360Dpad2[Xbox360Dpad2["Up"] = 12] = "Up";
  Xbox360Dpad2[Xbox360Dpad2["Down"] = 13] = "Down";
  Xbox360Dpad2[Xbox360Dpad2["Left"] = 14] = "Left";
  Xbox360Dpad2[Xbox360Dpad2["Right"] = 15] = "Right";
})(Xbox360Dpad || (Xbox360Dpad = {}));

class Xbox360Pad extends Gamepad {
  constructor(id, index, gamepad, xboxOne = false) {
    super(id, index, gamepad, 0, 1, 2, 3);
    this._leftTrigger = 0;
    this._rightTrigger = 0;
    this.onButtonDownObservable = new Observable;
    this.onButtonUpObservable = new Observable;
    this.onPadDownObservable = new Observable;
    this.onPadUpObservable = new Observable;
    this._buttonA = 0;
    this._buttonB = 0;
    this._buttonX = 0;
    this._buttonY = 0;
    this._buttonBack = 0;
    this._buttonStart = 0;
    this._buttonLB = 0;
    this._buttonRB = 0;
    this._buttonLeftStick = 0;
    this._buttonRightStick = 0;
    this._dPadUp = 0;
    this._dPadDown = 0;
    this._dPadLeft = 0;
    this._dPadRight = 0;
    this._isXboxOnePad = false;
    this.type = Gamepad.XBOX;
    this._isXboxOnePad = xboxOne;
  }
  onlefttriggerchanged(callback) {
    this._onlefttriggerchanged = callback;
  }
  onrighttriggerchanged(callback) {
    this._onrighttriggerchanged = callback;
  }
  get leftTrigger() {
    return this._leftTrigger;
  }
  set leftTrigger(newValue) {
    if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
      this._onlefttriggerchanged(newValue);
    }
    this._leftTrigger = newValue;
  }
  get rightTrigger() {
    return this._rightTrigger;
  }
  set rightTrigger(newValue) {
    if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
      this._onrighttriggerchanged(newValue);
    }
    this._rightTrigger = newValue;
  }
  onbuttondown(callback) {
    this._onbuttondown = callback;
  }
  onbuttonup(callback) {
    this._onbuttonup = callback;
  }
  ondpaddown(callback) {
    this._ondpaddown = callback;
  }
  ondpadup(callback) {
    this._ondpadup = callback;
  }
  _setButtonValue(newValue, currentValue, buttonType) {
    if (newValue !== currentValue) {
      if (newValue === 1) {
        if (this._onbuttondown) {
          this._onbuttondown(buttonType);
        }
        this.onButtonDownObservable.notifyObservers(buttonType);
      }
      if (newValue === 0) {
        if (this._onbuttonup) {
          this._onbuttonup(buttonType);
        }
        this.onButtonUpObservable.notifyObservers(buttonType);
      }
    }
    return newValue;
  }
  _setDPadValue(newValue, currentValue, buttonType) {
    if (newValue !== currentValue) {
      if (newValue === 1) {
        if (this._ondpaddown) {
          this._ondpaddown(buttonType);
        }
        this.onPadDownObservable.notifyObservers(buttonType);
      }
      if (newValue === 0) {
        if (this._ondpadup) {
          this._ondpadup(buttonType);
        }
        this.onPadUpObservable.notifyObservers(buttonType);
      }
    }
    return newValue;
  }
  get buttonA() {
    return this._buttonA;
  }
  set buttonA(value) {
    this._buttonA = this._setButtonValue(value, this._buttonA, 0);
  }
  get buttonB() {
    return this._buttonB;
  }
  set buttonB(value) {
    this._buttonB = this._setButtonValue(value, this._buttonB, 1);
  }
  get buttonX() {
    return this._buttonX;
  }
  set buttonX(value) {
    this._buttonX = this._setButtonValue(value, this._buttonX, 2);
  }
  get buttonY() {
    return this._buttonY;
  }
  set buttonY(value) {
    this._buttonY = this._setButtonValue(value, this._buttonY, 3);
  }
  get buttonStart() {
    return this._buttonStart;
  }
  set buttonStart(value) {
    this._buttonStart = this._setButtonValue(value, this._buttonStart, 9);
  }
  get buttonBack() {
    return this._buttonBack;
  }
  set buttonBack(value) {
    this._buttonBack = this._setButtonValue(value, this._buttonBack, 8);
  }
  get buttonLB() {
    return this._buttonLB;
  }
  set buttonLB(value) {
    this._buttonLB = this._setButtonValue(value, this._buttonLB, 4);
  }
  get buttonRB() {
    return this._buttonRB;
  }
  set buttonRB(value) {
    this._buttonRB = this._setButtonValue(value, this._buttonRB, 5);
  }
  get buttonLeftStick() {
    return this._buttonLeftStick;
  }
  set buttonLeftStick(value) {
    this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 10);
  }
  get buttonRightStick() {
    return this._buttonRightStick;
  }
  set buttonRightStick(value) {
    this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 11);
  }
  get dPadUp() {
    return this._dPadUp;
  }
  set dPadUp(value) {
    this._dPadUp = this._setDPadValue(value, this._dPadUp, 12);
  }
  get dPadDown() {
    return this._dPadDown;
  }
  set dPadDown(value) {
    this._dPadDown = this._setDPadValue(value, this._dPadDown, 13);
  }
  get dPadLeft() {
    return this._dPadLeft;
  }
  set dPadLeft(value) {
    this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 14);
  }
  get dPadRight() {
    return this._dPadRight;
  }
  set dPadRight(value) {
    this._dPadRight = this._setDPadValue(value, this._dPadRight, 15);
  }
  update() {
    super.update();
    if (this._isXboxOnePad) {
      this.buttonA = this.browserGamepad.buttons[0].value;
      this.buttonB = this.browserGamepad.buttons[1].value;
      this.buttonX = this.browserGamepad.buttons[2].value;
      this.buttonY = this.browserGamepad.buttons[3].value;
      this.buttonLB = this.browserGamepad.buttons[4].value;
      this.buttonRB = this.browserGamepad.buttons[5].value;
      this.leftTrigger = this.browserGamepad.buttons[6].value;
      this.rightTrigger = this.browserGamepad.buttons[7].value;
      this.buttonBack = this.browserGamepad.buttons[8].value;
      this.buttonStart = this.browserGamepad.buttons[9].value;
      this.buttonLeftStick = this.browserGamepad.buttons[10].value;
      this.buttonRightStick = this.browserGamepad.buttons[11].value;
      this.dPadUp = this.browserGamepad.buttons[12].value;
      this.dPadDown = this.browserGamepad.buttons[13].value;
      this.dPadLeft = this.browserGamepad.buttons[14].value;
      this.dPadRight = this.browserGamepad.buttons[15].value;
    } else {
      this.buttonA = this.browserGamepad.buttons[0].value;
      this.buttonB = this.browserGamepad.buttons[1].value;
      this.buttonX = this.browserGamepad.buttons[2].value;
      this.buttonY = this.browserGamepad.buttons[3].value;
      this.buttonLB = this.browserGamepad.buttons[4].value;
      this.buttonRB = this.browserGamepad.buttons[5].value;
      this.leftTrigger = this.browserGamepad.buttons[6].value;
      this.rightTrigger = this.browserGamepad.buttons[7].value;
      this.buttonBack = this.browserGamepad.buttons[8].value;
      this.buttonStart = this.browserGamepad.buttons[9].value;
      this.buttonLeftStick = this.browserGamepad.buttons[10].value;
      this.buttonRightStick = this.browserGamepad.buttons[11].value;
      this.dPadUp = this.browserGamepad.buttons[12].value;
      this.dPadDown = this.browserGamepad.buttons[13].value;
      this.dPadLeft = this.browserGamepad.buttons[14].value;
      this.dPadRight = this.browserGamepad.buttons[15].value;
    }
  }
  dispose() {
    super.dispose();
    this.onButtonDownObservable.clear();
    this.onButtonUpObservable.clear();
    this.onPadDownObservable.clear();
    this.onPadUpObservable.clear();
  }
}

// node_modules/@babylonjs/core/Gamepads/dualShockGamepad.js
init_observable();
var DualShockButton;
(function(DualShockButton2) {
  DualShockButton2[DualShockButton2["Cross"] = 0] = "Cross";
  DualShockButton2[DualShockButton2["Circle"] = 1] = "Circle";
  DualShockButton2[DualShockButton2["Square"] = 2] = "Square";
  DualShockButton2[DualShockButton2["Triangle"] = 3] = "Triangle";
  DualShockButton2[DualShockButton2["L1"] = 4] = "L1";
  DualShockButton2[DualShockButton2["R1"] = 5] = "R1";
  DualShockButton2[DualShockButton2["Share"] = 8] = "Share";
  DualShockButton2[DualShockButton2["Options"] = 9] = "Options";
  DualShockButton2[DualShockButton2["LeftStick"] = 10] = "LeftStick";
  DualShockButton2[DualShockButton2["RightStick"] = 11] = "RightStick";
})(DualShockButton || (DualShockButton = {}));
var DualShockDpad;
(function(DualShockDpad2) {
  DualShockDpad2[DualShockDpad2["Up"] = 12] = "Up";
  DualShockDpad2[DualShockDpad2["Down"] = 13] = "Down";
  DualShockDpad2[DualShockDpad2["Left"] = 14] = "Left";
  DualShockDpad2[DualShockDpad2["Right"] = 15] = "Right";
})(DualShockDpad || (DualShockDpad = {}));

class DualShockPad extends Gamepad {
  constructor(id, index, gamepad) {
    super(id.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), index, gamepad, 0, 1, 2, 3);
    this._leftTrigger = 0;
    this._rightTrigger = 0;
    this.onButtonDownObservable = new Observable;
    this.onButtonUpObservable = new Observable;
    this.onPadDownObservable = new Observable;
    this.onPadUpObservable = new Observable;
    this._buttonCross = 0;
    this._buttonCircle = 0;
    this._buttonSquare = 0;
    this._buttonTriangle = 0;
    this._buttonShare = 0;
    this._buttonOptions = 0;
    this._buttonL1 = 0;
    this._buttonR1 = 0;
    this._buttonLeftStick = 0;
    this._buttonRightStick = 0;
    this._dPadUp = 0;
    this._dPadDown = 0;
    this._dPadLeft = 0;
    this._dPadRight = 0;
    this.type = Gamepad.DUALSHOCK;
  }
  onlefttriggerchanged(callback) {
    this._onlefttriggerchanged = callback;
  }
  onrighttriggerchanged(callback) {
    this._onrighttriggerchanged = callback;
  }
  get leftTrigger() {
    return this._leftTrigger;
  }
  set leftTrigger(newValue) {
    if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
      this._onlefttriggerchanged(newValue);
    }
    this._leftTrigger = newValue;
  }
  get rightTrigger() {
    return this._rightTrigger;
  }
  set rightTrigger(newValue) {
    if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
      this._onrighttriggerchanged(newValue);
    }
    this._rightTrigger = newValue;
  }
  onbuttondown(callback) {
    this._onbuttondown = callback;
  }
  onbuttonup(callback) {
    this._onbuttonup = callback;
  }
  ondpaddown(callback) {
    this._ondpaddown = callback;
  }
  ondpadup(callback) {
    this._ondpadup = callback;
  }
  _setButtonValue(newValue, currentValue, buttonType) {
    if (newValue !== currentValue) {
      if (newValue === 1) {
        if (this._onbuttondown) {
          this._onbuttondown(buttonType);
        }
        this.onButtonDownObservable.notifyObservers(buttonType);
      }
      if (newValue === 0) {
        if (this._onbuttonup) {
          this._onbuttonup(buttonType);
        }
        this.onButtonUpObservable.notifyObservers(buttonType);
      }
    }
    return newValue;
  }
  _setDPadValue(newValue, currentValue, buttonType) {
    if (newValue !== currentValue) {
      if (newValue === 1) {
        if (this._ondpaddown) {
          this._ondpaddown(buttonType);
        }
        this.onPadDownObservable.notifyObservers(buttonType);
      }
      if (newValue === 0) {
        if (this._ondpadup) {
          this._ondpadup(buttonType);
        }
        this.onPadUpObservable.notifyObservers(buttonType);
      }
    }
    return newValue;
  }
  get buttonCross() {
    return this._buttonCross;
  }
  set buttonCross(value) {
    this._buttonCross = this._setButtonValue(value, this._buttonCross, 0);
  }
  get buttonCircle() {
    return this._buttonCircle;
  }
  set buttonCircle(value) {
    this._buttonCircle = this._setButtonValue(value, this._buttonCircle, 1);
  }
  get buttonSquare() {
    return this._buttonSquare;
  }
  set buttonSquare(value) {
    this._buttonSquare = this._setButtonValue(value, this._buttonSquare, 2);
  }
  get buttonTriangle() {
    return this._buttonTriangle;
  }
  set buttonTriangle(value) {
    this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, 3);
  }
  get buttonOptions() {
    return this._buttonOptions;
  }
  set buttonOptions(value) {
    this._buttonOptions = this._setButtonValue(value, this._buttonOptions, 9);
  }
  get buttonShare() {
    return this._buttonShare;
  }
  set buttonShare(value) {
    this._buttonShare = this._setButtonValue(value, this._buttonShare, 8);
  }
  get buttonL1() {
    return this._buttonL1;
  }
  set buttonL1(value) {
    this._buttonL1 = this._setButtonValue(value, this._buttonL1, 4);
  }
  get buttonR1() {
    return this._buttonR1;
  }
  set buttonR1(value) {
    this._buttonR1 = this._setButtonValue(value, this._buttonR1, 5);
  }
  get buttonLeftStick() {
    return this._buttonLeftStick;
  }
  set buttonLeftStick(value) {
    this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 10);
  }
  get buttonRightStick() {
    return this._buttonRightStick;
  }
  set buttonRightStick(value) {
    this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 11);
  }
  get dPadUp() {
    return this._dPadUp;
  }
  set dPadUp(value) {
    this._dPadUp = this._setDPadValue(value, this._dPadUp, 12);
  }
  get dPadDown() {
    return this._dPadDown;
  }
  set dPadDown(value) {
    this._dPadDown = this._setDPadValue(value, this._dPadDown, 13);
  }
  get dPadLeft() {
    return this._dPadLeft;
  }
  set dPadLeft(value) {
    this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 14);
  }
  get dPadRight() {
    return this._dPadRight;
  }
  set dPadRight(value) {
    this._dPadRight = this._setDPadValue(value, this._dPadRight, 15);
  }
  update() {
    super.update();
    this.buttonCross = this.browserGamepad.buttons[0].value;
    this.buttonCircle = this.browserGamepad.buttons[1].value;
    this.buttonSquare = this.browserGamepad.buttons[2].value;
    this.buttonTriangle = this.browserGamepad.buttons[3].value;
    this.buttonL1 = this.browserGamepad.buttons[4].value;
    this.buttonR1 = this.browserGamepad.buttons[5].value;
    this.leftTrigger = this.browserGamepad.buttons[6].value;
    this.rightTrigger = this.browserGamepad.buttons[7].value;
    this.buttonShare = this.browserGamepad.buttons[8].value;
    this.buttonOptions = this.browserGamepad.buttons[9].value;
    this.buttonLeftStick = this.browserGamepad.buttons[10].value;
    this.buttonRightStick = this.browserGamepad.buttons[11].value;
    this.dPadUp = this.browserGamepad.buttons[12].value;
    this.dPadDown = this.browserGamepad.buttons[13].value;
    this.dPadLeft = this.browserGamepad.buttons[14].value;
    this.dPadRight = this.browserGamepad.buttons[15].value;
  }
  dispose() {
    super.dispose();
    this.onButtonDownObservable.clear();
    this.onButtonUpObservable.clear();
    this.onPadDownObservable.clear();
    this.onPadUpObservable.clear();
  }
}

// node_modules/@babylonjs/core/Gamepads/gamepadManager.js
init_tools();
init_abstractEngine();

class GamepadManager {
  constructor(_scene) {
    this._scene = _scene;
    this._babylonGamepads = [];
    this._oneGamepadConnected = false;
    this._isMonitoring = false;
    this.onGamepadDisconnectedObservable = new Observable;
    if (!IsWindowObjectExist()) {
      this._gamepadEventSupported = false;
    } else {
      this._gamepadEventSupported = "GamepadEvent" in window;
      this._gamepadSupport = navigator && navigator.getGamepads;
    }
    this.onGamepadConnectedObservable = new Observable((observer) => {
      for (const i in this._babylonGamepads) {
        const gamepad = this._babylonGamepads[i];
        if (gamepad && gamepad._isConnected) {
          this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
        }
      }
    });
    this._onGamepadConnectedEvent = (evt) => {
      const gamepad = evt.gamepad;
      if (gamepad.index in this._babylonGamepads) {
        if (this._babylonGamepads[gamepad.index].isConnected) {
          return;
        }
      }
      let newGamepad;
      if (this._babylonGamepads[gamepad.index]) {
        newGamepad = this._babylonGamepads[gamepad.index];
        newGamepad.browserGamepad = gamepad;
        newGamepad._isConnected = true;
      } else {
        newGamepad = this._addNewGamepad(gamepad);
      }
      this.onGamepadConnectedObservable.notifyObservers(newGamepad);
      this._startMonitoringGamepads();
    };
    this._onGamepadDisconnectedEvent = (evt) => {
      const gamepad = evt.gamepad;
      for (const i in this._babylonGamepads) {
        if (this._babylonGamepads[i].index === gamepad.index) {
          const disconnectedGamepad = this._babylonGamepads[i];
          disconnectedGamepad._isConnected = false;
          this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
          disconnectedGamepad.dispose && disconnectedGamepad.dispose();
          break;
        }
      }
    };
    if (this._gamepadSupport) {
      this._updateGamepadObjects();
      if (this._babylonGamepads.length) {
        this._startMonitoringGamepads();
      }
      if (this._gamepadEventSupported) {
        const hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window;
        if (hostWindow) {
          hostWindow.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, false);
          hostWindow.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, false);
        }
      } else {
        this._startMonitoringGamepads();
      }
    }
  }
  get gamepads() {
    return this._babylonGamepads;
  }
  getGamepadByType(type = Gamepad.XBOX) {
    for (const gamepad of this._babylonGamepads) {
      if (gamepad && gamepad.type === type) {
        return gamepad;
      }
    }
    return null;
  }
  dispose() {
    if (this._gamepadEventSupported) {
      if (this._onGamepadConnectedEvent) {
        window.removeEventListener("gamepadconnected", this._onGamepadConnectedEvent);
      }
      if (this._onGamepadDisconnectedEvent) {
        window.removeEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent);
      }
      this._onGamepadConnectedEvent = null;
      this._onGamepadDisconnectedEvent = null;
    }
    this._babylonGamepads.forEach((gamepad) => {
      gamepad.dispose();
    });
    this.onGamepadConnectedObservable.clear();
    this.onGamepadDisconnectedObservable.clear();
    this._oneGamepadConnected = false;
    this._stopMonitoringGamepads();
    this._babylonGamepads = [];
  }
  _addNewGamepad(gamepad) {
    if (!this._oneGamepadConnected) {
      this._oneGamepadConnected = true;
    }
    let newGamepad;
    const dualShock = gamepad.id.search("054c") !== -1 && gamepad.id.search("0ce6") === -1;
    const xboxOne = gamepad.id.search("Xbox One") !== -1;
    if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1 || gamepad.id.search("045e") !== -1 && gamepad.id.search("Surface Dock") === -1) {
      newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
    } else if (dualShock) {
      newGamepad = new DualShockPad(gamepad.id, gamepad.index, gamepad);
    } else {
      newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
    }
    this._babylonGamepads[newGamepad.index] = newGamepad;
    return newGamepad;
  }
  _startMonitoringGamepads() {
    if (!this._isMonitoring) {
      this._isMonitoring = true;
      this._checkGamepadsStatus();
    }
  }
  _stopMonitoringGamepads() {
    this._isMonitoring = false;
  }
  _checkGamepadsStatus() {
    this._updateGamepadObjects();
    for (const i in this._babylonGamepads) {
      const gamepad = this._babylonGamepads[i];
      if (!gamepad || !gamepad.isConnected) {
        continue;
      }
      try {
        gamepad.update();
      } catch {
        if (this._loggedErrors.indexOf(gamepad.index) === -1) {
          Tools.Warn(`Error updating gamepad ${gamepad.id}`);
          this._loggedErrors.push(gamepad.index);
        }
      }
    }
    if (this._isMonitoring) {
      AbstractEngine.QueueNewFrame(() => {
        this._checkGamepadsStatus();
      });
    }
  }
  _updateGamepadObjects() {
    const gamepads = navigator.getGamepads ? navigator.getGamepads() : [];
    for (let i = 0;i < gamepads.length; i++) {
      const gamepad = gamepads[i];
      if (gamepad) {
        if (!this._babylonGamepads[gamepad.index]) {
          const newGamepad = this._addNewGamepad(gamepad);
          this.onGamepadConnectedObservable.notifyObservers(newGamepad);
        } else {
          this._babylonGamepads[i].browserGamepad = gamepad;
          if (!this._babylonGamepads[i].isConnected) {
            this._babylonGamepads[i]._isConnected = true;
            this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
          }
        }
      }
    }
  }
}

// node_modules/@babylonjs/core/Gamepads/gamepadSceneComponent.js
Object.defineProperty(Scene.prototype, "gamepadManager", {
  get: function() {
    if (!this._gamepadManager) {
      this._gamepadManager = new GamepadManager(this);
      let component = this._getComponent(SceneComponentConstants.NAME_GAMEPAD);
      if (!component) {
        component = new GamepadSystemSceneComponent(this);
        this._addComponent(component);
      }
    }
    return this._gamepadManager;
  },
  enumerable: true,
  configurable: true
});
FreeCameraInputsManager.prototype.addGamepad = function() {
  this.add(new FreeCameraGamepadInput);
  return this;
};
ArcRotateCameraInputsManager.prototype.addGamepad = function() {
  this.add(new ArcRotateCameraGamepadInput);
  return this;
};

class GamepadSystemSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_GAMEPAD;
    this.scene = scene;
  }
  register() {}
  rebuild() {}
  dispose() {
    const gamepadManager = this.scene._gamepadManager;
    if (gamepadManager) {
      gamepadManager.dispose();
      this.scene._gamepadManager = null;
    }
  }
}

// node_modules/@babylonjs/core/Cameras/universalCamera.js
Node2.AddNodeConstructor("FreeCamera", (name18, scene) => {
  return () => new UniversalCamera(name18, Vector3.Zero(), scene);
});

class UniversalCamera extends TouchCamera {
  get gamepadAngularSensibility() {
    const gamepad = this.inputs.attached["gamepad"];
    if (gamepad) {
      return gamepad.gamepadAngularSensibility;
    }
    return 0;
  }
  set gamepadAngularSensibility(value) {
    const gamepad = this.inputs.attached["gamepad"];
    if (gamepad) {
      gamepad.gamepadAngularSensibility = value;
    }
  }
  get gamepadMoveSensibility() {
    const gamepad = this.inputs.attached["gamepad"];
    if (gamepad) {
      return gamepad.gamepadMoveSensibility;
    }
    return 0;
  }
  set gamepadMoveSensibility(value) {
    const gamepad = this.inputs.attached["gamepad"];
    if (gamepad) {
      gamepad.gamepadMoveSensibility = value;
    }
  }
  constructor(name18, position, scene) {
    super(name18, position, scene);
    this.inputs.addGamepad();
  }
  getClassName() {
    return "UniversalCamera";
  }
}
Camera._CreateDefaultParsedCamera = (name18, scene) => {
  return new UniversalCamera(name18, Vector3.Zero(), scene);
};

// node_modules/@babylonjs/core/Cameras/gamepadCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("GamepadCamera", (name18, scene) => {
  return () => new GamepadCamera(name18, Vector3.Zero(), scene);
});

class GamepadCamera extends UniversalCamera {
  constructor(name18, position, scene) {
    super(name18, position, scene);
  }
  getClassName() {
    return "GamepadCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphArcRotateCamera.js
init_math_vector();
init_node();

// node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js
init_passPostProcess();

// node_modules/@babylonjs/core/PostProcesses/anaglyphPostProcess.js
init_postProcess();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinAnaglyphPostProcess.js
init_effectRenderer();
init_engine();

class ThinAnaglyphPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_anaglyph_fragment(), exports_anaglyph_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_anaglyph_fragment2(), exports_anaglyph_fragment2)));
    }
  }
  constructor(name20, engine = null, options) {
    super({
      ...options,
      name: name20,
      engine: engine || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinAnaglyphPostProcess.FragmentUrl,
      samplers: ThinAnaglyphPostProcess.Samplers
    });
  }
}
ThinAnaglyphPostProcess.FragmentUrl = "anaglyph";
ThinAnaglyphPostProcess.Samplers = ["leftSampler"];

// node_modules/@babylonjs/core/PostProcesses/anaglyphPostProcess.js
class AnaglyphPostProcess extends PostProcess {
  getClassName() {
    return "AnaglyphPostProcess";
  }
  constructor(name20, options, rigCameras, samplingMode, engine, reusable) {
    const localOptions = {
      samplers: ThinAnaglyphPostProcess.Samplers,
      size: typeof options === "number" ? options : undefined,
      camera: rigCameras[1],
      samplingMode,
      engine,
      reusable,
      ...options
    };
    super(name20, ThinAnaglyphPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinAnaglyphPostProcess(name20, engine, localOptions) : undefined,
      ...localOptions
    });
    this._passedProcess = rigCameras[0]._rigPostProcess;
    this.onApplyObservable.add((effect) => {
      effect.setTextureFromPostProcess("leftSampler", this._passedProcess);
    });
  }
}
RegisterClass("BABYLON.AnaglyphPostProcess", AnaglyphPostProcess);

// node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js
function setStereoscopicAnaglyphRigMode(camera) {
  camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1, camera._rigCameras[0]);
  camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + "_anaglyph", 1, camera._rigCameras);
}

// node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphArcRotateCamera.js
Node2.AddNodeConstructor("AnaglyphArcRotateCamera", (name20, scene, options) => {
  return () => new AnaglyphArcRotateCamera(name20, 0, 0, 1, Vector3.Zero(), options.interaxial_distance, scene);
});

class AnaglyphArcRotateCamera extends ArcRotateCamera {
  constructor(name20, alpha, beta, radius, target, interaxialDistance, scene) {
    super(name20, alpha, beta, radius, target, scene);
    this._setRigMode = () => setStereoscopicAnaglyphRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance });
  }
  getClassName() {
    return "AnaglyphArcRotateCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphFreeCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("AnaglyphFreeCamera", (name20, scene, options) => {
  return () => new AnaglyphFreeCamera(name20, Vector3.Zero(), options.interaxial_distance, scene);
});

class AnaglyphFreeCamera extends FreeCamera {
  constructor(name20, position, interaxialDistance, scene) {
    super(name20, position, scene);
    this._setRigMode = () => setStereoscopicAnaglyphRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance });
  }
  getClassName() {
    return "AnaglyphFreeCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphGamepadCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("AnaglyphGamepadCamera", (name20, scene, options) => {
  return () => new AnaglyphGamepadCamera(name20, Vector3.Zero(), options.interaxial_distance, scene);
});

class AnaglyphGamepadCamera extends GamepadCamera {
  constructor(name20, position, interaxialDistance, scene) {
    super(name20, position, scene);
    this._setRigMode = () => setStereoscopicAnaglyphRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance });
  }
  getClassName() {
    return "AnaglyphGamepadCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphUniversalCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("AnaglyphUniversalCamera", (name20, scene, options) => {
  return () => new AnaglyphUniversalCamera(name20, Vector3.Zero(), options.interaxial_distance, scene);
});

class AnaglyphUniversalCamera extends UniversalCamera {
  constructor(name20, position, interaxialDistance, scene) {
    super(name20, position, scene);
    this._setRigMode = () => setStereoscopicAnaglyphRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance });
  }
  getClassName() {
    return "AnaglyphUniversalCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicArcRotateCamera.js
init_math_vector();
init_node();

// node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicRigMode.js
init_passPostProcess();

// node_modules/@babylonjs/core/PostProcesses/stereoscopicInterlacePostProcess.js
init_math_vector();
init_postProcess();

// node_modules/@babylonjs/core/Shaders/stereoscopicInterlace.fragment.js
init_shaderStore();
var name20 = "stereoscopicInterlacePixelShader";
var shader19 = `const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;
#ifdef IS_STEREOSCOPIC_HORIZ
useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);
#else
#ifdef IS_STEREOSCOPIC_INTERLACED
float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);
#else
useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);
#endif
#endif
if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}
gl_FragColor=vec4((frag1+frag2)/TWO,1.0);}
`;
if (!ShaderStore.ShadersStore[name20]) {
  ShaderStore.ShadersStore[name20] = shader19;
}

// node_modules/@babylonjs/core/PostProcesses/stereoscopicInterlacePostProcess.js
class StereoscopicInterlacePostProcessI extends PostProcess {
  getClassName() {
    return "StereoscopicInterlacePostProcessI";
  }
  constructor(name21, rigCameras, isStereoscopicHoriz, isStereoscopicInterlaced, samplingMode, engine, reusable) {
    super(name21, "stereoscopicInterlace", ["stepSize"], ["camASampler"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicInterlaced ? "#define IS_STEREOSCOPIC_INTERLACED 1" : isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
    this._passedProcess = rigCameras[0]._rigPostProcess;
    this._stepSize = new Vector2(1 / this.width, 1 / this.height);
    this.onSizeChangedObservable.add(() => {
      this._stepSize = new Vector2(1 / this.width, 1 / this.height);
    });
    this.onApplyObservable.add((effect) => {
      effect.setTextureFromPostProcess("camASampler", this._passedProcess);
      effect.setFloat2("stepSize", this._stepSize.x, this._stepSize.y);
    });
  }
}

// node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicRigMode.js
function setStereoscopicRigMode(camera) {
  const isStereoscopicHoriz = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  const isCrossEye = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  const isInterlaced = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_INTERLACED;
  if (isInterlaced) {
    camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1, camera._rigCameras[0]);
    camera._rigCameras[1]._rigPostProcess = new StereoscopicInterlacePostProcessI(camera.name + "_stereoInterlace", camera._rigCameras, false, true);
  } else {
    camera._rigCameras[isCrossEye ? 1 : 0].viewport = new Viewport(0, 0, isStereoscopicHoriz ? 0.5 : 1, isStereoscopicHoriz ? 1 : 0.5);
    camera._rigCameras[isCrossEye ? 0 : 1].viewport = new Viewport(isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1, isStereoscopicHoriz ? 1 : 0.5);
  }
}

// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicArcRotateCamera.js
Node2.AddNodeConstructor("StereoscopicArcRotateCamera", (name21, scene, options) => {
  return () => new StereoscopicArcRotateCamera(name21, 0, 0, 1, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);
});

class StereoscopicArcRotateCamera extends ArcRotateCamera {
  constructor(name21, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
    super(name21, alpha, beta, radius, target, scene);
    this._setRigMode = () => setStereoscopicRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.isStereoscopicSideBySide = isStereoscopicSideBySide;
    this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {
      interaxialDistance
    });
  }
  getClassName() {
    return "StereoscopicArcRotateCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicFreeCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("StereoscopicFreeCamera", (name21, scene, options) => {
  return () => new StereoscopicFreeCamera(name21, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);
});

class StereoscopicFreeCamera extends FreeCamera {
  constructor(name21, position, interaxialDistance, isStereoscopicSideBySide, scene) {
    super(name21, position, scene);
    this._setRigMode = () => setStereoscopicRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.isStereoscopicSideBySide = isStereoscopicSideBySide;
    this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {
      interaxialDistance
    });
  }
  getClassName() {
    return "StereoscopicFreeCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicGamepadCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("StereoscopicGamepadCamera", (name21, scene, options) => {
  return () => new StereoscopicGamepadCamera(name21, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);
});

class StereoscopicGamepadCamera extends GamepadCamera {
  constructor(name21, position, interaxialDistance, isStereoscopicSideBySide, scene) {
    super(name21, position, scene);
    this._setRigMode = () => setStereoscopicRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.isStereoscopicSideBySide = isStereoscopicSideBySide;
    this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {
      interaxialDistance
    });
  }
  getClassName() {
    return "StereoscopicGamepadCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicUniversalCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("StereoscopicFreeCamera", (name21, scene, options) => {
  return () => new StereoscopicUniversalCamera(name21, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);
});

class StereoscopicUniversalCamera extends UniversalCamera {
  constructor(name21, position, interaxialDistance, isStereoscopicSideBySide, scene) {
    super(name21, position, scene);
    this._setRigMode = () => setStereoscopicRigMode(this);
    this.interaxialDistance = interaxialDistance;
    this.isStereoscopicSideBySide = isStereoscopicSideBySide;
    this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {
      interaxialDistance
    });
  }
  getClassName() {
    return "StereoscopicUniversalCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicScreenUniversalCamera.js
init_math_vector();
// node_modules/@babylonjs/core/Cameras/virtualJoysticksCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("VirtualJoysticksCamera", (name21, scene) => {
  return () => new VirtualJoysticksCamera(name21, Vector3.Zero(), scene);
});

class VirtualJoysticksCamera extends FreeCamera {
  constructor(name21, position, scene) {
    super(name21, position, scene);
    this.inputs.addVirtualJoystick();
  }
  getClassName() {
    return "VirtualJoysticksCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/VR/vrCameraMetrics.js
init_math_vector();

class VRCameraMetrics {
  constructor() {
    this.compensateDistortion = true;
    this.multiviewEnabled = false;
  }
  get aspectRatio() {
    return this.hResolution / (2 * this.vResolution);
  }
  get aspectRatioFov() {
    return 2 * Math.atan(this.postProcessScaleFactor * this.vScreenSize / (2 * this.eyeToScreenDistance));
  }
  get leftHMatrix() {
    const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;
    const h = 4 * meters / this.hScreenSize;
    return Matrix.Translation(h, 0, 0);
  }
  get rightHMatrix() {
    const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;
    const h = 4 * meters / this.hScreenSize;
    return Matrix.Translation(-h, 0, 0);
  }
  get leftPreViewMatrix() {
    return Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  }
  get rightPreViewMatrix() {
    return Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  }
  static GetDefault() {
    const result = new VRCameraMetrics;
    result.hResolution = 1280;
    result.vResolution = 800;
    result.hScreenSize = 0.149759993;
    result.vScreenSize = 0.0935999975;
    result.vScreenCenter = 0.0467999987;
    result.eyeToScreenDistance = 0.0410000011;
    result.lensSeparationDistance = 0.063500002;
    result.interpupillaryDistance = 0.064000003;
    result.distortionK = [1, 0.219999999, 0.239999995, 0];
    result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0];
    result.postProcessScaleFactor = 1.714605507808412;
    result.lensCenterOffset = 0.151976421;
    return result;
  }
}
// node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationArcRotateCamera.js
init_math_vector();
init_node();

// node_modules/@babylonjs/core/Cameras/RigModes/vrRigMode.js
init_math_vector();

// node_modules/@babylonjs/core/PostProcesses/vrDistortionCorrectionPostProcess.js
init_math_vector();
init_texture();
init_postProcess();

class VRDistortionCorrectionPostProcess extends PostProcess {
  getClassName() {
    return "VRDistortionCorrectionPostProcess";
  }
  constructor(name23, camera, isRightEye, vrMetrics) {
    super(name23, "vrDistortionCorrection", ["LensCenter", "Scale", "ScaleIn", "HmdWarpParam"], null, vrMetrics.postProcessScaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);
    this._isRightEye = isRightEye;
    this._distortionFactors = vrMetrics.distortionK;
    this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
    this._lensCenterOffset = vrMetrics.lensCenterOffset;
    this.adaptScaleToCurrentViewport = true;
    this.onSizeChangedObservable.add(() => {
      this._scaleIn = new Vector2(2, 2 / this.aspectRatio);
      this._scaleFactor = new Vector2(0.5 * (1 / this._postProcessScaleFactor), 0.5 * (1 / this._postProcessScaleFactor) * this.aspectRatio);
      this._lensCenter = new Vector2(this._isRightEye ? 0.5 - this._lensCenterOffset * 0.5 : 0.5 + this._lensCenterOffset * 0.5, 0.5);
    });
    this.onApplyObservable.add((effect) => {
      effect.setFloat2("LensCenter", this._lensCenter.x, this._lensCenter.y);
      effect.setFloat2("Scale", this._scaleFactor.x, this._scaleFactor.y);
      effect.setFloat2("ScaleIn", this._scaleIn.x, this._scaleIn.y);
      effect.setFloat4("HmdWarpParam", this._distortionFactors[0], this._distortionFactors[1], this._distortionFactors[2], this._distortionFactors[3]);
    });
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_vrDistortionCorrection_fragment(), exports_vrDistortionCorrection_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_vrDistortionCorrection_fragment2(), exports_vrDistortionCorrection_fragment2)));
    }
    super._gatherImports(useWebGPU, list);
  }
}

// node_modules/@babylonjs/core/PostProcesses/vrMultiviewToSingleviewPostProcess.js
init_texture();
init_postProcess();

// node_modules/@babylonjs/core/Shaders/vrMultiviewToSingleview.fragment.js
init_shaderStore();
var name23 = "vrMultiviewToSingleviewPixelShader";
var shader22 = `precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;
if (!ShaderStore.ShadersStore[name23]) {
  ShaderStore.ShadersStore[name23] = shader22;
}

// node_modules/@babylonjs/core/Engines/Extensions/engine.multiview.js
init_engine();
init_scene();
init_internalTexture();
init_math_vector();
init_uniformBuffer();

// node_modules/@babylonjs/core/Materials/Textures/MultiviewRenderTarget.js
init_renderTargetTexture();

class MultiviewRenderTarget extends RenderTargetTexture {
  set samples(value) {
    this._samples = value;
  }
  get samples() {
    return this._samples;
  }
  constructor(scene, size = 512) {
    super("multiview rtt", size, scene, false, true, 0, false, undefined, false, false, true, undefined, true);
    this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight());
    this._texture = this._renderTarget.texture;
    this._texture.isMultiview = true;
    this._texture.format = 5;
    this.samples = this._getEngine().getCaps().maxSamples || this.samples;
    this._texture.samples = this._samples;
  }
  _bindFrameBuffer() {
    if (!this._renderTarget) {
      return;
    }
    this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget);
  }
  getViewCount() {
    return 2;
  }
}

// node_modules/@babylonjs/core/Engines/Extensions/engine.multiview.js
init_math_frustum();
Engine.prototype.createMultiviewRenderTargetTexture = function(width, height, colorTexture, depthStencilTexture) {
  const gl = this._gl;
  if (!this.getCaps().multiview) {
    throw "Multiview is not supported";
  }
  const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, { width, height });
  rtWrapper._framebuffer = gl.createFramebuffer();
  const internalTexture = new InternalTexture(this, 0, true);
  internalTexture.width = width;
  internalTexture.height = height;
  internalTexture.isMultiview = true;
  if (!colorTexture) {
    colorTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D_ARRAY, colorTexture);
    gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2);
  }
  rtWrapper._colorTextureArray = colorTexture;
  if (!depthStencilTexture) {
    depthStencilTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D_ARRAY, depthStencilTexture);
    gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH24_STENCIL8, width, height, 2);
  }
  rtWrapper._depthStencilTextureArray = depthStencilTexture;
  internalTexture.isReady = true;
  rtWrapper.setTextures(internalTexture);
  rtWrapper._depthStencilTexture = internalTexture;
  return rtWrapper;
};
Engine.prototype.bindMultiviewFramebuffer = function(_multiviewTexture) {
  const multiviewTexture = _multiviewTexture;
  const gl = this._gl;
  const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;
  this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer);
  if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) {
    if (this.getCaps().oculusMultiview) {
      ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2);
      ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2);
    } else {
      ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2);
      ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2);
    }
  } else {
    throw "Invalid multiview frame buffer";
  }
};
Engine.prototype.bindSpaceWarpFramebuffer = function(_spaceWarpTexture) {
  const spaceWarpTexture = _spaceWarpTexture;
  const gl = this._gl;
  const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;
  this.bindFramebuffer(spaceWarpTexture, undefined, undefined, undefined, true);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, spaceWarpTexture._framebuffer);
  if (spaceWarpTexture._colorTextureArray && spaceWarpTexture._depthStencilTextureArray) {
    ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, spaceWarpTexture._colorTextureArray, 0, 0, 2);
    ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, spaceWarpTexture._depthStencilTextureArray, 0, 0, 2);
  } else {
    throw new Error("Invalid Space Warp framebuffer");
  }
};
Camera.prototype._useMultiviewToSingleView = false;
Camera.prototype._multiviewTexture = null;
Camera.prototype._resizeOrCreateMultiviewTexture = function(width, height) {
  if (!this._multiviewTexture) {
    this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width, height });
  } else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) {
    this._multiviewTexture.dispose();
    this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width, height });
  }
};
function createMultiviewUbo(engine, name24) {
  const ubo = new UniformBuffer(engine, undefined, true, name24);
  ubo.addUniform("viewProjection", 16);
  ubo.addUniform("viewProjectionR", 16);
  ubo.addUniform("view", 16);
  ubo.addUniform("projection", 16);
  ubo.addUniform("vEyePosition", 4);
  return ubo;
}
var currentCreateSceneUniformBuffer = Scene.prototype.createSceneUniformBuffer;
Scene.prototype._transformMatrixR = Matrix.Zero();
Scene.prototype._multiviewSceneUbo = null;
Scene.prototype._createMultiviewUbo = function() {
  this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), "scene_multiview");
};
Scene.prototype.createSceneUniformBuffer = function(name24) {
  if (this._multiviewSceneUbo) {
    return createMultiviewUbo(this.getEngine(), name24);
  }
  return currentCreateSceneUniformBuffer.bind(this)(name24);
};
Scene.prototype._updateMultiviewUbo = function(viewR, projectionR) {
  if (viewR && projectionR) {
    viewR.multiplyToRef(projectionR, this._transformMatrixR);
  }
  if (viewR && projectionR) {
    viewR.multiplyToRef(projectionR, TmpVectors.Matrix[0]);
    Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0], this._frustumPlanes[3]);
  }
  if (this._multiviewSceneUbo) {
    this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix());
    this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR);
    this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix);
    this._multiviewSceneUbo.updateMatrix("projection", this._projectionMatrix);
  }
};
Scene.prototype._renderMultiviewToSingleView = function(camera) {
  camera._resizeOrCreateMultiviewTexture(camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0 ? camera._rigPostProcess.width : this.getEngine().getRenderWidth(true), camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0 ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true));
  if (!this._multiviewSceneUbo) {
    this._createMultiviewUbo();
  }
  camera.outputRenderTarget = camera._multiviewTexture;
  this._renderForCamera(camera);
  camera.outputRenderTarget = null;
  for (let index = 0;index < camera._rigCameras.length; index++) {
    const engine = this.getEngine();
    this._activeCamera = camera._rigCameras[index];
    engine.setViewport(this._activeCamera.viewport);
    if (this.postProcessManager) {
      this.postProcessManager._prepareFrame();
      this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate);
    }
  }
};

// node_modules/@babylonjs/core/PostProcesses/vrMultiviewToSingleviewPostProcess.js
class VRMultiviewToSingleviewPostProcess extends PostProcess {
  getClassName() {
    return "VRMultiviewToSingleviewPostProcess";
  }
  constructor(name24, camera, scaleFactor) {
    super(name24, "vrMultiviewToSingleview", ["imageIndex"], ["multiviewSampler"], scaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);
    const cam = camera ?? this.getCamera();
    this.onSizeChangedObservable.add(() => {});
    this.onApplyObservable.add((effect) => {
      if (cam._scene.activeCamera && cam._scene.activeCamera.isLeftCamera) {
        effect.setInt("imageIndex", 0);
      } else {
        effect.setInt("imageIndex", 1);
      }
      effect.setTexture("multiviewSampler", cam._multiviewTexture);
    });
  }
}

// node_modules/@babylonjs/core/Cameras/RigModes/vrRigMode.js
init_logger();
function setVRRigMode(camera, rigParams) {
  const metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1);
  camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix;
  camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix;
  camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1);
  camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix;
  camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix;
  if (metrics.multiviewEnabled) {
    if (!camera.getScene().getEngine().getCaps().multiview) {
      Logger.Warn("Multiview is not supported, falling back to standard rendering");
      metrics.multiviewEnabled = false;
    } else {
      camera._useMultiviewToSingleView = true;
      camera._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor);
    }
  }
  if (metrics.compensateDistortion) {
    camera._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics);
    camera._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics);
  }
}

// node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationArcRotateCamera.js
Node2.AddNodeConstructor("VRDeviceOrientationArcRotateCamera", (name24, scene) => {
  return () => new VRDeviceOrientationArcRotateCamera(name24, 0, 0, 1, Vector3.Zero(), scene);
});

class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera {
  constructor(name24, alpha, beta, radius, target, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {
    super(name24, alpha, beta, radius, target, scene);
    this._setRigMode = (rigParams) => setVRRigMode(this, rigParams);
    vrCameraMetrics.compensateDistortion = compensateDistortion;
    this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics });
    this.inputs.addVRDeviceOrientation();
  }
  getClassName() {
    return "VRDeviceOrientationArcRotateCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationFreeCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("VRDeviceOrientationFreeCamera", (name24, scene) => {
  return () => new VRDeviceOrientationFreeCamera(name24, Vector3.Zero(), scene);
});

class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera {
  constructor(name24, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {
    super(name24, position, scene);
    this._setRigMode = (rigParams) => setVRRigMode(this, rigParams);
    vrCameraMetrics.compensateDistortion = compensateDistortion;
    this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics });
  }
  getClassName() {
    return "VRDeviceOrientationFreeCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationGamepadCamera.js
init_math_vector();
init_node();
Node2.AddNodeConstructor("VRDeviceOrientationGamepadCamera", (name24, scene) => {
  return () => new VRDeviceOrientationGamepadCamera(name24, Vector3.Zero(), scene);
});

class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera {
  constructor(name24, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {
    super(name24, position, scene, compensateDistortion, vrCameraMetrics);
    this._setRigMode = (rigParams) => setVRRigMode(this, rigParams);
    this.inputs.addGamepad();
  }
  getClassName() {
    return "VRDeviceOrientationGamepadCamera";
  }
}
// node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js
init_logger();
init_observable();
init_pointerEvents();
init_math_vector();
init_math_color();
init_imageProcessingConfiguration();

// node_modules/@babylonjs/core/Materials/standardMaterial.js
init_tslib_es6();
init_decorators();
init_smartArray();
init_scene();
init_math_color();
init_buffer();

// node_modules/@babylonjs/core/Materials/prePassConfiguration.js
class PrePassConfiguration {
  constructor() {
    this.previousWorldMatrices = {};
    this.previousBones = {};
  }
  static AddUniforms(uniforms) {
    uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones");
  }
  static AddSamplers(samplers) {}
  bindForSubMesh(effect, scene, mesh, world, isFrozen) {
    if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) {
      if (scene.prePassRenderer.getIndex(2) !== -1 || scene.prePassRenderer.getIndex(11) !== -1) {
        if (!this.previousWorldMatrices[mesh.uniqueId]) {
          this.previousWorldMatrices[mesh.uniqueId] = world.clone();
        }
        if (!this.previousViewProjection) {
          this.previousViewProjection = scene.getTransformMatrix().clone();
          this.currentViewProjection = scene.getTransformMatrix().clone();
        }
        const engine = scene.getEngine();
        if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {
          this._lastUpdateFrameId = engine.frameId;
          this.previousViewProjection.copyFrom(this.currentViewProjection);
          this.currentViewProjection.copyFrom(scene.getTransformMatrix());
        } else if (this._lastUpdateFrameId !== engine.frameId) {
          this._lastUpdateFrameId = engine.frameId;
          this.previousViewProjection.copyFrom(this.currentViewProjection);
        }
        effect.setMatrix("previousWorld", this.previousWorldMatrices[mesh.uniqueId]);
        effect.setMatrix("previousViewProjection", this.previousViewProjection);
        this.previousWorldMatrices[mesh.uniqueId] = world.clone();
      }
    }
  }
}

// node_modules/@babylonjs/core/Materials/standardMaterial.js
init_imageProcessingConfiguration();

// node_modules/@babylonjs/core/Materials/materialDefines.js
class MaterialDefines {
  constructor(externalProperties) {
    this._keys = [];
    this._isDirty = true;
    this._areLightsDirty = true;
    this._areLightsDisposed = false;
    this._areAttributesDirty = true;
    this._areTexturesDirty = true;
    this._areFresnelDirty = true;
    this._areMiscDirty = true;
    this._arePrePassDirty = true;
    this._areImageProcessingDirty = true;
    this._normals = false;
    this._uvs = false;
    this._needNormals = false;
    this._needUVs = false;
    this._externalProperties = externalProperties;
    if (externalProperties) {
      for (const prop in externalProperties) {
        if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) {
          this._setDefaultValue(prop);
        }
      }
    }
  }
  get isDirty() {
    return this._isDirty;
  }
  markAsProcessed() {
    this._isDirty = false;
    this._areAttributesDirty = false;
    this._areTexturesDirty = false;
    this._areFresnelDirty = false;
    this._areLightsDirty = false;
    this._areLightsDisposed = false;
    this._areMiscDirty = false;
    this._arePrePassDirty = false;
    this._areImageProcessingDirty = false;
  }
  markAsUnprocessed() {
    this._isDirty = true;
  }
  markAllAsDirty() {
    this._areTexturesDirty = true;
    this._areAttributesDirty = true;
    this._areLightsDirty = true;
    this._areFresnelDirty = true;
    this._areMiscDirty = true;
    this._arePrePassDirty = true;
    this._areImageProcessingDirty = true;
    this._isDirty = true;
  }
  markAsImageProcessingDirty() {
    this._areImageProcessingDirty = true;
    this._isDirty = true;
  }
  markAsLightDirty(disposed = false) {
    this._areLightsDirty = true;
    this._areLightsDisposed = this._areLightsDisposed || disposed;
    this._isDirty = true;
  }
  markAsAttributesDirty() {
    this._areAttributesDirty = true;
    this._isDirty = true;
  }
  markAsTexturesDirty() {
    this._areTexturesDirty = true;
    this._isDirty = true;
  }
  markAsFresnelDirty() {
    this._areFresnelDirty = true;
    this._isDirty = true;
  }
  markAsMiscDirty() {
    this._areMiscDirty = true;
    this._isDirty = true;
  }
  markAsPrePassDirty() {
    this._arePrePassDirty = true;
    this._isDirty = true;
  }
  rebuild() {
    this._keys.length = 0;
    for (const key of Object.keys(this)) {
      if (key[0] === "_") {
        continue;
      }
      this._keys.push(key);
    }
    if (this._externalProperties) {
      for (const name24 in this._externalProperties) {
        if (this._keys.indexOf(name24) === -1) {
          this._keys.push(name24);
        }
      }
    }
  }
  isEqual(other) {
    if (this._keys.length !== other._keys.length) {
      return false;
    }
    for (let index = 0;index < this._keys.length; index++) {
      const prop = this._keys[index];
      if (this[prop] !== other[prop]) {
        return false;
      }
    }
    return true;
  }
  cloneTo(other) {
    if (this._keys.length !== other._keys.length) {
      other._keys = this._keys.slice(0);
    }
    for (let index = 0;index < this._keys.length; index++) {
      const prop = this._keys[index];
      other[prop] = this[prop];
    }
  }
  reset() {
    this._keys.forEach((prop) => this._setDefaultValue(prop));
  }
  _setDefaultValue(prop) {
    const type = this._externalProperties?.[prop]?.type ?? typeof this[prop];
    const defValue = this._externalProperties?.[prop]?.default;
    switch (type) {
      case "number":
        this[prop] = defValue ?? 0;
        break;
      case "string":
        this[prop] = defValue ?? "";
        break;
      default:
        this[prop] = defValue ?? false;
        break;
    }
  }
  toString() {
    let result = "";
    for (let index = 0;index < this._keys.length; index++) {
      const prop = this._keys[index];
      const value = this[prop];
      const type = typeof value;
      switch (type) {
        case "number":
        case "string":
          result += "#define " + prop + " " + value + `
`;
          break;
        default:
          if (value) {
            result += "#define " + prop + `
`;
          }
          break;
      }
    }
    return result;
  }
}

// node_modules/@babylonjs/core/Materials/pushMaterial.js
init_math_vector();
class PushMaterial extends Material {
  constructor(name24, scene, storeEffectOnSubMeshes = true, forceGLSL = false) {
    super(name24, scene, undefined, forceGLSL);
    this._normalMatrix = new Matrix;
    this._storeEffectOnSubMeshes = storeEffectOnSubMeshes;
  }
  getEffect() {
    return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect();
  }
  isReady(mesh, useInstances) {
    if (!mesh) {
      return false;
    }
    if (!this._storeEffectOnSubMeshes) {
      return true;
    }
    if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
      return true;
    }
    return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  }
  _isReadyForSubMesh(subMesh) {
    const defines = subMesh.materialDefines;
    if (!this.checkReadyOnEveryCall && subMesh.effect && defines) {
      if (defines._renderId === this.getScene().getRenderId()) {
        return true;
      }
    }
    return false;
  }
  bindOnlyWorldMatrix(world) {
    this._activeEffect.setMatrix("world", world);
  }
  bindOnlyNormalMatrix(normalMatrix) {
    this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  }
  bind(world, mesh) {
    if (!mesh) {
      return;
    }
    this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  }
  _afterBind(mesh, effect = null, subMesh) {
    super._afterBind(mesh, effect, subMesh);
    this.getScene()._cachedEffect = effect;
    if (subMesh) {
      subMesh._drawWrapper._forceRebindOnNextCall = false;
    } else {
      this._drawWrapper._forceRebindOnNextCall = false;
    }
  }
  _mustRebind(scene, effect, subMesh, visibility = 1) {
    return subMesh._drawWrapper._forceRebindOnNextCall || scene.isCachedMaterialInvalid(this, effect, visibility);
  }
  dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
    this._activeEffect = undefined;
    super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  }
}

// node_modules/@babylonjs/core/Materials/standardMaterial.js
init_texture();
init_typeStore();

// node_modules/@babylonjs/core/Materials/materialFlags.js
init_abstractEngine();

class MaterialFlags {
  static get DiffuseTextureEnabled() {
    return this._DiffuseTextureEnabled;
  }
  static set DiffuseTextureEnabled(value) {
    if (this._DiffuseTextureEnabled === value) {
      return;
    }
    this._DiffuseTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get BaseWeightTextureEnabled() {
    return this._BaseWeightTextureEnabled;
  }
  static set BaseWeightTextureEnabled(value) {
    if (this._BaseWeightTextureEnabled === value) {
      return;
    }
    this._BaseWeightTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get DetailTextureEnabled() {
    return this._DetailTextureEnabled;
  }
  static set DetailTextureEnabled(value) {
    if (this._DetailTextureEnabled === value) {
      return;
    }
    this._DetailTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get DecalMapEnabled() {
    return this._DecalMapEnabled;
  }
  static set DecalMapEnabled(value) {
    if (this._DecalMapEnabled === value) {
      return;
    }
    this._DecalMapEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get AmbientTextureEnabled() {
    return this._AmbientTextureEnabled;
  }
  static set AmbientTextureEnabled(value) {
    if (this._AmbientTextureEnabled === value) {
      return;
    }
    this._AmbientTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get OpacityTextureEnabled() {
    return this._OpacityTextureEnabled;
  }
  static set OpacityTextureEnabled(value) {
    if (this._OpacityTextureEnabled === value) {
      return;
    }
    this._OpacityTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get ReflectionTextureEnabled() {
    return this._ReflectionTextureEnabled;
  }
  static set ReflectionTextureEnabled(value) {
    if (this._ReflectionTextureEnabled === value) {
      return;
    }
    this._ReflectionTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get EmissiveTextureEnabled() {
    return this._EmissiveTextureEnabled;
  }
  static set EmissiveTextureEnabled(value) {
    if (this._EmissiveTextureEnabled === value) {
      return;
    }
    this._EmissiveTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get SpecularTextureEnabled() {
    return this._SpecularTextureEnabled;
  }
  static set SpecularTextureEnabled(value) {
    if (this._SpecularTextureEnabled === value) {
      return;
    }
    this._SpecularTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get BumpTextureEnabled() {
    return this._BumpTextureEnabled;
  }
  static set BumpTextureEnabled(value) {
    if (this._BumpTextureEnabled === value) {
      return;
    }
    this._BumpTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get LightmapTextureEnabled() {
    return this._LightmapTextureEnabled;
  }
  static set LightmapTextureEnabled(value) {
    if (this._LightmapTextureEnabled === value) {
      return;
    }
    this._LightmapTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get RefractionTextureEnabled() {
    return this._RefractionTextureEnabled;
  }
  static set RefractionTextureEnabled(value) {
    if (this._RefractionTextureEnabled === value) {
      return;
    }
    this._RefractionTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get ColorGradingTextureEnabled() {
    return this._ColorGradingTextureEnabled;
  }
  static set ColorGradingTextureEnabled(value) {
    if (this._ColorGradingTextureEnabled === value) {
      return;
    }
    this._ColorGradingTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get FresnelEnabled() {
    return this._FresnelEnabled;
  }
  static set FresnelEnabled(value) {
    if (this._FresnelEnabled === value) {
      return;
    }
    this._FresnelEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(4);
  }
  static get ClearCoatTextureEnabled() {
    return this._ClearCoatTextureEnabled;
  }
  static set ClearCoatTextureEnabled(value) {
    if (this._ClearCoatTextureEnabled === value) {
      return;
    }
    this._ClearCoatTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get ClearCoatBumpTextureEnabled() {
    return this._ClearCoatBumpTextureEnabled;
  }
  static set ClearCoatBumpTextureEnabled(value) {
    if (this._ClearCoatBumpTextureEnabled === value) {
      return;
    }
    this._ClearCoatBumpTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get ClearCoatTintTextureEnabled() {
    return this._ClearCoatTintTextureEnabled;
  }
  static set ClearCoatTintTextureEnabled(value) {
    if (this._ClearCoatTintTextureEnabled === value) {
      return;
    }
    this._ClearCoatTintTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get SheenTextureEnabled() {
    return this._SheenTextureEnabled;
  }
  static set SheenTextureEnabled(value) {
    if (this._SheenTextureEnabled === value) {
      return;
    }
    this._SheenTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get AnisotropicTextureEnabled() {
    return this._AnisotropicTextureEnabled;
  }
  static set AnisotropicTextureEnabled(value) {
    if (this._AnisotropicTextureEnabled === value) {
      return;
    }
    this._AnisotropicTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get ThicknessTextureEnabled() {
    return this._ThicknessTextureEnabled;
  }
  static set ThicknessTextureEnabled(value) {
    if (this._ThicknessTextureEnabled === value) {
      return;
    }
    this._ThicknessTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get RefractionIntensityTextureEnabled() {
    return this._ThicknessTextureEnabled;
  }
  static set RefractionIntensityTextureEnabled(value) {
    if (this._RefractionIntensityTextureEnabled === value) {
      return;
    }
    this._RefractionIntensityTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get TranslucencyIntensityTextureEnabled() {
    return this._TranslucencyIntensityTextureEnabled;
  }
  static set TranslucencyIntensityTextureEnabled(value) {
    if (this._TranslucencyIntensityTextureEnabled === value) {
      return;
    }
    this._TranslucencyIntensityTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get TranslucencyColorTextureEnabled() {
    return this._TranslucencyColorTextureEnabled;
  }
  static set TranslucencyColorTextureEnabled(value) {
    if (this._TranslucencyColorTextureEnabled === value) {
      return;
    }
    this._TranslucencyColorTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
  static get IridescenceTextureEnabled() {
    return this._IridescenceTextureEnabled;
  }
  static set IridescenceTextureEnabled(value) {
    if (this._IridescenceTextureEnabled === value) {
      return;
    }
    this._IridescenceTextureEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(1);
  }
}
MaterialFlags._DiffuseTextureEnabled = true;
MaterialFlags._BaseWeightTextureEnabled = true;
MaterialFlags._DetailTextureEnabled = true;
MaterialFlags._DecalMapEnabled = true;
MaterialFlags._AmbientTextureEnabled = true;
MaterialFlags._OpacityTextureEnabled = true;
MaterialFlags._ReflectionTextureEnabled = true;
MaterialFlags._EmissiveTextureEnabled = true;
MaterialFlags._SpecularTextureEnabled = true;
MaterialFlags._BumpTextureEnabled = true;
MaterialFlags._LightmapTextureEnabled = true;
MaterialFlags._RefractionTextureEnabled = true;
MaterialFlags._ColorGradingTextureEnabled = true;
MaterialFlags._FresnelEnabled = true;
MaterialFlags._ClearCoatTextureEnabled = true;
MaterialFlags._ClearCoatBumpTextureEnabled = true;
MaterialFlags._ClearCoatTintTextureEnabled = true;
MaterialFlags._SheenTextureEnabled = true;
MaterialFlags._AnisotropicTextureEnabled = true;
MaterialFlags._ThicknessTextureEnabled = true;
MaterialFlags._RefractionIntensityTextureEnabled = true;
MaterialFlags._TranslucencyIntensityTextureEnabled = true;
MaterialFlags._TranslucencyColorTextureEnabled = true;
MaterialFlags._IridescenceTextureEnabled = true;

// node_modules/@babylonjs/core/Materials/effectFallbacks.js
class EffectFallbacks {
  constructor() {
    this._defines = {};
    this._currentRank = 32;
    this._maxRank = -1;
    this._mesh = null;
  }
  unBindMesh() {
    this._mesh = null;
  }
  addFallback(rank, define) {
    if (!this._defines[rank]) {
      if (rank < this._currentRank) {
        this._currentRank = rank;
      }
      if (rank > this._maxRank) {
        this._maxRank = rank;
      }
      this._defines[rank] = new Array;
    }
    this._defines[rank].push(define);
  }
  addCPUSkinningFallback(rank, mesh) {
    this._mesh = mesh;
    if (rank < this._currentRank) {
      this._currentRank = rank;
    }
    if (rank > this._maxRank) {
      this._maxRank = rank;
    }
  }
  get hasMoreFallbacks() {
    return this._currentRank <= this._maxRank;
  }
  reduce(currentDefines, effect) {
    if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
      this._mesh.computeBonesUsingShaders = false;
      currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
      effect._bonesComputationForcedToCPU = true;
      const scene = this._mesh.getScene();
      for (let index = 0;index < scene.meshes.length; index++) {
        const otherMesh = scene.meshes[index];
        if (!otherMesh.material) {
          if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
            otherMesh.computeBonesUsingShaders = false;
          }
          continue;
        }
        if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
          continue;
        }
        if (otherMesh.material.getEffect() === effect) {
          otherMesh.computeBonesUsingShaders = false;
        } else if (otherMesh.subMeshes) {
          for (const subMesh of otherMesh.subMeshes) {
            const subMeshEffect = subMesh.effect;
            if (subMeshEffect === effect) {
              otherMesh.computeBonesUsingShaders = false;
              break;
            }
          }
        }
      }
    } else {
      const currentFallbacks = this._defines[this._currentRank];
      if (currentFallbacks) {
        for (let index = 0;index < currentFallbacks.length; index++) {
          currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
        }
      }
      this._currentRank++;
    }
    return currentDefines;
  }
}

// node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js
init_tslib_es6();
init_decorators();

// node_modules/@babylonjs/core/Materials/materialPluginBase.js
init_tslib_es6();
init_decorators();

// node_modules/@babylonjs/core/Materials/materialPluginManager.js
init_engineStore();
init_shaderProcessor();
init_shaderStore();
var rxOption = new RegExp("^([gimus]+)!");

class MaterialPluginManager {
  constructor(material) {
    this._plugins = [];
    this._activePlugins = [];
    this._activePluginsForExtraEvents = [];
    this._material = material;
    this._scene = material.getScene();
    this._engine = this._scene.getEngine();
  }
  _addPlugin(plugin) {
    for (let i = 0;i < this._plugins.length; ++i) {
      if (this._plugins[i].name === plugin.name) {
        return false;
      }
    }
    if (this._material._uniformBufferLayoutBuilt) {
      this._material.resetDrawCache();
      this._material._createUniformBuffer();
    }
    if (!plugin.isCompatible(this._material.shaderLanguage)) {
      throw `The plugin "${plugin.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;
    }
    const pluginClassName = plugin.getClassName();
    if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) {
      MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = "MATERIALPLUGIN_" + ++MaterialPluginManager._MaterialPluginCounter;
    }
    this._material._callbackPluginEventGeneric = (id, info) => this._handlePluginEvent(id, info);
    this._plugins.push(plugin);
    this._plugins.sort((a, b) => a.priority - b.priority);
    this._codeInjectionPoints = {};
    const defineNamesFromPlugins = {};
    defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = {
      type: "boolean",
      default: true
    };
    for (const plugin2 of this._plugins) {
      plugin2.collectDefines(defineNamesFromPlugins);
      this._collectPointNames("vertex", plugin2.getCustomCode("vertex", this._material.shaderLanguage));
      this._collectPointNames("fragment", plugin2.getCustomCode("fragment", this._material.shaderLanguage));
    }
    this._defineNamesFromPlugins = defineNamesFromPlugins;
    return true;
  }
  _activatePlugin(plugin) {
    if (this._activePlugins.indexOf(plugin) === -1) {
      this._activePlugins.push(plugin);
      this._activePlugins.sort((a, b) => a.priority - b.priority);
      this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this);
      this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this);
      this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this);
      this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this);
      if (plugin.registerForExtraEvents) {
        this._activePluginsForExtraEvents.push(plugin);
        this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority);
        this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this);
        this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this);
        this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this);
      }
    }
  }
  getPlugin(name24) {
    for (let i = 0;i < this._plugins.length; ++i) {
      if (this._plugins[i].name === name24) {
        return this._plugins[i];
      }
    }
    return null;
  }
  _handlePluginEventIsReadyForSubMesh(eventData) {
    let isReady = true;
    for (const plugin of this._activePlugins) {
      isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh);
    }
    eventData.isReadyForSubMesh = isReady;
  }
  _handlePluginEventPrepareDefinesBeforeAttributes(eventData) {
    for (const plugin of this._activePlugins) {
      plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh);
    }
  }
  _handlePluginEventPrepareDefines(eventData) {
    for (const plugin of this._activePlugins) {
      plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh);
    }
  }
  _handlePluginEventHardBindForSubMesh(eventData) {
    for (const plugin of this._activePluginsForExtraEvents) {
      plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);
    }
  }
  _handlePluginEventBindForSubMesh(eventData) {
    for (const plugin of this._activePlugins) {
      plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);
    }
  }
  _handlePluginEventHasRenderTargetTextures(eventData) {
    let hasRenderTargetTextures = false;
    for (const plugin of this._activePluginsForExtraEvents) {
      hasRenderTargetTextures = plugin.hasRenderTargetTextures();
      if (hasRenderTargetTextures) {
        break;
      }
    }
    eventData.hasRenderTargetTextures = hasRenderTargetTextures;
  }
  _handlePluginEventFillRenderTargetTextures(eventData) {
    for (const plugin of this._activePluginsForExtraEvents) {
      plugin.fillRenderTargetTextures(eventData.renderTargets);
    }
  }
  _handlePluginEvent(id, info) {
    switch (id) {
      case 512: {
        const eventData = info;
        for (const plugin of this._activePlugins) {
          plugin.getActiveTextures(eventData.activeTextures);
        }
        break;
      }
      case 256: {
        const eventData = info;
        for (const plugin of this._activePlugins) {
          plugin.getAnimatables(eventData.animatables);
        }
        break;
      }
      case 1024: {
        const eventData = info;
        let hasTexture = false;
        for (const plugin of this._activePlugins) {
          hasTexture = plugin.hasTexture(eventData.texture);
          if (hasTexture) {
            break;
          }
        }
        eventData.hasTexture = hasTexture;
        break;
      }
      case 2: {
        const eventData = info;
        for (const plugin of this._plugins) {
          plugin.dispose(eventData.forceDisposeTextures);
        }
        break;
      }
      case 4: {
        const eventData = info;
        eventData.defineNames = this._defineNamesFromPlugins;
        break;
      }
      case 128: {
        const eventData = info;
        for (const plugin of this._activePlugins) {
          eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank);
          plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh);
        }
        if (this._uniformList.length > 0) {
          eventData.uniforms.push(...this._uniformList);
        }
        if (this._samplerList.length > 0) {
          eventData.samplers.push(...this._samplerList);
        }
        if (this._uboList.length > 0) {
          eventData.uniformBuffersNames.push(...this._uboList);
        }
        eventData.customCode = this._injectCustomCode(eventData, eventData.customCode);
        break;
      }
      case 8: {
        const eventData = info;
        this._uboDeclaration = "";
        this._vertexDeclaration = "";
        this._fragmentDeclaration = "";
        this._uniformList = [];
        this._samplerList = [];
        this._uboList = [];
        const isWebGPU = this._material.shaderLanguage === 1;
        for (const plugin of this._plugins) {
          const uniforms = plugin.getUniforms(this._material.shaderLanguage);
          if (uniforms) {
            if (uniforms.ubo) {
              for (const uniform of uniforms.ubo) {
                if (uniform.size && uniform.type) {
                  const arraySize = uniform.arraySize ?? 0;
                  eventData.ubo.addUniform(uniform.name, uniform.size, arraySize);
                  if (isWebGPU) {
                    let type;
                    switch (uniform.type) {
                      case "mat4":
                        type = "mat4x4f";
                        break;
                      case "float":
                        type = "f32";
                        break;
                      default:
                        type = `${uniform.type}f`;
                        break;
                    }
                    this._uboDeclaration += `uniform ${uniform.name}: ${type}${arraySize > 0 ? `[${arraySize}]` : ""};
`;
                  } else {
                    this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : ""};
`;
                  }
                }
                this._uniformList.push(uniform.name);
              }
            }
            if (uniforms.vertex) {
              this._vertexDeclaration += uniforms.vertex + `
`;
            }
            if (uniforms.fragment) {
              this._fragmentDeclaration += uniforms.fragment + `
`;
            }
          }
          plugin.getSamplers(this._samplerList);
          plugin.getUniformBuffersNames(this._uboList);
        }
        break;
      }
    }
  }
  _collectPointNames(shaderType, customCode) {
    if (!customCode) {
      return;
    }
    for (const pointName in customCode) {
      if (!this._codeInjectionPoints[shaderType]) {
        this._codeInjectionPoints[shaderType] = {};
      }
      this._codeInjectionPoints[shaderType][pointName] = true;
    }
  }
  _injectCustomCode(eventData, existingCallback) {
    return (shaderType, code) => {
      if (existingCallback) {
        code = existingCallback(shaderType, code);
      }
      if (this._uboDeclaration) {
        code = code.replace("#define ADDITIONAL_UBO_DECLARATION", this._uboDeclaration);
      }
      if (this._vertexDeclaration) {
        code = code.replace("#define ADDITIONAL_VERTEX_DECLARATION", this._vertexDeclaration);
      }
      if (this._fragmentDeclaration) {
        code = code.replace("#define ADDITIONAL_FRAGMENT_DECLARATION", this._fragmentDeclaration);
      }
      const points = this._codeInjectionPoints?.[shaderType];
      if (!points) {
        return code;
      }
      let processorOptions = null;
      for (let pointName in points) {
        let injectedCode = "";
        for (const plugin of this._activePlugins) {
          let customCode = plugin.getCustomCode(shaderType, this._material.shaderLanguage)?.[pointName];
          if (!customCode) {
            continue;
          }
          if (plugin.resolveIncludes) {
            if (processorOptions === null) {
              const shaderLanguage = 0;
              processorOptions = {
                defines: [],
                indexParameters: eventData.indexParameters,
                isFragment: false,
                shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,
                processor: undefined,
                supportsUniformBuffers: this._engine.supportsUniformBuffers,
                shadersRepository: ShaderStore.GetShadersRepository(shaderLanguage),
                includesShadersStore: ShaderStore.GetIncludesShadersStore(shaderLanguage),
                version: undefined,
                platformName: this._engine.shaderPlatformName,
                processingContext: undefined,
                isNDCHalfZRange: this._engine.isNDCHalfZRange,
                useReverseDepthBuffer: this._engine.useReverseDepthBuffer,
                processCodeAfterIncludes: undefined
              };
            }
            processorOptions.isFragment = shaderType === "fragment";
            _ProcessIncludes(customCode, processorOptions, (code2) => customCode = code2);
          }
          injectedCode += customCode + `
`;
        }
        if (injectedCode.length > 0) {
          if (pointName.charAt(0) === "!") {
            pointName = pointName.substring(1);
            let regexFlags = "g";
            if (pointName.charAt(0) === "!") {
              regexFlags = "";
              pointName = pointName.substring(1);
            } else {
              const matchOption = rxOption.exec(pointName);
              if (matchOption && matchOption.length >= 2) {
                regexFlags = matchOption[1];
                pointName = pointName.substring(regexFlags.length + 1);
              }
            }
            if (regexFlags.indexOf("g") < 0) {
              regexFlags += "g";
            }
            const sourceCode = code;
            const rx = new RegExp(pointName, regexFlags);
            let match = rx.exec(sourceCode);
            while (match !== null) {
              let newCode = injectedCode;
              for (let i = 0;i < match.length; ++i) {
                newCode = newCode.replace("$" + i, match[i]);
              }
              code = code.replace(match[0], newCode);
              match = rx.exec(sourceCode);
            }
          } else {
            const fullPointName = "#define " + pointName;
            code = code.replace(fullPointName, `
` + injectedCode + `
` + fullPointName);
          }
        }
      }
      return code;
    };
  }
}
MaterialPluginManager._MaterialPluginClassToMainDefine = {};
MaterialPluginManager._MaterialPluginCounter = 0;
(() => {
  EngineStore.OnEnginesDisposedObservable.add(() => {
    UnregisterAllMaterialPlugins();
  });
})();
var plugins = [];
var inited = false;
var observer = null;
function RegisterMaterialPlugin(pluginName, factory) {
  if (!inited) {
    observer = Material.OnEventObservable.add((material) => {
      for (const [, factory2] of plugins) {
        factory2(material);
      }
    }, 1);
    inited = true;
  }
  const existing = plugins.filter(([name24, _factory]) => name24 === pluginName);
  if (existing.length > 0) {
    existing[0][1] = factory;
  } else {
    plugins.push([pluginName, factory]);
  }
}
function UnregisterAllMaterialPlugins() {
  plugins.length = 0;
  inited = false;
  Material.OnEventObservable.remove(observer);
  observer = null;
}

// node_modules/@babylonjs/core/Materials/materialPluginBase.js
init_decorators_serialization();
init_typeStore();

class MaterialPluginBase {
  isCompatible(shaderLanguage) {
    switch (shaderLanguage) {
      case 0:
        return true;
      default:
        return false;
    }
  }
  _enable(enable) {
    if (enable) {
      this._pluginManager._activatePlugin(this);
    }
  }
  constructor(material, name24, priority, defines, addToPluginList = true, enable = false, resolveIncludes = false) {
    this.priority = 500;
    this.resolveIncludes = false;
    this.registerForExtraEvents = false;
    this.doNotSerialize = false;
    this._material = material;
    this.name = name24;
    this.priority = priority;
    this.resolveIncludes = resolveIncludes;
    if (!material.pluginManager) {
      material.pluginManager = new MaterialPluginManager(material);
      material.onDisposeObservable.add(() => {
        material.pluginManager = undefined;
      });
    }
    this._pluginDefineNames = defines;
    this._pluginManager = material.pluginManager;
    if (addToPluginList) {
      this._pluginManager._addPlugin(this);
    }
    if (enable) {
      this._enable(true);
    }
    this.markAllDefinesAsDirty = material._dirtyCallbacks[127];
  }
  getClassName() {
    return "MaterialPluginBase";
  }
  isReadyForSubMesh(_defines, _scene, _engine, _subMesh) {
    return true;
  }
  hardBindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) {}
  bindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) {}
  dispose(_forceDisposeTextures) {}
  getCustomCode(_shaderType, _shaderLanguage = 0) {
    return null;
  }
  collectDefines(defines) {
    if (!this._pluginDefineNames) {
      return;
    }
    for (const key of Object.keys(this._pluginDefineNames)) {
      if (key[0] === "_") {
        continue;
      }
      const type = typeof this._pluginDefineNames[key];
      defines[key] = {
        type: type === "number" ? "number" : type === "string" ? "string" : type === "boolean" ? "boolean" : "object",
        default: this._pluginDefineNames[key]
      };
    }
  }
  prepareDefinesBeforeAttributes(_defines, _scene, _mesh) {}
  prepareDefines(_defines, _scene, _mesh) {}
  hasTexture(_texture) {
    return false;
  }
  hasRenderTargetTextures() {
    return false;
  }
  fillRenderTargetTextures(_renderTargets) {}
  getActiveTextures(_activeTextures) {}
  getAnimatables(_animatables) {}
  addFallbacks(defines, fallbacks, currentRank) {
    return currentRank;
  }
  getSamplers(_samplers) {}
  getAttributes(_attributes, _scene, _mesh) {}
  getUniformBuffersNames(_ubos) {}
  getUniforms(_shaderLanguage = 0) {
    return {};
  }
  copyTo(plugin) {
    SerializationHelper.Clone(() => plugin, this);
  }
  serialize() {
    return SerializationHelper.Serialize(this);
  }
  parse(source, scene, rootUrl) {
    SerializationHelper.Parse(() => this, source, scene, rootUrl);
  }
}
__decorate([
  serialize()
], MaterialPluginBase.prototype, "name", undefined);
__decorate([
  serialize()
], MaterialPluginBase.prototype, "priority", undefined);
__decorate([
  serialize()
], MaterialPluginBase.prototype, "resolveIncludes", undefined);
__decorate([
  serialize()
], MaterialPluginBase.prototype, "registerForExtraEvents", undefined);
RegisterClass("BABYLON.MaterialPluginBase", MaterialPluginBase);

// node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js
init_materialHelper_functions();

class MaterialDetailMapDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.DETAIL = false;
    this.DETAILDIRECTUV = 0;
    this.DETAIL_NORMALBLENDMETHOD = 0;
  }
}

class DetailMapConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "DetailMap", 140, new MaterialDetailMapDefines, addToPluginList);
    this._texture = null;
    this.diffuseBlendLevel = 1;
    this.roughnessBlendLevel = 1;
    this.bumpLevel = 1;
    this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT;
    this._isEnabled = false;
    this.isEnabled = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
  }
  isReadyForSubMesh(defines, scene, engine) {
    if (!this._isEnabled) {
      return true;
    }
    if (defines._areTexturesDirty && scene.texturesEnabled) {
      if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) {
        if (!this._texture.isReady()) {
          return false;
        }
      }
    }
    return true;
  }
  prepareDefines(defines, scene) {
    if (this._isEnabled) {
      defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
      const engine = scene.getEngine();
      if (defines._areTexturesDirty) {
        if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) {
          PrepareDefinesForMergedUV(this._texture, defines, "DETAIL");
          defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;
        } else {
          defines.DETAIL = false;
        }
      }
    } else {
      defines.DETAIL = false;
    }
  }
  bindForSubMesh(uniformBuffer, scene) {
    if (!this._isEnabled) {
      return;
    }
    const isFrozen = this._material.isFrozen;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if (this._texture && MaterialFlags.DetailTextureEnabled) {
        uniformBuffer.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel);
        BindTextureMatrix(this._texture, uniformBuffer, "detail");
      }
    }
    if (scene.texturesEnabled) {
      if (this._texture && MaterialFlags.DetailTextureEnabled) {
        uniformBuffer.setTexture("detailSampler", this._texture);
      }
    }
  }
  hasTexture(texture) {
    if (this._texture === texture) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._texture) {
      activeTextures.push(this._texture);
    }
  }
  getAnimatables(animatables) {
    if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
      animatables.push(this._texture);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._texture?.dispose();
    }
  }
  getClassName() {
    return "DetailMapConfiguration";
  }
  getSamplers(samplers) {
    samplers.push("detailSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vDetailInfos", size: 4, type: "vec4" },
        { name: "detailMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
__decorate([
  serializeAsTexture("detailTexture"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], DetailMapConfiguration.prototype, "texture", undefined);
__decorate([
  serialize()
], DetailMapConfiguration.prototype, "diffuseBlendLevel", undefined);
__decorate([
  serialize()
], DetailMapConfiguration.prototype, "roughnessBlendLevel", undefined);
__decorate([
  serialize()
], DetailMapConfiguration.prototype, "bumpLevel", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], DetailMapConfiguration.prototype, "normalBlendMethod", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], DetailMapConfiguration.prototype, "isEnabled", undefined);

// node_modules/@babylonjs/core/Materials/standardMaterial.js
init_materialHelper_functions();
init_decorators_serialization();

// node_modules/@babylonjs/core/Materials/materialHelper.geometryrendering.js
init_math_vector();
var GeometryRenderingTextureClearType;
(function(GeometryRenderingTextureClearType2) {
  GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["Zero"] = 0] = "Zero";
  GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["One"] = 1] = "One";
  GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["MaxViewZ"] = 2] = "MaxViewZ";
})(GeometryRenderingTextureClearType || (GeometryRenderingTextureClearType = {}));

class MaterialHelperGeometryRendering {
  static CreateConfiguration(renderPassId) {
    MaterialHelperGeometryRendering._Configurations[renderPassId] = {
      defines: {},
      previousWorldMatrices: {},
      previousViewProjection: Matrix.Zero(),
      currentViewProjection: Matrix.Zero(),
      previousBones: {},
      lastUpdateFrameId: -1,
      excludedSkinnedMesh: [],
      reverseCulling: false
    };
    return MaterialHelperGeometryRendering._Configurations[renderPassId];
  }
  static DeleteConfiguration(renderPassId) {
    delete MaterialHelperGeometryRendering._Configurations[renderPassId];
  }
  static GetConfiguration(renderPassId) {
    return MaterialHelperGeometryRendering._Configurations[renderPassId];
  }
  static AddUniformsAndSamplers(uniforms, _samplers) {
    uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones");
  }
  static MarkAsDirty(renderPassId, meshes) {
    for (const mesh of meshes) {
      if (!mesh.subMeshes) {
        continue;
      }
      for (const subMesh of mesh.subMeshes) {
        subMesh._removeDrawWrapper(renderPassId);
      }
    }
  }
  static PrepareDefines(renderPassId, mesh, defines) {
    if (!defines._arePrePassDirty) {
      return;
    }
    const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId];
    if (!configuration) {
      return;
    }
    defines["PREPASS"] = true;
    defines["PREPASS_COLOR"] = false;
    defines["PREPASS_COLOR_INDEX"] = -1;
    let numMRT = 0;
    for (let i = 0;i < MaterialHelperGeometryRendering.GeometryTextureDescriptions.length; i++) {
      const geometryTextureDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[i];
      const defineName = geometryTextureDescription.define;
      const defineIndex = geometryTextureDescription.defineIndex;
      const index = configuration.defines[defineIndex];
      if (index !== undefined) {
        defines[defineName] = true;
        defines[defineIndex] = index;
        numMRT++;
      } else {
        defines[defineName] = false;
        delete defines[defineIndex];
      }
    }
    defines["SCENE_MRT_COUNT"] = numMRT;
    defines["BONES_VELOCITY_ENABLED"] = mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton && !mesh.skeleton.isUsingTextureForMatrices && configuration.excludedSkinnedMesh.indexOf(mesh) === -1;
  }
  static Bind(renderPassId, effect, mesh, world, material) {
    const configuration = MaterialHelperGeometryRendering._Configurations[renderPassId];
    if (!configuration) {
      return;
    }
    const scene = mesh.getScene();
    const engine = scene.getEngine();
    if (configuration.reverseCulling) {
      engine.setStateCullFaceType(scene._mirroredCameraPosition ? material.cullBackFaces : !material.cullBackFaces);
    }
    if (configuration.defines["PREPASS_VELOCITY_INDEX"] !== undefined || configuration.defines["PREPASS_VELOCITY_LINEAR_INDEX"] !== undefined) {
      if (!configuration.previousWorldMatrices[mesh.uniqueId]) {
        configuration.previousWorldMatrices[mesh.uniqueId] = world.clone();
      }
      if (!configuration.previousViewProjection) {
        configuration.previousViewProjection = scene.getTransformMatrix().clone();
        configuration.currentViewProjection = scene.getTransformMatrix().clone();
      }
      if (configuration.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {
        configuration.lastUpdateFrameId = engine.frameId;
        configuration.previousViewProjection.copyFrom(configuration.currentViewProjection);
        configuration.currentViewProjection.copyFrom(scene.getTransformMatrix());
      } else if (configuration.lastUpdateFrameId !== engine.frameId) {
        configuration.lastUpdateFrameId = engine.frameId;
        configuration.previousViewProjection.copyFrom(configuration.currentViewProjection);
      }
      effect.setMatrix("previousWorld", configuration.previousWorldMatrices[mesh.uniqueId]);
      effect.setMatrix("previousViewProjection", configuration.previousViewProjection);
      configuration.previousWorldMatrices[mesh.uniqueId] = world.clone();
      if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
        const skeleton2 = mesh.skeleton;
        if (!skeleton2.isUsingTextureForMatrices || effect.getUniformIndex("boneTextureWidth") === -1) {
          const matrices = skeleton2.getTransformMatrices(mesh);
          if (matrices) {
            if (!configuration.previousBones[mesh.uniqueId]) {
              configuration.previousBones[mesh.uniqueId] = matrices.slice();
            }
            effect.setMatrices("mPreviousBones", configuration.previousBones[mesh.uniqueId]);
            configuration.previousBones[mesh.uniqueId].set(matrices);
          }
        }
      }
    }
  }
}
MaterialHelperGeometryRendering.GeometryTextureDescriptions = [
  {
    type: 0,
    name: "Irradiance",
    clearType: 0,
    define: "PREPASS_IRRADIANCE",
    defineIndex: "PREPASS_IRRADIANCE_INDEX"
  },
  {
    type: 1,
    name: "WorldPosition",
    clearType: 0,
    define: "PREPASS_POSITION",
    defineIndex: "PREPASS_POSITION_INDEX"
  },
  {
    type: 2,
    name: "Velocity",
    clearType: 0,
    define: "PREPASS_VELOCITY",
    defineIndex: "PREPASS_VELOCITY_INDEX"
  },
  {
    type: 3,
    name: "Reflectivity",
    clearType: 0,
    define: "PREPASS_REFLECTIVITY",
    defineIndex: "PREPASS_REFLECTIVITY_INDEX"
  },
  {
    type: 5,
    name: "ViewDepth",
    clearType: 2,
    define: "PREPASS_DEPTH",
    defineIndex: "PREPASS_DEPTH_INDEX"
  },
  {
    type: 6,
    name: "ViewNormal",
    clearType: 0,
    define: "PREPASS_NORMAL",
    defineIndex: "PREPASS_NORMAL_INDEX"
  },
  {
    type: 7,
    name: "AlbedoSqrt",
    clearType: 0,
    define: "PREPASS_ALBEDO_SQRT",
    defineIndex: "PREPASS_ALBEDO_SQRT_INDEX"
  },
  {
    type: 8,
    name: "WorldNormal",
    clearType: 0,
    define: "PREPASS_WORLD_NORMAL",
    defineIndex: "PREPASS_WORLD_NORMAL_INDEX"
  },
  {
    type: 9,
    name: "LocalPosition",
    clearType: 0,
    define: "PREPASS_LOCAL_POSITION",
    defineIndex: "PREPASS_LOCAL_POSITION_INDEX"
  },
  {
    type: 10,
    name: "ScreenDepth",
    clearType: 1,
    define: "PREPASS_SCREENSPACE_DEPTH",
    defineIndex: "PREPASS_SCREENSPACE_DEPTH_INDEX"
  },
  {
    type: 11,
    name: "LinearVelocity",
    clearType: 0,
    define: "PREPASS_VELOCITY_LINEAR",
    defineIndex: "PREPASS_VELOCITY_LINEAR_INDEX"
  },
  {
    type: 12,
    name: "Albedo",
    clearType: 0,
    define: "PREPASS_ALBEDO",
    defineIndex: "PREPASS_ALBEDO_INDEX"
  }
];
MaterialHelperGeometryRendering._Configurations = {};

// node_modules/@babylonjs/core/Materials/standardMaterial.js
var onCreatedEffectParameters = { effect: null, subMesh: null };

class StandardMaterialDefines extends MaterialDefines {
  constructor(externalProperties) {
    super(externalProperties);
    this.MAINUV1 = false;
    this.MAINUV2 = false;
    this.MAINUV3 = false;
    this.MAINUV4 = false;
    this.MAINUV5 = false;
    this.MAINUV6 = false;
    this.DIFFUSE = false;
    this.DIFFUSEDIRECTUV = 0;
    this.BAKED_VERTEX_ANIMATION_TEXTURE = false;
    this.AMBIENT = false;
    this.AMBIENTDIRECTUV = 0;
    this.OPACITY = false;
    this.OPACITYDIRECTUV = 0;
    this.OPACITYRGB = false;
    this.REFLECTION = false;
    this.EMISSIVE = false;
    this.EMISSIVEDIRECTUV = 0;
    this.SPECULAR = false;
    this.SPECULARDIRECTUV = 0;
    this.BUMP = false;
    this.BUMPDIRECTUV = 0;
    this.PARALLAX = false;
    this.PARALLAX_RHS = false;
    this.PARALLAXOCCLUSION = false;
    this.SPECULAROVERALPHA = false;
    this.CLIPPLANE = false;
    this.CLIPPLANE2 = false;
    this.CLIPPLANE3 = false;
    this.CLIPPLANE4 = false;
    this.CLIPPLANE5 = false;
    this.CLIPPLANE6 = false;
    this.ALPHATEST = false;
    this.DEPTHPREPASS = false;
    this.ALPHAFROMDIFFUSE = false;
    this.POINTSIZE = false;
    this.FOG = false;
    this.SPECULARTERM = false;
    this.DIFFUSEFRESNEL = false;
    this.OPACITYFRESNEL = false;
    this.REFLECTIONFRESNEL = false;
    this.REFRACTIONFRESNEL = false;
    this.EMISSIVEFRESNEL = false;
    this.FRESNEL = false;
    this.NORMAL = false;
    this.TANGENT = false;
    this.UV1 = false;
    this.UV2 = false;
    this.UV3 = false;
    this.UV4 = false;
    this.UV5 = false;
    this.UV6 = false;
    this.VERTEXCOLOR = false;
    this.VERTEXALPHA = false;
    this.NUM_BONE_INFLUENCERS = 0;
    this.BonesPerMesh = 0;
    this.BONETEXTURE = false;
    this.BONES_VELOCITY_ENABLED = false;
    this.INSTANCES = false;
    this.THIN_INSTANCES = false;
    this.INSTANCESCOLOR = false;
    this.GLOSSINESS = false;
    this.ROUGHNESS = false;
    this.EMISSIVEASILLUMINATION = false;
    this.LINKEMISSIVEWITHDIFFUSE = false;
    this.REFLECTIONFRESNELFROMSPECULAR = false;
    this.LIGHTMAP = false;
    this.LIGHTMAPDIRECTUV = 0;
    this.OBJECTSPACE_NORMALMAP = false;
    this.USELIGHTMAPASSHADOWMAP = false;
    this.REFLECTIONMAP_3D = false;
    this.REFLECTIONMAP_SPHERICAL = false;
    this.REFLECTIONMAP_PLANAR = false;
    this.REFLECTIONMAP_CUBIC = false;
    this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
    this.USE_LOCAL_REFRACTIONMAP_CUBIC = false;
    this.REFLECTIONMAP_PROJECTION = false;
    this.REFLECTIONMAP_SKYBOX = false;
    this.REFLECTIONMAP_EXPLICIT = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
    this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
    this.REFLECTIONMAP_OPPOSITEZ = false;
    this.INVERTCUBICMAP = false;
    this.LOGARITHMICDEPTH = false;
    this.REFRACTION = false;
    this.REFRACTIONMAP_3D = false;
    this.REFLECTIONOVERALPHA = false;
    this.TWOSIDEDLIGHTING = false;
    this.SHADOWFLOAT = false;
    this.MORPHTARGETS = false;
    this.MORPHTARGETS_POSITION = false;
    this.MORPHTARGETS_NORMAL = false;
    this.MORPHTARGETS_TANGENT = false;
    this.MORPHTARGETS_UV = false;
    this.MORPHTARGETS_UV2 = false;
    this.MORPHTARGETS_COLOR = false;
    this.MORPHTARGETTEXTURE_HASPOSITIONS = false;
    this.MORPHTARGETTEXTURE_HASNORMALS = false;
    this.MORPHTARGETTEXTURE_HASTANGENTS = false;
    this.MORPHTARGETTEXTURE_HASUVS = false;
    this.MORPHTARGETTEXTURE_HASUV2S = false;
    this.MORPHTARGETTEXTURE_HASCOLORS = false;
    this.NUM_MORPH_INFLUENCERS = 0;
    this.MORPHTARGETS_TEXTURE = false;
    this.NONUNIFORMSCALING = false;
    this.PREMULTIPLYALPHA = false;
    this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false;
    this.ALPHABLEND = true;
    this.PREPASS = false;
    this.PREPASS_COLOR = false;
    this.PREPASS_COLOR_INDEX = -1;
    this.PREPASS_IRRADIANCE = false;
    this.PREPASS_IRRADIANCE_INDEX = -1;
    this.PREPASS_ALBEDO = false;
    this.PREPASS_ALBEDO_INDEX = -1;
    this.PREPASS_ALBEDO_SQRT = false;
    this.PREPASS_ALBEDO_SQRT_INDEX = -1;
    this.PREPASS_DEPTH = false;
    this.PREPASS_DEPTH_INDEX = -1;
    this.PREPASS_SCREENSPACE_DEPTH = false;
    this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1;
    this.PREPASS_NORMAL = false;
    this.PREPASS_NORMAL_INDEX = -1;
    this.PREPASS_NORMAL_WORLDSPACE = false;
    this.PREPASS_WORLD_NORMAL = false;
    this.PREPASS_WORLD_NORMAL_INDEX = -1;
    this.PREPASS_POSITION = false;
    this.PREPASS_POSITION_INDEX = -1;
    this.PREPASS_LOCAL_POSITION = false;
    this.PREPASS_LOCAL_POSITION_INDEX = -1;
    this.PREPASS_VELOCITY = false;
    this.PREPASS_VELOCITY_INDEX = -1;
    this.PREPASS_VELOCITY_LINEAR = false;
    this.PREPASS_VELOCITY_LINEAR_INDEX = -1;
    this.PREPASS_REFLECTIVITY = false;
    this.PREPASS_REFLECTIVITY_INDEX = -1;
    this.SCENE_MRT_COUNT = 0;
    this.RGBDLIGHTMAP = false;
    this.RGBDREFLECTION = false;
    this.RGBDREFRACTION = false;
    this.IMAGEPROCESSING = false;
    this.VIGNETTE = false;
    this.VIGNETTEBLENDMODEMULTIPLY = false;
    this.VIGNETTEBLENDMODEOPAQUE = false;
    this.TONEMAPPING = 0;
    this.CONTRAST = false;
    this.COLORCURVES = false;
    this.COLORGRADING = false;
    this.COLORGRADING3D = false;
    this.SAMPLER3DGREENDEPTH = false;
    this.SAMPLER3DBGRMAP = false;
    this.DITHER = false;
    this.IMAGEPROCESSINGPOSTPROCESS = false;
    this.SKIPFINALCOLORCLAMP = false;
    this.MULTIVIEW = false;
    this.ORDER_INDEPENDENT_TRANSPARENCY = false;
    this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;
    this.CAMERA_ORTHOGRAPHIC = false;
    this.CAMERA_PERSPECTIVE = false;
    this.AREALIGHTSUPPORTED = true;
    this.IS_REFLECTION_LINEAR = false;
    this.IS_REFRACTION_LINEAR = false;
    this.EXPOSURE = false;
    this.DECAL_AFTER_DETAIL = false;
    this.rebuild();
  }
  setReflectionMode(modeToEnable) {
    const modes = [
      "REFLECTIONMAP_CUBIC",
      "REFLECTIONMAP_EXPLICIT",
      "REFLECTIONMAP_PLANAR",
      "REFLECTIONMAP_PROJECTION",
      "REFLECTIONMAP_PROJECTION",
      "REFLECTIONMAP_SKYBOX",
      "REFLECTIONMAP_SPHERICAL",
      "REFLECTIONMAP_EQUIRECTANGULAR",
      "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
      "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
    ];
    for (const mode of modes) {
      this[mode] = mode === modeToEnable;
    }
  }
}

class StandardMaterial extends PushMaterial {
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    this._attachImageProcessingConfiguration(value);
    this._markAllSubMeshesAsTexturesDirty();
  }
  _attachImageProcessingConfiguration(configuration) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (!configuration) {
      this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
    } else {
      this._imageProcessingConfiguration = configuration;
    }
    if (this._imageProcessingConfiguration) {
      this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
        this._markAllSubMeshesAsImageProcessingDirty();
      });
    }
  }
  get isPrePassCapable() {
    return !this.disableDepthWrite;
  }
  get cameraColorCurvesEnabled() {
    return this.imageProcessingConfiguration.colorCurvesEnabled;
  }
  set cameraColorCurvesEnabled(value) {
    this.imageProcessingConfiguration.colorCurvesEnabled = value;
  }
  get cameraColorGradingEnabled() {
    return this.imageProcessingConfiguration.colorGradingEnabled;
  }
  set cameraColorGradingEnabled(value) {
    this.imageProcessingConfiguration.colorGradingEnabled = value;
  }
  get cameraToneMappingEnabled() {
    return this._imageProcessingConfiguration.toneMappingEnabled;
  }
  set cameraToneMappingEnabled(value) {
    this._imageProcessingConfiguration.toneMappingEnabled = value;
  }
  get cameraExposure() {
    return this._imageProcessingConfiguration.exposure;
  }
  set cameraExposure(value) {
    this._imageProcessingConfiguration.exposure = value;
  }
  get cameraContrast() {
    return this._imageProcessingConfiguration.contrast;
  }
  set cameraContrast(value) {
    this._imageProcessingConfiguration.contrast = value;
  }
  get cameraColorGradingTexture() {
    return this._imageProcessingConfiguration.colorGradingTexture;
  }
  set cameraColorGradingTexture(value) {
    this._imageProcessingConfiguration.colorGradingTexture = value;
  }
  get cameraColorCurves() {
    return this._imageProcessingConfiguration.colorCurves;
  }
  set cameraColorCurves(value) {
    this._imageProcessingConfiguration.colorCurves = value;
  }
  get canRenderToMRT() {
    return true;
  }
  constructor(name144, scene, forceGLSL = false) {
    super(name144, scene, undefined, forceGLSL || StandardMaterial.ForceGLSL);
    this._diffuseTexture = null;
    this._ambientTexture = null;
    this._opacityTexture = null;
    this._reflectionTexture = null;
    this._emissiveTexture = null;
    this._specularTexture = null;
    this._bumpTexture = null;
    this._lightmapTexture = null;
    this._refractionTexture = null;
    this.ambientColor = new Color3(0, 0, 0);
    this.diffuseColor = new Color3(1, 1, 1);
    this.specularColor = new Color3(1, 1, 1);
    this.emissiveColor = new Color3(0, 0, 0);
    this.specularPower = 64;
    this._useAlphaFromDiffuseTexture = false;
    this._useEmissiveAsIllumination = false;
    this._linkEmissiveWithDiffuse = false;
    this._useSpecularOverAlpha = false;
    this._useReflectionOverAlpha = false;
    this._disableLighting = false;
    this._useObjectSpaceNormalMap = false;
    this._useParallax = false;
    this._useParallaxOcclusion = false;
    this.parallaxScaleBias = 0.05;
    this._roughness = 0;
    this.indexOfRefraction = 0.98;
    this.invertRefractionY = true;
    this.alphaCutOff = 0.4;
    this._useLightmapAsShadowmap = false;
    this._useReflectionFresnelFromSpecular = false;
    this._useGlossinessFromSpecularMapAlpha = false;
    this._maxSimultaneousLights = 4;
    this._invertNormalMapX = false;
    this._invertNormalMapY = false;
    this._twoSidedLighting = false;
    this._applyDecalMapAfterDetailMap = false;
    this._shadersLoaded = false;
    this._renderTargets = new SmartArray(16);
    this._globalAmbientColor = new Color3(0, 0, 0);
    this._cacheHasRenderTargetTextures = false;
    this.detailMap = new DetailMapConfiguration(this);
    this._attachImageProcessingConfiguration(null);
    this.prePassConfiguration = new PrePassConfiguration;
    this.getRenderTargetTextures = () => {
      this._renderTargets.reset();
      if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
        this._renderTargets.push(this._reflectionTexture);
      }
      if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
        this._renderTargets.push(this._refractionTexture);
      }
      this._eventInfo.renderTargets = this._renderTargets;
      this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);
      return this._renderTargets;
    };
  }
  get hasRenderTargetTextures() {
    if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
      return true;
    }
    if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
      return true;
    }
    return this._cacheHasRenderTargetTextures;
  }
  getClassName() {
    return "StandardMaterial";
  }
  needAlphaBlending() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsBlend;
    }
    if (this._disableAlphaBlending) {
      return false;
    }
    return this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  }
  needAlphaTesting() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsTest;
    }
    return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST);
  }
  _shouldUseAlphaFromDiffuseTexture() {
    return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE;
  }
  _hasAlphaChannel() {
    return this._diffuseTexture != null && this._diffuseTexture.hasAlpha || this._opacityTexture != null;
  }
  getAlphaTestTexture() {
    return this._diffuseTexture;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances = false) {
    if (!this._uniformBufferLayoutBuilt) {
      this.buildUniformLayout();
    }
    const drawWrapper = subMesh._drawWrapper;
    if (drawWrapper.effect && this.isFrozen) {
      if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    if (!subMesh.materialDefines) {
      this._callbackPluginEventGeneric(4, this._eventInfo);
      subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames);
    }
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (this._isReadyForSubMesh(subMesh)) {
      return true;
    }
    const engine = scene.getEngine();
    defines._needNormals = PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
    PrepareDefinesForMultiview(scene, defines);
    const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;
    PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);
    PrepareDefinesForOIT(scene, defines, oit);
    MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines);
    if (defines._areTexturesDirty) {
      this._eventInfo.hasRenderTargetTextures = false;
      this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
      this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;
      defines._needUVs = false;
      for (let i = 1;i <= 6; ++i) {
        defines["MAINUV" + i] = false;
      }
      if (scene.texturesEnabled) {
        defines.DIFFUSEDIRECTUV = 0;
        defines.BUMPDIRECTUV = 0;
        defines.AMBIENTDIRECTUV = 0;
        defines.OPACITYDIRECTUV = 0;
        defines.EMISSIVEDIRECTUV = 0;
        defines.SPECULARDIRECTUV = 0;
        defines.LIGHTMAPDIRECTUV = 0;
        if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
          if (!this._diffuseTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
          }
        } else {
          defines.DIFFUSE = false;
        }
        if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
          if (!this._ambientTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
          }
        } else {
          defines.AMBIENT = false;
        }
        if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
          if (!this._opacityTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
            defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
          }
        } else {
          defines.OPACITY = false;
        }
        if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
          if (!this._reflectionTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            defines._needNormals = true;
            defines.REFLECTION = true;
            defines.ROUGHNESS = this._roughness > 0;
            defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
            defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;
            defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
            defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ;
            defines.RGBDREFLECTION = this._reflectionTexture.isRGBD;
            switch (this._reflectionTexture.coordinatesMode) {
              case Texture.EXPLICIT_MODE:
                defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
                break;
              case Texture.PLANAR_MODE:
                defines.setReflectionMode("REFLECTIONMAP_PLANAR");
                break;
              case Texture.PROJECTION_MODE:
                defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
                break;
              case Texture.SKYBOX_MODE:
                defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
                break;
              case Texture.SPHERICAL_MODE:
                defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
                break;
              case Texture.EQUIRECTANGULAR_MODE:
                defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
                break;
              case Texture.FIXED_EQUIRECTANGULAR_MODE:
                defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
                break;
              case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
                break;
              case Texture.CUBIC_MODE:
              case Texture.INVCUBIC_MODE:
              default:
                defines.setReflectionMode("REFLECTIONMAP_CUBIC");
                break;
            }
            defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
          }
        } else {
          defines.REFLECTION = false;
          defines.REFLECTIONMAP_OPPOSITEZ = false;
        }
        if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
          if (!this._emissiveTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
          }
        } else {
          defines.EMISSIVE = false;
        }
        if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
          if (!this._lightmapTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
            defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
            defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
          }
        } else {
          defines.LIGHTMAP = false;
        }
        if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
          if (!this._specularTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
            defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
          }
        } else {
          defines.SPECULAR = false;
        }
        if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
          if (!this._bumpTexture.isReady()) {
            return false;
          } else {
            PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
            defines.PARALLAX = this._useParallax;
            defines.PARALLAX_RHS = scene.useRightHandedSystem;
            defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
          }
          defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
        } else {
          defines.BUMP = false;
          defines.PARALLAX = false;
          defines.PARALLAX_RHS = false;
          defines.PARALLAXOCCLUSION = false;
        }
        if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
          if (!this._refractionTexture.isReadyOrNotBlocking()) {
            return false;
          } else {
            defines._needUVs = true;
            defines.REFRACTION = true;
            defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
            defines.RGBDREFRACTION = this._refractionTexture.isRGBD;
            defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false;
          }
        } else {
          defines.REFRACTION = false;
        }
        defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
      } else {
        defines.DIFFUSE = false;
        defines.AMBIENT = false;
        defines.OPACITY = false;
        defines.REFLECTION = false;
        defines.EMISSIVE = false;
        defines.LIGHTMAP = false;
        defines.BUMP = false;
        defines.REFRACTION = false;
      }
      defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
      defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
      defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
      defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
      defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;
      defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null;
      defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh);
    }
    this._eventInfo.isReadyForSubMesh = true;
    this._eventInfo.defines = defines;
    this._eventInfo.subMesh = subMesh;
    this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
    if (!this._eventInfo.isReadyForSubMesh) {
      return false;
    }
    if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
      if (!this._imageProcessingConfiguration.isReady()) {
        return false;
      }
      this._imageProcessingConfiguration.prepareDefines(defines);
      defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace;
      defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace;
    }
    if (defines._areFresnelDirty) {
      if (StandardMaterial.FresnelEnabled) {
        if (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) {
          defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled;
          defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
          defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled;
          defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
          defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled;
          defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled;
          defines._needNormals = true;
          defines.FRESNEL = true;
        }
      } else {
        defines.FRESNEL = false;
      }
    }
    if (defines["AREALIGHTUSED"]) {
      for (let index = 0;index < mesh.lightSources.length; index++) {
        if (!mesh.lightSources[index]._isReady()) {
          return false;
        }
      }
    }
    PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap);
    PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
    this._eventInfo.defines = defines;
    this._eventInfo.mesh = mesh;
    this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);
    PrepareDefinesForAttributes(mesh, defines, true, true, true);
    this._callbackPluginEventPrepareDefines(this._eventInfo);
    let forceWasNotReadyPreviously = false;
    if (defines.isDirty) {
      const lightDisposed = defines._areLightsDisposed;
      defines.markAsProcessed();
      const fallbacks = new EffectFallbacks;
      if (defines.REFLECTION) {
        fallbacks.addFallback(0, "REFLECTION");
      }
      if (defines.SPECULAR) {
        fallbacks.addFallback(0, "SPECULAR");
      }
      if (defines.BUMP) {
        fallbacks.addFallback(0, "BUMP");
      }
      if (defines.PARALLAX) {
        fallbacks.addFallback(1, "PARALLAX");
      }
      if (defines.PARALLAX_RHS) {
        fallbacks.addFallback(1, "PARALLAX_RHS");
      }
      if (defines.PARALLAXOCCLUSION) {
        fallbacks.addFallback(0, "PARALLAXOCCLUSION");
      }
      if (defines.SPECULAROVERALPHA) {
        fallbacks.addFallback(0, "SPECULAROVERALPHA");
      }
      if (defines.FOG) {
        fallbacks.addFallback(1, "FOG");
      }
      if (defines.POINTSIZE) {
        fallbacks.addFallback(0, "POINTSIZE");
      }
      if (defines.LOGARITHMICDEPTH) {
        fallbacks.addFallback(0, "LOGARITHMICDEPTH");
      }
      HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
      if (defines.SPECULARTERM) {
        fallbacks.addFallback(0, "SPECULARTERM");
      }
      if (defines.DIFFUSEFRESNEL) {
        fallbacks.addFallback(1, "DIFFUSEFRESNEL");
      }
      if (defines.OPACITYFRESNEL) {
        fallbacks.addFallback(2, "OPACITYFRESNEL");
      }
      if (defines.REFLECTIONFRESNEL) {
        fallbacks.addFallback(3, "REFLECTIONFRESNEL");
      }
      if (defines.EMISSIVEFRESNEL) {
        fallbacks.addFallback(4, "EMISSIVEFRESNEL");
      }
      if (defines.FRESNEL) {
        fallbacks.addFallback(4, "FRESNEL");
      }
      if (defines.MULTIVIEW) {
        fallbacks.addFallback(0, "MULTIVIEW");
      }
      const attribs = [VertexBuffer.PositionKind];
      if (defines.NORMAL) {
        attribs.push(VertexBuffer.NormalKind);
      }
      if (defines.TANGENT) {
        attribs.push(VertexBuffer.TangentKind);
      }
      for (let i = 1;i <= 6; ++i) {
        if (defines["UV" + i]) {
          attribs.push(`uv${i === 1 ? "" : i}`);
        }
      }
      if (defines.VERTEXCOLOR) {
        attribs.push(VertexBuffer.ColorKind);
      }
      PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
      PrepareAttributesForInstances(attribs, defines);
      PrepareAttributesForMorphTargets(attribs, mesh, defines);
      PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
      let shaderName = "default";
      const uniforms = [
        "world",
        "view",
        "viewProjection",
        "vEyePosition",
        "vLightsType",
        "vAmbientColor",
        "vDiffuseColor",
        "vSpecularColor",
        "vEmissiveColor",
        "visibility",
        "vFogInfos",
        "vFogColor",
        "pointSize",
        "vDiffuseInfos",
        "vAmbientInfos",
        "vOpacityInfos",
        "vReflectionInfos",
        "vEmissiveInfos",
        "vSpecularInfos",
        "vBumpInfos",
        "vLightmapInfos",
        "vRefractionInfos",
        "mBones",
        "diffuseMatrix",
        "ambientMatrix",
        "opacityMatrix",
        "reflectionMatrix",
        "emissiveMatrix",
        "specularMatrix",
        "bumpMatrix",
        "normalMatrix",
        "lightmapMatrix",
        "refractionMatrix",
        "diffuseLeftColor",
        "diffuseRightColor",
        "opacityParts",
        "reflectionLeftColor",
        "reflectionRightColor",
        "emissiveLeftColor",
        "emissiveRightColor",
        "refractionLeftColor",
        "refractionRightColor",
        "vReflectionPosition",
        "vReflectionSize",
        "vRefractionPosition",
        "vRefractionSize",
        "logarithmicDepthConstant",
        "vTangentSpaceParams",
        "alphaCutOff",
        "boneTextureWidth",
        "morphTargetTextureInfo",
        "morphTargetTextureIndices"
      ];
      const samplers = [
        "diffuseSampler",
        "ambientSampler",
        "opacitySampler",
        "reflectionCubeSampler",
        "reflection2DSampler",
        "emissiveSampler",
        "specularSampler",
        "bumpSampler",
        "lightmapSampler",
        "refractionCubeSampler",
        "refraction2DSampler",
        "boneSampler",
        "morphTargets",
        "oitDepthSampler",
        "oitFrontColorSampler",
        "areaLightsLTC1Sampler",
        "areaLightsLTC2Sampler"
      ];
      const uniformBuffers = ["Material", "Scene", "Mesh"];
      const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS };
      this._eventInfo.fallbacks = fallbacks;
      this._eventInfo.fallbackRank = 0;
      this._eventInfo.defines = defines;
      this._eventInfo.uniforms = uniforms;
      this._eventInfo.attributes = attribs;
      this._eventInfo.samplers = samplers;
      this._eventInfo.uniformBuffersNames = uniformBuffers;
      this._eventInfo.customCode = undefined;
      this._eventInfo.mesh = mesh;
      this._eventInfo.indexParameters = indexParameters;
      this._callbackPluginEventGeneric(128, this._eventInfo);
      MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers);
      PrePassConfiguration.AddUniforms(uniforms);
      PrePassConfiguration.AddSamplers(samplers);
      if (ImageProcessingConfiguration) {
        ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
        ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
      }
      PrepareUniformsAndSamplersList({
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines,
        maxSimultaneousLights: this._maxSimultaneousLights
      });
      addClipPlaneUniforms(uniforms);
      const csnrOptions = {};
      if (this.customShaderNameResolve) {
        shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
      }
      const join6 = defines.toString();
      const previousEffect = subMesh.effect;
      let effect = scene.getEngine().createEffect(shaderName, {
        attributes: attribs,
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: this.onCompiled,
        onError: this.onError,
        indexParameters,
        processFinalCode: csnrOptions.processFinalCode,
        processCodeAfterIncludes: this._eventInfo.customCode,
        multiTarget: defines.PREPASS,
        shaderLanguage: this._shaderLanguage,
        extraInitializationsAsync: this._shadersLoaded ? undefined : async () => {
          if (this._shaderLanguage === 1) {
            await Promise.all([Promise.resolve().then(() => (init_default_vertex(), exports_default_vertex)), Promise.resolve().then(() => (init_default_fragment(), exports_default_fragment))]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_default_vertex2(), exports_default_vertex2)), Promise.resolve().then(() => (init_default_fragment2(), exports_default_fragment2))]);
          }
          this._shadersLoaded = true;
        }
      }, engine);
      this._eventInfo.customCode = undefined;
      if (effect) {
        if (this._onEffectCreatedObservable) {
          onCreatedEffectParameters.effect = effect;
          onCreatedEffectParameters.subMesh = subMesh;
          this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
        }
        if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
          effect = previousEffect;
          defines.markAsUnprocessed();
          forceWasNotReadyPreviously = this.isFrozen;
          if (lightDisposed) {
            defines._areLightsDisposed = true;
            return false;
          }
        } else {
          scene.resetCachedMaterial();
          subMesh.setEffect(effect, defines, this._materialContext);
        }
      }
    }
    if (!subMesh.effect || !subMesh.effect.isReady()) {
      return false;
    }
    defines._renderId = scene.getRenderId();
    drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;
    drawWrapper._wasPreviouslyUsingInstances = useInstances;
    this._checkScenePerformancePriority();
    return true;
  }
  buildUniformLayout() {
    const ubo = this._uniformBuffer;
    ubo.addUniform("diffuseLeftColor", 4);
    ubo.addUniform("diffuseRightColor", 4);
    ubo.addUniform("opacityParts", 4);
    ubo.addUniform("reflectionLeftColor", 4);
    ubo.addUniform("reflectionRightColor", 4);
    ubo.addUniform("refractionLeftColor", 4);
    ubo.addUniform("refractionRightColor", 4);
    ubo.addUniform("emissiveLeftColor", 4);
    ubo.addUniform("emissiveRightColor", 4);
    ubo.addUniform("vDiffuseInfos", 2);
    ubo.addUniform("vAmbientInfos", 2);
    ubo.addUniform("vOpacityInfos", 2);
    ubo.addUniform("vReflectionInfos", 2);
    ubo.addUniform("vReflectionPosition", 3);
    ubo.addUniform("vReflectionSize", 3);
    ubo.addUniform("vEmissiveInfos", 2);
    ubo.addUniform("vLightmapInfos", 2);
    ubo.addUniform("vSpecularInfos", 2);
    ubo.addUniform("vBumpInfos", 3);
    ubo.addUniform("diffuseMatrix", 16);
    ubo.addUniform("ambientMatrix", 16);
    ubo.addUniform("opacityMatrix", 16);
    ubo.addUniform("reflectionMatrix", 16);
    ubo.addUniform("emissiveMatrix", 16);
    ubo.addUniform("lightmapMatrix", 16);
    ubo.addUniform("specularMatrix", 16);
    ubo.addUniform("bumpMatrix", 16);
    ubo.addUniform("vTangentSpaceParams", 2);
    ubo.addUniform("pointSize", 1);
    ubo.addUniform("alphaCutOff", 1);
    ubo.addUniform("refractionMatrix", 16);
    ubo.addUniform("vRefractionInfos", 4);
    ubo.addUniform("vRefractionPosition", 3);
    ubo.addUniform("vRefractionSize", 3);
    ubo.addUniform("vSpecularColor", 4);
    ubo.addUniform("vEmissiveColor", 3);
    ubo.addUniform("vDiffuseColor", 4);
    ubo.addUniform("vAmbientColor", 3);
    super.buildUniformLayout();
  }
  bindForSubMesh(world, mesh, subMesh) {
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (!defines) {
      return;
    }
    const effect = subMesh.effect;
    if (!effect) {
      return;
    }
    this._activeEffect = effect;
    mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
    mesh.transferToEffect(world);
    this._uniformBuffer.bindToEffect(effect, "Material");
    this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);
    MaterialHelperGeometryRendering.Bind(scene.getEngine().currentRenderPassId, this._activeEffect, mesh, world, this);
    this._eventInfo.subMesh = subMesh;
    this._callbackPluginEventHardBindForSubMesh(this._eventInfo);
    if (defines.OBJECTSPACE_NORMALMAP) {
      world.toNormalMatrix(this._normalMatrix);
      this.bindOnlyNormalMatrix(this._normalMatrix);
    }
    const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
    BindBonesParameters(mesh, effect);
    const ubo = this._uniformBuffer;
    if (mustRebind) {
      this.bindViewProjection(effect);
      if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) {
        if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
          if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
            ubo.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
            ubo.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
          }
          if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
            ubo.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
          }
          if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
            ubo.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
            ubo.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
          }
          if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
            ubo.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
            ubo.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
          }
          if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
            ubo.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
            ubo.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
          }
        }
        if (scene.texturesEnabled) {
          if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
            ubo.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
            BindTextureMatrix(this._diffuseTexture, ubo, "diffuse");
          }
          if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
            ubo.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
            BindTextureMatrix(this._ambientTexture, ubo, "ambient");
          }
          if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
            ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
            BindTextureMatrix(this._opacityTexture, ubo, "opacity");
          }
          if (this._hasAlphaChannel()) {
            ubo.updateFloat("alphaCutOff", this.alphaCutOff);
          }
          if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
            ubo.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
            ubo.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
            if (this._reflectionTexture.boundingBoxSize) {
              const cubeTexture = this._reflectionTexture;
              ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
              ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
            }
          } else {
            ubo.updateFloat2("vReflectionInfos", 0, this.roughness);
          }
          if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
            ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
            BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
          }
          if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
            ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
            BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
          }
          if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
            ubo.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
            BindTextureMatrix(this._specularTexture, ubo, "specular");
          }
          if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
            ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1 / this._bumpTexture.level, this.parallaxScaleBias);
            BindTextureMatrix(this._bumpTexture, ubo, "bump");
            if (scene._mirroredCameraPosition) {
              ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1);
            } else {
              ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1);
            }
          }
          if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
            let depth = 1;
            if (!this._refractionTexture.isCube) {
              ubo.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
              if (this._refractionTexture.depth) {
                depth = this._refractionTexture.depth;
              }
            }
            ubo.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
            if (this._refractionTexture.boundingBoxSize) {
              const cubeTexture = this._refractionTexture;
              ubo.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition);
              ubo.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize);
            }
          }
        }
        if (this.pointsCloud) {
          ubo.updateFloat("pointSize", this.pointSize);
        }
        ubo.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
        ubo.updateColor3("vEmissiveColor", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly);
        ubo.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha);
        scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
        ubo.updateColor3("vAmbientColor", this._globalAmbientColor);
      }
      if (scene.texturesEnabled) {
        if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
          effect.setTexture("diffuseSampler", this._diffuseTexture);
        }
        if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
          effect.setTexture("ambientSampler", this._ambientTexture);
        }
        if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
          effect.setTexture("opacitySampler", this._opacityTexture);
        }
        if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
          if (this._reflectionTexture.isCube) {
            effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
          } else {
            effect.setTexture("reflection2DSampler", this._reflectionTexture);
          }
        }
        if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
          effect.setTexture("emissiveSampler", this._emissiveTexture);
        }
        if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
          effect.setTexture("lightmapSampler", this._lightmapTexture);
        }
        if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
          effect.setTexture("specularSampler", this._specularTexture);
        }
        if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
          effect.setTexture("bumpSampler", this._bumpTexture);
        }
        if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
          if (this._refractionTexture.isCube) {
            effect.setTexture("refractionCubeSampler", this._refractionTexture);
          } else {
            effect.setTexture("refraction2DSampler", this._refractionTexture);
          }
        }
      }
      if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {
        this.getScene().depthPeelingRenderer.bind(effect);
      }
      this._eventInfo.subMesh = subMesh;
      this._callbackPluginEventBindForSubMesh(this._eventInfo);
      bindClipPlane(effect, this, scene);
      this.bindEyePosition(effect);
    } else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
      this._needToBindSceneUbo = true;
    }
    if (mustRebind || !this.isFrozen) {
      if (scene.lightsEnabled && !this._disableLighting) {
        BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
      }
      if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture || mesh.receiveShadows || defines.PREPASS) {
        this.bindView(effect);
      }
      BindFogParameters(scene, mesh, effect);
      if (defines.NUM_MORPH_INFLUENCERS) {
        BindMorphTargetParameters(mesh, effect);
      }
      if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {
        mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES);
      }
      if (this.useLogarithmicDepth) {
        BindLogDepth(defines, effect, scene);
      }
      if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
        this._imageProcessingConfiguration.bind(this._activeEffect);
      }
    }
    this._afterBind(mesh, this._activeEffect, subMesh);
    ubo.update();
  }
  getAnimatables() {
    const results = super.getAnimatables();
    if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
      results.push(this._diffuseTexture);
    }
    if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
      results.push(this._ambientTexture);
    }
    if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
      results.push(this._opacityTexture);
    }
    if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
      results.push(this._reflectionTexture);
    }
    if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
      results.push(this._emissiveTexture);
    }
    if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
      results.push(this._specularTexture);
    }
    if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
      results.push(this._bumpTexture);
    }
    if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
      results.push(this._lightmapTexture);
    }
    if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
      results.push(this._refractionTexture);
    }
    return results;
  }
  getActiveTextures() {
    const activeTextures = super.getActiveTextures();
    if (this._diffuseTexture) {
      activeTextures.push(this._diffuseTexture);
    }
    if (this._ambientTexture) {
      activeTextures.push(this._ambientTexture);
    }
    if (this._opacityTexture) {
      activeTextures.push(this._opacityTexture);
    }
    if (this._reflectionTexture) {
      activeTextures.push(this._reflectionTexture);
    }
    if (this._emissiveTexture) {
      activeTextures.push(this._emissiveTexture);
    }
    if (this._specularTexture) {
      activeTextures.push(this._specularTexture);
    }
    if (this._bumpTexture) {
      activeTextures.push(this._bumpTexture);
    }
    if (this._lightmapTexture) {
      activeTextures.push(this._lightmapTexture);
    }
    if (this._refractionTexture) {
      activeTextures.push(this._refractionTexture);
    }
    return activeTextures;
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    if (this._diffuseTexture === texture) {
      return true;
    }
    if (this._ambientTexture === texture) {
      return true;
    }
    if (this._opacityTexture === texture) {
      return true;
    }
    if (this._reflectionTexture === texture) {
      return true;
    }
    if (this._emissiveTexture === texture) {
      return true;
    }
    if (this._specularTexture === texture) {
      return true;
    }
    if (this._bumpTexture === texture) {
      return true;
    }
    if (this._lightmapTexture === texture) {
      return true;
    }
    if (this._refractionTexture === texture) {
      return true;
    }
    return false;
  }
  dispose(forceDisposeEffect, forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._diffuseTexture?.dispose();
      this._ambientTexture?.dispose();
      this._opacityTexture?.dispose();
      this._reflectionTexture?.dispose();
      this._emissiveTexture?.dispose();
      this._specularTexture?.dispose();
      this._bumpTexture?.dispose();
      this._lightmapTexture?.dispose();
      this._refractionTexture?.dispose();
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    super.dispose(forceDisposeEffect, forceDisposeTextures);
  }
  clone(name144, cloneTexturesOnlyOnce = true, rootUrl = "") {
    const result = SerializationHelper.Clone(() => new StandardMaterial(name144, this.getScene()), this, { cloneTexturesOnlyOnce });
    result.name = name144;
    result.id = name144;
    this.stencil.copyTo(result.stencil);
    this._clonePlugins(result, rootUrl);
    return result;
  }
  static Parse(source, scene, rootUrl) {
    const material = SerializationHelper.Parse(() => new StandardMaterial(source.name, scene), source, scene, rootUrl);
    if (source.stencil) {
      material.stencil.parse(source.stencil, scene, rootUrl);
    }
    Material._ParsePlugins(source, material, scene, rootUrl);
    return material;
  }
  static get DiffuseTextureEnabled() {
    return MaterialFlags.DiffuseTextureEnabled;
  }
  static set DiffuseTextureEnabled(value) {
    MaterialFlags.DiffuseTextureEnabled = value;
  }
  static get DetailTextureEnabled() {
    return MaterialFlags.DetailTextureEnabled;
  }
  static set DetailTextureEnabled(value) {
    MaterialFlags.DetailTextureEnabled = value;
  }
  static get AmbientTextureEnabled() {
    return MaterialFlags.AmbientTextureEnabled;
  }
  static set AmbientTextureEnabled(value) {
    MaterialFlags.AmbientTextureEnabled = value;
  }
  static get OpacityTextureEnabled() {
    return MaterialFlags.OpacityTextureEnabled;
  }
  static set OpacityTextureEnabled(value) {
    MaterialFlags.OpacityTextureEnabled = value;
  }
  static get ReflectionTextureEnabled() {
    return MaterialFlags.ReflectionTextureEnabled;
  }
  static set ReflectionTextureEnabled(value) {
    MaterialFlags.ReflectionTextureEnabled = value;
  }
  static get EmissiveTextureEnabled() {
    return MaterialFlags.EmissiveTextureEnabled;
  }
  static set EmissiveTextureEnabled(value) {
    MaterialFlags.EmissiveTextureEnabled = value;
  }
  static get SpecularTextureEnabled() {
    return MaterialFlags.SpecularTextureEnabled;
  }
  static set SpecularTextureEnabled(value) {
    MaterialFlags.SpecularTextureEnabled = value;
  }
  static get BumpTextureEnabled() {
    return MaterialFlags.BumpTextureEnabled;
  }
  static set BumpTextureEnabled(value) {
    MaterialFlags.BumpTextureEnabled = value;
  }
  static get LightmapTextureEnabled() {
    return MaterialFlags.LightmapTextureEnabled;
  }
  static set LightmapTextureEnabled(value) {
    MaterialFlags.LightmapTextureEnabled = value;
  }
  static get RefractionTextureEnabled() {
    return MaterialFlags.RefractionTextureEnabled;
  }
  static set RefractionTextureEnabled(value) {
    MaterialFlags.RefractionTextureEnabled = value;
  }
  static get ColorGradingTextureEnabled() {
    return MaterialFlags.ColorGradingTextureEnabled;
  }
  static set ColorGradingTextureEnabled(value) {
    MaterialFlags.ColorGradingTextureEnabled = value;
  }
  static get FresnelEnabled() {
    return MaterialFlags.FresnelEnabled;
  }
  static set FresnelEnabled(value) {
    MaterialFlags.FresnelEnabled = value;
  }
}
StandardMaterial.ForceGLSL = false;
__decorate([
  serializeAsTexture("diffuseTexture")
], StandardMaterial.prototype, "_diffuseTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], StandardMaterial.prototype, "diffuseTexture", undefined);
__decorate([
  serializeAsTexture("ambientTexture")
], StandardMaterial.prototype, "_ambientTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "ambientTexture", undefined);
__decorate([
  serializeAsTexture("opacityTexture")
], StandardMaterial.prototype, "_opacityTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], StandardMaterial.prototype, "opacityTexture", undefined);
__decorate([
  serializeAsTexture("reflectionTexture")
], StandardMaterial.prototype, "_reflectionTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "reflectionTexture", undefined);
__decorate([
  serializeAsTexture("emissiveTexture")
], StandardMaterial.prototype, "_emissiveTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "emissiveTexture", undefined);
__decorate([
  serializeAsTexture("specularTexture")
], StandardMaterial.prototype, "_specularTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "specularTexture", undefined);
__decorate([
  serializeAsTexture("bumpTexture")
], StandardMaterial.prototype, "_bumpTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "bumpTexture", undefined);
__decorate([
  serializeAsTexture("lightmapTexture")
], StandardMaterial.prototype, "_lightmapTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "lightmapTexture", undefined);
__decorate([
  serializeAsTexture("refractionTexture")
], StandardMaterial.prototype, "_refractionTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "refractionTexture", undefined);
__decorate([
  serializeAsColor3("ambient")
], StandardMaterial.prototype, "ambientColor", undefined);
__decorate([
  serializeAsColor3("diffuse")
], StandardMaterial.prototype, "diffuseColor", undefined);
__decorate([
  serializeAsColor3("specular")
], StandardMaterial.prototype, "specularColor", undefined);
__decorate([
  serializeAsColor3("emissive")
], StandardMaterial.prototype, "emissiveColor", undefined);
__decorate([
  serialize()
], StandardMaterial.prototype, "specularPower", undefined);
__decorate([
  serialize("useAlphaFromDiffuseTexture")
], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", undefined);
__decorate([
  serialize("useEmissiveAsIllumination")
], StandardMaterial.prototype, "_useEmissiveAsIllumination", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useEmissiveAsIllumination", undefined);
__decorate([
  serialize("linkEmissiveWithDiffuse")
], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "linkEmissiveWithDiffuse", undefined);
__decorate([
  serialize("useSpecularOverAlpha")
], StandardMaterial.prototype, "_useSpecularOverAlpha", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useSpecularOverAlpha", undefined);
__decorate([
  serialize("useReflectionOverAlpha")
], StandardMaterial.prototype, "_useReflectionOverAlpha", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useReflectionOverAlpha", undefined);
__decorate([
  serialize("disableLighting")
], StandardMaterial.prototype, "_disableLighting", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial.prototype, "disableLighting", undefined);
__decorate([
  serialize("useObjectSpaceNormalMap")
], StandardMaterial.prototype, "_useObjectSpaceNormalMap", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useObjectSpaceNormalMap", undefined);
__decorate([
  serialize("useParallax")
], StandardMaterial.prototype, "_useParallax", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useParallax", undefined);
__decorate([
  serialize("useParallaxOcclusion")
], StandardMaterial.prototype, "_useParallaxOcclusion", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useParallaxOcclusion", undefined);
__decorate([
  serialize()
], StandardMaterial.prototype, "parallaxScaleBias", undefined);
__decorate([
  serialize("roughness")
], StandardMaterial.prototype, "_roughness", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "roughness", undefined);
__decorate([
  serialize()
], StandardMaterial.prototype, "indexOfRefraction", undefined);
__decorate([
  serialize()
], StandardMaterial.prototype, "invertRefractionY", undefined);
__decorate([
  serialize()
], StandardMaterial.prototype, "alphaCutOff", undefined);
__decorate([
  serialize("useLightmapAsShadowmap")
], StandardMaterial.prototype, "_useLightmapAsShadowmap", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useLightmapAsShadowmap", undefined);
__decorate([
  serializeAsFresnelParameters("diffuseFresnelParameters")
], StandardMaterial.prototype, "_diffuseFresnelParameters", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "diffuseFresnelParameters", undefined);
__decorate([
  serializeAsFresnelParameters("opacityFresnelParameters")
], StandardMaterial.prototype, "_opacityFresnelParameters", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
], StandardMaterial.prototype, "opacityFresnelParameters", undefined);
__decorate([
  serializeAsFresnelParameters("reflectionFresnelParameters")
], StandardMaterial.prototype, "_reflectionFresnelParameters", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "reflectionFresnelParameters", undefined);
__decorate([
  serializeAsFresnelParameters("refractionFresnelParameters")
], StandardMaterial.prototype, "_refractionFresnelParameters", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "refractionFresnelParameters", undefined);
__decorate([
  serializeAsFresnelParameters("emissiveFresnelParameters")
], StandardMaterial.prototype, "_emissiveFresnelParameters", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "emissiveFresnelParameters", undefined);
__decorate([
  serialize("useReflectionFresnelFromSpecular")
], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", undefined);
__decorate([
  serialize("useGlossinessFromSpecularMapAlpha")
], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", undefined);
__decorate([
  serialize("maxSimultaneousLights")
], StandardMaterial.prototype, "_maxSimultaneousLights", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial.prototype, "maxSimultaneousLights", undefined);
__decorate([
  serialize("invertNormalMapX")
], StandardMaterial.prototype, "_invertNormalMapX", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "invertNormalMapX", undefined);
__decorate([
  serialize("invertNormalMapY")
], StandardMaterial.prototype, "_invertNormalMapY", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "invertNormalMapY", undefined);
__decorate([
  serialize("twoSidedLighting")
], StandardMaterial.prototype, "_twoSidedLighting", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial.prototype, "twoSidedLighting", undefined);
__decorate([
  serialize("applyDecalMapAfterDetailMap")
], StandardMaterial.prototype, "_applyDecalMapAfterDetailMap", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], StandardMaterial.prototype, "applyDecalMapAfterDetailMap", undefined);
RegisterClass("BABYLON.StandardMaterial", StandardMaterial);
Scene.DefaultMaterialFactory = (scene) => {
  return new StandardMaterial("default material", scene);
};

// node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js
init_logger();
init_texture();

// node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicTexture.js
init_thinEngine();
init_internalTexture();
ThinEngine.prototype.createDynamicTexture = function(width, height, generateMipMaps, samplingMode) {
  const texture = new InternalTexture(this, 4);
  texture.baseWidth = width;
  texture.baseHeight = height;
  if (generateMipMaps) {
    width = this.needPOTTextures ? GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
    height = this.needPOTTextures ? GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  }
  texture.width = width;
  texture.height = height;
  texture.isReady = false;
  texture.generateMipMaps = generateMipMaps;
  texture.samplingMode = samplingMode;
  this.updateTextureSamplingMode(samplingMode, texture);
  this._internalTexturesCache.push(texture);
  return texture;
};
ThinEngine.prototype.updateDynamicTexture = function(texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, allowGPUOptimization = false) {
  if (!texture) {
    return;
  }
  const gl = this._gl;
  const target = gl.TEXTURE_2D;
  const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture);
  this._unpackFlipY(invertY === undefined ? texture.invertY : invertY);
  if (premulAlpha) {
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  }
  const textureType = this._getWebGLTextureType(texture.type);
  const glformat = this._getInternalFormat(format ? format : texture.format);
  const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat);
  gl.texImage2D(target, 0, internalFormat, glformat, textureType, source);
  if (texture.generateMipMaps) {
    gl.generateMipmap(target);
  }
  if (!wasPreviouslyBound) {
    this._bindTextureDirectly(target, null);
  }
  if (premulAlpha) {
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  }
  if (format) {
    texture.format = format;
  }
  texture._dynamicTextureSource = source;
  texture._premulAlpha = premulAlpha;
  texture.invertY = invertY || false;
  texture.isReady = true;
};

// node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js
class DynamicTexture extends Texture {
  constructor(name144, canvasOrSize, sceneOrOptions, generateMipMaps = false, samplingMode = 3, format = 5, invertY) {
    const isScene = !sceneOrOptions || sceneOrOptions._isScene;
    const scene = isScene ? sceneOrOptions : sceneOrOptions?.scene;
    const noMipmap = isScene ? !generateMipMaps : sceneOrOptions;
    super(null, scene, noMipmap, invertY, samplingMode, undefined, undefined, undefined, undefined, format);
    this.name = name144;
    this.wrapU = Texture.CLAMP_ADDRESSMODE;
    this.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._generateMipMaps = generateMipMaps;
    const engine = this._getEngine();
    if (!engine) {
      return;
    }
    if (canvasOrSize.getContext) {
      this._canvas = canvasOrSize;
      this._ownCanvas = false;
      this._texture = engine.createDynamicTexture(this._canvas.width, this._canvas.height, generateMipMaps, samplingMode);
    } else {
      this._canvas = engine.createCanvas(1, 1);
      this._ownCanvas = true;
      const optionsAsSize = canvasOrSize;
      if (optionsAsSize.width || optionsAsSize.width === 0) {
        this._texture = engine.createDynamicTexture(optionsAsSize.width, optionsAsSize.height, generateMipMaps, samplingMode);
      } else {
        this._texture = engine.createDynamicTexture(canvasOrSize, canvasOrSize, generateMipMaps, samplingMode);
      }
    }
    const textureSize = this.getSize();
    if (this._canvas.width !== textureSize.width) {
      this._canvas.width = textureSize.width;
    }
    if (this._canvas.height !== textureSize.height) {
      this._canvas.height = textureSize.height;
    }
    this._context = this._canvas.getContext("2d");
  }
  getClassName() {
    return "DynamicTexture";
  }
  get canRescale() {
    return true;
  }
  _recreate(textureSize) {
    this._canvas.width = textureSize.width;
    this._canvas.height = textureSize.height;
    this.releaseInternalTexture();
    this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode);
  }
  scale(ratio) {
    const textureSize = this.getSize();
    textureSize.width *= ratio;
    textureSize.height *= ratio;
    this._recreate(textureSize);
  }
  scaleTo(width, height) {
    const textureSize = this.getSize();
    textureSize.width = width;
    textureSize.height = height;
    this._recreate(textureSize);
  }
  getContext() {
    return this._context;
  }
  clear(clearColor) {
    const size = this.getSize();
    if (clearColor) {
      this._context.fillStyle = clearColor;
    }
    this._context.clearRect(0, 0, size.width, size.height);
  }
  update(invertY, premulAlpha = false, allowGPUOptimization = false) {
    this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined, undefined, allowGPUOptimization);
  }
  drawText(text, x, y, font, color, fillColor, invertY, update = true) {
    const size = this.getSize();
    if (fillColor) {
      this._context.fillStyle = fillColor;
      this._context.fillRect(0, 0, size.width, size.height);
    }
    this._context.font = font;
    if (x === null || x === undefined) {
      const textSize = this._context.measureText(text);
      x = (size.width - textSize.width) / 2;
    }
    if (y === null || y === undefined) {
      const fontSize = parseInt(font.replace(/\D/g, ""));
      y = size.height / 2 + fontSize / 3.65;
    }
    this._context.fillStyle = color || "";
    this._context.fillText(text, x, y);
    if (update) {
      this.update(invertY);
    }
  }
  dispose() {
    super.dispose();
    if (this._ownCanvas) {
      this._canvas?.remove?.();
    }
    this._canvas = null;
    this._context = null;
  }
  clone() {
    const scene = this.getScene();
    if (!scene) {
      return this;
    }
    const textureSize = this.getSize();
    const newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
    newTexture.hasAlpha = this.hasAlpha;
    newTexture.level = this.level;
    newTexture.wrapU = this.wrapU;
    newTexture.wrapV = this.wrapV;
    return newTexture;
  }
  serialize() {
    const scene = this.getScene();
    if (scene && !scene.isReady()) {
      Logger.Warn("The scene must be ready before serializing the dynamic texture");
    }
    const serializationObject = super.serialize();
    if (DynamicTexture._IsCanvasElement(this._canvas)) {
      serializationObject.base64String = this._canvas.toDataURL();
    }
    serializationObject.invertY = this._invertY;
    serializationObject.samplingMode = this.samplingMode;
    return serializationObject;
  }
  static _IsCanvasElement(canvas) {
    return canvas.toDataURL !== undefined;
  }
  _rebuild() {
    this.update();
  }
}

// node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js
init_easing();
init_animation();
init_animatable();

// node_modules/@babylonjs/core/XR/webXRSessionManager.js
init_logger();
init_observable();

// node_modules/@babylonjs/core/XR/webXRManagedOutputCanvas.js
init_observable();
init_tools();

// node_modules/@babylonjs/core/XR/webXRLayerWrapper.js
class WebXRLayerWrapper {
  get isFixedFoveationSupported() {
    return this.layerType == "XRWebGLLayer" && typeof this.layer.fixedFoveation == "number";
  }
  get fixedFoveation() {
    if (this.isFixedFoveationSupported) {
      return this.layer.fixedFoveation;
    }
    return null;
  }
  set fixedFoveation(value) {
    if (this.isFixedFoveationSupported) {
      const val = Math.max(0, Math.min(1, value || 0));
      this.layer.fixedFoveation = val;
    }
  }
  createRenderTargetTextureProvider(xrSessionManager) {
    this._rttWrapper = this._createRenderTargetTextureProvider(xrSessionManager);
    return this._rttWrapper;
  }
  dispose() {
    if (this._rttWrapper) {
      this._rttWrapper.dispose();
      this._rttWrapper = null;
    }
  }
  constructor(getWidth, getHeight, layer, layerType, _createRenderTargetTextureProvider) {
    this.getWidth = getWidth;
    this.getHeight = getHeight;
    this.layer = layer;
    this.layerType = layerType;
    this._createRenderTargetTextureProvider = _createRenderTargetTextureProvider;
    this._rttWrapper = null;
  }
}

// node_modules/@babylonjs/core/XR/webXRRenderTargetTextureProvider.js
init_internalTexture();
init_renderTargetTexture();

class WebXRLayerRenderTargetTextureProvider {
  constructor(_scene, layerWrapper) {
    this._scene = _scene;
    this.layerWrapper = layerWrapper;
    this._renderTargetTextures = new Array;
    this._engine = _scene.getEngine();
  }
  _createInternalTexture(textureSize, texture) {
    const internalTexture = new InternalTexture(this._engine, 0, true);
    internalTexture.width = textureSize.width;
    internalTexture.height = textureSize.height;
    internalTexture._hardwareTexture = new WebGLHardwareTexture(texture, this._engine._gl);
    internalTexture.isReady = true;
    return internalTexture;
  }
  _createRenderTargetTexture(width, height, framebuffer, colorTexture, depthStencilTexture, multiview) {
    if (!this._engine) {
      throw new Error("Engine is disposed");
    }
    const textureSize = { width, height };
    const renderTargetTexture = multiview ? new MultiviewRenderTarget(this._scene, textureSize) : new RenderTargetTexture("XR renderTargetTexture", textureSize, this._scene);
    const renderTargetWrapper = renderTargetTexture.renderTarget;
    renderTargetWrapper._samples = renderTargetTexture.samples;
    if (framebuffer || !colorTexture) {
      renderTargetWrapper._framebuffer = framebuffer;
    }
    if (colorTexture) {
      if (multiview) {
        renderTargetWrapper._colorTextureArray = colorTexture;
      } else {
        const internalTexture = this._createInternalTexture(textureSize, colorTexture);
        renderTargetWrapper.setTexture(internalTexture, 0);
        renderTargetTexture._texture = internalTexture;
      }
    }
    if (depthStencilTexture) {
      if (multiview) {
        renderTargetWrapper._depthStencilTextureArray = depthStencilTexture;
      } else {
        renderTargetWrapper._depthStencilTexture = this._createInternalTexture(textureSize, depthStencilTexture);
      }
    }
    renderTargetTexture.disableRescaling();
    this._renderTargetTextures.push(renderTargetTexture);
    return renderTargetTexture;
  }
  _destroyRenderTargetTexture(renderTargetTexture) {
    this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(renderTargetTexture), 1);
    renderTargetTexture.dispose();
  }
  getFramebufferDimensions() {
    return this._framebufferDimensions;
  }
  dispose() {
    this._renderTargetTextures.forEach((rtt) => rtt.dispose());
    this._renderTargetTextures.length = 0;
  }
}

// node_modules/@babylonjs/core/XR/webXRWebGLLayer.js
class WebXRWebGLLayerWrapper extends WebXRLayerWrapper {
  constructor(layer) {
    super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new WebXRWebGLLayerRenderTargetTextureProvider(sessionManager.scene, this));
    this.layer = layer;
  }
}

class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {
  constructor(scene, layerWrapper) {
    super(scene, layerWrapper);
    this.layerWrapper = layerWrapper;
    this._layer = layerWrapper.layer;
    this._framebufferDimensions = {
      framebufferWidth: this._layer.framebufferWidth,
      framebufferHeight: this._layer.framebufferHeight
    };
  }
  trySetViewportForView(viewport, view) {
    const xrViewport = this._layer.getViewport(view);
    if (!xrViewport) {
      return false;
    }
    const framebufferWidth = this._framebufferDimensions.framebufferWidth;
    const framebufferHeight = this._framebufferDimensions.framebufferHeight;
    viewport.x = xrViewport.x / framebufferWidth;
    viewport.y = xrViewport.y / framebufferHeight;
    viewport.width = xrViewport.width / framebufferWidth;
    viewport.height = xrViewport.height / framebufferHeight;
    return true;
  }
  getRenderTargetTextureForEye(eye) {
    const layerWidth = this._layer.framebufferWidth;
    const layerHeight = this._layer.framebufferHeight;
    const framebuffer = this._layer.framebuffer;
    if (!this._rtt || layerWidth !== this._framebufferDimensions.framebufferWidth || layerHeight !== this._framebufferDimensions.framebufferHeight || framebuffer !== this._framebuffer) {
      this._rtt = this._createRenderTargetTexture(layerWidth, layerHeight, framebuffer);
      this._framebufferDimensions.framebufferWidth = layerWidth;
      this._framebufferDimensions.framebufferHeight = layerHeight;
      this._framebuffer = framebuffer;
    }
    return this._rtt;
  }
  getRenderTargetTextureForView(view) {
    return this.getRenderTargetTextureForEye(view.eye);
  }
}

// node_modules/@babylonjs/core/XR/webXRManagedOutputCanvas.js
class WebXRManagedOutputCanvasOptions {
  static GetDefaults(engine) {
    const defaults = new WebXRManagedOutputCanvasOptions;
    defaults.canvasOptions = {
      antialias: true,
      depth: true,
      stencil: engine ? engine.isStencilEnable : true,
      alpha: true,
      framebufferScaleFactor: 1
    };
    defaults.newCanvasCssStyle = "position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;";
    return defaults;
  }
}

class WebXRManagedOutputCanvas {
  constructor(_xrSessionManager, _options = WebXRManagedOutputCanvasOptions.GetDefaults()) {
    this._options = _options;
    this._canvas = null;
    this._engine = null;
    this.xrLayer = null;
    this._xrLayerWrapper = null;
    this.onXRLayerInitObservable = new Observable;
    this._engine = _xrSessionManager.scene.getEngine();
    this._engine.onDisposeObservable.addOnce(() => {
      this._engine = null;
    });
    if (!_options.canvasElement) {
      const canvas = document.createElement("canvas");
      canvas.style.cssText = this._options.newCanvasCssStyle || "position:absolute; bottom:0px;right:0px;";
      this._setManagedOutputCanvas(canvas);
    } else {
      this._setManagedOutputCanvas(_options.canvasElement);
    }
    _xrSessionManager.onXRSessionInit.add(() => {
      this._addCanvas();
    });
    _xrSessionManager.onXRSessionEnded.add(() => {
      this._removeCanvas();
    });
    this._makeCanvasCompatibleAsync();
  }
  dispose() {
    this._removeCanvas();
    this._setManagedOutputCanvas(null);
    this.onXRLayerInitObservable.clear();
  }
  _makeCanvasCompatibleAsync() {
    this._canvasCompatiblePromise = new Promise((resolve3, reject) => {
      try {
        if (this.canvasContext && this.canvasContext.makeXRCompatible) {
          this.canvasContext.makeXRCompatible().then(() => {
            resolve3();
          }, () => {
            Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.");
            resolve3();
          });
        } else {
          resolve3();
        }
      } catch (e) {
        reject(e);
      }
    });
  }
  async initializeXRLayerAsync(xrSession) {
    const createLayer = () => {
      this.xrLayer = new XRWebGLLayer(xrSession, this.canvasContext, this._options.canvasOptions);
      this._xrLayerWrapper = new WebXRWebGLLayerWrapper(this.xrLayer);
      this.onXRLayerInitObservable.notifyObservers(this.xrLayer);
      return this.xrLayer;
    };
    return this._canvasCompatiblePromise.then(() => {}, () => {}).then(() => {
      return createLayer();
    });
  }
  _addCanvas() {
    if (this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas()) {
      document.body.appendChild(this._canvas);
    }
    if (this.xrLayer) {
      this._setCanvasSize(true);
    } else {
      this.onXRLayerInitObservable.addOnce(() => {
        this._setCanvasSize(true);
      });
    }
  }
  _removeCanvas() {
    if (this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas()) {
      document.body.removeChild(this._canvas);
    }
    this._setCanvasSize(false);
  }
  _setCanvasSize(init = true, xrLayer = this._xrLayerWrapper) {
    if (!this._canvas || !this._engine) {
      return;
    }
    if (init) {
      if (xrLayer) {
        if (this._canvas !== this._engine.getRenderingCanvas()) {
          this._canvas.style.width = xrLayer.getWidth() + "px";
          this._canvas.style.height = xrLayer.getHeight() + "px";
        } else {
          this._engine.setSize(xrLayer.getWidth(), xrLayer.getHeight());
        }
      }
    } else {
      if (this._originalCanvasSize) {
        if (this._canvas !== this._engine.getRenderingCanvas()) {
          this._canvas.style.width = this._originalCanvasSize.width + "px";
          this._canvas.style.height = this._originalCanvasSize.height + "px";
        } else {
          this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height);
        }
      }
    }
  }
  _setManagedOutputCanvas(canvas) {
    this._removeCanvas();
    if (!canvas) {
      this._canvas = null;
      this.canvasContext = null;
    } else {
      this._originalCanvasSize = {
        width: canvas.offsetWidth,
        height: canvas.offsetHeight
      };
      this._canvas = canvas;
      this.canvasContext = this._canvas.getContext("webgl2");
      if (!this.canvasContext) {
        this.canvasContext = this._canvas.getContext("webgl");
      }
    }
  }
}

// node_modules/@babylonjs/core/XR/native/nativeXRRenderTarget.js
class NativeXRLayerWrapper extends WebXRLayerWrapper {
  constructor(layer) {
    super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new NativeXRLayerRenderTargetTextureProvider(sessionManager, this));
    this.layer = layer;
  }
}

class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {
  constructor(sessionManager, layerWrapper) {
    super(sessionManager.scene, layerWrapper);
    this.layerWrapper = layerWrapper;
    this._nativeRTTProvider = navigator.xr.getNativeRenderTargetProvider(sessionManager.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this));
    this._nativeLayer = layerWrapper.layer;
  }
  trySetViewportForView(viewport) {
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = 1;
    viewport.height = 1;
    return true;
  }
  getRenderTargetTextureForEye(eye) {
    return this._nativeRTTProvider.getRenderTargetForEye(eye);
  }
  getRenderTargetTextureForView(view) {
    return this._nativeRTTProvider.getRenderTargetForEye(view.eye);
  }
  getFramebufferDimensions() {
    return {
      framebufferWidth: this._nativeLayer.framebufferWidth,
      framebufferHeight: this._nativeLayer.framebufferHeight
    };
  }
}

class NativeXRRenderTarget {
  constructor(_xrSessionManager) {
    this._nativeRenderTarget = navigator.xr.getWebXRRenderTarget(_xrSessionManager.scene.getEngine());
  }
  async initializeXRLayerAsync(xrSession) {
    await this._nativeRenderTarget.initializeXRLayerAsync(xrSession);
    this.xrLayer = this._nativeRenderTarget.xrLayer;
    return this.xrLayer;
  }
  dispose() {}
}

// node_modules/@babylonjs/core/XR/webXRSessionManager.js
class WebXRSessionManager {
  get worldScalingFactor() {
    return this._worldScalingFactor;
  }
  set worldScalingFactor(value) {
    const oldValue = this._worldScalingFactor;
    this._worldScalingFactor = value;
    this.onWorldScaleFactorChangedObservable.notifyObservers({
      previousScaleFactor: oldValue,
      newScaleFactor: value
    });
  }
  constructor(scene) {
    this.scene = scene;
    this.currentTimestamp = -1;
    this.defaultHeightCompensation = 1.7;
    this.onXRFrameObservable = new Observable;
    this.onXRReferenceSpaceChanged = new Observable;
    this.onXRSessionEnded = new Observable;
    this.onXRSessionInit = new Observable;
    this.onXRReferenceSpaceInitialized = new Observable;
    this.onXRReady = new Observable;
    this.inXRFrameLoop = false;
    this.inXRSession = false;
    this._worldScalingFactor = 1;
    this.onWorldScaleFactorChangedObservable = new Observable(undefined, true);
    this._engine = scene.getEngine();
    this._onEngineDisposedObserver = this._engine.onDisposeObservable.addOnce(() => {
      this._engine = null;
    });
    scene.onDisposeObservable.addOnce(() => {
      this.dispose();
    });
  }
  get referenceSpace() {
    return this._referenceSpace;
  }
  set referenceSpace(newReferenceSpace) {
    this._referenceSpace = newReferenceSpace;
    this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace);
  }
  get sessionMode() {
    return this._sessionMode;
  }
  dispose() {
    if (this.inXRSession) {
      this.exitXRAsync();
    }
    this.onXRReady.clear();
    this.onXRFrameObservable.clear();
    this.onXRSessionEnded.clear();
    this.onXRReferenceSpaceChanged.clear();
    this.onXRSessionInit.clear();
    this.onWorldScaleFactorChangedObservable.clear();
    this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver);
    this._engine = null;
  }
  async exitXRAsync() {
    if (this.session && this.inXRSession) {
      this.inXRSession = false;
      try {
        return await this.session.end();
      } catch {
        Logger.Warn("Could not end XR session.");
      }
    }
    return Promise.resolve();
  }
  trySetViewportForView(viewport, view) {
    return this._baseLayerRTTProvider?.trySetViewportForView(viewport, view) || false;
  }
  getRenderTargetTextureForEye(eye) {
    return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(eye) || null;
  }
  getRenderTargetTextureForView(view) {
    return this._baseLayerRTTProvider?.getRenderTargetTextureForView(view) || null;
  }
  getWebXRRenderTarget(options) {
    const engine = this.scene.getEngine();
    if (this._xrNavigator.xr.native) {
      return new NativeXRRenderTarget(this);
    } else {
      options = options || WebXRManagedOutputCanvasOptions.GetDefaults(engine);
      options.canvasElement = options.canvasElement || engine.getRenderingCanvas() || undefined;
      return new WebXRManagedOutputCanvas(this, options);
    }
  }
  initializeAsync() {
    this._xrNavigator = navigator;
    if (!this._xrNavigator.xr) {
      return Promise.reject("WebXR not available");
    }
    return Promise.resolve();
  }
  initializeSessionAsync(xrSessionMode = "immersive-vr", xrSessionInit = {}) {
    return this._xrNavigator.xr.requestSession(xrSessionMode, xrSessionInit).then((session) => {
      this.session = session;
      this._sessionMode = xrSessionMode;
      this.inXRSession = true;
      this.onXRSessionInit.notifyObservers(session);
      this.session.addEventListener("end", () => {
        this.inXRSession = false;
        this.onXRSessionEnded.notifyObservers(null);
        if (this._engine) {
          this._engine.framebufferDimensionsObject = null;
          this._engine.restoreDefaultFramebuffer();
          this._engine.customAnimationFrameRequester = null;
          this._engine._renderLoop();
        }
        if (this.isNative) {
          this._baseLayerRTTProvider?.dispose();
        }
        this._baseLayerRTTProvider = null;
        this._baseLayerWrapper = null;
      }, { once: true });
      return this.session;
    });
  }
  isSessionSupportedAsync(sessionMode) {
    return WebXRSessionManager.IsSessionSupportedAsync(sessionMode);
  }
  resetReferenceSpace() {
    this.referenceSpace = this.baseReferenceSpace;
  }
  runXRRenderLoop() {
    if (!this.inXRSession || !this._engine) {
      return;
    }
    this._engine.customAnimationFrameRequester = {
      requestAnimationFrame: (callback) => this.session.requestAnimationFrame(callback),
      renderFunction: (timestamp, xrFrame) => {
        if (!this.inXRSession || !this._engine) {
          return;
        }
        this.currentFrame = xrFrame;
        this.currentTimestamp = timestamp;
        if (xrFrame) {
          this.inXRFrameLoop = true;
          const framebufferDimensionsObject = this._baseLayerRTTProvider?.getFramebufferDimensions() || null;
          if (this._engine.framebufferDimensionsObject !== framebufferDimensionsObject) {
            this._engine.framebufferDimensionsObject = framebufferDimensionsObject;
          }
          this.onXRFrameObservable.notifyObservers(xrFrame);
          this._engine._renderLoop();
          this._engine.framebufferDimensionsObject = null;
          this.inXRFrameLoop = false;
        }
      }
    };
    this._engine.framebufferDimensionsObject = this._baseLayerRTTProvider?.getFramebufferDimensions() || null;
    this.onXRFrameObservable.addOnce(() => {
      this.onXRReady.notifyObservers(this);
    });
    if (typeof window !== "undefined" && window.cancelAnimationFrame) {
      window.cancelAnimationFrame(this._engine._frameHandler);
    }
    this._engine._renderLoop();
  }
  setReferenceSpaceTypeAsync(referenceSpaceType = "local-floor") {
    return this.session.requestReferenceSpace(referenceSpaceType).then((referenceSpace) => {
      return referenceSpace;
    }, (rejectionReason) => {
      Logger.Error("XR.requestReferenceSpace failed for the following reason: ");
      Logger.Error(rejectionReason);
      Logger.Log('Defaulting to universally-supported "viewer" reference space type.');
      return this.session.requestReferenceSpace("viewer").then((referenceSpace) => {
        const heightCompensation = new XRRigidTransform({ x: 0, y: -this.defaultHeightCompensation, z: 0 });
        return referenceSpace.getOffsetReferenceSpace(heightCompensation);
      }, (rejectionReason2) => {
        Logger.Error(rejectionReason2);
        throw 'XR initialization failed: required "viewer" reference space type not supported.';
      });
    }).then((referenceSpace) => {
      return this.session.requestReferenceSpace("viewer").then((viewerReferenceSpace) => {
        this.viewerReferenceSpace = viewerReferenceSpace;
        return referenceSpace;
      });
    }).then((referenceSpace) => {
      this.referenceSpace = this.baseReferenceSpace = referenceSpace;
      this.onXRReferenceSpaceInitialized.notifyObservers(referenceSpace);
      return this.referenceSpace;
    });
  }
  updateRenderStateAsync(state) {
    return Promise.resolve(this.session.updateRenderState(state));
  }
  _setBaseLayerWrapper(baseLayerWrapper) {
    if (this.isNative) {
      this._baseLayerRTTProvider?.dispose();
    }
    this._baseLayerWrapper = baseLayerWrapper;
    this._baseLayerRTTProvider = this._baseLayerWrapper?.createRenderTargetTextureProvider(this) || null;
  }
  _getBaseLayerWrapper() {
    return this._baseLayerWrapper;
  }
  updateRenderState(state) {
    if (state.baseLayer) {
      this._setBaseLayerWrapper(this.isNative ? new NativeXRLayerWrapper(state.baseLayer) : new WebXRWebGLLayerWrapper(state.baseLayer));
    }
    this.session.updateRenderState(state);
  }
  static IsSessionSupportedAsync(sessionMode) {
    if (!navigator.xr) {
      return Promise.resolve(false);
    }
    const functionToUse = navigator.xr.isSessionSupported || navigator.xr.supportsSession;
    if (!functionToUse) {
      return Promise.resolve(false);
    } else {
      return functionToUse.call(navigator.xr, sessionMode).then((result) => {
        const returnValue = typeof result === "undefined" ? true : result;
        return Promise.resolve(returnValue);
      }).catch((e) => {
        Logger.Warn(e);
        return Promise.resolve(false);
      });
    }
  }
  get isNative() {
    return this._xrNavigator.xr.native ?? false;
  }
  get currentFrameRate() {
    return this.session?.frameRate;
  }
  get supportedFrameRates() {
    return this.session?.supportedFrameRates;
  }
  updateTargetFrameRate(rate) {
    return this.session.updateTargetFrameRate(rate);
  }
  runInXRFrame(callback, ignoreIfNotInSession = true) {
    if (this.inXRFrameLoop) {
      callback();
    } else if (this.inXRSession || !ignoreIfNotInSession) {
      this.onXRFrameObservable.addOnce(callback);
    }
  }
  get isFixedFoveationSupported() {
    return this._baseLayerWrapper?.isFixedFoveationSupported || false;
  }
  get fixedFoveation() {
    return this._baseLayerWrapper?.fixedFoveation || null;
  }
  set fixedFoveation(value) {
    const val = Math.max(0, Math.min(1, value || 0));
    if (this._baseLayerWrapper) {
      this._baseLayerWrapper.fixedFoveation = val;
    }
  }
  get enabledFeatures() {
    return this.session?.enabledFeatures ?? null;
  }
}

// node_modules/@babylonjs/core/Meshes/Builders/groundBuilder.js
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Meshes/groundMesh.js
init_math_vector();
init_buffer();
Mesh._GroundMeshParser = (parsedMesh, scene) => {
  return GroundMesh.Parse(parsedMesh, scene);
};

class GroundMesh extends Mesh {
  constructor(name144, scene) {
    super(name144, scene);
    this.generateOctree = false;
  }
  getClassName() {
    return "GroundMesh";
  }
  get subdivisions() {
    return Math.min(this._subdivisionsX, this._subdivisionsY);
  }
  get subdivisionsX() {
    return this._subdivisionsX;
  }
  get subdivisionsY() {
    return this._subdivisionsY;
  }
  optimize(chunksCount, octreeBlocksSize = 32) {
    this._subdivisionsX = chunksCount;
    this._subdivisionsY = chunksCount;
    this.subdivide(chunksCount);
    const thisAsAny = this;
    if (thisAsAny.createOrUpdateSubmeshesOctree) {
      thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
    }
  }
  getHeightAtCoordinates(x, z) {
    const world = this.getWorldMatrix();
    const invMat = TmpVectors.Matrix[5];
    world.invertToRef(invMat);
    const tmpVect = TmpVectors.Vector3[8];
    Vector3.TransformCoordinatesFromFloatsToRef(x, 0, z, invMat, tmpVect);
    x = tmpVect.x;
    z = tmpVect.z;
    if (x < this._minX || x >= this._maxX || z <= this._minZ || z > this._maxZ) {
      return this.position.y;
    }
    if (!this._heightQuads || this._heightQuads.length == 0) {
      this._initHeightQuads();
      this._computeHeightQuads();
    }
    const facet = this._getFacetAt(x, z);
    const y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
    Vector3.TransformCoordinatesFromFloatsToRef(0, y, 0, world, tmpVect);
    return tmpVect.y;
  }
  getNormalAtCoordinates(x, z) {
    const normal = new Vector3(0, 1, 0);
    this.getNormalAtCoordinatesToRef(x, z, normal);
    return normal;
  }
  getNormalAtCoordinatesToRef(x, z, ref) {
    const world = this.getWorldMatrix();
    const tmpMat = TmpVectors.Matrix[5];
    world.invertToRef(tmpMat);
    const tmpVect = TmpVectors.Vector3[8];
    Vector3.TransformCoordinatesFromFloatsToRef(x, 0, z, tmpMat, tmpVect);
    x = tmpVect.x;
    z = tmpVect.z;
    if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
      return this;
    }
    if (!this._heightQuads || this._heightQuads.length == 0) {
      this._initHeightQuads();
      this._computeHeightQuads();
    }
    const facet = this._getFacetAt(x, z);
    Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
    return this;
  }
  updateCoordinateHeights() {
    if (!this._heightQuads || this._heightQuads.length == 0) {
      this._initHeightQuads();
    }
    this._computeHeightQuads();
    return this;
  }
  _getFacetAt(x, z) {
    const col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
    const row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
    const quad = this._heightQuads[row * this._subdivisionsX + col];
    let facet;
    if (z < quad.slope.x * x + quad.slope.y) {
      facet = quad.facet1;
    } else {
      facet = quad.facet2;
    }
    return facet;
  }
  _initHeightQuads() {
    const subdivisionsX = this._subdivisionsX;
    const subdivisionsY = this._subdivisionsY;
    this._heightQuads = new Array;
    for (let row = 0;row < subdivisionsY; row++) {
      for (let col = 0;col < subdivisionsX; col++) {
        const quad = { slope: Vector2.Zero(), facet1: new Vector4(0, 0, 0, 0), facet2: new Vector4(0, 0, 0, 0) };
        this._heightQuads[row * subdivisionsX + col] = quad;
      }
    }
    return this;
  }
  _computeHeightQuads() {
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    if (!positions) {
      return this;
    }
    const v1 = TmpVectors.Vector3[3];
    const v2 = TmpVectors.Vector3[2];
    const v3 = TmpVectors.Vector3[1];
    const v4 = TmpVectors.Vector3[0];
    const v1v2 = TmpVectors.Vector3[4];
    const v1v3 = TmpVectors.Vector3[5];
    const v1v4 = TmpVectors.Vector3[6];
    const norm1 = TmpVectors.Vector3[7];
    const norm2 = TmpVectors.Vector3[8];
    let i = 0;
    let j = 0;
    let k = 0;
    let cd = 0;
    let h = 0;
    let d1 = 0;
    let d2 = 0;
    const subdivisionsX = this._subdivisionsX;
    const subdivisionsY = this._subdivisionsY;
    for (let row = 0;row < subdivisionsY; row++) {
      for (let col = 0;col < subdivisionsX; col++) {
        i = col * 3;
        j = row * (subdivisionsX + 1) * 3;
        k = (row + 1) * (subdivisionsX + 1) * 3;
        v1.x = positions[j + i];
        v1.y = positions[j + i + 1];
        v1.z = positions[j + i + 2];
        v2.x = positions[j + i + 3];
        v2.y = positions[j + i + 4];
        v2.z = positions[j + i + 5];
        v3.x = positions[k + i];
        v3.y = positions[k + i + 1];
        v3.z = positions[k + i + 2];
        v4.x = positions[k + i + 3];
        v4.y = positions[k + i + 4];
        v4.z = positions[k + i + 5];
        cd = (v4.z - v1.z) / (v4.x - v1.x);
        h = v1.z - cd * v1.x;
        v2.subtractToRef(v1, v1v2);
        v3.subtractToRef(v1, v1v3);
        v4.subtractToRef(v1, v1v4);
        Vector3.CrossToRef(v1v4, v1v3, norm1);
        Vector3.CrossToRef(v1v2, v1v4, norm2);
        norm1.normalize();
        norm2.normalize();
        d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
        d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
        const quad = this._heightQuads[row * subdivisionsX + col];
        quad.slope.copyFromFloats(cd, h);
        quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
        quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
      }
    }
    return this;
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.subdivisionsX = this._subdivisionsX;
    serializationObject.subdivisionsY = this._subdivisionsY;
    serializationObject.minX = this._minX;
    serializationObject.maxX = this._maxX;
    serializationObject.minZ = this._minZ;
    serializationObject.maxZ = this._maxZ;
    serializationObject.width = this._width;
    serializationObject.height = this._height;
  }
  static Parse(parsedMesh, scene) {
    const result = new GroundMesh(parsedMesh.name, scene);
    result._subdivisionsX = parsedMesh.subdivisionsX || 1;
    result._subdivisionsY = parsedMesh.subdivisionsY || 1;
    result._minX = parsedMesh.minX;
    result._maxX = parsedMesh.maxX;
    result._minZ = parsedMesh.minZ;
    result._maxZ = parsedMesh.maxZ;
    result._width = parsedMesh.width;
    result._height = parsedMesh.height;
    return result;
  }
}

// node_modules/@babylonjs/core/Meshes/Builders/groundBuilder.js
init_tools();
init_engineStore();
init_math_constants();
init_compatibilityOptions();
function CreateGroundVertexData(options) {
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  let row, col;
  const width = options.width || options.size || 1;
  const height = options.height || options.size || 1;
  const subdivisionsX = (options.subdivisionsX || options.subdivisions || 1) | 0;
  const subdivisionsY = (options.subdivisionsY || options.subdivisions || 1) | 0;
  for (row = 0;row <= subdivisionsY; row++) {
    for (col = 0;col <= subdivisionsX; col++) {
      const position = new Vector3(col * width / subdivisionsX - width / 2, 0, (subdivisionsY - row) * height / subdivisionsY - height / 2);
      const normal = new Vector3(0, 1, 0);
      positions.push(position.x, position.y, position.z);
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(col / subdivisionsX, useOpenGLOrientationForUV ? row / subdivisionsY : 1 - row / subdivisionsY);
    }
  }
  for (row = 0;row < subdivisionsY; row++) {
    for (col = 0;col < subdivisionsX; col++) {
      indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
      indices.push(col + 1 + row * (subdivisionsX + 1));
      indices.push(col + row * (subdivisionsX + 1));
      indices.push(col + (row + 1) * (subdivisionsX + 1));
      indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
      indices.push(col + row * (subdivisionsX + 1));
    }
  }
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateTiledGroundVertexData(options) {
  const xmin = options.xmin !== undefined && options.xmin !== null ? options.xmin : -1;
  const zmin = options.zmin !== undefined && options.zmin !== null ? options.zmin : -1;
  const xmax = options.xmax !== undefined && options.xmax !== null ? options.xmax : 1;
  const zmax = options.zmax !== undefined && options.zmax !== null ? options.zmax : 1;
  const subdivisions = options.subdivisions || { w: 1, h: 1 };
  const precision = options.precision || { w: 1, h: 1 };
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  let row, col, tileRow, tileCol;
  subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h;
  subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w;
  precision.w = precision.w < 1 ? 1 : precision.w;
  precision.h = precision.h < 1 ? 1 : precision.h;
  const tileSize = {
    w: (xmax - xmin) / subdivisions.w,
    h: (zmax - zmin) / subdivisions.h
  };
  function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
    const base = positions.length / 3;
    const rowLength = precision.w + 1;
    for (row = 0;row < precision.h; row++) {
      for (col = 0;col < precision.w; col++) {
        const square = [base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength];
        indices.push(square[1]);
        indices.push(square[2]);
        indices.push(square[3]);
        indices.push(square[0]);
        indices.push(square[1]);
        indices.push(square[3]);
      }
    }
    const position = Vector3.Zero();
    const normal = new Vector3(0, 1, 0);
    for (row = 0;row <= precision.h; row++) {
      position.z = row * (zTileMax - zTileMin) / precision.h + zTileMin;
      for (col = 0;col <= precision.w; col++) {
        position.x = col * (xTileMax - xTileMin) / precision.w + xTileMin;
        position.y = 0;
        positions.push(position.x, position.y, position.z);
        normals.push(normal.x, normal.y, normal.z);
        uvs.push(col / precision.w, row / precision.h);
      }
    }
  }
  for (tileRow = 0;tileRow < subdivisions.h; tileRow++) {
    for (tileCol = 0;tileCol < subdivisions.w; tileCol++) {
      applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
    }
  }
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateGroundFromHeightMapVertexData(options) {
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  let row, col;
  const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);
  const alphaFilter = options.alphaFilter || 0;
  let invert = false;
  if (options.minHeight > options.maxHeight) {
    invert = true;
    const temp = options.maxHeight;
    options.maxHeight = options.minHeight;
    options.minHeight = temp;
  }
  for (row = 0;row <= options.subdivisions; row++) {
    for (col = 0;col <= options.subdivisions; col++) {
      const position = new Vector3(col * options.width / options.subdivisions - options.width / 2, 0, (options.subdivisions - row) * options.height / options.subdivisions - options.height / 2);
      const heightMapX = (position.x + options.width / 2) / options.width * (options.bufferWidth - 1) | 0;
      const heightMapY = (1 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1) | 0;
      const pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
      let r = options.buffer[pos] / 255;
      let g = options.buffer[pos + 1] / 255;
      let b = options.buffer[pos + 2] / 255;
      const a = options.buffer[pos + 3] / 255;
      if (invert) {
        r = 1 - r;
        g = 1 - g;
        b = 1 - b;
      }
      const gradient = r * filter.r + g * filter.g + b * filter.b;
      if (a >= alphaFilter) {
        position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
      } else {
        position.y = options.minHeight - Epsilon;
      }
      if (options.heightBuffer) {
        options.heightBuffer[row * (options.subdivisions + 1) + col] = position.y;
      }
      positions.push(position.x, position.y, position.z);
      normals.push(0, 0, 0);
      uvs.push(col / options.subdivisions, 1 - row / options.subdivisions);
    }
  }
  for (row = 0;row < options.subdivisions; row++) {
    for (col = 0;col < options.subdivisions; col++) {
      const idx1 = col + 1 + (row + 1) * (options.subdivisions + 1);
      const idx2 = col + 1 + row * (options.subdivisions + 1);
      const idx3 = col + row * (options.subdivisions + 1);
      const idx4 = col + (row + 1) * (options.subdivisions + 1);
      const isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
      const isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
      const isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
      if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
        indices.push(idx1);
        indices.push(idx2);
        indices.push(idx3);
      }
      const isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
      if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
        indices.push(idx4);
        indices.push(idx1);
        indices.push(idx3);
      }
    }
  }
  VertexData.ComputeNormals(positions, indices, normals);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateGround(name144, options = {}, scene) {
  const ground = new GroundMesh(name144, scene);
  ground._setReady(false);
  ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  ground._width = options.width || 1;
  ground._height = options.height || 1;
  ground._maxX = ground._width / 2;
  ground._maxZ = ground._height / 2;
  ground._minX = -ground._maxX;
  ground._minZ = -ground._maxZ;
  const vertexData = CreateGroundVertexData(options);
  vertexData.applyToMesh(ground, options.updatable);
  ground._setReady(true);
  return ground;
}
function CreateTiledGround(name144, options, scene = null) {
  const tiledGround = new Mesh(name144, scene);
  const vertexData = CreateTiledGroundVertexData(options);
  vertexData.applyToMesh(tiledGround, options.updatable);
  return tiledGround;
}
function CreateGroundFromHeightMap(name144, url, options = {}, scene = null) {
  const width = options.width || 10;
  const height = options.height || 10;
  const subdivisions = options.subdivisions || 1 | 0;
  const minHeight = options.minHeight || 0;
  const maxHeight = options.maxHeight || 1;
  const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);
  const alphaFilter = options.alphaFilter || 0;
  const updatable = options.updatable;
  const onReady = options.onReady;
  scene = scene || EngineStore.LastCreatedScene;
  const ground = new GroundMesh(name144, scene);
  ground._subdivisionsX = subdivisions;
  ground._subdivisionsY = subdivisions;
  ground._width = width;
  ground._height = height;
  ground._maxX = ground._width / 2;
  ground._maxZ = ground._height / 2;
  ground._minX = -ground._maxX;
  ground._minZ = -ground._maxZ;
  ground._setReady(false);
  let heightBuffer;
  if (options.passHeightBufferInCallback) {
    heightBuffer = new Float32Array((subdivisions + 1) * (subdivisions + 1));
  }
  const onBufferLoaded = (buffer2, bufferWidth, bufferHeight) => {
    const vertexData = CreateGroundFromHeightMapVertexData({
      width,
      height,
      subdivisions,
      minHeight,
      maxHeight,
      colorFilter: filter,
      buffer: buffer2,
      bufferWidth,
      bufferHeight,
      alphaFilter,
      heightBuffer
    });
    vertexData.applyToMesh(ground, updatable);
    if (onReady) {
      onReady(ground, heightBuffer);
    }
    ground._setReady(true);
  };
  if (typeof url === "string") {
    const onload = (img) => {
      const bufferWidth = img.width;
      const bufferHeight = img.height;
      if (scene.isDisposed) {
        return;
      }
      const buffer2 = scene?.getEngine().resizeImageBitmap(img, bufferWidth, bufferHeight);
      onBufferLoaded(buffer2, bufferWidth, bufferHeight);
    };
    Tools.LoadImage(url, onload, options.onError ? options.onError : () => {}, scene.offlineProvider);
  } else {
    onBufferLoaded(url.data, url.width, url.height);
  }
  return ground;
}
VertexData.CreateGround = CreateGroundVertexData;
VertexData.CreateTiledGround = CreateTiledGroundVertexData;
VertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData;
Mesh.CreateGround = (name144, width, height, subdivisions, scene, updatable) => {
  const options = {
    width,
    height,
    subdivisions,
    updatable
  };
  return CreateGround(name144, options, scene);
};
Mesh.CreateTiledGround = (name144, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) => {
  const options = {
    xmin,
    zmin,
    xmax,
    zmax,
    subdivisions,
    precision,
    updatable
  };
  return CreateTiledGround(name144, options, scene);
};
Mesh.CreateGroundFromHeightMap = (name144, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) => {
  const options = {
    width,
    height,
    subdivisions,
    minHeight,
    maxHeight,
    updatable,
    onReady,
    alphaFilter
  };
  return CreateGroundFromHeightMap(name144, url, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/torusBuilder.js
init_math_vector();
init_compatibilityOptions();
function CreateTorusVertexData(options) {
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  const diameter = options.diameter || 1;
  const thickness = options.thickness || 0.5;
  const tessellation = (options.tessellation || 16) | 0;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const stride = tessellation + 1;
  for (let i = 0;i <= tessellation; i++) {
    const u = i / tessellation;
    const outerAngle = i * Math.PI * 2 / tessellation - Math.PI / 2;
    const transform = Matrix.Translation(diameter / 2, 0, 0).multiply(Matrix.RotationY(outerAngle));
    for (let j = 0;j <= tessellation; j++) {
      const v = 1 - j / tessellation;
      const innerAngle = j * Math.PI * 2 / tessellation + Math.PI;
      const dx = Math.cos(innerAngle);
      const dy = Math.sin(innerAngle);
      let normal = new Vector3(dx, dy, 0);
      let position = normal.scale(thickness / 2);
      const textureCoordinate = new Vector2(u, v);
      position = Vector3.TransformCoordinates(position, transform);
      normal = Vector3.TransformNormal(normal, transform);
      positions.push(position.x, position.y, position.z);
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(textureCoordinate.x, useOpenGLOrientationForUV ? 1 - textureCoordinate.y : textureCoordinate.y);
      const nextI = (i + 1) % stride;
      const nextJ = (j + 1) % stride;
      indices.push(i * stride + j);
      indices.push(i * stride + nextJ);
      indices.push(nextI * stride + j);
      indices.push(i * stride + nextJ);
      indices.push(nextI * stride + nextJ);
      indices.push(nextI * stride + j);
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateTorus(name144, options = {}, scene) {
  const torus = new Mesh(name144, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  torus._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateTorusVertexData(options);
  vertexData.applyToMesh(torus, options.updatable);
  return torus;
}
VertexData.CreateTorus = CreateTorusVertexData;
Mesh.CreateTorus = (name144, diameter, thickness, tessellation, scene, updatable, sideOrientation) => {
  const options = {
    diameter,
    thickness,
    tessellation,
    sideOrientation,
    updatable
  };
  return CreateTorus(name144, options, scene);
};

// node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js
class VRExperienceHelperGazer {
  constructor(scene, gazeTrackerToClone = null) {
    this.scene = scene;
    this._pointerDownOnMeshAsked = false;
    this._isActionableMesh = false;
    this._teleportationRequestInitiated = false;
    this._teleportationBackRequestInitiated = false;
    this._rotationRightAsked = false;
    this._rotationLeftAsked = false;
    this._dpadPressed = true;
    this._activePointer = false;
    this._id = VRExperienceHelperGazer._IdCounter++;
    if (!gazeTrackerToClone) {
      this._gazeTracker = CreateTorus("gazeTracker", {
        diameter: 0.0035,
        thickness: 0.0025,
        tessellation: 20,
        updatable: false
      }, scene);
      this._gazeTracker.bakeCurrentTransformIntoVertices();
      this._gazeTracker.isPickable = false;
      this._gazeTracker.isVisible = false;
      const targetMat = new StandardMaterial("targetMat", scene);
      targetMat.specularColor = Color3.Black();
      targetMat.emissiveColor = new Color3(0.7, 0.7, 0.7);
      targetMat.backFaceCulling = false;
      this._gazeTracker.material = targetMat;
    } else {
      this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
    }
  }
  _getForwardRay(length) {
    return new Ray(Vector3.Zero(), new Vector3(0, 0, length));
  }
  _selectionPointerDown() {
    this._pointerDownOnMeshAsked = true;
    if (this._currentHit) {
      this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
    }
  }
  _selectionPointerUp() {
    if (this._currentHit) {
      this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
    }
    this._pointerDownOnMeshAsked = false;
  }
  _activatePointer() {
    this._activePointer = true;
  }
  _deactivatePointer() {
    this._activePointer = false;
  }
  _updatePointerDistance(distance = 100) {}
  dispose() {
    this._interactionsEnabled = false;
    this._teleportationEnabled = false;
    if (this._gazeTracker) {
      this._gazeTracker.dispose();
    }
  }
}
VRExperienceHelperGazer._IdCounter = 0;

class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer {
  constructor(_getCamera, scene) {
    super(scene);
    this._getCamera = _getCamera;
  }
  _getForwardRay(length) {
    const camera = this._getCamera();
    if (camera) {
      return camera.getForwardRay(length);
    } else {
      return new Ray(Vector3.Zero(), Vector3.Forward());
    }
  }
}
class VRExperienceHelper {
  get onEnteringVR() {
    return this.onEnteringVRObservable;
  }
  get onExitingVR() {
    return this.onExitingVRObservable;
  }
  get teleportationTarget() {
    return this._teleportationTarget;
  }
  set teleportationTarget(value) {
    if (value) {
      value.name = "teleportationTarget";
      this._isDefaultTeleportationTarget = false;
      this._teleportationTarget = value;
    }
  }
  get gazeTrackerMesh() {
    return this._cameraGazer._gazeTracker;
  }
  set gazeTrackerMesh(value) {
    if (value) {
      if (this._cameraGazer._gazeTracker) {
        this._cameraGazer._gazeTracker.dispose();
      }
      this._cameraGazer._gazeTracker = value;
      this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
      this._cameraGazer._gazeTracker.isPickable = false;
      this._cameraGazer._gazeTracker.isVisible = false;
      this._cameraGazer._gazeTracker.name = "gazeTracker";
    }
  }
  get displayGaze() {
    return this._displayGaze;
  }
  set displayGaze(value) {
    this._displayGaze = value;
    if (!value) {
      this._cameraGazer._gazeTracker.isVisible = false;
    }
  }
  get displayLaserPointer() {
    return this._displayLaserPointer;
  }
  set displayLaserPointer(value) {
    this._displayLaserPointer = value;
  }
  get deviceOrientationCamera() {
    return this._deviceOrientationCamera;
  }
  get currentVRCamera() {
    return this._scene.activeCamera;
  }
  get vrDeviceOrientationCamera() {
    return this._vrDeviceOrientationCamera;
  }
  get vrButton() {
    return this._btnVR;
  }
  get _teleportationRequestInitiated() {
    return this._cameraGazer._teleportationRequestInitiated;
  }
  constructor(scene, webVROptions = {}) {
    this.webVROptions = webVROptions;
    this._fullscreenVRpresenting = false;
    this.enableGazeEvenWhenNoPointerLock = false;
    this.exitVROnDoubleTap = true;
    this.onEnteringVRObservable = new Observable;
    this.onAfterEnteringVRObservable = new Observable;
    this.onExitingVRObservable = new Observable;
    this._useCustomVRButton = false;
    this._teleportActive = false;
    this._floorMeshesCollection = [];
    this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME;
    this._teleportationTime = 122;
    this._teleportationSpeed = 20;
    this._rotationAllowed = true;
    this._teleportBackwardsVector = new Vector3(0, -1, -1);
    this._isDefaultTeleportationTarget = true;
    this._teleportationFillColor = "#444444";
    this._teleportationBorderColor = "#FFFFFF";
    this._rotationAngle = 0;
    this._haloCenter = new Vector3(0, 0, 0);
    this._padSensibilityUp = 0.65;
    this._padSensibilityDown = 0.35;
    this._pickedLaserColor = new Color3(0.2, 0.2, 1);
    this._pickedGazeColor = new Color3(0, 0, 1);
    this.onNewMeshSelected = new Observable;
    this.onNewMeshPicked = new Observable;
    this.onBeforeCameraTeleport = new Observable;
    this.onAfterCameraTeleport = new Observable;
    this.onSelectedMeshUnselected = new Observable;
    this.teleportationEnabled = true;
    this._teleportationInitialized = false;
    this._interactionsEnabled = false;
    this._displayGaze = true;
    this._displayLaserPointer = true;
    this.updateGazeTrackerScale = true;
    this.updateGazeTrackerColor = true;
    this.updateControllerLaserColor = true;
    this.requestPointerLockOnFullScreen = true;
    this.xrTestDone = false;
    this._onResize = () => {
      this._moveButtonToBottomRight();
    };
    this._onFullscreenChange = () => {
      this._fullscreenVRpresenting = !!document.fullscreenElement;
      if (!this._fullscreenVRpresenting && this._inputElement) {
        this.exitVR();
        if (!this._useCustomVRButton && this._btnVR) {
          this._btnVR.style.top = this._inputElement.offsetTop + this._inputElement.offsetHeight - 70 + "px";
          this._btnVR.style.left = this._inputElement.offsetLeft + this._inputElement.offsetWidth - 100 + "px";
          this._updateButtonVisibility();
        }
      }
    };
    this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null };
    this._beforeRender = () => {
      if (this._scene.getEngine().isPointerLock || this.enableGazeEvenWhenNoPointerLock) {} else {
        this._cameraGazer._gazeTracker.isVisible = false;
      }
    };
    this._onNewGamepadConnected = (gamepad) => {
      if (gamepad.type !== Gamepad.POSE_ENABLED) {
        if (gamepad.leftStick) {
          gamepad.onleftstickchanged((stickValues) => {
            if (this._teleportationInitialized && this.teleportationEnabled) {
              this._checkTeleportWithRay(stickValues, this._cameraGazer);
              this._checkTeleportBackwards(stickValues, this._cameraGazer);
            }
          });
        }
        if (gamepad.rightStick) {
          gamepad.onrightstickchanged((stickValues) => {
            if (this._teleportationInitialized) {
              this._checkRotate(stickValues, this._cameraGazer);
            }
          });
        }
        if (gamepad.type === Gamepad.XBOX) {
          gamepad.onbuttondown((buttonPressed) => {
            if (this._interactionsEnabled && buttonPressed === 0) {
              this._cameraGazer._selectionPointerDown();
            }
          });
          gamepad.onbuttonup((buttonPressed) => {
            if (this._interactionsEnabled && buttonPressed === 0) {
              this._cameraGazer._selectionPointerUp();
            }
          });
        }
      }
    };
    this._workingVector = Vector3.Zero();
    this._workingQuaternion = Quaternion.Identity();
    this._workingMatrix = Matrix.Identity();
    Logger.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead");
    this._scene = scene;
    this._inputElement = scene.getEngine().getInputElement();
    const vrSupported = "getVRDisplays" in navigator;
    if (!vrSupported && webVROptions.useXR === undefined) {
      webVROptions.useXR = true;
    }
    if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
      webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
    }
    if (webVROptions.createDeviceOrientationCamera === undefined) {
      webVROptions.createDeviceOrientationCamera = true;
    }
    if (webVROptions.laserToggle === undefined) {
      webVROptions.laserToggle = true;
    }
    this._hasEnteredVR = false;
    if (this._scene.activeCamera) {
      this._position = this._scene.activeCamera.position.clone();
    } else {
      this._position = new Vector3(0, this._defaultHeight, 0);
    }
    if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
      this._deviceOrientationCamera = new DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
      if (this._scene.activeCamera) {
        this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
        this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
        if (this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation) {
          const targetCamera = this._scene.activeCamera;
          if (targetCamera.rotationQuaternion) {
            this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
          } else {
            this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
          }
          this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
        }
      }
      this._scene.activeCamera = this._deviceOrientationCamera;
      if (this._inputElement) {
        this._scene.activeCamera.attachControl();
      }
    } else {
      this._existingCamera = this._scene.activeCamera;
    }
    if (this.webVROptions.useXR && navigator.xr) {
      WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then((supported) => {
        if (supported) {
          Logger.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly");
          scene.createDefaultXRExperienceAsync({
            floorMeshes: webVROptions.floorMeshes || []
          }).then((xr) => {
            this.xr = xr;
            this.xrTestDone = true;
            this._cameraGazer = new VRExperienceHelperCameraGazer(() => {
              return this.xr.baseExperience.camera;
            }, scene);
            this.xr.baseExperience.onStateChangedObservable.add((state) => {
              switch (state) {
                case 0:
                  this.onEnteringVRObservable.notifyObservers(this);
                  if (!this._interactionsEnabled) {
                    this.xr.pointerSelection.detach();
                  }
                  this.xr.pointerSelection.displayLaserPointer = this._displayLaserPointer;
                  break;
                case 1:
                  this.onExitingVRObservable.notifyObservers(this);
                  this._scene.getEngine().resize();
                  break;
                case 2:
                  this._hasEnteredVR = true;
                  break;
                case 3:
                  this._hasEnteredVR = false;
                  break;
              }
            });
          });
        } else {
          this._completeVRInit(scene, webVROptions);
        }
      });
    } else {
      this._completeVRInit(scene, webVROptions);
    }
  }
  _completeVRInit(scene, webVROptions) {
    this.xrTestDone = true;
    if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
      this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics);
      this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
    }
    this._cameraGazer = new VRExperienceHelperCameraGazer(() => {
      return this.currentVRCamera;
    }, scene);
    if (!this._useCustomVRButton) {
      this._btnVR = document.createElement("BUTTON");
      this._btnVR.className = "babylonVRicon";
      this._btnVR.id = "babylonVRiconbtn";
      this._btnVR.title = "Click to switch to VR";
      const url = !window.SVGSVGElement ? "https://cdn.babylonjs.com/Assets/vrButton.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A";
      let css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + url + "); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
      css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
      const style = document.createElement("style");
      style.appendChild(document.createTextNode(css));
      document.getElementsByTagName("head")[0].appendChild(style);
      this._moveButtonToBottomRight();
    }
    if (this._btnVR) {
      this._btnVR.addEventListener("click", () => {
        if (!this.isInVRMode) {
          this.enterVR();
        }
      });
    }
    const hostWindow = this._scene.getEngine().getHostWindow();
    if (!hostWindow) {
      return;
    }
    hostWindow.addEventListener("resize", this._onResize);
    document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
    if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
      this._displayVRButton();
    }
    this._onKeyDown = (event) => {
      if (event.keyCode === 27 && this.isInVRMode) {
        this.exitVR();
      }
    };
    document.addEventListener("keydown", this._onKeyDown);
    this._scene.onPrePointerObservable.add(() => {
      if (this._hasEnteredVR && this.exitVROnDoubleTap) {
        this.exitVR();
        if (this._fullscreenVRpresenting) {
          this._scene.getEngine().exitFullscreen();
        }
      }
    }, PointerEventTypes.POINTERDOUBLETAP, false);
    scene.onDisposeObservable.add(() => {
      this.dispose();
    });
    this._updateButtonVisibility();
    this._circleEase = new CircleEase;
    this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
    this._teleportationEasing = this._circleEase;
    scene.onPointerObservable.add((e) => {
      if (this._interactionsEnabled) {
        if (scene.activeCamera === this.vrDeviceOrientationCamera && e.event.pointerType === "mouse") {
          if (e.type === PointerEventTypes.POINTERDOWN) {
            this._cameraGazer._selectionPointerDown();
          } else if (e.type === PointerEventTypes.POINTERUP) {
            this._cameraGazer._selectionPointerUp();
          }
        }
      }
    });
    if (this.webVROptions.floorMeshes) {
      this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
    }
  }
  get isInVRMode() {
    return this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === 2 || this._fullscreenVRpresenting;
  }
  _moveButtonToBottomRight() {
    if (this._inputElement && !this._useCustomVRButton && this._btnVR) {
      const rect = this._inputElement.getBoundingClientRect();
      this._btnVR.style.top = rect.top + rect.height - 70 + "px";
      this._btnVR.style.left = rect.left + rect.width - 100 + "px";
    }
  }
  _displayVRButton() {
    if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) {
      document.body.appendChild(this._btnVR);
      this._btnVRDisplayed = true;
    }
  }
  _updateButtonVisibility() {
    if (!this._btnVR || this._useCustomVRButton) {
      return;
    }
    this._btnVR.className = "babylonVRicon";
    if (this.isInVRMode) {
      this._btnVR.className += " vrdisplaypresenting";
    }
  }
  enterVR() {
    if (this.xr) {
      this.xr.baseExperience.enterXRAsync("immersive-vr", "local-floor", this.xr.renderTarget);
      return;
    }
    if (this.onEnteringVRObservable) {
      try {
        this.onEnteringVRObservable.notifyObservers(this);
      } catch (err) {
        Logger.Warn("Error in your custom logic onEnteringVR: " + err);
      }
    }
    if (this._scene.activeCamera) {
      this._position = this._scene.activeCamera.position.clone();
      if (this.vrDeviceOrientationCamera) {
        this.vrDeviceOrientationCamera.rotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles();
        this.vrDeviceOrientationCamera.angularSensibility = 2000;
      }
      this._existingCamera = this._scene.activeCamera;
      if (this._existingCamera.angularSensibilityX) {
        this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX;
        this._existingCamera.angularSensibilityX = Number.MAX_VALUE;
      }
      if (this._existingCamera.angularSensibilityY) {
        this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY;
        this._existingCamera.angularSensibilityY = Number.MAX_VALUE;
      }
      if (this._existingCamera.angularSensibility) {
        this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility;
        this._existingCamera.angularSensibility = Number.MAX_VALUE;
      }
    }
    if (this._vrDeviceOrientationCamera) {
      this._vrDeviceOrientationCamera.position = this._position;
      if (this._scene.activeCamera) {
        this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
      }
      this._scene.activeCamera = this._vrDeviceOrientationCamera;
      this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen);
      this._updateButtonVisibility();
      this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(() => {
        this.onAfterEnteringVRObservable.notifyObservers({ success: true });
      });
    }
    if (this._scene.activeCamera && this._inputElement) {
      this._scene.activeCamera.attachControl();
    }
    if (this._interactionsEnabled) {
      this._scene.registerBeforeRender(this._beforeRender);
    }
    this._hasEnteredVR = true;
  }
  exitVR() {
    if (this.xr) {
      this.xr.baseExperience.exitXRAsync();
      return;
    }
    if (this._hasEnteredVR) {
      if (this.onExitingVRObservable) {
        try {
          this.onExitingVRObservable.notifyObservers(this);
        } catch (err) {
          Logger.Warn("Error in your custom logic onExitingVR: " + err);
        }
      }
      if (this._scene.activeCamera) {
        this._position = this._scene.activeCamera.position.clone();
      }
      if (this.vrDeviceOrientationCamera) {
        this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
      }
      if (this._deviceOrientationCamera) {
        this._deviceOrientationCamera.position = this._position;
        this._scene.activeCamera = this._deviceOrientationCamera;
        if (this._cachedAngularSensibility.angularSensibilityX) {
          this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
          this._cachedAngularSensibility.angularSensibilityX = null;
        }
        if (this._cachedAngularSensibility.angularSensibilityY) {
          this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
          this._cachedAngularSensibility.angularSensibilityY = null;
        }
        if (this._cachedAngularSensibility.angularSensibility) {
          this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
          this._cachedAngularSensibility.angularSensibility = null;
        }
      } else if (this._existingCamera) {
        this._existingCamera.position = this._position;
        this._scene.activeCamera = this._existingCamera;
        if (this._inputElement) {
          this._scene.activeCamera.attachControl();
        }
        if (this._cachedAngularSensibility.angularSensibilityX) {
          this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
          this._cachedAngularSensibility.angularSensibilityX = null;
        }
        if (this._cachedAngularSensibility.angularSensibilityY) {
          this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
          this._cachedAngularSensibility.angularSensibilityY = null;
        }
        if (this._cachedAngularSensibility.angularSensibility) {
          this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
          this._cachedAngularSensibility.angularSensibility = null;
        }
      }
      this._updateButtonVisibility();
      if (this._interactionsEnabled) {
        this._scene.unregisterBeforeRender(this._beforeRender);
        this._cameraGazer._gazeTracker.isVisible = false;
      }
      this._scene.getEngine().resize();
      this._hasEnteredVR = false;
    }
  }
  get position() {
    return this._position;
  }
  set position(value) {
    this._position = value;
    if (this._scene.activeCamera) {
      this._scene.activeCamera.position = value;
    }
  }
  enableInteractions() {
    if (!this._interactionsEnabled) {
      if (this.xr) {
        if (this.xr.baseExperience.state === 2) {
          this.xr.pointerSelection.attach();
        }
        return;
      }
      this.raySelectionPredicate = (mesh) => {
        return mesh.isVisible && (mesh.isPickable || mesh.name === this._floorMeshName);
      };
      this.meshSelectionPredicate = () => {
        return true;
      };
      this._raySelectionPredicate = (mesh) => {
        if (this._isTeleportationFloor(mesh) || mesh.name.indexOf("gazeTracker") === -1 && mesh.name.indexOf("teleportationTarget") === -1 && mesh.name.indexOf("torusTeleportation") === -1) {
          return this.raySelectionPredicate(mesh);
        }
        return false;
      };
      this._interactionsEnabled = true;
    }
  }
  _isTeleportationFloor(mesh) {
    for (let i = 0;i < this._floorMeshesCollection.length; i++) {
      if (this._floorMeshesCollection[i].id === mesh.id) {
        return true;
      }
    }
    if (this._floorMeshName && mesh.name === this._floorMeshName) {
      return true;
    }
    return false;
  }
  addFloorMesh(floorMesh) {
    if (!this._floorMeshesCollection) {
      return;
    }
    if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
      return;
    }
    this._floorMeshesCollection.push(floorMesh);
  }
  removeFloorMesh(floorMesh) {
    if (!this._floorMeshesCollection) {
      return;
    }
    const meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
    if (meshIndex !== -1) {
      this._floorMeshesCollection.splice(meshIndex, 1);
    }
  }
  enableTeleportation(vrTeleportationOptions = {}) {
    if (!this._teleportationInitialized) {
      this.enableInteractions();
      if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) {
        const floorMeshes = vrTeleportationOptions.floorMeshes || [];
        if (!floorMeshes.length) {
          const floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName);
          if (floorMesh) {
            floorMeshes.push(floorMesh);
          }
        }
        if (this.xr) {
          floorMeshes.forEach((mesh) => {
            this.xr.teleportation.addFloorMesh(mesh);
          });
          if (!this.xr.teleportation.attached) {
            this.xr.teleportation.attach();
          }
          return;
        } else if (!this.xrTestDone) {
          const waitForXr = () => {
            if (this.xrTestDone) {
              this._scene.unregisterBeforeRender(waitForXr);
              if (this.xr) {
                if (!this.xr.teleportation.attached) {
                  this.xr.teleportation.attach();
                }
              } else {
                this.enableTeleportation(vrTeleportationOptions);
              }
            }
          };
          this._scene.registerBeforeRender(waitForXr);
          return;
        }
      }
      if (vrTeleportationOptions.floorMeshName) {
        this._floorMeshName = vrTeleportationOptions.floorMeshName;
      }
      if (vrTeleportationOptions.floorMeshes) {
        this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
      }
      if (vrTeleportationOptions.teleportationMode) {
        this._teleportationMode = vrTeleportationOptions.teleportationMode;
      }
      if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) {
        this._teleportationTime = vrTeleportationOptions.teleportationTime;
      }
      if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) {
        this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed;
      }
      if (vrTeleportationOptions.easingFunction !== undefined) {
        this._teleportationEasing = vrTeleportationOptions.easingFunction;
      }
      const imageProcessingConfiguration = new ImageProcessingConfiguration;
      imageProcessingConfiguration.vignetteColor = new Color4(0, 0, 0, 0);
      imageProcessingConfiguration.vignetteEnabled = true;
      this._teleportationInitialized = true;
      if (this._isDefaultTeleportationTarget) {
        this._createTeleportationCircles();
      }
    }
  }
  _checkTeleportWithRay(stateObject, gazer) {
    if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
      return;
    }
    if (!gazer._teleportationRequestInitiated) {
      if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
        gazer._activatePointer();
        gazer._teleportationRequestInitiated = true;
      }
    } else {
      if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
        if (this._teleportActive) {
          this.teleportCamera(this._haloCenter);
        }
        gazer._teleportationRequestInitiated = false;
      }
    }
  }
  _checkRotate(stateObject, gazer) {
    if (gazer._teleportationRequestInitiated) {
      return;
    }
    if (!gazer._rotationLeftAsked) {
      if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
        gazer._rotationLeftAsked = true;
        if (this._rotationAllowed) {
          this._rotateCamera(false);
        }
      }
    } else {
      if (stateObject.x > -this._padSensibilityDown) {
        gazer._rotationLeftAsked = false;
      }
    }
    if (!gazer._rotationRightAsked) {
      if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
        gazer._rotationRightAsked = true;
        if (this._rotationAllowed) {
          this._rotateCamera(true);
        }
      }
    } else {
      if (stateObject.x < this._padSensibilityDown) {
        gazer._rotationRightAsked = false;
      }
    }
  }
  _checkTeleportBackwards(stateObject, gazer) {
    if (gazer._teleportationRequestInitiated) {
      return;
    }
    if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
      if (!gazer._teleportationBackRequestInitiated) {
        if (!this.currentVRCamera) {
          return;
        }
        const rotation = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
        const position = this.currentVRCamera.position;
        rotation.toEulerAnglesToRef(this._workingVector);
        this._workingVector.z = 0;
        this._workingVector.x = 0;
        Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
        this._workingQuaternion.toRotationMatrix(this._workingMatrix);
        Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
        const ray = new Ray(position, this._workingVector);
        const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
        if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
          this.teleportCamera(hit.pickedPoint);
        }
        gazer._teleportationBackRequestInitiated = true;
      }
    } else {
      gazer._teleportationBackRequestInitiated = false;
    }
  }
  _createTeleportationCircles() {
    this._teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, this._scene);
    this._teleportationTarget.isPickable = false;
    const length = 512;
    const dynamicTexture = new DynamicTexture("DynamicTexture", length, this._scene, true);
    dynamicTexture.hasAlpha = true;
    const context = dynamicTexture.getContext();
    const centerX = length / 2;
    const centerY = length / 2;
    const radius = 200;
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = this._teleportationFillColor;
    context.fill();
    context.lineWidth = 10;
    context.strokeStyle = this._teleportationBorderColor;
    context.stroke();
    context.closePath();
    dynamicTexture.update();
    const teleportationCircleMaterial = new StandardMaterial("TextPlaneMaterial", this._scene);
    teleportationCircleMaterial.diffuseTexture = dynamicTexture;
    this._teleportationTarget.material = teleportationCircleMaterial;
    const torus = CreateTorus("torusTeleportation", {
      diameter: 0.75,
      thickness: 0.1,
      tessellation: 25,
      updatable: false
    }, this._scene);
    torus.isPickable = false;
    torus.parent = this._teleportationTarget;
    const animationInnerCircle = new Animation("animationInnerCircle", "position.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);
    const keys = [];
    keys.push({
      frame: 0,
      value: 0
    });
    keys.push({
      frame: 30,
      value: 0.4
    });
    keys.push({
      frame: 60,
      value: 0
    });
    animationInnerCircle.setKeys(keys);
    const easingFunction = new SineEase;
    easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
    animationInnerCircle.setEasingFunction(easingFunction);
    torus.animations = [];
    torus.animations.push(animationInnerCircle);
    this._scene.beginAnimation(torus, 0, 60, true);
    this._hideTeleportationTarget();
  }
  _hideTeleportationTarget() {
    this._teleportActive = false;
    if (this._teleportationInitialized) {
      this._teleportationTarget.isVisible = false;
      if (this._isDefaultTeleportationTarget) {
        this._teleportationTarget.getChildren()[0].isVisible = false;
      }
    }
  }
  _rotateCamera(right) {
    if (!(this.currentVRCamera instanceof FreeCamera)) {
      return;
    }
    if (right) {
      this._rotationAngle++;
    } else {
      this._rotationAngle--;
    }
    this.currentVRCamera.animations = [];
    const target = Quaternion.FromRotationMatrix(Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
    const animationRotation = new Animation("animationRotation", "rotationQuaternion", 90, Animation.ANIMATIONTYPE_QUATERNION, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const animationRotationKeys = [];
    animationRotationKeys.push({
      frame: 0,
      value: this.currentVRCamera.rotationQuaternion
    });
    animationRotationKeys.push({
      frame: 6,
      value: target
    });
    animationRotation.setKeys(animationRotationKeys);
    animationRotation.setEasingFunction(this._circleEase);
    this.currentVRCamera.animations.push(animationRotation);
    this._postProcessMove.animations = [];
    const animationPP = new Animation("animationPP", "vignetteWeight", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const vignetteWeightKeys = [];
    vignetteWeightKeys.push({
      frame: 0,
      value: 0
    });
    vignetteWeightKeys.push({
      frame: 3,
      value: 4
    });
    vignetteWeightKeys.push({
      frame: 6,
      value: 0
    });
    animationPP.setKeys(vignetteWeightKeys);
    animationPP.setEasingFunction(this._circleEase);
    this._postProcessMove.animations.push(animationPP);
    const animationPP2 = new Animation("animationPP2", "vignetteStretch", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const vignetteStretchKeys = [];
    vignetteStretchKeys.push({
      frame: 0,
      value: 0
    });
    vignetteStretchKeys.push({
      frame: 3,
      value: 10
    });
    vignetteStretchKeys.push({
      frame: 6,
      value: 0
    });
    animationPP2.setKeys(vignetteStretchKeys);
    animationPP2.setEasingFunction(this._circleEase);
    this._postProcessMove.animations.push(animationPP2);
    this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
    this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
    this._postProcessMove.samples = 4;
    this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  }
  teleportCamera(location2) {
    if (!(this.currentVRCamera instanceof FreeCamera)) {
      return;
    }
    this._workingVector.copyFrom(location2);
    if (this.isInVRMode) {} else {
      this._workingVector.y += this._defaultHeight;
    }
    this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
    const FPS = 90;
    let speedRatio, lastFrame;
    if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) {
      lastFrame = FPS;
      const dist = Vector3.Distance(this.currentVRCamera.position, this._workingVector);
      speedRatio = this._teleportationSpeed / dist;
    } else {
      lastFrame = Math.round(this._teleportationTime * FPS / 1000);
      speedRatio = 1;
    }
    this.currentVRCamera.animations = [];
    const animationCameraTeleportation = new Animation("animationCameraTeleportation", "position", FPS, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const animationCameraTeleportationKeys = [
      {
        frame: 0,
        value: this.currentVRCamera.position
      },
      {
        frame: lastFrame,
        value: this._workingVector
      }
    ];
    animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
    animationCameraTeleportation.setEasingFunction(this._teleportationEasing);
    this.currentVRCamera.animations.push(animationCameraTeleportation);
    this._postProcessMove.animations = [];
    const midFrame = Math.round(lastFrame / 2);
    const animationPP = new Animation("animationPP", "vignetteWeight", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const vignetteWeightKeys = [];
    vignetteWeightKeys.push({
      frame: 0,
      value: 0
    });
    vignetteWeightKeys.push({
      frame: midFrame,
      value: 8
    });
    vignetteWeightKeys.push({
      frame: lastFrame,
      value: 0
    });
    animationPP.setKeys(vignetteWeightKeys);
    this._postProcessMove.animations.push(animationPP);
    const animationPP2 = new Animation("animationPP2", "vignetteStretch", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const vignetteStretchKeys = [];
    vignetteStretchKeys.push({
      frame: 0,
      value: 0
    });
    vignetteStretchKeys.push({
      frame: midFrame,
      value: 10
    });
    vignetteStretchKeys.push({
      frame: lastFrame,
      value: 0
    });
    animationPP2.setKeys(vignetteStretchKeys);
    this._postProcessMove.animations.push(animationPP2);
    this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
    this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
    this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, () => {
      this.onAfterCameraTeleport.notifyObservers(this._workingVector);
    });
    this._hideTeleportationTarget();
  }
  setLaserColor(color, pickedColor = this._pickedLaserColor) {
    this._pickedLaserColor = pickedColor;
  }
  setLaserLightingState(_enabled = true) {}
  setGazeColor(color, pickedColor = this._pickedGazeColor) {
    this._pickedGazeColor = pickedColor;
  }
  changeLaserColor(_color) {
    if (!this.updateControllerLaserColor) {
      return;
    }
  }
  changeGazeColor(color) {
    if (!this.updateGazeTrackerColor) {
      return;
    }
    if (!this._cameraGazer._gazeTracker.material) {
      return;
    }
    this._cameraGazer._gazeTracker.material.emissiveColor = color;
  }
  dispose() {
    if (this.isInVRMode) {
      this.exitVR();
    }
    if (this._postProcessMove) {
      this._postProcessMove.dispose();
    }
    if (this._vrDeviceOrientationCamera) {
      this._vrDeviceOrientationCamera.dispose();
    }
    if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) {
      document.body.removeChild(this._btnVR);
    }
    if (this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera) {
      this._deviceOrientationCamera.dispose();
    }
    if (this._cameraGazer) {
      this._cameraGazer.dispose();
    }
    if (this._teleportationTarget) {
      this._teleportationTarget.dispose();
    }
    if (this.xr) {
      this.xr.dispose();
    }
    this._floorMeshesCollection.length = 0;
    document.removeEventListener("keydown", this._onKeyDown);
    window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChangeBind);
    window.removeEventListener("resize", this._onResize);
    document.removeEventListener("fullscreenchange", this._onFullscreenChange);
    this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
    this._scene.unregisterBeforeRender(this._beforeRender);
  }
  getClassName() {
    return "VRExperienceHelper";
  }
}
VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0;
VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1;
// node_modules/@babylonjs/core/Collisions/collider.js
init_math_vector();
init_math_plane();
var intersectBoxAASphere = (boxMin, boxMax, sphereCenter, sphereRadius) => {
  if (boxMin.x > sphereCenter.x + sphereRadius) {
    return false;
  }
  if (sphereCenter.x - sphereRadius > boxMax.x) {
    return false;
  }
  if (boxMin.y > sphereCenter.y + sphereRadius) {
    return false;
  }
  if (sphereCenter.y - sphereRadius > boxMax.y) {
    return false;
  }
  if (boxMin.z > sphereCenter.z + sphereRadius) {
    return false;
  }
  if (sphereCenter.z - sphereRadius > boxMax.z) {
    return false;
  }
  return true;
};
var getLowestRoot = function() {
  const result = { root: 0, found: false };
  return function(a, b, c, maxR) {
    result.root = 0;
    result.found = false;
    const determinant = b * b - 4 * a * c;
    if (determinant < 0) {
      return result;
    }
    const sqrtD = Math.sqrt(determinant);
    let r1 = (-b - sqrtD) / (2 * a);
    let r2 = (-b + sqrtD) / (2 * a);
    if (r1 > r2) {
      const temp = r2;
      r2 = r1;
      r1 = temp;
    }
    if (r1 > 0 && r1 < maxR) {
      result.root = r1;
      result.found = true;
      return result;
    }
    if (r2 > 0 && r2 < maxR) {
      result.root = r2;
      result.found = true;
      return result;
    }
    return result;
  };
}();

class Collider {
  constructor() {
    this._collisionPoint = Vector3.Zero();
    this._planeIntersectionPoint = Vector3.Zero();
    this._tempVector = Vector3.Zero();
    this._tempVector2 = Vector3.Zero();
    this._tempVector3 = Vector3.Zero();
    this._tempVector4 = Vector3.Zero();
    this._edge = Vector3.Zero();
    this._baseToVertex = Vector3.Zero();
    this._destinationPoint = Vector3.Zero();
    this._slidePlaneNormal = Vector3.Zero();
    this._displacementVector = Vector3.Zero();
    this._radius = Vector3.One();
    this._retry = 0;
    this._basePointWorld = Vector3.Zero();
    this._velocityWorld = Vector3.Zero();
    this._normalizedVelocity = Vector3.Zero();
    this._collisionMask = -1;
  }
  get collisionMask() {
    return this._collisionMask;
  }
  set collisionMask(mask) {
    this._collisionMask = !isNaN(mask) ? mask : -1;
  }
  get slidePlaneNormal() {
    return this._slidePlaneNormal;
  }
  _initialize(source, dir, e) {
    this._velocity = dir;
    this._velocitySquaredLength = this._velocity.lengthSquared();
    const len = Math.sqrt(this._velocitySquaredLength);
    if (len === 0 || len === 1) {
      this._normalizedVelocity.copyFromFloats(dir._x, dir._y, dir._z);
    } else {
      dir.scaleToRef(1 / len, this._normalizedVelocity);
    }
    this._basePoint = source;
    source.multiplyToRef(this._radius, this._basePointWorld);
    dir.multiplyToRef(this._radius, this._velocityWorld);
    this._velocityWorldLength = this._velocityWorld.length();
    this._epsilon = e;
    this.collisionFound = false;
  }
  _checkPointInTriangle(point, pa, pb, pc, n) {
    pa.subtractToRef(point, this._tempVector);
    pb.subtractToRef(point, this._tempVector2);
    Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
    let d = Vector3.Dot(this._tempVector4, n);
    if (d < 0) {
      return false;
    }
    pc.subtractToRef(point, this._tempVector3);
    Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
    d = Vector3.Dot(this._tempVector4, n);
    if (d < 0) {
      return false;
    }
    Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
    d = Vector3.Dot(this._tempVector4, n);
    return d >= 0;
  }
  _canDoCollision(sphereCenter, sphereRadius, vecMin, vecMax) {
    const distance = Vector3.Distance(this._basePointWorld, sphereCenter);
    const max = Math.max(this._radius.x, this._radius.y, this._radius.z);
    if (distance > this._velocityWorldLength + max + sphereRadius) {
      return false;
    }
    if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
      return false;
    }
    return true;
  }
  _testTriangle(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) {
    let t0;
    let embeddedInPlane = false;
    if (!trianglePlaneArray) {
      trianglePlaneArray = [];
    }
    if (!trianglePlaneArray[faceIndex]) {
      trianglePlaneArray[faceIndex] = new Plane(0, 0, 0, 0);
      trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
    }
    const trianglePlane = trianglePlaneArray[faceIndex];
    if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
      return;
    }
    const signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
    const normalDotVelocity = Vector3.Dot(trianglePlane.normal, this._velocity);
    if (Collider.DoubleSidedCheck && normalDotVelocity > 0.0001) {
      return;
    }
    if (normalDotVelocity == 0) {
      if (Math.abs(signedDistToTrianglePlane) >= 1) {
        return;
      }
      embeddedInPlane = true;
      t0 = 0;
    } else {
      t0 = (-1 - signedDistToTrianglePlane) / normalDotVelocity;
      let t1 = (1 - signedDistToTrianglePlane) / normalDotVelocity;
      if (t0 > t1) {
        const temp = t1;
        t1 = t0;
        t0 = temp;
      }
      if (t0 > 1 || t1 < 0) {
        return;
      }
      if (t0 < 0) {
        t0 = 0;
      }
      if (t0 > 1) {
        t0 = 1;
      }
    }
    this._collisionPoint.copyFromFloats(0, 0, 0);
    let found = false;
    let t = 1;
    if (!embeddedInPlane) {
      this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
      this._velocity.scaleToRef(t0, this._tempVector);
      this._planeIntersectionPoint.addInPlace(this._tempVector);
      if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
        found = true;
        t = t0;
        this._collisionPoint.copyFrom(this._planeIntersectionPoint);
      }
    }
    if (!found) {
      let a = this._velocitySquaredLength;
      this._basePoint.subtractToRef(p1, this._tempVector);
      let b = 2 * Vector3.Dot(this._velocity, this._tempVector);
      let c = this._tempVector.lengthSquared() - 1;
      let lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        t = lowestRoot.root;
        found = true;
        this._collisionPoint.copyFrom(p1);
      }
      this._basePoint.subtractToRef(p2, this._tempVector);
      b = 2 * Vector3.Dot(this._velocity, this._tempVector);
      c = this._tempVector.lengthSquared() - 1;
      lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        t = lowestRoot.root;
        found = true;
        this._collisionPoint.copyFrom(p2);
      }
      this._basePoint.subtractToRef(p3, this._tempVector);
      b = 2 * Vector3.Dot(this._velocity, this._tempVector);
      c = this._tempVector.lengthSquared() - 1;
      lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        t = lowestRoot.root;
        found = true;
        this._collisionPoint.copyFrom(p3);
      }
      p2.subtractToRef(p1, this._edge);
      p1.subtractToRef(this._basePoint, this._baseToVertex);
      let edgeSquaredLength = this._edge.lengthSquared();
      let edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
      let edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
      a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
      b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);
      c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
      lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
        if (f >= 0 && f <= 1) {
          t = lowestRoot.root;
          found = true;
          this._edge.scaleInPlace(f);
          p1.addToRef(this._edge, this._collisionPoint);
        }
      }
      p3.subtractToRef(p2, this._edge);
      p2.subtractToRef(this._basePoint, this._baseToVertex);
      edgeSquaredLength = this._edge.lengthSquared();
      edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
      edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
      a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
      b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);
      c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
      lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
        if (f >= 0 && f <= 1) {
          t = lowestRoot.root;
          found = true;
          this._edge.scaleInPlace(f);
          p2.addToRef(this._edge, this._collisionPoint);
        }
      }
      p1.subtractToRef(p3, this._edge);
      p3.subtractToRef(this._basePoint, this._baseToVertex);
      edgeSquaredLength = this._edge.lengthSquared();
      edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
      edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
      a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
      b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);
      c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
      lowestRoot = getLowestRoot(a, b, c, t);
      if (lowestRoot.found) {
        const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
        if (f >= 0 && f <= 1) {
          t = lowestRoot.root;
          found = true;
          this._edge.scaleInPlace(f);
          p3.addToRef(this._edge, this._collisionPoint);
        }
      }
    }
    if (found) {
      const distToCollisionSquared = t * t * this._velocitySquaredLength;
      if (!this.collisionFound || distToCollisionSquared < this._nearestDistanceSquared) {
        if (hostMesh.collisionResponse) {
          if (!this.intersectionPoint) {
            this.intersectionPoint = this._collisionPoint.clone();
          } else {
            this.intersectionPoint.copyFrom(this._collisionPoint);
          }
          this._nearestDistanceSquared = distToCollisionSquared;
          this._nearestDistance = Math.sqrt(distToCollisionSquared);
          this.collisionFound = true;
        }
        this.collidedMesh = hostMesh;
      }
    }
  }
  _collide(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh, invertTriangles, triangleStrip = false) {
    if (triangleStrip) {
      if (!indices || indices.length === 0) {
        for (let i = 0;i < pts.length - 2; i += 1) {
          const p1 = pts[i];
          const p2 = pts[i + 1];
          const p3 = pts[i + 2];
          if (!p1 || !p2 || !p3) {
            continue;
          }
          if ((invertTriangles ? 1 : 0) ^ i % 2) {
            this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);
          } else {
            this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);
          }
        }
      } else {
        for (let i = indexStart;i < indexEnd - 2; i += 1) {
          const indexA = indices[i];
          const indexB = indices[i + 1];
          const indexC = indices[i + 2];
          if (indexC === 4294967295) {
            i += 2;
            continue;
          }
          const p1 = pts[indexA];
          const p2 = pts[indexB];
          const p3 = pts[indexC];
          if (!p1 || !p2 || !p3) {
            continue;
          }
          if ((invertTriangles ? 1 : 0) ^ i % 2) {
            this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);
          } else {
            this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);
          }
        }
      }
    } else if (!indices || indices.length === 0) {
      for (let i = 0;i < pts.length; i += 3) {
        const p1 = pts[i];
        const p2 = pts[i + 1];
        const p3 = pts[i + 2];
        if (invertTriangles) {
          this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);
        } else {
          this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);
        }
      }
    } else {
      for (let i = indexStart;i < indexEnd; i += 3) {
        const p1 = pts[indices[i] - decal];
        const p2 = pts[indices[i + 1] - decal];
        const p3 = pts[indices[i + 2] - decal];
        if (invertTriangles) {
          this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);
        } else {
          this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);
        }
      }
    }
  }
  _getResponse(pos, vel) {
    pos.addToRef(vel, this._destinationPoint);
    vel.scaleInPlace(this._nearestDistance / vel.length());
    this._basePoint.addToRef(vel, pos);
    pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
    this._slidePlaneNormal.normalize();
    this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
    pos.addInPlace(this._displacementVector);
    this.intersectionPoint.addInPlace(this._displacementVector);
    this._slidePlaneNormal.scaleInPlace(Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
    this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
    this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  }
}
Collider.DoubleSidedCheck = false;
// node_modules/@babylonjs/core/Collisions/collisionCoordinator.js
init_scene();
init_math_vector();
init_abstractEngine();

class DefaultCollisionCoordinator {
  constructor() {
    this._scaledPosition = Vector3.Zero();
    this._scaledVelocity = Vector3.Zero();
    this._finalPosition = Vector3.Zero();
  }
  getNewPosition(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
    position.divideToRef(collider._radius, this._scaledPosition);
    displacement.divideToRef(collider._radius, this._scaledVelocity);
    collider.collidedMesh = null;
    collider._retry = 0;
    collider._initialVelocity = this._scaledVelocity;
    collider._initialPosition = this._scaledPosition;
    this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
    this._finalPosition.multiplyInPlace(collider._radius);
    onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  }
  createCollider() {
    return new Collider;
  }
  init(scene) {
    this._scene = scene;
  }
  _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh = null) {
    const closeDistance = AbstractEngine.CollisionsEpsilon * 10;
    if (collider._retry >= maximumRetry) {
      finalPosition.copyFrom(position);
      return;
    }
    const collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask;
    collider._initialize(position, velocity, closeDistance);
    const meshes = excludedMesh && excludedMesh.surroundingMeshes || this._scene.meshes;
    for (let index = 0;index < meshes.length; index++) {
      const mesh = meshes[index];
      if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && (collisionMask & mesh.collisionGroup) !== 0) {
        mesh._checkCollision(collider);
      }
    }
    if (!collider.collisionFound) {
      position.addToRef(velocity, finalPosition);
      return;
    }
    if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
      collider._getResponse(position, velocity);
    }
    if (velocity.length() <= closeDistance) {
      finalPosition.copyFrom(position);
      return;
    }
    collider._retry++;
    this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  }
}
Scene.CollisionCoordinatorFactory = () => {
  return new DefaultCollisionCoordinator;
};

// node_modules/@babylonjs/core/Collisions/index.js
init_pickingInfo();

// node_modules/@babylonjs/core/Collisions/gpuPicker.js
init_renderTargetTexture();

// node_modules/@babylonjs/core/Materials/shaderMaterial.js
init_decorators_serialization();
init_scene();
init_math_vector();
init_buffer();
init_texture();
init_typeStore();
init_math_color();
init_webRequest();
init_engineStore();
init_materialHelper_functions();
var onCreatedEffectParameters2 = { effect: null, subMesh: null };

class ShaderMaterial extends PushMaterial {
  constructor(name144, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) {
    super(name144, scene, storeEffectOnSubMeshes);
    this._textures = {};
    this._textureArrays = {};
    this._externalTextures = {};
    this._floats = {};
    this._ints = {};
    this._uints = {};
    this._floatsArrays = {};
    this._colors3 = {};
    this._colors3Arrays = {};
    this._colors4 = {};
    this._colors4Arrays = {};
    this._vectors2 = {};
    this._vectors3 = {};
    this._vectors4 = {};
    this._quaternions = {};
    this._quaternionsArrays = {};
    this._matrices = {};
    this._matrixArrays = {};
    this._matrices3x3 = {};
    this._matrices2x2 = {};
    this._vectors2Arrays = {};
    this._vectors3Arrays = {};
    this._vectors4Arrays = {};
    this._uniformBuffers = {};
    this._textureSamplers = {};
    this._storageBuffers = {};
    this._cachedWorldViewMatrix = new Matrix;
    this._cachedWorldViewProjectionMatrix = new Matrix;
    this._multiview = false;
    this._materialHelperNeedsPreviousMatrices = false;
    this._shaderPath = shaderPath;
    this._options = {
      needAlphaBlending: false,
      needAlphaTesting: false,
      attributes: ["position", "normal", "uv"],
      uniforms: ["worldViewProjection"],
      uniformBuffers: [],
      samplers: [],
      externalTextures: [],
      samplerObjects: [],
      storageBuffers: [],
      defines: [],
      useClipPlane: false,
      ...options
    };
  }
  get shaderPath() {
    return this._shaderPath;
  }
  set shaderPath(shaderPath) {
    this._shaderPath = shaderPath;
  }
  get options() {
    return this._options;
  }
  get isMultiview() {
    return this._multiview;
  }
  getClassName() {
    return "ShaderMaterial";
  }
  needAlphaBlending() {
    return this.alpha < 1 || this._options.needAlphaBlending;
  }
  needAlphaTesting() {
    return this._options.needAlphaTesting;
  }
  _checkUniform(uniformName) {
    if (this._options.uniforms.indexOf(uniformName) === -1) {
      this._options.uniforms.push(uniformName);
    }
  }
  setTexture(name144, texture) {
    if (this._options.samplers.indexOf(name144) === -1) {
      this._options.samplers.push(name144);
    }
    this._textures[name144] = texture;
    return this;
  }
  removeTexture(name144) {
    delete this._textures[name144];
  }
  setTextureArray(name144, textures) {
    if (this._options.samplers.indexOf(name144) === -1) {
      this._options.samplers.push(name144);
    }
    this._checkUniform(name144);
    this._textureArrays[name144] = textures;
    return this;
  }
  setExternalTexture(name144, texture) {
    if (this._options.externalTextures.indexOf(name144) === -1) {
      this._options.externalTextures.push(name144);
    }
    this._externalTextures[name144] = texture;
    return this;
  }
  setFloat(name144, value) {
    this._checkUniform(name144);
    this._floats[name144] = value;
    return this;
  }
  setInt(name144, value) {
    this._checkUniform(name144);
    this._ints[name144] = value;
    return this;
  }
  setUInt(name144, value) {
    this._checkUniform(name144);
    this._uints[name144] = value;
    return this;
  }
  setFloats(name144, value) {
    this._checkUniform(name144);
    this._floatsArrays[name144] = value;
    return this;
  }
  setColor3(name144, value) {
    this._checkUniform(name144);
    this._colors3[name144] = value;
    return this;
  }
  setColor3Array(name144, value) {
    this._checkUniform(name144);
    this._colors3Arrays[name144] = value.reduce((arr, color) => {
      color.toArray(arr, arr.length);
      return arr;
    }, []);
    return this;
  }
  setColor4(name144, value) {
    this._checkUniform(name144);
    this._colors4[name144] = value;
    return this;
  }
  setColor4Array(name144, value) {
    this._checkUniform(name144);
    this._colors4Arrays[name144] = value.reduce((arr, color) => {
      color.toArray(arr, arr.length);
      return arr;
    }, []);
    return this;
  }
  setVector2(name144, value) {
    this._checkUniform(name144);
    this._vectors2[name144] = value;
    return this;
  }
  setVector3(name144, value) {
    this._checkUniform(name144);
    this._vectors3[name144] = value;
    return this;
  }
  setVector4(name144, value) {
    this._checkUniform(name144);
    this._vectors4[name144] = value;
    return this;
  }
  setQuaternion(name144, value) {
    this._checkUniform(name144);
    this._quaternions[name144] = value;
    return this;
  }
  setQuaternionArray(name144, value) {
    this._checkUniform(name144);
    this._quaternionsArrays[name144] = value.reduce((arr, quaternion) => {
      quaternion.toArray(arr, arr.length);
      return arr;
    }, []);
    return this;
  }
  setMatrix(name144, value) {
    this._checkUniform(name144);
    this._matrices[name144] = value;
    return this;
  }
  setMatrices(name144, value) {
    this._checkUniform(name144);
    const float32Array = new Float32Array(value.length * 16);
    for (let index = 0;index < value.length; index++) {
      const matrix = value[index];
      matrix.copyToArray(float32Array, index * 16);
    }
    this._matrixArrays[name144] = float32Array;
    return this;
  }
  setMatrix3x3(name144, value) {
    this._checkUniform(name144);
    this._matrices3x3[name144] = value;
    return this;
  }
  setMatrix2x2(name144, value) {
    this._checkUniform(name144);
    this._matrices2x2[name144] = value;
    return this;
  }
  setArray2(name144, value) {
    this._checkUniform(name144);
    this._vectors2Arrays[name144] = value;
    return this;
  }
  setArray3(name144, value) {
    this._checkUniform(name144);
    this._vectors3Arrays[name144] = value;
    return this;
  }
  setArray4(name144, value) {
    this._checkUniform(name144);
    this._vectors4Arrays[name144] = value;
    return this;
  }
  setUniformBuffer(name144, buffer2) {
    if (this._options.uniformBuffers.indexOf(name144) === -1) {
      this._options.uniformBuffers.push(name144);
    }
    this._uniformBuffers[name144] = buffer2;
    return this;
  }
  setTextureSampler(name144, sampler) {
    if (this._options.samplerObjects.indexOf(name144) === -1) {
      this._options.samplerObjects.push(name144);
    }
    this._textureSamplers[name144] = sampler;
    return this;
  }
  setStorageBuffer(name144, buffer2) {
    if (this._options.storageBuffers.indexOf(name144) === -1) {
      this._options.storageBuffers.push(name144);
    }
    this._storageBuffers[name144] = buffer2;
    return this;
  }
  setDefine(define, value) {
    const defineName = define.trimEnd() + " ";
    const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName));
    if (existingDefineIdx >= 0) {
      this.options.defines.splice(existingDefineIdx, 1);
    }
    if (typeof value !== "boolean" || value) {
      this.options.defines.push(defineName + value);
    }
    return this;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances) {
    return this.isReady(mesh, useInstances, subMesh);
  }
  isReady(mesh, useInstances, subMesh) {
    const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;
    if (this.isFrozen) {
      const drawWrapper2 = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper;
      if (drawWrapper2.effect && drawWrapper2._wasPreviouslyReady && drawWrapper2._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    const scene = this.getScene();
    const engine = scene.getEngine();
    const defines = [];
    const attribs = [];
    let fallbacks = null;
    let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers;
    if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) {
      this._multiview = true;
      defines.push("#define MULTIVIEW");
      if (uniforms.indexOf("viewProjection") !== -1 && uniforms.indexOf("viewProjectionR") === -1) {
        uniforms.push("viewProjectionR");
      }
    }
    for (let index = 0;index < this._options.defines.length; index++) {
      const defineToAdd = this._options.defines[index].indexOf("#define") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`;
      defines.push(defineToAdd);
    }
    for (let index = 0;index < this._options.attributes.length; index++) {
      attribs.push(this._options.attributes[index]);
    }
    if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
      if (attribs.indexOf(VertexBuffer.ColorKind) === -1) {
        attribs.push(VertexBuffer.ColorKind);
      }
      defines.push("#define VERTEXCOLOR");
    }
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices);
      if (mesh?.hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
        if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) {
          attribs.push(VertexBuffer.ColorInstanceKind);
          defines.push("#define INSTANCESCOLOR");
        }
      }
    }
    if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      const skeleton2 = mesh.skeleton;
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
      fallbacks = new EffectFallbacks;
      fallbacks.addCPUSkinningFallback(0, mesh);
      if (skeleton2.isUsingTextureForMatrices) {
        defines.push("#define BONETEXTURE");
        if (uniforms.indexOf("boneTextureWidth") === -1) {
          uniforms.push("boneTextureWidth");
        }
        if (this._options.samplers.indexOf("boneSampler") === -1) {
          this._options.samplers.push("boneSampler");
        }
      } else {
        defines.push("#define BonesPerMesh " + (skeleton2.bones.length + 1));
        if (uniforms.indexOf("mBones") === -1) {
          uniforms.push("mBones");
        }
      }
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
    }
    let numInfluencers = 0;
    const manager = mesh ? mesh.morphTargetManager : null;
    if (manager) {
      const uv = defines.indexOf("#define UV1") !== -1;
      const uv2 = defines.indexOf("#define UV2") !== -1;
      const tangent = defines.indexOf("#define TANGENT") !== -1;
      const normal = defines.indexOf("#define NORMAL") !== -1;
      const color = defines.indexOf("#define VERTEXCOLOR") !== -1;
      numInfluencers = PrepareDefinesAndAttributesForMorphTargets(manager, defines, attribs, mesh, true, normal, tangent, uv, uv2, color);
      if (manager.isUsingTextureForTargets) {
        if (uniforms.indexOf("morphTargetTextureIndices") === -1) {
          uniforms.push("morphTargetTextureIndices");
        }
        if (this._options.samplers.indexOf("morphTargets") === -1) {
          this._options.samplers.push("morphTargets");
        }
      }
      if (numInfluencers > 0) {
        uniforms = uniforms.slice();
        uniforms.push("morphTargetInfluences");
        uniforms.push("morphTargetCount");
        uniforms.push("morphTargetTextureInfo");
        uniforms.push("morphTargetTextureIndices");
      }
    } else {
      defines.push("#define NUM_MORPH_INFLUENCERS 0");
    }
    if (mesh) {
      const bvaManager = mesh.bakedVertexAnimationManager;
      if (bvaManager && bvaManager.isEnabled) {
        defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
        if (uniforms.indexOf("bakedVertexAnimationSettings") === -1) {
          uniforms.push("bakedVertexAnimationSettings");
        }
        if (uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1) {
          uniforms.push("bakedVertexAnimationTextureSizeInverted");
        }
        if (uniforms.indexOf("bakedVertexAnimationTime") === -1) {
          uniforms.push("bakedVertexAnimationTime");
        }
        if (this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1) {
          this._options.samplers.push("bakedVertexAnimationTexture");
        }
      }
      PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
    }
    for (const name144 in this._textures) {
      if (!this._textures[name144].isReady()) {
        return false;
      }
    }
    if (mesh && this.needAlphaTestingForMesh(mesh)) {
      defines.push("#define ALPHATEST");
    }
    if (this._options.useClipPlane !== false) {
      addClipPlaneUniforms(uniforms);
      prepareStringDefinesForClipPlanes(this, scene, defines);
    }
    if (scene.fogEnabled && mesh?.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {
      defines.push("#define FOG");
      if (uniforms.indexOf("view") === -1) {
        uniforms.push("view");
      }
      if (uniforms.indexOf("vFogInfos") === -1) {
        uniforms.push("vFogInfos");
      }
      if (uniforms.indexOf("vFogColor") === -1) {
        uniforms.push("vFogColor");
      }
    }
    if (this._useLogarithmicDepth) {
      defines.push("#define LOGARITHMICDEPTH");
      if (uniforms.indexOf("logarithmicDepthConstant") === -1) {
        uniforms.push("logarithmicDepthConstant");
      }
    }
    if (this.customShaderNameResolve) {
      uniforms = uniforms.slice();
      uniformBuffers = uniformBuffers.slice();
      samplers = samplers.slice();
      shaderName = this.customShaderNameResolve(this.name, uniforms, uniformBuffers, samplers, defines, attribs);
    }
    const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper(undefined, true) : this._drawWrapper;
    const previousEffect = drawWrapper?.effect ?? null;
    const previousDefines = drawWrapper?.defines ?? null;
    const join6 = defines.join(`
`);
    let effect = previousEffect;
    if (previousDefines !== join6) {
      effect = engine.createEffect(shaderName, {
        attributes: attribs,
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: this.onCompiled,
        onError: this.onError,
        indexParameters: { maxSimultaneousMorphTargets: numInfluencers },
        shaderLanguage: this._options.shaderLanguage,
        extraInitializationsAsync: this._options.extraInitializationsAsync
      }, engine);
      if (storeEffectOnSubMeshes) {
        subMesh.setEffect(effect, join6, this._materialContext);
      } else if (drawWrapper) {
        drawWrapper.setEffect(effect, join6);
      }
      if (this._onEffectCreatedObservable) {
        onCreatedEffectParameters2.effect = effect;
        onCreatedEffectParameters2.subMesh = subMesh ?? mesh?.subMeshes[0] ?? null;
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters2);
      }
    }
    drawWrapper._wasPreviouslyUsingInstances = !!useInstances;
    if (!effect?.isReady()) {
      return false;
    }
    if (previousEffect !== effect) {
      scene.resetCachedMaterial();
    }
    drawWrapper._wasPreviouslyReady = true;
    return true;
  }
  bindOnlyWorldMatrix(world, effectOverride) {
    const effect = effectOverride ?? this.getEffect();
    if (!effect) {
      return;
    }
    const uniforms = this._options.uniforms;
    if (uniforms.indexOf("world") !== -1) {
      effect.setMatrix("world", world);
    }
    const scene = this.getScene();
    if (uniforms.indexOf("worldView") !== -1) {
      world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
      effect.setMatrix("worldView", this._cachedWorldViewMatrix);
    }
    if (uniforms.indexOf("worldViewProjection") !== -1) {
      world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
      effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix);
    }
    if (uniforms.indexOf("view") !== -1) {
      effect.setMatrix("view", scene.getViewMatrix());
    }
  }
  bindForSubMesh(world, mesh, subMesh) {
    this.bind(world, mesh, subMesh._drawWrapperOverride?.effect, subMesh);
  }
  bind(world, mesh, effectOverride, subMesh) {
    const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;
    const effect = effectOverride ?? (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect());
    if (!effect) {
      return;
    }
    const scene = this.getScene();
    this._activeEffect = effect;
    this.bindOnlyWorldMatrix(world, effectOverride);
    const uniformBuffers = this._options.uniformBuffers;
    let useSceneUBO = false;
    if (effect && uniformBuffers && uniformBuffers.length > 0 && scene.getEngine().supportsUniformBuffers) {
      for (let i = 0;i < uniformBuffers.length; ++i) {
        const bufferName = uniformBuffers[i];
        switch (bufferName) {
          case "Mesh":
            if (mesh) {
              mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
              mesh.transferToEffect(world);
            }
            break;
          case "Scene":
            BindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
            scene.finalizeSceneUbo();
            useSceneUBO = true;
            break;
        }
      }
    }
    const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(scene, effect, subMesh, mesh.visibility) : scene.getCachedMaterial() !== this;
    if (effect && mustRebind) {
      if (!useSceneUBO && this._options.uniforms.indexOf("view") !== -1) {
        effect.setMatrix("view", scene.getViewMatrix());
      }
      if (!useSceneUBO && this._options.uniforms.indexOf("projection") !== -1) {
        effect.setMatrix("projection", scene.getProjectionMatrix());
      }
      if (!useSceneUBO && this._options.uniforms.indexOf("viewProjection") !== -1) {
        effect.setMatrix("viewProjection", scene.getTransformMatrix());
        if (this._multiview) {
          effect.setMatrix("viewProjectionR", scene._transformMatrixR);
        }
      }
      if (scene.activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) {
        effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
      }
      BindBonesParameters(mesh, effect);
      bindClipPlane(effect, this, scene);
      if (this._useLogarithmicDepth) {
        BindLogDepth(storeEffectOnSubMeshes ? subMesh.materialDefines : effect.defines, effect, scene);
      }
      if (mesh) {
        BindFogParameters(scene, mesh, effect);
      }
      let name144;
      for (name144 in this._textures) {
        effect.setTexture(name144, this._textures[name144]);
      }
      for (name144 in this._textureArrays) {
        effect.setTextureArray(name144, this._textureArrays[name144]);
      }
      for (name144 in this._ints) {
        effect.setInt(name144, this._ints[name144]);
      }
      for (name144 in this._uints) {
        effect.setUInt(name144, this._uints[name144]);
      }
      for (name144 in this._floats) {
        effect.setFloat(name144, this._floats[name144]);
      }
      for (name144 in this._floatsArrays) {
        effect.setArray(name144, this._floatsArrays[name144]);
      }
      for (name144 in this._colors3) {
        effect.setColor3(name144, this._colors3[name144]);
      }
      for (name144 in this._colors3Arrays) {
        effect.setArray3(name144, this._colors3Arrays[name144]);
      }
      for (name144 in this._colors4) {
        const color = this._colors4[name144];
        effect.setFloat4(name144, color.r, color.g, color.b, color.a);
      }
      for (name144 in this._colors4Arrays) {
        effect.setArray4(name144, this._colors4Arrays[name144]);
      }
      for (name144 in this._vectors2) {
        effect.setVector2(name144, this._vectors2[name144]);
      }
      for (name144 in this._vectors3) {
        effect.setVector3(name144, this._vectors3[name144]);
      }
      for (name144 in this._vectors4) {
        effect.setVector4(name144, this._vectors4[name144]);
      }
      for (name144 in this._quaternions) {
        effect.setQuaternion(name144, this._quaternions[name144]);
      }
      for (name144 in this._matrices) {
        effect.setMatrix(name144, this._matrices[name144]);
      }
      for (name144 in this._matrixArrays) {
        effect.setMatrices(name144, this._matrixArrays[name144]);
      }
      for (name144 in this._matrices3x3) {
        effect.setMatrix3x3(name144, this._matrices3x3[name144]);
      }
      for (name144 in this._matrices2x2) {
        effect.setMatrix2x2(name144, this._matrices2x2[name144]);
      }
      for (name144 in this._vectors2Arrays) {
        effect.setArray2(name144, this._vectors2Arrays[name144]);
      }
      for (name144 in this._vectors3Arrays) {
        effect.setArray3(name144, this._vectors3Arrays[name144]);
      }
      for (name144 in this._vectors4Arrays) {
        effect.setArray4(name144, this._vectors4Arrays[name144]);
      }
      for (name144 in this._quaternionsArrays) {
        effect.setArray4(name144, this._quaternionsArrays[name144]);
      }
      for (name144 in this._uniformBuffers) {
        const buffer2 = this._uniformBuffers[name144].getBuffer();
        if (buffer2) {
          effect.bindUniformBuffer(buffer2, name144);
        }
      }
      const engineWebGPU = scene.getEngine();
      const setExternalTexture = engineWebGPU.setExternalTexture;
      if (setExternalTexture) {
        for (name144 in this._externalTextures) {
          setExternalTexture.call(engineWebGPU, name144, this._externalTextures[name144]);
        }
      }
      const setTextureSampler = engineWebGPU.setTextureSampler;
      if (setTextureSampler) {
        for (name144 in this._textureSamplers) {
          setTextureSampler.call(engineWebGPU, name144, this._textureSamplers[name144]);
        }
      }
      const setStorageBuffer = engineWebGPU.setStorageBuffer;
      if (setStorageBuffer) {
        for (name144 in this._storageBuffers) {
          setStorageBuffer.call(engineWebGPU, name144, this._storageBuffers[name144]);
        }
      }
    }
    if (effect && mesh && (mustRebind || !this.isFrozen)) {
      BindMorphTargetParameters(mesh, effect);
      if (mesh.morphTargetManager && mesh.morphTargetManager.isUsingTextureForTargets) {
        mesh.morphTargetManager._bind(effect);
      }
      const bvaManager = mesh.bakedVertexAnimationManager;
      if (bvaManager && bvaManager.isEnabled) {
        const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper;
        mesh.bakedVertexAnimationManager?.bind(effect, !!drawWrapper._wasPreviouslyUsingInstances);
      }
    }
    this._afterBind(mesh, effect, subMesh);
  }
  getActiveTextures() {
    const activeTextures = super.getActiveTextures();
    for (const name144 in this._textures) {
      activeTextures.push(this._textures[name144]);
    }
    for (const name144 in this._textureArrays) {
      const array = this._textureArrays[name144];
      for (let index = 0;index < array.length; index++) {
        activeTextures.push(array[index]);
      }
    }
    return activeTextures;
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    for (const name144 in this._textures) {
      if (this._textures[name144] === texture) {
        return true;
      }
    }
    for (const name144 in this._textureArrays) {
      const array = this._textureArrays[name144];
      for (let index = 0;index < array.length; index++) {
        if (array[index] === texture) {
          return true;
        }
      }
    }
    return false;
  }
  clone(name144) {
    const result = SerializationHelper.Clone(() => new ShaderMaterial(name144, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this);
    result.name = name144;
    result.id = name144;
    if (typeof result._shaderPath === "object") {
      result._shaderPath = { ...result._shaderPath };
    }
    this._options = { ...this._options };
    Object.keys(this._options).forEach((propName) => {
      const propValue = this._options[propName];
      if (Array.isArray(propValue)) {
        this._options[propName] = propValue.slice(0);
      }
    });
    this.stencil.copyTo(result.stencil);
    for (const key in this._textures) {
      result.setTexture(key, this._textures[key]);
    }
    for (const key in this._textureArrays) {
      result.setTextureArray(key, this._textureArrays[key]);
    }
    for (const key in this._externalTextures) {
      result.setExternalTexture(key, this._externalTextures[key]);
    }
    for (const key in this._ints) {
      result.setInt(key, this._ints[key]);
    }
    for (const key in this._uints) {
      result.setUInt(key, this._uints[key]);
    }
    for (const key in this._floats) {
      result.setFloat(key, this._floats[key]);
    }
    for (const key in this._floatsArrays) {
      result.setFloats(key, this._floatsArrays[key]);
    }
    for (const key in this._colors3) {
      result.setColor3(key, this._colors3[key]);
    }
    for (const key in this._colors3Arrays) {
      result._colors3Arrays[key] = this._colors3Arrays[key];
    }
    for (const key in this._colors4) {
      result.setColor4(key, this._colors4[key]);
    }
    for (const key in this._colors4Arrays) {
      result._colors4Arrays[key] = this._colors4Arrays[key];
    }
    for (const key in this._vectors2) {
      result.setVector2(key, this._vectors2[key]);
    }
    for (const key in this._vectors3) {
      result.setVector3(key, this._vectors3[key]);
    }
    for (const key in this._vectors4) {
      result.setVector4(key, this._vectors4[key]);
    }
    for (const key in this._quaternions) {
      result.setQuaternion(key, this._quaternions[key]);
    }
    for (const key in this._quaternionsArrays) {
      result._quaternionsArrays[key] = this._quaternionsArrays[key];
    }
    for (const key in this._matrices) {
      result.setMatrix(key, this._matrices[key]);
    }
    for (const key in this._matrixArrays) {
      result._matrixArrays[key] = this._matrixArrays[key].slice();
    }
    for (const key in this._matrices3x3) {
      result.setMatrix3x3(key, this._matrices3x3[key]);
    }
    for (const key in this._matrices2x2) {
      result.setMatrix2x2(key, this._matrices2x2[key]);
    }
    for (const key in this._vectors2Arrays) {
      result.setArray2(key, this._vectors2Arrays[key]);
    }
    for (const key in this._vectors3Arrays) {
      result.setArray3(key, this._vectors3Arrays[key]);
    }
    for (const key in this._vectors4Arrays) {
      result.setArray4(key, this._vectors4Arrays[key]);
    }
    for (const key in this._uniformBuffers) {
      result.setUniformBuffer(key, this._uniformBuffers[key]);
    }
    for (const key in this._textureSamplers) {
      result.setTextureSampler(key, this._textureSamplers[key]);
    }
    for (const key in this._storageBuffers) {
      result.setStorageBuffer(key, this._storageBuffers[key]);
    }
    return result;
  }
  dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
    if (forceDisposeTextures) {
      let name144;
      for (name144 in this._textures) {
        this._textures[name144].dispose();
      }
      for (name144 in this._textureArrays) {
        const array = this._textureArrays[name144];
        for (let index = 0;index < array.length; index++) {
          array[index].dispose();
        }
      }
    }
    this._textures = {};
    super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "BABYLON.ShaderMaterial";
    serializationObject.uniqueId = this.uniqueId;
    serializationObject.options = this._options;
    serializationObject.shaderPath = this._shaderPath;
    serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;
    let name144;
    serializationObject.stencil = this.stencil.serialize();
    serializationObject.textures = {};
    for (name144 in this._textures) {
      serializationObject.textures[name144] = this._textures[name144].serialize();
    }
    serializationObject.textureArrays = {};
    for (name144 in this._textureArrays) {
      serializationObject.textureArrays[name144] = [];
      const array = this._textureArrays[name144];
      for (let index = 0;index < array.length; index++) {
        serializationObject.textureArrays[name144].push(array[index].serialize());
      }
    }
    serializationObject.ints = {};
    for (name144 in this._ints) {
      serializationObject.ints[name144] = this._ints[name144];
    }
    serializationObject.uints = {};
    for (name144 in this._uints) {
      serializationObject.uints[name144] = this._uints[name144];
    }
    serializationObject.floats = {};
    for (name144 in this._floats) {
      serializationObject.floats[name144] = this._floats[name144];
    }
    serializationObject.floatsArrays = {};
    for (name144 in this._floatsArrays) {
      serializationObject.floatsArrays[name144] = this._floatsArrays[name144];
    }
    serializationObject.colors3 = {};
    for (name144 in this._colors3) {
      serializationObject.colors3[name144] = this._colors3[name144].asArray();
    }
    serializationObject.colors3Arrays = {};
    for (name144 in this._colors3Arrays) {
      serializationObject.colors3Arrays[name144] = this._colors3Arrays[name144];
    }
    serializationObject.colors4 = {};
    for (name144 in this._colors4) {
      serializationObject.colors4[name144] = this._colors4[name144].asArray();
    }
    serializationObject.colors4Arrays = {};
    for (name144 in this._colors4Arrays) {
      serializationObject.colors4Arrays[name144] = this._colors4Arrays[name144];
    }
    serializationObject.vectors2 = {};
    for (name144 in this._vectors2) {
      const v2 = this._vectors2[name144];
      serializationObject.vectors2[name144] = [v2.x, v2.y];
    }
    serializationObject.vectors3 = {};
    for (name144 in this._vectors3) {
      const v3 = this._vectors3[name144];
      serializationObject.vectors3[name144] = [v3.x, v3.y, v3.z];
    }
    serializationObject.vectors4 = {};
    for (name144 in this._vectors4) {
      const v4 = this._vectors4[name144];
      serializationObject.vectors4[name144] = [v4.x, v4.y, v4.z, v4.w];
    }
    serializationObject.quaternions = {};
    for (name144 in this._quaternions) {
      serializationObject.quaternions[name144] = this._quaternions[name144].asArray();
    }
    serializationObject.matrices = {};
    for (name144 in this._matrices) {
      serializationObject.matrices[name144] = this._matrices[name144].asArray();
    }
    serializationObject.matrixArray = {};
    for (name144 in this._matrixArrays) {
      serializationObject.matrixArray[name144] = this._matrixArrays[name144];
    }
    serializationObject.matrices3x3 = {};
    for (name144 in this._matrices3x3) {
      serializationObject.matrices3x3[name144] = this._matrices3x3[name144];
    }
    serializationObject.matrices2x2 = {};
    for (name144 in this._matrices2x2) {
      serializationObject.matrices2x2[name144] = this._matrices2x2[name144];
    }
    serializationObject.vectors2Arrays = {};
    for (name144 in this._vectors2Arrays) {
      serializationObject.vectors2Arrays[name144] = this._vectors2Arrays[name144];
    }
    serializationObject.vectors3Arrays = {};
    for (name144 in this._vectors3Arrays) {
      serializationObject.vectors3Arrays[name144] = this._vectors3Arrays[name144];
    }
    serializationObject.vectors4Arrays = {};
    for (name144 in this._vectors4Arrays) {
      serializationObject.vectors4Arrays[name144] = this._vectors4Arrays[name144];
    }
    serializationObject.quaternionsArrays = {};
    for (name144 in this._quaternionsArrays) {
      serializationObject.quaternionsArrays[name144] = this._quaternionsArrays[name144];
    }
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl);
    let name144;
    if (source.stencil) {
      material.stencil.parse(source.stencil, scene, rootUrl);
    }
    for (name144 in source.textures) {
      material.setTexture(name144, Texture.Parse(source.textures[name144], scene, rootUrl));
    }
    for (name144 in source.textureArrays) {
      const array = source.textureArrays[name144];
      const textureArray = [];
      for (let index = 0;index < array.length; index++) {
        textureArray.push(Texture.Parse(array[index], scene, rootUrl));
      }
      material.setTextureArray(name144, textureArray);
    }
    for (name144 in source.ints) {
      material.setInt(name144, source.ints[name144]);
    }
    for (name144 in source.uints) {
      material.setUInt(name144, source.uints[name144]);
    }
    for (name144 in source.floats) {
      material.setFloat(name144, source.floats[name144]);
    }
    for (name144 in source.floatsArrays) {
      material.setFloats(name144, source.floatsArrays[name144]);
    }
    for (name144 in source.colors3) {
      material.setColor3(name144, Color3.FromArray(source.colors3[name144]));
    }
    for (name144 in source.colors3Arrays) {
      const colors = source.colors3Arrays[name144].reduce((arr, num, i) => {
        if (i % 3 === 0) {
          arr.push([num]);
        } else {
          arr[arr.length - 1].push(num);
        }
        return arr;
      }, []).map((color) => Color3.FromArray(color));
      material.setColor3Array(name144, colors);
    }
    for (name144 in source.colors4) {
      material.setColor4(name144, Color4.FromArray(source.colors4[name144]));
    }
    for (name144 in source.colors4Arrays) {
      const colors = source.colors4Arrays[name144].reduce((arr, num, i) => {
        if (i % 4 === 0) {
          arr.push([num]);
        } else {
          arr[arr.length - 1].push(num);
        }
        return arr;
      }, []).map((color) => Color4.FromArray(color));
      material.setColor4Array(name144, colors);
    }
    for (name144 in source.vectors2) {
      material.setVector2(name144, Vector2.FromArray(source.vectors2[name144]));
    }
    for (name144 in source.vectors3) {
      material.setVector3(name144, Vector3.FromArray(source.vectors3[name144]));
    }
    for (name144 in source.vectors4) {
      material.setVector4(name144, Vector4.FromArray(source.vectors4[name144]));
    }
    for (name144 in source.quaternions) {
      material.setQuaternion(name144, Quaternion.FromArray(source.quaternions[name144]));
    }
    for (name144 in source.matrices) {
      material.setMatrix(name144, Matrix.FromArray(source.matrices[name144]));
    }
    for (name144 in source.matrixArray) {
      material._matrixArrays[name144] = new Float32Array(source.matrixArray[name144]);
    }
    for (name144 in source.matrices3x3) {
      material.setMatrix3x3(name144, source.matrices3x3[name144]);
    }
    for (name144 in source.matrices2x2) {
      material.setMatrix2x2(name144, source.matrices2x2[name144]);
    }
    for (name144 in source.vectors2Arrays) {
      material.setArray2(name144, source.vectors2Arrays[name144]);
    }
    for (name144 in source.vectors3Arrays) {
      material.setArray3(name144, source.vectors3Arrays[name144]);
    }
    for (name144 in source.vectors4Arrays) {
      material.setArray4(name144, source.vectors4Arrays[name144]);
    }
    for (name144 in source.quaternionsArrays) {
      material.setArray4(name144, source.quaternionsArrays[name144]);
    }
    return material;
  }
  static ParseFromFileAsync(name144, url, scene, rootUrl = "") {
    return new Promise((resolve3, reject) => {
      const request = new WebRequest;
      request.addEventListener("readystatechange", () => {
        if (request.readyState == 4) {
          if (request.status == 200) {
            const serializationObject = JSON.parse(request.responseText);
            const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
            if (name144) {
              output.name = name144;
            }
            resolve3(output);
          } else {
            reject("Unable to load the ShaderMaterial");
          }
        }
      });
      request.open("GET", url);
      request.send();
    });
  }
  static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") {
    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);
            const serializationObject = JSON.parse(snippet.shaderMaterial);
            const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
            output.snippetId = snippetId;
            resolve3(output);
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
}
ShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`;
ShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync;
RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial);

// node_modules/@babylonjs/core/Collisions/gpuPicker.js
init_math_color();

// node_modules/@babylonjs/core/Meshes/buffer.js
init_buffer();

// node_modules/@babylonjs/core/Collisions/gpuPicker.js
class GPUPicker {
  constructor() {
    this._pickingTexture = null;
    this._idMap = [];
    this._thinIdMap = [];
    this._idColors = [];
    this._meshMaterialMap = new Map;
    this._meshRenderingCount = 0;
    this._attributeName = "instanceMeshID";
    this._shaderLanguage = 0;
    this._pickingInProgress = false;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  get pickingInProgress() {
    return this._pickingInProgress;
  }
  static _IdToRgb(id) {
    GPUPicker._TempColor.r = (id & 16711680) >> 16;
    GPUPicker._TempColor.g = (id & 65280) >> 8;
    GPUPicker._TempColor.b = (id & 255) >> 0;
  }
  _getColorIdFromReadBuffer(offset) {
    const r = this._readbuffer[offset];
    const g = this._readbuffer[offset + 1];
    const b = this._readbuffer[offset + 2];
    return (r << 16) + (g << 8) + b;
  }
  static _SetColorData(buffer2, i, r, g, b) {
    buffer2[i] = r / 255;
    buffer2[i + 1] = g / 255;
    buffer2[i + 2] = b / 255;
    buffer2[i + 3] = 1;
  }
  _createRenderTarget(scene, width, height) {
    if (this._pickingTexture) {
      this._pickingTexture.dispose();
    }
    this._pickingTexture = new RenderTargetTexture("pickingTexure", { width, height }, scene, false, undefined, 0, false, 1);
  }
  async _createColorMaterialAsync(scene) {
    if (this._defaultRenderMaterial) {
      this._defaultRenderMaterial.dispose();
    }
    this._defaultRenderMaterial = null;
    const engine = scene.getEngine();
    if (engine.isWebGPU) {
      this._shaderLanguage = 1;
    }
    const defines = [];
    const options = {
      attributes: [VertexBuffer.PositionKind, this._attributeName, "bakedVertexAnimationSettingsInstanced"],
      uniforms: ["world", "viewProjection", "meshID"],
      needAlphaBlending: false,
      defines,
      useClipPlane: null,
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this.shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_picking_fragment(), exports_picking_fragment)), Promise.resolve().then(() => (init_picking_vertex(), exports_picking_vertex))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_picking_fragment2(), exports_picking_fragment2)), Promise.resolve().then(() => (init_picking_vertex2(), exports_picking_vertex2))]);
        }
      }
    };
    this._defaultRenderMaterial = new ShaderMaterial("pickingShader", scene, "picking", options, false);
    this._defaultRenderMaterial.onBindObservable.add(this._materialBindCallback, undefined, undefined, this);
  }
  _materialBindCallback(mesh) {
    if (!mesh) {
      return;
    }
    const material = this._meshMaterialMap.get(mesh);
    const effect = material.getEffect();
    if (!mesh.hasInstances && !mesh.isAnInstance && !mesh.hasThinInstances) {
      effect.setColor4("meshID", this._idColors[mesh.uniqueId], 1);
    }
    this._meshRenderingCount++;
  }
  _generateColorData(instanceCount, id, index, r, g, b, onInstance) {
    const colorData = new Float32Array(4 * (instanceCount + 1));
    GPUPicker._SetColorData(colorData, 0, r, g, b);
    for (let i = 0;i < instanceCount; i++) {
      GPUPicker._IdToRgb(id);
      onInstance(i, id);
      GPUPicker._SetColorData(colorData, (i + 1) * 4, GPUPicker._TempColor.r, GPUPicker._TempColor.g, GPUPicker._TempColor.b);
      id++;
    }
    return colorData;
  }
  _generateThinInstanceColorData(instanceCount, id, onInstance) {
    const colorData = new Float32Array(4 * instanceCount);
    for (let i = 0;i < instanceCount; i++) {
      GPUPicker._IdToRgb(id);
      onInstance(i, id);
      GPUPicker._SetColorData(colorData, i * 4, GPUPicker._TempColor.r, GPUPicker._TempColor.g, GPUPicker._TempColor.b);
      id++;
    }
    return colorData;
  }
  setPickingList(list) {
    if (this._pickableMeshes) {
      for (let index = 0;index < this._pickableMeshes.length; index++) {
        const mesh = this._pickableMeshes[index];
        if (mesh.hasInstances) {
          mesh.removeVerticesData(this._attributeName);
        }
        if (mesh.hasThinInstances) {
          mesh.thinInstanceSetBuffer(this._attributeName, null);
        }
        if (this._pickingTexture) {
          this._pickingTexture.setMaterialForRendering(mesh, undefined);
        }
        const material = this._meshMaterialMap.get(mesh);
        if (material !== this._defaultRenderMaterial) {
          material.onBindObservable.removeCallback(this._materialBindCallback);
        }
      }
      this._pickableMeshes.length = 0;
      this._meshMaterialMap.clear();
      this._idMap.length = 0;
      this._thinIdMap.length = 0;
      this._idColors.length = 0;
      if (this._pickingTexture) {
        this._pickingTexture.renderList = [];
      }
    }
    if (!list || list.length === 0) {
      return;
    }
    this._pickableMeshes = list;
    const scene = ("mesh" in list[0] ? list[0].mesh : list[0]).getScene();
    const engine = scene.getEngine();
    const rttSizeW = engine.getRenderWidth();
    const rttSizeH = engine.getRenderHeight();
    if (!this._pickingTexture) {
      this._createRenderTarget(scene, rttSizeW, rttSizeH);
    } else {
      const size = this._pickingTexture.getSize();
      if (size.width !== rttSizeW || size.height !== rttSizeH || this._cachedScene !== scene) {
        this._createRenderTarget(scene, rttSizeW, rttSizeH);
      }
    }
    if (!this._cachedScene || this._cachedScene !== scene) {
      this._createColorMaterialAsync(scene);
    }
    this._cachedScene = scene;
    this._engine = scene.getEngine();
    for (let i = 0;i < list.length; i++) {
      const item = list[i];
      if ("mesh" in item) {
        this._meshMaterialMap.set(item.mesh, item.material);
        list[i] = item.mesh;
      } else {
        this._meshMaterialMap.set(item, this._defaultRenderMaterial);
      }
    }
    this._pickingTexture.renderList = [];
    let id = 1;
    for (let index = 0;index < this._pickableMeshes.length; index++) {
      const mesh = this._pickableMeshes[index];
      const material = this._meshMaterialMap.get(mesh);
      if (material !== this._defaultRenderMaterial) {
        material.onBindObservable.add(this._materialBindCallback, undefined, undefined, this);
      }
      this._pickingTexture.setMaterialForRendering(mesh, material);
      this._pickingTexture.renderList.push(mesh);
      if (mesh.isAnInstance) {
        continue;
      }
      GPUPicker._IdToRgb(id);
      if (mesh.hasThinInstances) {
        const colorData = this._generateThinInstanceColorData(mesh.thinInstanceCount, id, (i, id2) => {
          this._thinIdMap[id2] = { meshId: index, thinId: i };
        });
        id += mesh.thinInstanceCount;
        mesh.thinInstanceSetBuffer(this._attributeName, colorData, 4);
      } else {
        this._idMap[id] = index;
        id++;
        if (mesh.hasInstances) {
          const instances = mesh.instances;
          const colorData = this._generateColorData(instances.length, id, index, GPUPicker._TempColor.r, GPUPicker._TempColor.g, GPUPicker._TempColor.b, (i, id2) => {
            const instance = instances[i];
            this._idMap[id2] = this._pickableMeshes.indexOf(instance);
          });
          id += instances.length;
          const engine2 = mesh.getEngine();
          const buffer2 = new VertexBuffer(engine2, colorData, this._attributeName, false, false, 4, true);
          mesh.setVerticesBuffer(buffer2, true);
        } else {
          this._idColors[mesh.uniqueId] = Color3.FromInts(GPUPicker._TempColor.r, GPUPicker._TempColor.g, GPUPicker._TempColor.b);
        }
      }
    }
  }
  async pickAsync(x, y, disposeWhenDone = false) {
    if (this._pickingInProgress) {
      return null;
    }
    if (!this._pickableMeshes || this._pickableMeshes.length === 0) {
      return null;
    }
    const { x: adjustedX, y: adjustedY, rttSizeW, rttSizeH } = this._prepareForPicking(x, y);
    if (adjustedX < 0 || adjustedY < 0 || adjustedX >= rttSizeW || adjustedY >= rttSizeH) {
      return null;
    }
    this._pickingInProgress = true;
    const invertedY = rttSizeH - adjustedY - 1;
    this._preparePickingBuffer(this._engine, rttSizeW, rttSizeH, adjustedX, invertedY);
    return this._executePicking(adjustedX, invertedY, disposeWhenDone);
  }
  async multiPickAsync(xy, disposeWhenDone = false) {
    if (this._pickingInProgress) {
      return null;
    }
    if (!this._pickableMeshes || this._pickableMeshes.length === 0 || xy.length === 0) {
      return null;
    }
    if (xy.length === 1) {
      const pi = await this.pickAsync(xy[0].x, xy[0].y, disposeWhenDone);
      return {
        meshes: [pi?.mesh ?? null],
        thinInstanceIndexes: pi?.thinInstanceIndex ? [pi.thinInstanceIndex] : undefined
      };
    }
    this._pickingInProgress = true;
    let minX = xy[0].x, maxX = xy[0].x, minY = xy[0].y, maxY = xy[0].y;
    for (let i = 1;i < xy.length; i++) {
      const { x, y } = xy[i];
      minX = Math.min(minX, x);
      maxX = Math.max(maxX, x);
      minY = Math.min(minY, y);
      maxY = Math.max(maxY, y);
    }
    const { rttSizeW, rttSizeH } = this._prepareForPicking(minX, minY);
    const w = Math.max(maxX - minX, 1);
    const h = Math.max(maxY - minY, 1);
    const partialCutH = rttSizeH - maxY - 1;
    this._preparePickingBuffer(this._engine, rttSizeW, rttSizeH, minX, partialCutH, w, h);
    return this._executeMultiPicking(xy, minX, maxY, rttSizeH, w, h, disposeWhenDone);
  }
  _prepareForPicking(x, y) {
    const scene = this._cachedScene;
    const engine = scene.getEngine();
    const rttSizeW = engine.getRenderWidth();
    const rttSizeH = engine.getRenderHeight();
    const devicePixelRatio = 1 / engine._hardwareScalingLevel;
    const intX = devicePixelRatio * x >> 0;
    const intY = devicePixelRatio * y >> 0;
    return { x: intX, y: intY, rttSizeW, rttSizeH };
  }
  _preparePickingBuffer(engine, rttSizeW, rttSizeH, x, y, w = 1, h = 1) {
    this._meshRenderingCount = 0;
    const requiredBufferSize = engine.isWebGPU ? 4 * w * h + 255 & ~255 : 4 * w * h;
    if (!this._readbuffer || this._readbuffer.length < requiredBufferSize) {
      this._readbuffer = new Uint8Array(requiredBufferSize);
    }
    const size = this._pickingTexture.getSize();
    if (size.width !== rttSizeW || size.height !== rttSizeH) {
      this._createRenderTarget(this._cachedScene, rttSizeW, rttSizeH);
      this._updateRenderList();
    }
    this._pickingTexture.clearColor = new Color4(0, 0, 0, 0);
    this._pickingTexture.onBeforeRender = () => {
      this._enableScissor(x, y, w, h);
    };
    this._cachedScene.customRenderTargets.push(this._pickingTexture);
  }
  _executePicking(x, y, disposeWhenDone) {
    return new Promise((resolve3, reject) => {
      if (!this._pickingTexture) {
        this._pickingInProgress = false;
        reject();
        return;
      }
      this._pickingTexture.onAfterRender = async () => {
        this._disableScissor();
        if (this._checkRenderStatus()) {
          this._pickingTexture.onAfterRender = null;
          let pickedMesh = null;
          let thinInstanceIndex = undefined;
          const index = this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);
          if (index > -1) {
            this._cachedScene.customRenderTargets.splice(index, 1);
          }
          if (await this._readTexturePixelsAsync(x, y)) {
            const colorId = this._getColorIdFromReadBuffer(0);
            if (this._thinIdMap[colorId]) {
              pickedMesh = this._pickableMeshes[this._thinIdMap[colorId].meshId];
              thinInstanceIndex = this._thinIdMap[colorId].thinId;
            } else {
              pickedMesh = this._pickableMeshes[this._idMap[colorId]];
            }
          }
          if (disposeWhenDone) {
            this.dispose();
          }
          this._pickingInProgress = false;
          if (pickedMesh) {
            resolve3({ mesh: pickedMesh, thinInstanceIndex });
          } else {
            resolve3(null);
          }
        }
      };
    });
  }
  _executeMultiPicking(xy, minX, maxY, rttSizeH, w, h, disposeWhenDone) {
    return new Promise((resolve3, reject) => {
      if (!this._pickingTexture) {
        this._pickingInProgress = false;
        reject();
        return;
      }
      this._pickingTexture.onAfterRender = async () => {
        this._disableScissor();
        if (this._checkRenderStatus()) {
          this._pickingTexture.onAfterRender = null;
          const pickedMeshes = [];
          const thinInstanceIndexes = [];
          if (await this._readTexturePixelsAsync(minX, rttSizeH - maxY - 1, w, h)) {
            for (let i = 0;i < xy.length; i++) {
              const { pickedMesh, thinInstanceIndex } = this._getMeshFromMultiplePoints(xy[i].x, xy[i].y, minX, maxY, w);
              pickedMeshes.push(pickedMesh);
              thinInstanceIndexes.push(thinInstanceIndex ?? 0);
            }
          }
          if (disposeWhenDone) {
            this.dispose();
          }
          this._pickingInProgress = false;
          resolve3({ meshes: pickedMeshes, thinInstanceIndexes });
        }
      };
    });
  }
  _enableScissor(x, y, w = 1, h = 1) {
    if (this._engine.enableScissor) {
      this._engine.enableScissor(x, y, w, h);
    }
  }
  _disableScissor() {
    if (this._engine.disableScissor) {
      this._engine.disableScissor();
    }
  }
  _checkRenderStatus() {
    const wasSuccessfull = this._meshRenderingCount > 0;
    if (wasSuccessfull) {
      const index = this._cachedScene.customRenderTargets.indexOf(this._pickingTexture);
      if (index > -1) {
        this._cachedScene.customRenderTargets.splice(index, 1);
      }
      return true;
    }
    this._meshRenderingCount = 0;
    return false;
  }
  _getMeshFromMultiplePoints(x, y, minX, maxY, w) {
    let offsetX = (x - minX - 1) * 4;
    let offsetY = (maxY - y - 1) * w * 4;
    offsetX = Math.max(offsetX, 0);
    offsetY = Math.max(offsetY, 0);
    const colorId = this._getColorIdFromReadBuffer(offsetX + offsetY);
    let pickedMesh = null;
    let thinInstanceIndex;
    if (colorId > 0) {
      if (this._thinIdMap[colorId]) {
        pickedMesh = this._pickableMeshes[this._thinIdMap[colorId].meshId];
        thinInstanceIndex = this._thinIdMap[colorId].thinId;
      } else {
        pickedMesh = this._pickableMeshes[this._idMap[colorId]];
      }
    }
    return { pickedMesh, thinInstanceIndex };
  }
  _updateRenderList() {
    this._pickingTexture.renderList = [];
    for (const mesh of this._pickableMeshes) {
      this._pickingTexture.setMaterialForRendering(mesh, this._meshMaterialMap.get(mesh));
      this._pickingTexture.renderList.push(mesh);
    }
  }
  async _readTexturePixelsAsync(x, y, w = 1, h = 1) {
    if (!this._cachedScene || !this._pickingTexture?._texture) {
      return false;
    }
    const engine = this._cachedScene.getEngine();
    await engine._readTexturePixels(this._pickingTexture._texture, w, h, -1, 0, this._readbuffer, true, true, x, y);
    return true;
  }
  dispose() {
    this.setPickingList(null);
    this._cachedScene = null;
    this._pickingTexture?.dispose();
    this._pickingTexture = null;
    this._defaultRenderMaterial?.dispose();
    this._defaultRenderMaterial = null;
  }
}
GPUPicker._TempColor = {
  r: 0,
  g: 0,
  b: 0
};

// node_modules/@babylonjs/core/Collisions/index.js
init_picking_fragment2();
init_picking_vertex2();
init_picking_fragment();
init_picking_vertex();
// node_modules/@babylonjs/core/Compat/index.js
init_compatibilityOptions();
// node_modules/@babylonjs/core/Compute/computeEffect.js
init_logger();
init_observable();
init_domManagement();
init_shaderProcessor();
init_shaderStore();
init_timingTools();

class ComputeEffect {
  constructor(baseName, options, engine, key = "") {
    this.defines = "";
    this.onCompiled = null;
    this.onError = null;
    this.uniqueId = 0;
    this.onCompileObservable = new Observable;
    this.onErrorObservable = new Observable;
    this.onBindObservable = new Observable;
    this._wasPreviouslyReady = false;
    this._isReady = false;
    this._compilationError = "";
    this._key = "";
    this._computeSourceCodeOverride = "";
    this._pipelineContext = null;
    this._computeSourceCode = "";
    this._rawComputeSourceCode = "";
    this._shaderLanguage = 1;
    this.name = baseName;
    this._key = key;
    this._engine = engine;
    this.uniqueId = ComputeEffect._UniqueIdSeed++;
    this.defines = options.defines ?? "";
    this.onError = options.onError;
    this.onCompiled = options.onCompiled;
    this._entryPoint = options.entryPoint ?? "main";
    this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage);
    this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage);
    this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage);
    let computeSource;
    const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null;
    if (typeof baseName === "string") {
      computeSource = baseName;
    } else if (baseName.computeSource) {
      computeSource = "source:" + baseName.computeSource;
    } else if (baseName.computeElement) {
      computeSource = hostDocument?.getElementById(baseName.computeElement) || baseName.computeElement;
    } else {
      computeSource = baseName.compute || baseName;
    }
    const processorOptions = {
      defines: this.defines.split(`
`),
      indexParameters: undefined,
      isFragment: false,
      shouldUseHighPrecisionShader: false,
      processor: null,
      supportsUniformBuffers: this._engine.supportsUniformBuffers,
      shadersRepository: this._shaderRepository,
      includesShadersStore: this._includeShaderStore,
      version: (this._engine.version * 100).toString(),
      platformName: this._engine.shaderPlatformName,
      processingContext: null,
      isNDCHalfZRange: this._engine.isNDCHalfZRange,
      useReverseDepthBuffer: this._engine.useReverseDepthBuffer,
      processCodeAfterIncludes: (shaderType, code, defines) => {
        if (!defines) {
          return code;
        }
        for (const define of defines) {
          const keyValue = define.replace("#define", "").replace(";", "").trim();
          const split = keyValue.split(" ");
          if (split.length === 2) {
            const key2 = split[0];
            const value = split[1];
            if (!isNaN(parseInt(value)) || !isNaN(parseFloat(value))) {
              code = `const ${key2} = ${value};
` + code;
            }
          }
        }
        return code;
      }
    };
    this._loadShader(computeSource, "Compute", "", (computeCode) => {
      Initialize(processorOptions);
      PreProcess(computeCode, processorOptions, (migratedComputeCode) => {
        this._rawComputeSourceCode = computeCode;
        if (options.processFinalCode) {
          migratedComputeCode = options.processFinalCode(migratedComputeCode);
        }
        const finalShaders = Finalize(migratedComputeCode, "", processorOptions);
        this._useFinalCode(finalShaders.vertexCode, baseName);
      }, this._engine);
    });
  }
  _useFinalCode(migratedCommputeCode, baseName) {
    if (baseName) {
      const compute = baseName.computeElement || baseName.compute || baseName.spectorName || baseName;
      this._computeSourceCode = "//#define SHADER_NAME compute:" + compute + `
` + migratedCommputeCode;
    } else {
      this._computeSourceCode = migratedCommputeCode;
    }
    this._prepareEffect();
  }
  get key() {
    return this._key;
  }
  isReady() {
    try {
      return this._isReadyInternal();
    } catch {
      return false;
    }
  }
  _isReadyInternal() {
    if (this._isReady) {
      return true;
    }
    if (this._pipelineContext) {
      return this._pipelineContext.isReady;
    }
    return false;
  }
  getEngine() {
    return this._engine;
  }
  getPipelineContext() {
    return this._pipelineContext;
  }
  getCompilationError() {
    return this._compilationError;
  }
  executeWhenCompiled(func) {
    if (this.isReady()) {
      func(this);
      return;
    }
    this.onCompileObservable.add((effect) => {
      func(effect);
    });
    if (!this._pipelineContext || this._pipelineContext.isAsync) {
      this._checkIsReady(null);
    }
  }
  _checkIsReady(previousPipelineContext) {
    _retryWithInterval(() => this._isReadyInternal(), () => {}, (e) => {
      this._processCompilationErrors(e, previousPipelineContext);
    }, undefined, undefined, false);
  }
  _loadShader(shader147, key, optionalKey, callback) {
    if (typeof HTMLElement !== "undefined") {
      if (shader147 instanceof HTMLElement) {
        const shaderCode = GetDOMTextContent(shader147);
        callback(shaderCode);
        return;
      }
    }
    if (shader147.substring(0, 7) === "source:") {
      callback(shader147.substring(7));
      return;
    }
    if (shader147.substring(0, 7) === "base64:") {
      const shaderBinary = window.atob(shader147.substring(7));
      callback(shaderBinary);
      return;
    }
    if (this._shaderStore[shader147 + key + "Shader"]) {
      callback(this._shaderStore[shader147 + key + "Shader"]);
      return;
    }
    if (optionalKey && this._shaderStore[shader147 + optionalKey + "Shader"]) {
      callback(this._shaderStore[shader147 + optionalKey + "Shader"]);
      return;
    }
    let shaderUrl;
    if (shader147[0] === "." || shader147[0] === "/" || shader147.indexOf("http") > -1) {
      shaderUrl = shader147;
    } else {
      shaderUrl = this._shaderRepository + shader147;
    }
    this._engine._loadFile(shaderUrl + "." + key.toLowerCase() + ".fx", callback);
  }
  get computeSourceCode() {
    return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._pipelineContext?._getComputeShaderCode() ?? this._computeSourceCode;
  }
  get rawComputeSourceCode() {
    return this._rawComputeSourceCode;
  }
  _prepareEffect() {
    const defines = this.defines;
    const previousPipelineContext = this._pipelineContext;
    this._isReady = false;
    try {
      const engine = this._engine;
      this._pipelineContext = engine.createComputePipelineContext();
      this._pipelineContext._name = this._key;
      engine._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : defines, this._entryPoint);
      engine._executeWhenComputeStateIsCompiled(this._pipelineContext, (messages) => {
        if (messages && messages.numErrors > 0) {
          this._processCompilationErrors(messages, previousPipelineContext);
          return;
        }
        this._compilationError = "";
        this._isReady = true;
        if (this.onCompiled) {
          this.onCompiled(this);
        }
        this.onCompileObservable.notifyObservers(this);
        this.onCompileObservable.clear();
        if (previousPipelineContext) {
          this.getEngine()._deleteComputePipelineContext(previousPipelineContext);
        }
      });
      if (this._pipelineContext.isAsync) {
        this._checkIsReady(previousPipelineContext);
      }
    } catch (e) {
      this._processCompilationErrors(e, previousPipelineContext);
    }
  }
  _processCompilationErrors(e, previousPipelineContext = null) {
    this._compilationError = "";
    Logger.Error("Unable to compile compute effect:");
    if (this.defines) {
      Logger.Error(`Defines:
` + this.defines);
    }
    if (ComputeEffect.LogShaderCodeOnCompilationError) {
      const code = this._pipelineContext?._getComputeShaderCode();
      if (code) {
        Logger.Error("Compute code:");
        Logger.Error(code);
      }
    }
    if (typeof e === "string") {
      this._compilationError = e;
      Logger.Error("Error: " + this._compilationError);
    } else {
      for (const message of e.messages) {
        let msg = "";
        if (message.line !== undefined) {
          msg += "Line " + message.line + ", ";
        }
        if (message.offset !== undefined) {
          msg += "Offset " + message.offset + ", ";
        }
        if (message.length !== undefined) {
          msg += "Length " + message.length + ", ";
        }
        msg += message.type + ": " + message.text;
        if (this._compilationError) {
          this._compilationError += `
`;
        }
        this._compilationError += msg;
        Logger.Error(msg);
      }
    }
    if (previousPipelineContext) {
      this._pipelineContext = previousPipelineContext;
      this._isReady = true;
    }
    if (this.onError) {
      this.onError(this, this._compilationError);
    }
    this.onErrorObservable.notifyObservers(this);
  }
  dispose() {
    if (this._pipelineContext) {
      this._pipelineContext.dispose();
    }
    this._engine._releaseComputeEffect(this);
  }
  static RegisterShader(name148, computeShader) {
    ShaderStore.GetShadersStore(1)[`${name148}ComputeShader`] = computeShader;
  }
}
ComputeEffect._UniqueIdSeed = 0;
ComputeEffect.LogShaderCodeOnCompilationError = true;

// node_modules/@babylonjs/core/Compute/index.js
init_computeShader();
// node_modules/@babylonjs/core/Culling/index.js
init_transformFeedbackBoundingHelper();
init_computeShaderBoundingHelper();

// node_modules/@babylonjs/core/Culling/Octrees/octree.js
init_smartArray();

// node_modules/@babylonjs/core/Culling/Octrees/octreeBlock.js
init_math_vector();
class OctreeBlock {
  constructor(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
    this.entries = [];
    this._boundingVectors = new Array;
    this._capacity = capacity;
    this._depth = depth;
    this._maxDepth = maxDepth;
    this._creationFunc = creationFunc;
    this._minPoint = minPoint;
    this._maxPoint = maxPoint;
    this._boundingVectors.push(minPoint.clone());
    this._boundingVectors.push(maxPoint.clone());
    this._boundingVectors.push(minPoint.clone());
    this._boundingVectors[2].x = maxPoint.x;
    this._boundingVectors.push(minPoint.clone());
    this._boundingVectors[3].y = maxPoint.y;
    this._boundingVectors.push(minPoint.clone());
    this._boundingVectors[4].z = maxPoint.z;
    this._boundingVectors.push(maxPoint.clone());
    this._boundingVectors[5].z = minPoint.z;
    this._boundingVectors.push(maxPoint.clone());
    this._boundingVectors[6].x = minPoint.x;
    this._boundingVectors.push(maxPoint.clone());
    this._boundingVectors[7].y = minPoint.y;
  }
  get capacity() {
    return this._capacity;
  }
  get minPoint() {
    return this._minPoint;
  }
  get maxPoint() {
    return this._maxPoint;
  }
  addEntry(entry) {
    if (this.blocks) {
      for (let index = 0;index < this.blocks.length; index++) {
        const block = this.blocks[index];
        block.addEntry(entry);
      }
      return;
    }
    this._creationFunc(entry, this);
    if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
      this.createInnerBlocks();
    }
  }
  removeEntry(entry) {
    if (this.blocks) {
      for (let index = 0;index < this.blocks.length; index++) {
        const block = this.blocks[index];
        block.removeEntry(entry);
      }
      return;
    }
    const entryIndex = this.entries.indexOf(entry);
    if (entryIndex > -1) {
      this.entries.splice(entryIndex, 1);
    }
  }
  addEntries(entries) {
    for (let index = 0;index < entries.length; index++) {
      const mesh = entries[index];
      this.addEntry(mesh);
    }
  }
  select(frustumPlanes, selection, allowDuplicate) {
    if (BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
      if (this.blocks) {
        for (let index = 0;index < this.blocks.length; index++) {
          const block = this.blocks[index];
          block.select(frustumPlanes, selection, allowDuplicate);
        }
        return;
      }
      if (allowDuplicate) {
        selection.concat(this.entries);
      } else {
        selection.concatWithNoDuplicate(this.entries);
      }
    }
  }
  intersects(sphereCenter, sphereRadius, selection, allowDuplicate) {
    if (BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
      if (this.blocks) {
        for (let index = 0;index < this.blocks.length; index++) {
          const block = this.blocks[index];
          block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
        }
        return;
      }
      if (allowDuplicate) {
        selection.concat(this.entries);
      } else {
        selection.concatWithNoDuplicate(this.entries);
      }
    }
  }
  intersectsRay(ray, selection) {
    if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
      if (this.blocks) {
        for (let index = 0;index < this.blocks.length; index++) {
          const block = this.blocks[index];
          block.intersectsRay(ray, selection);
        }
        return;
      }
      selection.concatWithNoDuplicate(this.entries);
    }
  }
  createInnerBlocks() {
    OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
    this.entries.splice(0);
  }
  static _CreateBlocks(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
    target.blocks = new Array;
    const blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
    for (let x = 0;x < 2; x++) {
      for (let y = 0;y < 2; y++) {
        for (let z = 0;z < 2; z++) {
          const localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
          const localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
          const block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
          block.addEntries(entries);
          target.blocks.push(block);
        }
      }
    }
  }
}

// node_modules/@babylonjs/core/Culling/Octrees/octree.js
class Octree {
  constructor(creationFunc, maxBlockCapacity, maxDepth = 2) {
    this.maxDepth = maxDepth;
    this.dynamicContent = [];
    this._maxBlockCapacity = maxBlockCapacity || 64;
    this._selectionContent = new SmartArrayNoDuplicate(1024);
    this._creationFunc = creationFunc;
  }
  update(worldMin, worldMax, entries) {
    OctreeBlock._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  }
  addMesh(entry) {
    for (let index = 0;index < this.blocks.length; index++) {
      const block = this.blocks[index];
      block.addEntry(entry);
    }
  }
  removeMesh(entry) {
    for (let index = 0;index < this.blocks.length; index++) {
      const block = this.blocks[index];
      block.removeEntry(entry);
    }
  }
  select(frustumPlanes, allowDuplicate) {
    this._selectionContent.reset();
    for (let index = 0;index < this.blocks.length; index++) {
      const block = this.blocks[index];
      block.select(frustumPlanes, this._selectionContent, allowDuplicate);
    }
    if (allowDuplicate) {
      this._selectionContent.concat(this.dynamicContent);
    } else {
      this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
    }
    return this._selectionContent;
  }
  intersects(sphereCenter, sphereRadius, allowDuplicate) {
    this._selectionContent.reset();
    for (let index = 0;index < this.blocks.length; index++) {
      const block = this.blocks[index];
      block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
    }
    if (allowDuplicate) {
      this._selectionContent.concat(this.dynamicContent);
    } else {
      this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
    }
    return this._selectionContent;
  }
  intersectsRay(ray) {
    this._selectionContent.reset();
    for (let index = 0;index < this.blocks.length; index++) {
      const block = this.blocks[index];
      block.intersectsRay(ray, this._selectionContent);
    }
    this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
    return this._selectionContent;
  }
}
Octree.CreationFuncForMeshes = (entry, block) => {
  const boundingInfo = entry.getBoundingInfo();
  if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
    block.entries.push(entry);
  }
};
Octree.CreationFuncForSubMeshes = (entry, block) => {
  const boundingInfo = entry.getBoundingInfo();
  if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
    block.entries.push(entry);
  }
};
// node_modules/@babylonjs/core/Culling/Octrees/octreeSceneComponent.js
init_scene();
init_math_vector();
init_sceneComponent();
init_engineStore();
Scene.prototype.createOrUpdateSelectionOctree = function(maxCapacity = 64, maxDepth = 2) {
  let component = this._getComponent(SceneComponentConstants.NAME_OCTREE);
  if (!component) {
    component = new OctreeSceneComponent(this);
    this._addComponent(component);
  }
  if (!this._selectionOctree) {
    this._selectionOctree = new Octree(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  }
  const worldExtends = this.getWorldExtends();
  this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  return this._selectionOctree;
};
Object.defineProperty(Scene.prototype, "selectionOctree", {
  get: function() {
    return this._selectionOctree;
  },
  enumerable: true,
  configurable: true
});
AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function(maxCapacity = 64, maxDepth = 2) {
  const scene = this.getScene();
  let component = scene._getComponent(SceneComponentConstants.NAME_OCTREE);
  if (!component) {
    component = new OctreeSceneComponent(scene);
    scene._addComponent(component);
  }
  if (!this._submeshesOctree) {
    this._submeshesOctree = new Octree(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  }
  this.computeWorldMatrix(true);
  const boundingInfo = this.getBoundingInfo();
  const bbox = boundingInfo.boundingBox;
  this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  return this._submeshesOctree;
};

class OctreeSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_OCTREE;
    this.checksIsEnabled = true;
    this._tempRay = new Ray(Vector3.Zero(), new Vector3(1, 1, 1));
    scene = scene || EngineStore.LastCreatedScene;
    if (!scene) {
      return;
    }
    this.scene = scene;
    this.scene.getActiveMeshCandidates = () => this.getActiveMeshCandidates();
    this.scene.getActiveSubMeshCandidates = (mesh) => this.getActiveSubMeshCandidates(mesh);
    this.scene.getCollidingSubMeshCandidates = (mesh, collider2) => this.getCollidingSubMeshCandidates(mesh, collider2);
    this.scene.getIntersectingSubMeshCandidates = (mesh, localRay) => this.getIntersectingSubMeshCandidates(mesh, localRay);
  }
  register() {
    this.scene.onMeshRemovedObservable.add((mesh) => {
      const sceneOctree = this.scene.selectionOctree;
      if (sceneOctree !== undefined && sceneOctree !== null) {
        const index = sceneOctree.dynamicContent.indexOf(mesh);
        if (index !== -1) {
          sceneOctree.dynamicContent.splice(index, 1);
        }
      }
    });
    this.scene.onMeshImportedObservable.add((mesh) => {
      const sceneOctree = this.scene.selectionOctree;
      if (sceneOctree !== undefined && sceneOctree !== null) {
        sceneOctree.addMesh(mesh);
      }
    });
  }
  getActiveMeshCandidates() {
    return this.scene._selectionOctree?.select(this.scene.frustumPlanes) || this.scene._getDefaultMeshCandidates();
  }
  getActiveSubMeshCandidates(mesh) {
    if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
      const intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
      return intersections;
    }
    return this.scene._getDefaultSubMeshCandidates(mesh);
  }
  getIntersectingSubMeshCandidates(mesh, localRay) {
    if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
      Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
      const intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
      return intersections;
    }
    return this.scene._getDefaultSubMeshCandidates(mesh);
  }
  getCollidingSubMeshCandidates(mesh, collider2) {
    if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
      const radius = collider2._velocityWorldLength + Math.max(collider2._radius.x, collider2._radius.y, collider2._radius.z);
      const intersections = mesh._submeshesOctree.intersects(collider2._basePointWorld, radius);
      return intersections;
    }
    return this.scene._getDefaultSubMeshCandidates(mesh);
  }
  rebuild() {}
  dispose() {}
}
// node_modules/@babylonjs/core/Debug/axesViewer.js
init_math_vector();

// node_modules/@babylonjs/core/Gizmos/axisDragGizmo.js
init_observable();

// node_modules/@babylonjs/core/Meshes/Builders/cylinderBuilder.js
init_math_vector();
init_math_color();
init_scene();
init_math_axis();
init_compatibilityOptions();
function CreateCylinderVertexData(options) {
  const height = options.height || 2;
  let diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1;
  let diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1;
  diameterTop = diameterTop || 0.00001;
  diameterBottom = diameterBottom || 0.00001;
  const tessellation = (options.tessellation || 24) | 0;
  const subdivisions = (options.subdivisions || 1) | 0;
  const hasRings = options.hasRings ? true : false;
  const enclose = options.enclose ? true : false;
  const cap = options.cap === 0 ? 0 : options.cap || Mesh.CAP_ALL;
  const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const faceUV = options.faceUV || new Array(3);
  const faceColors = options.faceColors;
  const quadNb = arc !== 1 && enclose ? 2 : 0;
  const ringNb = hasRings ? subdivisions : 1;
  const surfaceNb = 2 + (1 + quadNb) * ringNb;
  let f;
  for (f = 0;f < surfaceNb; f++) {
    if (faceColors && faceColors[f] === undefined) {
      faceColors[f] = new Color4(1, 1, 1, 1);
    }
  }
  for (f = 0;f < surfaceNb; f++) {
    if (faceUV && faceUV[f] === undefined) {
      faceUV[f] = new Vector4(0, 0, 1, 1);
    }
  }
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  const colors = [];
  const angleStep = Math.PI * 2 * arc / tessellation;
  let angle;
  let h;
  let radius;
  const tan = (diameterBottom - diameterTop) / 2 / height;
  const ringVertex = Vector3.Zero();
  const ringNormal = Vector3.Zero();
  const ringFirstVertex = Vector3.Zero();
  const ringFirstNormal = Vector3.Zero();
  const quadNormal = Vector3.Zero();
  const Y = Axis.Y;
  let i;
  let j;
  let r;
  let ringIdx = 1;
  let s = 1;
  let cs = 0;
  let v = 0;
  for (i = 0;i <= subdivisions; i++) {
    h = i / subdivisions;
    radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
    ringIdx = hasRings && i !== 0 && i !== subdivisions ? 2 : 1;
    for (r = 0;r < ringIdx; r++) {
      if (hasRings) {
        s += r;
      }
      if (enclose) {
        s += 2 * r;
      }
      for (j = 0;j <= tessellation; j++) {
        angle = j * angleStep;
        ringVertex.x = Math.cos(-angle) * radius;
        ringVertex.y = -height / 2 + h * height;
        ringVertex.z = Math.sin(-angle) * radius;
        if (diameterTop === 0 && i === subdivisions) {
          ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
          ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
          ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
        } else {
          ringNormal.x = ringVertex.x;
          ringNormal.z = ringVertex.z;
          ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
          ringNormal.normalize();
        }
        if (j === 0) {
          ringFirstVertex.copyFrom(ringVertex);
          ringFirstNormal.copyFrom(ringNormal);
        }
        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
        normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
        if (hasRings) {
          v = cs !== s ? faceUV[s].y : faceUV[s].w;
        } else {
          v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
        }
        uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, useOpenGLOrientationForUV ? 1 - v : v);
        if (faceColors) {
          colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
        }
      }
      if (arc !== 1 && enclose) {
        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
        positions.push(0, ringVertex.y, 0);
        positions.push(0, ringVertex.y, 0);
        positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
        Vector3.CrossToRef(Y, ringNormal, quadNormal);
        quadNormal.normalize();
        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
        Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
        quadNormal.normalize();
        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
        if (hasRings) {
          v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w;
        } else {
          v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
        }
        uvs.push(faceUV[s + 1].x, useOpenGLOrientationForUV ? 1 - v : v);
        uvs.push(faceUV[s + 1].z, useOpenGLOrientationForUV ? 1 - v : v);
        if (hasRings) {
          v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w;
        } else {
          v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
        }
        uvs.push(faceUV[s + 2].x, useOpenGLOrientationForUV ? 1 - v : v);
        uvs.push(faceUV[s + 2].z, useOpenGLOrientationForUV ? 1 - v : v);
        if (faceColors) {
          colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
          colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
          colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
          colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
        }
      }
      if (cs !== s) {
        cs = s;
      }
    }
  }
  const e = arc !== 1 && enclose ? tessellation + 4 : tessellation;
  i = 0;
  for (s = 0;s < subdivisions; s++) {
    let i0 = 0;
    let i1 = 0;
    let i2 = 0;
    let i3 = 0;
    for (j = 0;j < tessellation; j++) {
      i0 = i * (e + 1) + j;
      i1 = (i + 1) * (e + 1) + j;
      i2 = i * (e + 1) + (j + 1);
      i3 = (i + 1) * (e + 1) + (j + 1);
      indices.push(i0, i1, i2);
      indices.push(i3, i2, i1);
    }
    if (arc !== 1 && enclose) {
      indices.push(i0 + 2, i1 + 2, i2 + 2);
      indices.push(i3 + 2, i2 + 2, i1 + 2);
      indices.push(i0 + 4, i1 + 4, i2 + 4);
      indices.push(i3 + 4, i2 + 4, i1 + 4);
    }
    i = hasRings ? i + 2 : i + 1;
  }
  const createCylinderCap = (isTop) => {
    const radius2 = isTop ? diameterTop / 2 : diameterBottom / 2;
    if (radius2 === 0) {
      return;
    }
    let angle2;
    let circleVector;
    let i2;
    const u = isTop ? faceUV[surfaceNb - 1] : faceUV[0];
    let c = null;
    if (faceColors) {
      c = isTop ? faceColors[surfaceNb - 1] : faceColors[0];
    }
    const vbase = positions.length / 3;
    const offset = isTop ? height / 2 : -height / 2;
    const center = new Vector3(0, offset, 0);
    positions.push(center.x, center.y, center.z);
    normals.push(0, isTop ? 1 : -1, 0);
    const v2 = u.y + (u.w - u.y) * 0.5;
    uvs.push(u.x + (u.z - u.x) * 0.5, useOpenGLOrientationForUV ? 1 - v2 : v2);
    if (c) {
      colors.push(c.r, c.g, c.b, c.a);
    }
    const textureScale = new Vector2(0.5, 0.5);
    for (i2 = 0;i2 <= tessellation; i2++) {
      angle2 = Math.PI * 2 * i2 * arc / tessellation;
      const cos = Math.cos(-angle2);
      const sin = Math.sin(-angle2);
      circleVector = new Vector3(cos * radius2, offset, sin * radius2);
      const textureCoordinate = new Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
      positions.push(circleVector.x, circleVector.y, circleVector.z);
      normals.push(0, isTop ? 1 : -1, 0);
      const v3 = u.y + (u.w - u.y) * textureCoordinate.y;
      uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, useOpenGLOrientationForUV ? 1 - v3 : v3);
      if (c) {
        colors.push(c.r, c.g, c.b, c.a);
      }
    }
    for (i2 = 0;i2 < tessellation; i2++) {
      if (!isTop) {
        indices.push(vbase);
        indices.push(vbase + (i2 + 1));
        indices.push(vbase + (i2 + 2));
      } else {
        indices.push(vbase);
        indices.push(vbase + (i2 + 2));
        indices.push(vbase + (i2 + 1));
      }
    }
  };
  if (cap === Mesh.CAP_START || cap === Mesh.CAP_ALL) {
    createCylinderCap(false);
  }
  if (cap === Mesh.CAP_END || cap === Mesh.CAP_ALL) {
    createCylinderCap(true);
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  if (faceColors) {
    vertexData.colors = colors;
  }
  return vertexData;
}
function CreateCylinder(name151, options = {}, scene) {
  const cylinder = new Mesh(name151, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  cylinder._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateCylinderVertexData(options);
  vertexData.applyToMesh(cylinder, options.updatable);
  return cylinder;
}
VertexData.CreateCylinder = CreateCylinderVertexData;
Mesh.CreateCylinder = (name151, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) => {
  if (scene === undefined || !(scene instanceof Scene)) {
    if (scene !== undefined) {
      sideOrientation = updatable || Mesh.DEFAULTSIDE;
      updatable = scene;
    }
    scene = subdivisions;
    subdivisions = 1;
  }
  const options = {
    height,
    diameterTop,
    diameterBottom,
    tessellation,
    subdivisions,
    sideOrientation,
    updatable
  };
  return CreateCylinder(name151, options, scene);
};

// node_modules/@babylonjs/core/Gizmos/gizmo.js
init_math_vector();

// node_modules/@babylonjs/core/Rendering/utilityLayerRenderer.js
init_scene();
init_observable();
init_pointerEvents();
init_pickingInfo();
init_engineStore();

// node_modules/@babylonjs/core/Lights/hemisphericLight.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_math_color();
init_node();
init_typeStore();
Node2.AddNodeConstructor("Light_Type_3", (name151, scene) => {
  return () => new HemisphericLight(name151, Vector3.Zero(), scene);
});

class HemisphericLight extends Light {
  constructor(name151, direction, scene) {
    super(name151, scene);
    this.groundColor = new Color3(0, 0, 0);
    this.direction = direction || Vector3.Up();
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("vLightData", 4);
    this._uniformBuffer.addUniform("vLightDiffuse", 4);
    this._uniformBuffer.addUniform("vLightSpecular", 4);
    this._uniformBuffer.addUniform("vLightGround", 3);
    this._uniformBuffer.addUniform("shadowsInfo", 3);
    this._uniformBuffer.addUniform("depthValues", 2);
    this._uniformBuffer.create();
  }
  getClassName() {
    return "HemisphericLight";
  }
  setDirectionToTarget(target) {
    this.direction = Vector3.Normalize(target.subtract(Vector3.Zero()));
    return this.direction;
  }
  getShadowGenerator() {
    return null;
  }
  transferToEffect(_effect, lightIndex) {
    const normalizeDirection = Vector3.Normalize(this.direction);
    this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0, lightIndex);
    this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
    return this;
  }
  transferToNodeMaterialEffect(effect, lightDataUniformName) {
    const normalizeDirection = Vector3.Normalize(this.direction);
    effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
    return this;
  }
  computeWorldMatrix() {
    if (!this._worldMatrix) {
      this._worldMatrix = Matrix.Identity();
    }
    return this._worldMatrix;
  }
  getTypeID() {
    return Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  }
  prepareLightSpecificDefines(defines, lightIndex) {
    defines["HEMILIGHT" + lightIndex] = true;
  }
}
__decorate([
  serializeAsColor3()
], HemisphericLight.prototype, "groundColor", undefined);
__decorate([
  serializeAsVector3()
], HemisphericLight.prototype, "direction", undefined);
RegisterClass("BABYLON.HemisphericLight", HemisphericLight);

// node_modules/@babylonjs/core/Rendering/utilityLayerRenderer.js
init_math_vector();
init_math_color();

class UtilityLayerRenderer {
  getRenderCamera(getRigParentIfPossible) {
    if (this._renderCamera) {
      return this._renderCamera;
    } else {
      let activeCam;
      if (this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1) {
        activeCam = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1];
      } else {
        activeCam = this.originalScene.activeCamera;
      }
      if (getRigParentIfPossible && activeCam && activeCam.isRigCamera) {
        return activeCam.rigParent;
      }
      return activeCam;
    }
  }
  setRenderCamera(cam) {
    this._renderCamera = cam;
  }
  _getSharedGizmoLight() {
    if (!this._sharedGizmoLight) {
      this._sharedGizmoLight = new HemisphericLight("shared gizmo light", new Vector3(0, 1, 0), this.utilityLayerScene);
      this._sharedGizmoLight.intensity = 2;
      this._sharedGizmoLight.groundColor = Color3.Gray();
    }
    return this._sharedGizmoLight;
  }
  static get DefaultUtilityLayer() {
    if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
      return UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene);
    }
    return UtilityLayerRenderer._DefaultUtilityLayer;
  }
  static _CreateDefaultUtilityLayerFromScene(scene) {
    UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(scene);
    UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {
      UtilityLayerRenderer._DefaultUtilityLayer = null;
    });
    return UtilityLayerRenderer._DefaultUtilityLayer;
  }
  static get DefaultKeepDepthUtilityLayer() {
    if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
      UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(EngineStore.LastCreatedScene);
      UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
      UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {
        UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
      });
    }
    return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  }
  constructor(originalScene, handleEvents = true, manualRender = false) {
    this.originalScene = originalScene;
    this.handleEvents = handleEvents;
    this._pointerCaptures = {};
    this._lastPointerEvents = {};
    this._sharedGizmoLight = null;
    this._renderCamera = null;
    this.pickUtilitySceneFirst = true;
    this.shouldRender = true;
    this.onlyCheckPointerDownEvents = true;
    this.processAllEvents = false;
    this.pickingEnabled = true;
    this.onPointerOutObservable = new Observable;
    this.utilityLayerScene = new Scene(originalScene.getEngine(), { virtual: true });
    this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
    this.utilityLayerScene._allowPostProcessClearColor = false;
    this.utilityLayerScene.postProcessesEnabled = false;
    this.utilityLayerScene.detachControl();
    if (handleEvents) {
      this._originalPointerObserver = originalScene.onPrePointerObservable.add((prePointerInfo) => {
        if (!this.utilityLayerScene.activeCamera) {
          return;
        }
        if (!this.pickingEnabled) {
          return;
        }
        if (!this.processAllEvents) {
          if (prePointerInfo.type !== PointerEventTypes.POINTERMOVE && prePointerInfo.type !== PointerEventTypes.POINTERUP && prePointerInfo.type !== PointerEventTypes.POINTERDOWN && prePointerInfo.type !== PointerEventTypes.POINTERDOUBLETAP) {
            return;
          }
        }
        this.utilityLayerScene.pointerX = originalScene.pointerX;
        this.utilityLayerScene.pointerY = originalScene.pointerY;
        const pointerEvent = prePointerInfo.event;
        if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
          this._pointerCaptures[pointerEvent.pointerId] = false;
          return;
        }
        const getNearPickDataForScene = (scene) => {
          let scenePick = null;
          if (prePointerInfo.nearInteractionPickingInfo) {
            if (prePointerInfo.nearInteractionPickingInfo.pickedMesh.getScene() == scene) {
              scenePick = prePointerInfo.nearInteractionPickingInfo;
            } else {
              scenePick = new PickingInfo;
            }
          } else if (scene !== this.utilityLayerScene && prePointerInfo.originalPickingInfo) {
            scenePick = prePointerInfo.originalPickingInfo;
          } else {
            let previousActiveCamera = null;
            if (this._renderCamera) {
              previousActiveCamera = scene._activeCamera;
              scene._activeCamera = this._renderCamera;
              prePointerInfo.ray = null;
            }
            scenePick = prePointerInfo.ray ? scene.pickWithRay(prePointerInfo.ray) : scene.pick(originalScene.pointerX, originalScene.pointerY);
            if (previousActiveCamera) {
              scene._activeCamera = previousActiveCamera;
            }
          }
          return scenePick;
        };
        const utilityScenePick = getNearPickDataForScene(this.utilityLayerScene);
        if (!prePointerInfo.ray && utilityScenePick) {
          prePointerInfo.ray = utilityScenePick.ray;
        }
        if (prePointerInfo.originalPickingInfo?.aimTransform && utilityScenePick) {
          utilityScenePick.aimTransform = prePointerInfo.originalPickingInfo.aimTransform;
          utilityScenePick.gripTransform = prePointerInfo.originalPickingInfo.gripTransform;
        }
        this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
        if (this.onlyCheckPointerDownEvents && prePointerInfo.type != PointerEventTypes.POINTERDOWN) {
          if (!prePointerInfo.skipOnPointerObservable) {
            this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);
          }
          if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) {
            this._pointerCaptures[pointerEvent.pointerId] = false;
          }
          return;
        }
        if (this.utilityLayerScene.autoClearDepthAndStencil || this.pickUtilitySceneFirst) {
          if (utilityScenePick && utilityScenePick.hit) {
            if (!prePointerInfo.skipOnPointerObservable) {
              this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);
            }
            prePointerInfo.skipOnPointerObservable = true;
          }
        } else {
          const originalScenePick = getNearPickDataForScene(originalScene);
          const pointerEvent2 = prePointerInfo.event;
          if (originalScenePick && utilityScenePick) {
            if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
              if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
                this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent2);
                prePointerInfo.skipOnPointerObservable = true;
              } else if (prePointerInfo.type === PointerEventTypes.POINTERDOWN) {
                this._pointerCaptures[pointerEvent2.pointerId] = true;
                this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent2);
              } else if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {
                if (this._lastPointerEvents[pointerEvent2.pointerId]) {
                  this.onPointerOutObservable.notifyObservers(pointerEvent2.pointerId);
                  delete this._lastPointerEvents[pointerEvent2.pointerId];
                }
                this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent2);
              }
            } else if (!this._pointerCaptures[pointerEvent2.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
              this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent2);
              if (!prePointerInfo.skipOnPointerObservable) {
                prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
              }
            } else if (!this._pointerCaptures[pointerEvent2.pointerId] && utilityScenePick.distance >= originalScenePick.distance) {
              if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
                this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent2);
                prePointerInfo.skipOnPointerObservable = true;
              } else {
                if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {
                  if (this._lastPointerEvents[pointerEvent2.pointerId]) {
                    this.onPointerOutObservable.notifyObservers(pointerEvent2.pointerId);
                    delete this._lastPointerEvents[pointerEvent2.pointerId];
                  }
                }
                this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent2);
              }
            }
            if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent2.pointerId]) {
              this._pointerCaptures[pointerEvent2.pointerId] = false;
            }
          }
        }
      });
      if (this._originalPointerObserver) {
        originalScene.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver);
      }
    }
    this.utilityLayerScene.autoClear = false;
    if (!manualRender) {
      this._afterRenderObserver = this.originalScene.onAfterRenderCameraObservable.add((camera2) => {
        if (this.shouldRender && camera2 == this.getRenderCamera()) {
          this.render();
        }
      });
    }
    this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(() => {
      this.dispose();
    });
    this._updateCamera();
  }
  _notifyObservers(prePointerInfo, pickInfo, pointerEvent) {
    if (!prePointerInfo.skipOnPointerObservable) {
      this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo), prePointerInfo.type);
      this._lastPointerEvents[pointerEvent.pointerId] = true;
    }
  }
  render() {
    this._updateCamera();
    if (this.utilityLayerScene.activeCamera) {
      const oldScene = this.utilityLayerScene.activeCamera.getScene();
      const camera2 = this.utilityLayerScene.activeCamera;
      camera2._scene = this.utilityLayerScene;
      if (camera2.leftCamera) {
        camera2.leftCamera._scene = this.utilityLayerScene;
      }
      if (camera2.rightCamera) {
        camera2.rightCamera._scene = this.utilityLayerScene;
      }
      this.utilityLayerScene.render(false);
      camera2._scene = oldScene;
      if (camera2.leftCamera) {
        camera2.leftCamera._scene = oldScene;
      }
      if (camera2.rightCamera) {
        camera2.rightCamera._scene = oldScene;
      }
    }
  }
  dispose() {
    this.onPointerOutObservable.clear();
    if (this._afterRenderObserver) {
      this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver);
    }
    if (this._sceneDisposeObserver) {
      this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
    }
    if (this._originalPointerObserver) {
      this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
    }
    this.utilityLayerScene.dispose();
  }
  _updateCamera() {
    this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera();
    this.utilityLayerScene.activeCamera = this.getRenderCamera();
  }
}
UtilityLayerRenderer._DefaultUtilityLayer = null;
UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;

// node_modules/@babylonjs/core/Gizmos/gizmo.js
init_pointerEvents();
var GizmoAnchorPoint;
(function(GizmoAnchorPoint2) {
  GizmoAnchorPoint2[GizmoAnchorPoint2["Origin"] = 0] = "Origin";
  GizmoAnchorPoint2[GizmoAnchorPoint2["Pivot"] = 1] = "Pivot";
})(GizmoAnchorPoint || (GizmoAnchorPoint = {}));
var GizmoCoordinatesMode;
(function(GizmoCoordinatesMode2) {
  GizmoCoordinatesMode2[GizmoCoordinatesMode2["World"] = 0] = "World";
  GizmoCoordinatesMode2[GizmoCoordinatesMode2["Local"] = 1] = "Local";
})(GizmoCoordinatesMode || (GizmoCoordinatesMode = {}));

class Gizmo {
  set scaleRatio(value) {
    this._scaleRatio = value;
  }
  get scaleRatio() {
    return this._scaleRatio;
  }
  get isHovered() {
    return this._isHovered;
  }
  get attachedMesh() {
    return this._attachedMesh;
  }
  set attachedMesh(value) {
    this._attachedMesh = value;
    if (value) {
      this._attachedNode = value;
    }
    this._rootMesh.setEnabled(value ? true : false);
    this._attachedNodeChanged(value);
  }
  get attachedNode() {
    return this._attachedNode;
  }
  set attachedNode(value) {
    this._attachedNode = value;
    this._attachedMesh = null;
    this._rootMesh.setEnabled(value ? true : false);
    this._attachedNodeChanged(value);
  }
  setCustomMesh(mesh) {
    if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
      throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
    }
    this._rootMesh.getChildMeshes().forEach((c) => {
      c.dispose();
    });
    mesh.parent = this._rootMesh;
    this._customMeshSet = true;
  }
  get additionalTransformNode() {
    return this._additionalTransformNode;
  }
  set additionalTransformNode(value) {
    this._additionalTransformNode = value;
  }
  set updateGizmoRotationToMatchAttachedMesh(value) {
    this._updateGizmoRotationToMatchAttachedMesh = value;
  }
  get updateGizmoRotationToMatchAttachedMesh() {
    return this._updateGizmoRotationToMatchAttachedMesh;
  }
  set updateGizmoPositionToMatchAttachedMesh(value) {
    this._updateGizmoPositionToMatchAttachedMesh = value;
  }
  get updateGizmoPositionToMatchAttachedMesh() {
    return this._updateGizmoPositionToMatchAttachedMesh;
  }
  set anchorPoint(value) {
    this._anchorPoint = value;
  }
  get anchorPoint() {
    return this._anchorPoint;
  }
  set coordinatesMode(coordinatesMode) {
    this._coordinatesMode = coordinatesMode;
    const local = coordinatesMode == 1;
    this.updateGizmoRotationToMatchAttachedMesh = local;
    this.updateGizmoPositionToMatchAttachedMesh = true;
  }
  get coordinatesMode() {
    return this._coordinatesMode;
  }
  set updateScale(value) {
    this._updateScale = value;
  }
  get updateScale() {
    return this._updateScale;
  }
  _attachedNodeChanged(value) {}
  constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer) {
    this.gizmoLayer = gizmoLayer;
    this._attachedMesh = null;
    this._attachedNode = null;
    this._customRotationQuaternion = null;
    this._scaleRatio = 1;
    this._isHovered = false;
    this._customMeshSet = false;
    this._updateGizmoRotationToMatchAttachedMesh = true;
    this._updateGizmoPositionToMatchAttachedMesh = true;
    this._anchorPoint = 0;
    this._updateScale = true;
    this._coordinatesMode = 1;
    this._interactionsEnabled = true;
    this._rightHandtoLeftHandMatrix = Matrix.RotationY(Math.PI);
    this._rootMesh = new Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
    this._rootMesh.rotationQuaternion = Quaternion.Identity();
    this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(() => {
      this._update();
    });
  }
  get customRotationQuaternion() {
    return this._customRotationQuaternion;
  }
  set customRotationQuaternion(customRotationQuaternion) {
    this._customRotationQuaternion = customRotationQuaternion;
  }
  _update() {
    if (this.attachedNode) {
      let effectiveNode = this.attachedNode;
      if (this.attachedMesh) {
        effectiveNode = this.attachedMesh || this.attachedNode;
      }
      if (this.updateGizmoPositionToMatchAttachedMesh) {
        if (this.anchorPoint == 1 && effectiveNode.getAbsolutePivotPoint) {
          const position = effectiveNode.getAbsolutePivotPoint();
          this._rootMesh.position.copyFrom(position);
        } else {
          const row = effectiveNode.getWorldMatrix().getRow(3);
          const position = row ? row.toVector3() : new Vector3(0, 0, 0);
          this._rootMesh.position.copyFrom(position);
        }
      }
      if (this.updateGizmoRotationToMatchAttachedMesh) {
        const supportedNode = effectiveNode._isMesh || effectiveNode.getClassName() === "AbstractMesh" || effectiveNode.getClassName() === "TransformNode" || effectiveNode.getClassName() === "InstancedMesh";
        const transformNode = supportedNode ? effectiveNode : undefined;
        effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion, undefined, Gizmo.PreserveScaling ? transformNode : undefined);
        this._rootMesh.rotationQuaternion.normalize();
      } else {
        if (this._customRotationQuaternion) {
          this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion);
        } else {
          this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
        }
      }
      if (this.updateScale) {
        const activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera;
        const cameraPosition = activeCamera.globalPosition;
        this._rootMesh.position.subtractToRef(cameraPosition, TmpVectors.Vector3[0]);
        let scale = this.scaleRatio;
        if (activeCamera.mode == Camera.ORTHOGRAPHIC_CAMERA) {
          if (activeCamera.orthoTop && activeCamera.orthoBottom) {
            const orthoHeight = activeCamera.orthoTop - activeCamera.orthoBottom;
            scale *= orthoHeight;
          }
        } else {
          const camForward = activeCamera.getScene().useRightHandedSystem ? Vector3.RightHandedForwardReadOnly : Vector3.LeftHandedForwardReadOnly;
          const direction = activeCamera.getDirection(camForward);
          scale *= Vector3.Dot(TmpVectors.Vector3[0], direction);
        }
        this._rootMesh.scaling.setAll(scale);
        if (effectiveNode._getWorldMatrixDeterminant() < 0 && !Gizmo.PreserveScaling) {
          this._rootMesh.scaling.y *= -1;
        }
      } else {
        this._rootMesh.scaling.setAll(this.scaleRatio);
      }
    }
    if (this.additionalTransformNode) {
      this._rootMesh.computeWorldMatrix(true);
      this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(), TmpVectors.Matrix[0]);
      TmpVectors.Matrix[0].decompose(this._rootMesh.scaling, this._rootMesh.rotationQuaternion, this._rootMesh.position);
    }
  }
  _handlePivotMatrixInverse(transform, localMatrix, result) {
    if (transform.isUsingPivotMatrix() && !transform.isUsingPostMultiplyPivotMatrix()) {
      transform.getPivotMatrix().invertToRef(TmpVectors.Matrix[5]);
      TmpVectors.Matrix[5].multiplyToRef(localMatrix, result);
      return;
    }
    result.copyFrom(localMatrix);
  }
  _matrixChanged() {
    if (!this._attachedNode) {
      return;
    }
    if (this._attachedNode._isCamera) {
      const camera2 = this._attachedNode;
      let worldMatrix;
      let worldMatrixUC;
      if (camera2.parent) {
        const parentInv = TmpVectors.Matrix[1];
        camera2.parent._worldMatrix.invertToRef(parentInv);
        this._attachedNode._worldMatrix.multiplyToRef(parentInv, TmpVectors.Matrix[0]);
        worldMatrix = TmpVectors.Matrix[0];
      } else {
        worldMatrix = this._attachedNode._worldMatrix;
      }
      if (camera2.getScene().useRightHandedSystem) {
        this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, TmpVectors.Matrix[1]);
        worldMatrixUC = TmpVectors.Matrix[1];
      } else {
        worldMatrixUC = worldMatrix;
      }
      worldMatrixUC.decompose(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);
      const inheritsTargetCamera = this._attachedNode.getClassName() === "FreeCamera" || this._attachedNode.getClassName() === "FlyCamera" || this._attachedNode.getClassName() === "ArcFollowCamera" || this._attachedNode.getClassName() === "TargetCamera" || this._attachedNode.getClassName() === "TouchCamera" || this._attachedNode.getClassName() === "UniversalCamera";
      if (inheritsTargetCamera) {
        const targetCamera2 = this._attachedNode;
        targetCamera2.rotation = TmpVectors.Quaternion[0].toEulerAngles();
        if (targetCamera2.rotationQuaternion) {
          targetCamera2.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);
          targetCamera2.rotationQuaternion.normalize();
        }
      }
      camera2.position.copyFrom(TmpVectors.Vector3[0]);
    } else if (this._attachedNode._isMesh || this._attachedNode.getClassName() === "AbstractMesh" || this._attachedNode.getClassName() === "TransformNode" || this._attachedNode.getClassName() === "InstancedMesh") {
      const transform = this._attachedNode;
      if (transform.parent) {
        const parentInv = TmpVectors.Matrix[0];
        const localMat = TmpVectors.Matrix[1];
        transform.parent.getWorldMatrix().invertToRef(parentInv);
        this._attachedNode.getWorldMatrix().multiplyToRef(parentInv, localMat);
        const matrixToDecompose = TmpVectors.Matrix[4];
        this._handlePivotMatrixInverse(transform, localMat, matrixToDecompose);
        matrixToDecompose.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined, Gizmo.UseAbsoluteScaling);
        TmpVectors.Quaternion[0].normalize();
        if (transform.isUsingPivotMatrix()) {
          const r = TmpVectors.Quaternion[1];
          Quaternion.RotationYawPitchRollToRef(transform.rotation.y, transform.rotation.x, transform.rotation.z, r);
          const scaleMatrix = TmpVectors.Matrix[2];
          Matrix.ScalingToRef(transform.scaling.x, transform.scaling.y, transform.scaling.z, scaleMatrix);
          const rotationMatrix = TmpVectors.Matrix[2];
          r.toRotationMatrix(rotationMatrix);
          const pivotMatrix = transform.getPivotMatrix();
          const invPivotMatrix = TmpVectors.Matrix[3];
          pivotMatrix.invertToRef(invPivotMatrix);
          pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);
          TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, TmpVectors.Matrix[5]);
          TmpVectors.Matrix[5].multiplyToRef(invPivotMatrix, TmpVectors.Matrix[6]);
          TmpVectors.Matrix[6].getTranslationToRef(TmpVectors.Vector3[1]);
          transform.position.subtractInPlace(TmpVectors.Vector3[1]);
        }
      } else {
        const matrixToDecompose = TmpVectors.Matrix[4];
        this._handlePivotMatrixInverse(transform, this._attachedNode._worldMatrix, matrixToDecompose);
        matrixToDecompose.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined, Gizmo.UseAbsoluteScaling);
      }
      TmpVectors.Vector3[0].scaleInPlace(1 / transform.scalingDeterminant);
      transform.scaling.copyFrom(TmpVectors.Vector3[0]);
      if (!transform.billboardMode) {
        if (transform.rotationQuaternion) {
          transform.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);
          transform.rotationQuaternion.normalize();
        } else {
          transform.rotation = TmpVectors.Quaternion[0].toEulerAngles();
        }
      }
    } else if (this._attachedNode.getClassName() === "Bone") {
      const bone2 = this._attachedNode;
      const parent = bone2.getParent();
      if (parent) {
        const invParent = TmpVectors.Matrix[0];
        const boneLocalMatrix = TmpVectors.Matrix[1];
        parent.getFinalMatrix().invertToRef(invParent);
        bone2.getFinalMatrix().multiplyToRef(invParent, boneLocalMatrix);
        const lmat = bone2.getLocalMatrix();
        lmat.copyFrom(boneLocalMatrix);
      } else {
        const lmat = bone2.getLocalMatrix();
        lmat.copyFrom(bone2.getFinalMatrix());
      }
      bone2.markAsDirty();
    } else {
      const light = this._attachedNode;
      if (light.getTypeID) {
        const type = light.getTypeID();
        if (type === Light.LIGHTTYPEID_DIRECTIONALLIGHT || type === Light.LIGHTTYPEID_SPOTLIGHT || type === Light.LIGHTTYPEID_POINTLIGHT) {
          const parent = light.parent;
          if (parent) {
            const invParent = TmpVectors.Matrix[0];
            const nodeLocalMatrix = TmpVectors.Matrix[1];
            parent.getWorldMatrix().invertToRef(invParent);
            light.getWorldMatrix().multiplyToRef(invParent, nodeLocalMatrix);
            nodeLocalMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);
          } else {
            this._attachedNode._worldMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);
          }
          light.position = new Vector3(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z);
          if (light.direction) {
            light.direction = new Vector3(light.direction.x, light.direction.y, light.direction.z);
          }
        }
      }
    }
  }
  _setGizmoMeshMaterial(gizmoMeshes, material) {
    if (gizmoMeshes) {
      gizmoMeshes.forEach((m) => {
        m.material = material;
        if (m.color) {
          m.color = material.diffuseColor;
        }
      });
    }
  }
  static GizmoAxisPointerObserver(gizmoLayer, gizmoAxisCache) {
    let dragging = false;
    let activeDragButton = -1;
    let forcePointerUp = false;
    const pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
      if (pointerInfo.pickInfo) {
        forcePointerUp = dragging && pointerInfo.event.button !== -1 && pointerInfo.event.button !== activeDragButton;
        if (forcePointerUp || pointerInfo.type === PointerEventTypes.POINTERUP) {
          gizmoAxisCache.forEach((cache) => {
            cache.active = false;
            dragging = false;
            activeDragButton = -1;
            cache.gizmoMeshes.forEach((m) => {
              m.material = cache.dragBehavior.enabled ? cache.material : cache.disableMaterial;
              if (m.color) {
                m.color = cache.material.diffuseColor;
              }
            });
          });
        } else if (pointerInfo.type === PointerEventTypes.POINTERMOVE) {
          if (dragging) {
            return;
          }
          gizmoAxisCache.forEach((cache) => {
            if (cache.colliderMeshes && cache.gizmoMeshes) {
              const isHovered = cache.colliderMeshes?.indexOf(pointerInfo?.pickInfo?.pickedMesh) != -1;
              const material = cache.dragBehavior.enabled ? isHovered || cache.active ? cache.hoverMaterial : cache.material : cache.disableMaterial;
              cache.gizmoMeshes.forEach((m) => {
                m.material = material;
                if (m.color) {
                  m.color = material.diffuseColor;
                }
              });
            }
          });
        } else if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {
          if (gizmoAxisCache.has(pointerInfo.pickInfo.pickedMesh?.parent)) {
            dragging = true;
            activeDragButton = pointerInfo.event.button;
            const statusMap = gizmoAxisCache.get(pointerInfo.pickInfo.pickedMesh?.parent);
            statusMap.active = true;
            gizmoAxisCache.forEach((cache) => {
              const isHovered = cache.colliderMeshes?.indexOf(pointerInfo?.pickInfo?.pickedMesh) != -1;
              const material = (isHovered || cache.active) && cache.dragBehavior.enabled ? cache.hoverMaterial : cache.disableMaterial;
              cache.gizmoMeshes.forEach((m) => {
                m.material = material;
                if (m.color) {
                  m.color = material.diffuseColor;
                }
              });
            });
          }
        }
      }
    });
    return pointerObserver;
  }
  dispose() {
    this._rootMesh.dispose();
    if (this._beforeRenderObserver) {
      this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
    }
  }
}
Gizmo.PreserveScaling = false;
Gizmo.UseAbsoluteScaling = true;

// node_modules/@babylonjs/core/Gizmos/axisDragGizmo.js
init_math_color();
init_math_vector();

// node_modules/@babylonjs/core/Debug/axesViewer.js
init_math_color();
init_engineStore();
// node_modules/@babylonjs/core/Debug/boneAxesViewer.js
init_math_vector();
init_math_axis();
// node_modules/@babylonjs/core/Debug/debugLayer.js
init_tools();
init_observable();
init_scene();
init_engineStore();
init_abstractEngine();
Object.defineProperty(Scene.prototype, "debugLayer", {
  get: function() {
    if (!this._debugLayer) {
      this._debugLayer = new DebugLayer(this);
    }
    return this._debugLayer;
  },
  enumerable: true,
  configurable: true
});
var DebugLayerTab;
(function(DebugLayerTab2) {
  DebugLayerTab2[DebugLayerTab2["Properties"] = 0] = "Properties";
  DebugLayerTab2[DebugLayerTab2["Debug"] = 1] = "Debug";
  DebugLayerTab2[DebugLayerTab2["Statistics"] = 2] = "Statistics";
  DebugLayerTab2[DebugLayerTab2["Tools"] = 3] = "Tools";
  DebugLayerTab2[DebugLayerTab2["Settings"] = 4] = "Settings";
})(DebugLayerTab || (DebugLayerTab = {}));

class DebugLayer {
  get onPropertyChangedObservable() {
    if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {
      return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable;
    }
    if (!this._onPropertyChangedObservable) {
      this._onPropertyChangedObservable = new Observable;
    }
    return this._onPropertyChangedObservable;
  }
  get onSelectionChangedObservable() {
    if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {
      return this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable;
    }
    if (!this._onSelectionChangedObservable) {
      this._onSelectionChangedObservable = new Observable;
    }
    return this._onSelectionChangedObservable;
  }
  constructor(scene) {
    this.BJSINSPECTOR = this._getGlobalInspector();
    this._scene = scene || EngineStore.LastCreatedScene;
    if (!this._scene) {
      return;
    }
    this._scene.onDisposeObservable.add(() => {
      if (this._scene._debugLayer) {
        this._scene._debugLayer.hide();
      }
    });
  }
  _createInspector(config) {
    if (this.isVisible()) {
      return;
    }
    if (this._onPropertyChangedObservable) {
      for (const observer2 of this._onPropertyChangedObservable.observers) {
        this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer2);
      }
      this._onPropertyChangedObservable.clear();
      this._onPropertyChangedObservable = undefined;
    }
    if (this._onSelectionChangedObservable) {
      for (const observer2 of this._onSelectionChangedObservable.observers) {
        this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(observer2);
      }
      this._onSelectionChangedObservable.clear();
      this._onSelectionChangedObservable = undefined;
    }
    const userOptions = {
      ...DebugLayer.Config,
      ...config
    };
    this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector();
    this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions);
  }
  select(entity, lineContainerTitles) {
    if (this.BJSINSPECTOR) {
      if (lineContainerTitles) {
        if (Object.prototype.toString.call(lineContainerTitles) == "[object String]") {
          this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles);
        } else {
          this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles);
        }
      }
      this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity);
    }
  }
  _getGlobalInspector() {
    if (typeof INSPECTOR !== "undefined") {
      return INSPECTOR;
    }
    if (typeof BABYLON !== "undefined" && typeof BABYLON.Inspector !== "undefined") {
      return BABYLON;
    }
    return;
  }
  isVisible() {
    return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible;
  }
  hide() {
    if (this.BJSINSPECTOR) {
      this.BJSINSPECTOR.Inspector.Hide();
    }
  }
  get openedPanes() {
    if (this.BJSINSPECTOR) {
      return this.BJSINSPECTOR.Inspector._OpenedPane;
    }
    return 0;
  }
  setAsActiveScene() {
    if (this.BJSINSPECTOR) {
      this.BJSINSPECTOR.Inspector._SetNewScene(this._scene);
    }
  }
  popupSceneExplorer() {
    if (this.BJSINSPECTOR) {
      this.BJSINSPECTOR.Inspector.PopupSceneExplorer();
    }
  }
  popupInspector() {
    if (this.BJSINSPECTOR) {
      this.BJSINSPECTOR.Inspector.PopupInspector();
    }
  }
  popupEmbed() {
    if (this.BJSINSPECTOR) {
      this.BJSINSPECTOR.Inspector.PopupEmbed();
    }
  }
  show(config) {
    return new Promise((resolve3) => {
      if (typeof this.BJSINSPECTOR == "undefined") {
        const inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL;
        Tools.LoadBabylonScript(inspectorUrl, () => {
          this._createInspector(config);
          resolve3(this);
        });
      } else {
        this._createInspector(config);
        resolve3(this);
      }
    });
  }
}
DebugLayer.InspectorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/inspector/babylon.inspector.bundle.js`;
DebugLayer.Config = {
  overlay: false,
  showExplorer: true,
  showInspector: true,
  embedMode: false,
  handleResize: true,
  enablePopup: true
};
// node_modules/@babylonjs/core/Meshes/Builders/boxBuilder.js
init_math_vector();
init_math_color();
init_compatibilityOptions();
function CreateBoxVertexData(options) {
  const nbFaces = 6;
  let indices = [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23];
  const normals = [
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0,
    0,
    -1,
    0
  ];
  const uvs = [];
  let positions = [];
  const width = options.width || options.size || 1;
  const height = options.height || options.size || 1;
  const depth = options.depth || options.size || 1;
  const wrap = options.wrap || false;
  let topBaseAt = options.topBaseAt === undefined ? 1 : options.topBaseAt;
  let bottomBaseAt = options.bottomBaseAt === undefined ? 0 : options.bottomBaseAt;
  topBaseAt = (topBaseAt + 4) % 4;
  bottomBaseAt = (bottomBaseAt + 4) % 4;
  const topOrder = [2, 0, 3, 1];
  const bottomOrder = [2, 0, 1, 3];
  let topIndex = topOrder[topBaseAt];
  let bottomIndex = bottomOrder[bottomBaseAt];
  let basePositions = [
    1,
    -1,
    1,
    -1,
    -1,
    1,
    -1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    -1,
    -1,
    1,
    -1,
    -1,
    -1,
    -1,
    1,
    -1,
    -1,
    1,
    1,
    -1,
    1,
    -1,
    -1,
    1,
    -1,
    1,
    1,
    1,
    1,
    -1,
    1,
    1,
    -1,
    -1,
    1,
    -1,
    -1,
    -1,
    -1,
    1,
    -1,
    -1,
    1,
    1,
    -1,
    1,
    -1,
    1,
    1,
    -1,
    1,
    1,
    1,
    1,
    -1,
    1,
    1,
    -1,
    -1,
    -1,
    -1,
    -1,
    -1,
    -1,
    1
  ];
  if (wrap) {
    indices = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14];
    basePositions = [
      -1,
      1,
      1,
      1,
      1,
      1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      -1,
      -1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      1,
      1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      -1,
      -1
    ];
    let topFaceBase = [
      [1, 1, 1],
      [-1, 1, 1],
      [-1, 1, -1],
      [1, 1, -1]
    ];
    let bottomFaceBase = [
      [-1, -1, 1],
      [1, -1, 1],
      [1, -1, -1],
      [-1, -1, -1]
    ];
    const topFaceOrder = [17, 18, 19, 16];
    const bottomFaceOrder = [22, 23, 20, 21];
    while (topIndex > 0) {
      topFaceBase.unshift(topFaceBase.pop());
      topFaceOrder.unshift(topFaceOrder.pop());
      topIndex--;
    }
    while (bottomIndex > 0) {
      bottomFaceBase.unshift(bottomFaceBase.pop());
      bottomFaceOrder.unshift(bottomFaceOrder.pop());
      bottomIndex--;
    }
    topFaceBase = topFaceBase.flat();
    bottomFaceBase = bottomFaceBase.flat();
    basePositions = basePositions.concat(topFaceBase).concat(bottomFaceBase);
    indices.push(topFaceOrder[0], topFaceOrder[2], topFaceOrder[3], topFaceOrder[0], topFaceOrder[1], topFaceOrder[2]);
    indices.push(bottomFaceOrder[0], bottomFaceOrder[2], bottomFaceOrder[3], bottomFaceOrder[0], bottomFaceOrder[1], bottomFaceOrder[2]);
  }
  const scaleArray = [width / 2, height / 2, depth / 2];
  positions = basePositions.reduce((accumulator, currentValue, currentIndex) => accumulator.concat(currentValue * scaleArray[currentIndex % 3]), []);
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const faceUV = options.faceUV || new Array(6);
  const faceColors = options.faceColors;
  const colors = [];
  for (let f = 0;f < 6; f++) {
    if (faceUV[f] === undefined) {
      faceUV[f] = new Vector4(0, 0, 1, 1);
    }
    if (faceColors && faceColors[f] === undefined) {
      faceColors[f] = new Color4(1, 1, 1, 1);
    }
  }
  for (let index = 0;index < nbFaces; index++) {
    uvs.push(faceUV[index].z, useOpenGLOrientationForUV ? 1 - faceUV[index].w : faceUV[index].w);
    uvs.push(faceUV[index].x, useOpenGLOrientationForUV ? 1 - faceUV[index].w : faceUV[index].w);
    uvs.push(faceUV[index].x, useOpenGLOrientationForUV ? 1 - faceUV[index].y : faceUV[index].y);
    uvs.push(faceUV[index].z, useOpenGLOrientationForUV ? 1 - faceUV[index].y : faceUV[index].y);
    if (faceColors) {
      for (let c = 0;c < 4; c++) {
        colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
      }
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  if (faceColors) {
    const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;
    vertexData.colors = totalColors;
  }
  return vertexData;
}
function CreateSegmentedBoxVertexData(options) {
  const width = options.width || options.size || 1;
  const height = options.height || options.size || 1;
  const depth = options.depth || options.size || 1;
  const widthSegments = (options.widthSegments || options.segments || 1) | 0;
  const heightSegments = (options.heightSegments || options.segments || 1) | 0;
  const depthSegments = (options.depthSegments || options.segments || 1) | 0;
  const rotationMatrix = new Matrix;
  const translationMatrix = new Matrix;
  const transformMatrix = new Matrix;
  const bottomPlane = CreateGroundVertexData({ width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments });
  Matrix.TranslationToRef(0, -height / 2, 0, translationMatrix);
  Matrix.RotationZToRef(Math.PI, rotationMatrix);
  rotationMatrix.multiplyToRef(translationMatrix, transformMatrix);
  bottomPlane.transform(transformMatrix);
  const topPlane = CreateGroundVertexData({ width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments });
  Matrix.TranslationToRef(0, height / 2, 0, transformMatrix);
  topPlane.transform(transformMatrix);
  const negXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments });
  Matrix.TranslationToRef(-width / 2, 0, 0, translationMatrix);
  Matrix.RotationZToRef(Math.PI / 2, rotationMatrix);
  rotationMatrix.multiplyToRef(translationMatrix, transformMatrix);
  negXPlane.transform(transformMatrix);
  const posXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments });
  Matrix.TranslationToRef(width / 2, 0, 0, translationMatrix);
  Matrix.RotationZToRef(-Math.PI / 2, rotationMatrix);
  rotationMatrix.multiplyToRef(translationMatrix, transformMatrix);
  posXPlane.transform(transformMatrix);
  const negZPlane = CreateGroundVertexData({ width, height, subdivisionsX: widthSegments, subdivisionsY: heightSegments });
  Matrix.TranslationToRef(0, 0, -depth / 2, translationMatrix);
  Matrix.RotationXToRef(-Math.PI / 2, rotationMatrix);
  rotationMatrix.multiplyToRef(translationMatrix, transformMatrix);
  negZPlane.transform(transformMatrix);
  const posZPlane = CreateGroundVertexData({ width, height, subdivisionsX: widthSegments, subdivisionsY: heightSegments });
  Matrix.TranslationToRef(0, 0, depth / 2, translationMatrix);
  Matrix.RotationXToRef(Math.PI / 2, rotationMatrix);
  rotationMatrix.multiplyToRef(translationMatrix, transformMatrix);
  posZPlane.transform(transformMatrix);
  bottomPlane.merge([topPlane, posXPlane, negXPlane, negZPlane, posZPlane], true);
  return bottomPlane;
}
function CreateBox(name151, options = {}, scene = null) {
  const box = new Mesh(name151, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  box._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateBoxVertexData(options);
  vertexData.applyToMesh(box, options.updatable);
  return box;
}
VertexData.CreateBox = CreateBoxVertexData;
Mesh.CreateBox = (name151, size, scene = null, updatable, sideOrientation) => {
  const options = {
    size,
    sideOrientation,
    updatable
  };
  return CreateBox(name151, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/sphereBuilder.js
init_math_vector();
init_compatibilityOptions();
function CreateSphereVertexData(options) {
  const segments = (options.segments || 32) | 0;
  const diameterX = options.diameterX || options.diameter || 1;
  const diameterY = options.diameterY || options.diameter || 1;
  const diameterZ = options.diameterZ || options.diameter || 1;
  const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  const slice = options.slice && options.slice <= 0 ? 1 : options.slice || 1;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const dedupTopBottomIndices = !!options.dedupTopBottomIndices;
  const radius = new Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  const totalZRotationSteps = 2 + segments;
  const totalYRotationSteps = 2 * totalZRotationSteps;
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  for (let zRotationStep = 0;zRotationStep <= totalZRotationSteps; zRotationStep++) {
    const normalizedZ = zRotationStep / totalZRotationSteps;
    const angleZ = normalizedZ * Math.PI * slice;
    for (let yRotationStep = 0;yRotationStep <= totalYRotationSteps; yRotationStep++) {
      const normalizedY = yRotationStep / totalYRotationSteps;
      const angleY = normalizedY * Math.PI * 2 * arc;
      const rotationZ = Matrix.RotationZ(-angleZ);
      const rotationY = Matrix.RotationY(angleY);
      const afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ);
      const complete = Vector3.TransformCoordinates(afterRotZ, rotationY);
      const vertex = complete.multiply(radius);
      const normal = complete.divide(radius).normalize();
      positions.push(vertex.x, vertex.y, vertex.z);
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(normalizedY, useOpenGLOrientationForUV ? 1 - normalizedZ : normalizedZ);
    }
    if (zRotationStep > 0) {
      const verticesCount = positions.length / 3;
      for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1);firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) {
        if (dedupTopBottomIndices) {
          if (zRotationStep > 1) {
            indices.push(firstIndex);
            indices.push(firstIndex + 1);
            indices.push(firstIndex + totalYRotationSteps + 1);
          }
          if (zRotationStep < totalZRotationSteps || slice < 1) {
            indices.push(firstIndex + totalYRotationSteps + 1);
            indices.push(firstIndex + 1);
            indices.push(firstIndex + totalYRotationSteps + 2);
          }
        } else {
          indices.push(firstIndex);
          indices.push(firstIndex + 1);
          indices.push(firstIndex + totalYRotationSteps + 1);
          indices.push(firstIndex + totalYRotationSteps + 1);
          indices.push(firstIndex + 1);
          indices.push(firstIndex + totalYRotationSteps + 2);
        }
      }
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateSphere(name151, options = {}, scene = null) {
  const sphere = new Mesh(name151, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  sphere._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateSphereVertexData(options);
  vertexData.applyToMesh(sphere, options.updatable);
  return sphere;
}
VertexData.CreateSphere = CreateSphereVertexData;
Mesh.CreateSphere = (name151, segments, diameter, scene, updatable, sideOrientation) => {
  const options = {
    segments,
    diameterX: diameter,
    diameterY: diameter,
    diameterZ: diameter,
    sideOrientation,
    updatable
  };
  return CreateSphere(name151, options, scene);
};

// node_modules/@babylonjs/core/Debug/physicsViewer.js
init_math_vector();
init_math_color();
init_engineStore();

// node_modules/@babylonjs/core/Physics/v1/physicsImpostor.js
init_logger();
init_arrayTools();
init_math_vector();

// node_modules/@babylonjs/core/Physics/v1/physicsJoint.js
class PhysicsJoint {
  constructor(type, jointData) {
    this.type = type;
    this.jointData = jointData;
    jointData.nativeParams = jointData.nativeParams || {};
  }
  get physicsJoint() {
    return this._physicsJoint;
  }
  set physicsJoint(newJoint) {
    this._physicsJoint = newJoint;
  }
  set physicsPlugin(physicsPlugin) {
    this._physicsPlugin = physicsPlugin;
  }
  executeNativeFunction(func) {
    func(this._physicsPlugin.world, this._physicsJoint);
  }
}
PhysicsJoint.DistanceJoint = 0;
PhysicsJoint.HingeJoint = 1;
PhysicsJoint.BallAndSocketJoint = 2;
PhysicsJoint.WheelJoint = 3;
PhysicsJoint.SliderJoint = 4;
PhysicsJoint.PrismaticJoint = 5;
PhysicsJoint.UniversalJoint = 6;
PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
PhysicsJoint.PointToPointJoint = 8;
PhysicsJoint.SpringJoint = 9;
PhysicsJoint.LockJoint = 10;

// node_modules/@babylonjs/core/Physics/v1/physicsImpostor.js
Mesh._PhysicsImpostorParser = function(scene, physicObject, jsonObject) {
  return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, {
    mass: jsonObject.physicsMass,
    friction: jsonObject.physicsFriction,
    restitution: jsonObject.physicsRestitution
  }, scene);
};

class PhysicsImpostor {
  get isDisposed() {
    return this._isDisposed;
  }
  get mass() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  }
  set mass(value) {
    this.setMass(value);
  }
  get friction() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  }
  set friction(value) {
    if (!this._physicsEngine) {
      return;
    }
    this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  }
  get restitution() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  }
  set restitution(value) {
    if (!this._physicsEngine) {
      return;
    }
    this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  }
  get pressure() {
    if (!this._physicsEngine) {
      return 0;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.setBodyPressure) {
      return 0;
    }
    return plugin.getBodyPressure(this);
  }
  set pressure(value) {
    if (!this._physicsEngine) {
      return;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.setBodyPressure) {
      return;
    }
    plugin.setBodyPressure(this, value);
  }
  get stiffness() {
    if (!this._physicsEngine) {
      return 0;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.getBodyStiffness) {
      return 0;
    }
    return plugin.getBodyStiffness(this);
  }
  set stiffness(value) {
    if (!this._physicsEngine) {
      return;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.setBodyStiffness) {
      return;
    }
    plugin.setBodyStiffness(this, value);
  }
  get velocityIterations() {
    if (!this._physicsEngine) {
      return 0;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.getBodyVelocityIterations) {
      return 0;
    }
    return plugin.getBodyVelocityIterations(this);
  }
  set velocityIterations(value) {
    if (!this._physicsEngine) {
      return;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.setBodyVelocityIterations) {
      return;
    }
    plugin.setBodyVelocityIterations(this, value);
  }
  get positionIterations() {
    if (!this._physicsEngine) {
      return 0;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.getBodyPositionIterations) {
      return 0;
    }
    return plugin.getBodyPositionIterations(this);
  }
  set positionIterations(value) {
    if (!this._physicsEngine) {
      return;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.setBodyPositionIterations) {
      return;
    }
    plugin.setBodyPositionIterations(this, value);
  }
  constructor(object, type, _options = { mass: 0 }, _scene) {
    this.object = object;
    this.type = type;
    this._options = _options;
    this._scene = _scene;
    this._pluginData = {};
    this._bodyUpdateRequired = false;
    this._onBeforePhysicsStepCallbacks = new Array;
    this._onAfterPhysicsStepCallbacks = new Array;
    this._onPhysicsCollideCallbacks = [];
    this._deltaPosition = Vector3.Zero();
    this._isDisposed = false;
    this.soft = false;
    this.segments = 0;
    this._tmpQuat = new Quaternion;
    this._tmpQuat2 = new Quaternion;
    this.beforeStep = () => {
      if (!this._physicsEngine) {
        return;
      }
      this.object.translate(this._deltaPosition, -1);
      this._deltaRotationConjugated && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion);
      this.object.computeWorldMatrix(false);
      if (this.object.parent && this.object.rotationQuaternion) {
        this.getParentsRotation();
        this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat);
      } else {
        this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion);
      }
      if (!this._options.disableBidirectionalTransformation) {
        this.object.rotationQuaternion && this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, this.object.getAbsolutePosition(), this._tmpQuat);
      }
      this._onBeforePhysicsStepCallbacks.forEach((func) => {
        func(this);
      });
    };
    this.afterStep = () => {
      if (!this._physicsEngine) {
        return;
      }
      this._onAfterPhysicsStepCallbacks.forEach((func) => {
        func(this);
      });
      this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);
      if (this.object.parent && this.object.rotationQuaternion) {
        this.getParentsRotation();
        this._tmpQuat.conjugateInPlace();
        this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion);
      }
      this.object.setAbsolutePosition(this.object.position);
      if (this._deltaRotation) {
        this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);
        this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation, PhysicsImpostor._TmpVecs[0]);
        this.object.translate(PhysicsImpostor._TmpVecs[0], 1);
      } else {
        this.object.translate(this._deltaPosition, 1);
      }
      this.object.computeWorldMatrix(true);
    };
    this.onCollideEvent = null;
    this.onCollide = (e) => {
      if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) {
        return;
      }
      if (!this._physicsEngine) {
        return;
      }
      const otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
      if (otherImpostor) {
        if (this.onCollideEvent) {
          this.onCollideEvent(this, otherImpostor);
        }
        this._onPhysicsCollideCallbacks.filter((obj) => {
          return obj.otherImpostors.indexOf(otherImpostor) !== -1;
        }).forEach((obj) => {
          obj.callback(this, otherImpostor, e.point, e.distance, e.impulse, e.normal);
        });
      }
    };
    if (!this.object) {
      Logger.Error("No object was provided. A physics object is obligatory");
      return;
    }
    if (this.object.parent && _options.mass !== 0) {
      Logger.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur.");
    }
    if (!this._scene && object.getScene) {
      this._scene = object.getScene();
    }
    if (!this._scene) {
      return;
    }
    if (this.type > 100) {
      this.soft = true;
    }
    this._physicsEngine = this._scene.getPhysicsEngine();
    if (!this._physicsEngine) {
      Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
    } else {
      if (!this.object.rotationQuaternion) {
        if (this.object.rotation) {
          this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
        } else {
          this.object.rotationQuaternion = new Quaternion;
        }
      }
      this._options.mass = _options.mass === undefined ? 0 : _options.mass;
      this._options.friction = _options.friction === undefined ? 0.2 : _options.friction;
      this._options.restitution = _options.restitution === undefined ? 0.2 : _options.restitution;
      if (this.soft) {
        this._options.mass = this._options.mass > 0 ? this._options.mass : 1;
        this._options.pressure = _options.pressure === undefined ? 200 : _options.pressure;
        this._options.stiffness = _options.stiffness === undefined ? 1 : _options.stiffness;
        this._options.velocityIterations = _options.velocityIterations === undefined ? 20 : _options.velocityIterations;
        this._options.positionIterations = _options.positionIterations === undefined ? 20 : _options.positionIterations;
        this._options.fixedPoints = _options.fixedPoints === undefined ? 0 : _options.fixedPoints;
        this._options.margin = _options.margin === undefined ? 0 : _options.margin;
        this._options.damping = _options.damping === undefined ? 0 : _options.damping;
        this._options.path = _options.path === undefined ? null : _options.path;
        this._options.shape = _options.shape === undefined ? null : _options.shape;
      }
      this._joints = [];
      if (!this.object.parent || this._options.ignoreParent) {
        this._init();
      } else if (this.object.parent.physicsImpostor) {
        Logger.Warn("You must affect impostors to children before affecting impostor to parent.");
      }
    }
  }
  _init() {
    if (!this._physicsEngine) {
      return;
    }
    this._physicsEngine.removeImpostor(this);
    this.physicsBody = null;
    this._parent = this._parent || this._getPhysicsParent();
    if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
      this._physicsEngine.addImpostor(this);
    }
  }
  _getPhysicsParent() {
    if (this.object.parent instanceof AbstractMesh) {
      const parentMesh = this.object.parent;
      return parentMesh.physicsImpostor;
    }
    return null;
  }
  isBodyInitRequired() {
    return this._bodyUpdateRequired || !this._physicsBody && (!this._parent || !!this._options.ignoreParent);
  }
  setScalingUpdated() {
    this.forceUpdate();
  }
  forceUpdate() {
    this._init();
    if (this.parent && !this._options.ignoreParent) {
      this.parent.forceUpdate();
    }
  }
  get physicsBody() {
    return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody;
  }
  get parent() {
    return !this._options.ignoreParent && this._parent ? this._parent : null;
  }
  set parent(value) {
    this._parent = value;
  }
  set physicsBody(physicsBody) {
    if (this._physicsBody && this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
    }
    this._physicsBody = physicsBody;
    this.resetUpdateFlags();
  }
  resetUpdateFlags() {
    this._bodyUpdateRequired = false;
  }
  getObjectExtents() {
    if (this.object.getBoundingInfo) {
      const q = this.object.rotationQuaternion;
      const scaling = this.object.scaling.clone();
      this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
      const worldMatrix = this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
      if (worldMatrix) {
        worldMatrix.decompose(scaling, undefined, undefined);
      }
      const boundingInfo2 = this.object.getBoundingInfo();
      const size = boundingInfo2.boundingBox.extendSize.scale(2).multiplyInPlace(scaling);
      size.x = Math.abs(size.x);
      size.y = Math.abs(size.y);
      size.z = Math.abs(size.z);
      this.object.rotationQuaternion = q;
      this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
      return size;
    } else {
      return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
    }
  }
  getObjectCenter() {
    if (this.object.getBoundingInfo) {
      const boundingInfo2 = this.object.getBoundingInfo();
      return boundingInfo2.boundingBox.centerWorld;
    } else {
      return this.object.position;
    }
  }
  getParam(paramName) {
    return this._options[paramName];
  }
  setParam(paramName, value) {
    this._options[paramName] = value;
    this._bodyUpdateRequired = true;
  }
  setMass(mass) {
    if (this.getParam("mass") !== mass) {
      this.setParam("mass", mass);
    }
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
    }
  }
  getLinearVelocity() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero();
  }
  setLinearVelocity(velocity) {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
    }
  }
  getAngularVelocity() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero();
  }
  setAngularVelocity(velocity) {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
    }
  }
  executeNativeFunction(func) {
    if (this._physicsEngine) {
      func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
    }
  }
  registerBeforePhysicsStep(func) {
    this._onBeforePhysicsStepCallbacks.push(func);
  }
  unregisterBeforePhysicsStep(func) {
    const index = this._onBeforePhysicsStepCallbacks.indexOf(func);
    if (index > -1) {
      this._onBeforePhysicsStepCallbacks.splice(index, 1);
    } else {
      Logger.Warn("Function to remove was not found");
    }
  }
  registerAfterPhysicsStep(func) {
    this._onAfterPhysicsStepCallbacks.push(func);
  }
  unregisterAfterPhysicsStep(func) {
    const index = this._onAfterPhysicsStepCallbacks.indexOf(func);
    if (index > -1) {
      this._onAfterPhysicsStepCallbacks.splice(index, 1);
    } else {
      Logger.Warn("Function to remove was not found");
    }
  }
  registerOnPhysicsCollide(collideAgainst, func) {
    const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
    this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  }
  unregisterOnPhysicsCollide(collideAgainst, func) {
    const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
    let index = -1;
    const found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => {
      if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
        const sameList = cbDef.otherImpostors.every((impostor) => {
          return collidedAgainstList.indexOf(impostor) > -1;
        });
        if (sameList) {
          index = idx;
        }
        return sameList;
      }
      return false;
    });
    if (found) {
      this._onPhysicsCollideCallbacks.splice(index, 1);
    } else {
      Logger.Warn("Function to remove was not found");
    }
  }
  getParentsRotation() {
    let parent = this.object.parent;
    this._tmpQuat.copyFromFloats(0, 0, 0, 1);
    while (parent) {
      if (parent.rotationQuaternion) {
        this._tmpQuat2.copyFrom(parent.rotationQuaternion);
      } else {
        Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
      }
      this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
      parent = parent.parent;
    }
    return this._tmpQuat;
  }
  applyForce(force, contactPoint) {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
    }
    return this;
  }
  applyImpulse(force, contactPoint) {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
    }
    return this;
  }
  createJoint(otherImpostor, jointType, jointData) {
    const joint = new PhysicsJoint(jointType, jointData);
    this.addJoint(otherImpostor, joint);
    return this;
  }
  addJoint(otherImpostor, joint) {
    this._joints.push({
      otherImpostor,
      joint
    });
    if (this._physicsEngine) {
      this._physicsEngine.addJoint(this, otherImpostor, joint);
    }
    return this;
  }
  addAnchor(otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies) {
    if (!this._physicsEngine) {
      return this;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.appendAnchor) {
      return this;
    }
    if (this._physicsEngine) {
      plugin.appendAnchor(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies);
    }
    return this;
  }
  addHook(otherImpostor, length, influence, noCollisionBetweenLinkedBodies) {
    if (!this._physicsEngine) {
      return this;
    }
    const plugin = this._physicsEngine.getPhysicsPlugin();
    if (!plugin.appendAnchor) {
      return this;
    }
    if (this._physicsEngine) {
      plugin.appendHook(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies);
    }
    return this;
  }
  sleep() {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().sleepBody(this);
    }
    return this;
  }
  wakeUp() {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
    }
    return this;
  }
  clone(newObject) {
    if (!newObject) {
      return null;
    }
    return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  }
  dispose() {
    if (!this._physicsEngine) {
      return;
    }
    this._joints.forEach((j) => {
      if (this._physicsEngine) {
        this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);
      }
    });
    this._physicsEngine.removeImpostor(this);
    if (this.parent) {
      this.parent.forceUpdate();
    } else {}
    this._isDisposed = true;
  }
  setDeltaPosition(position) {
    this._deltaPosition.copyFrom(position);
  }
  setDeltaRotation(rotation) {
    if (!this._deltaRotation) {
      this._deltaRotation = new Quaternion;
    }
    this._deltaRotation.copyFrom(rotation);
    this._deltaRotationConjugated = this._deltaRotation.conjugate();
  }
  getBoxSizeToRef(result) {
    if (this._physicsEngine) {
      this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
    }
    return this;
  }
  getRadius() {
    return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  }
  syncBoneWithImpostor(bone2, boneMesh, jointPivot, distToJoint, adjustRotation) {
    const tempVec = PhysicsImpostor._TmpVecs[0];
    const mesh = this.object;
    if (mesh.rotationQuaternion) {
      if (adjustRotation) {
        const tempQuat = PhysicsImpostor._TmpQuat;
        mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
        bone2.setRotationQuaternion(tempQuat, 1, boneMesh);
      } else {
        bone2.setRotationQuaternion(mesh.rotationQuaternion, 1, boneMesh);
      }
    }
    tempVec.x = 0;
    tempVec.y = 0;
    tempVec.z = 0;
    if (jointPivot) {
      tempVec.x = jointPivot.x;
      tempVec.y = jointPivot.y;
      tempVec.z = jointPivot.z;
      bone2.getDirectionToRef(tempVec, boneMesh, tempVec);
      if (distToJoint === undefined || distToJoint === null) {
        distToJoint = jointPivot.length();
      }
      tempVec.x *= distToJoint;
      tempVec.y *= distToJoint;
      tempVec.z *= distToJoint;
    }
    if (bone2.getParent()) {
      tempVec.addInPlace(mesh.getAbsolutePosition());
      bone2.setAbsolutePosition(tempVec, boneMesh);
    } else {
      boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
      boneMesh.position.x -= tempVec.x;
      boneMesh.position.y -= tempVec.y;
      boneMesh.position.z -= tempVec.z;
    }
  }
  syncImpostorWithBone(bone2, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
    const mesh = this.object;
    if (mesh.rotationQuaternion) {
      if (adjustRotation) {
        const tempQuat = PhysicsImpostor._TmpQuat;
        bone2.getRotationQuaternionToRef(1, boneMesh, tempQuat);
        tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
      } else {
        bone2.getRotationQuaternionToRef(1, boneMesh, mesh.rotationQuaternion);
      }
    }
    const pos = PhysicsImpostor._TmpVecs[0];
    const boneDir = PhysicsImpostor._TmpVecs[1];
    if (!boneAxis) {
      boneAxis = PhysicsImpostor._TmpVecs[2];
      boneAxis.x = 0;
      boneAxis.y = 1;
      boneAxis.z = 0;
    }
    bone2.getDirectionToRef(boneAxis, boneMesh, boneDir);
    bone2.getAbsolutePositionToRef(boneMesh, pos);
    if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
      distToJoint = jointPivot.length();
    }
    if (distToJoint !== undefined && distToJoint !== null) {
      pos.x += boneDir.x * distToJoint;
      pos.y += boneDir.y * distToJoint;
      pos.z += boneDir.z * distToJoint;
    }
    mesh.setAbsolutePosition(pos);
  }
}
PhysicsImpostor.DEFAULT_OBJECT_SIZE = new Vector3(1, 1, 1);
PhysicsImpostor.IDENTITY_QUATERNION = Quaternion.Identity();
PhysicsImpostor._TmpVecs = BuildArray(3, Vector3.Zero);
PhysicsImpostor._TmpQuat = Quaternion.Identity();
PhysicsImpostor.NoImpostor = 0;
PhysicsImpostor.SphereImpostor = 1;
PhysicsImpostor.BoxImpostor = 2;
PhysicsImpostor.PlaneImpostor = 3;
PhysicsImpostor.MeshImpostor = 4;
PhysicsImpostor.CapsuleImpostor = 6;
PhysicsImpostor.CylinderImpostor = 7;
PhysicsImpostor.ParticleImpostor = 8;
PhysicsImpostor.HeightmapImpostor = 9;
PhysicsImpostor.ConvexHullImpostor = 10;
PhysicsImpostor.CustomImpostor = 100;
PhysicsImpostor.RopeImpostor = 101;
PhysicsImpostor.ClothImpostor = 102;
PhysicsImpostor.SoftbodyImpostor = 103;

// node_modules/@babylonjs/core/Meshes/Builders/capsuleBuilder.js
init_math_vector();
init_compatibilityOptions();
function CreateCapsuleVertexData(options = {
  subdivisions: 2,
  tessellation: 16,
  height: 1,
  radius: 0.25,
  capSubdivisions: 6
}) {
  const subdivisions = Math.max(options.subdivisions ? options.subdivisions : 2, 1) | 0;
  const tessellation = Math.max(options.tessellation ? options.tessellation : 16, 3) | 0;
  const height = Math.max(options.height ? options.height : 1, 0);
  const radius = Math.max(options.radius ? options.radius : 0.25, 0);
  const capDetail = Math.max(options.capSubdivisions ? options.capSubdivisions : 6, 1) | 0;
  const radialSegments = tessellation;
  const heightSegments = subdivisions;
  const radiusTop = Math.max(options.radiusTop ? options.radiusTop : radius, 0);
  const radiusBottom = Math.max(options.radiusBottom ? options.radiusBottom : radius, 0);
  const heightMinusCaps = height - (radiusTop + radiusBottom);
  const thetaStart = 0;
  const thetaLength = 2 * Math.PI;
  const capsTopSegments = Math.max(options.topCapSubdivisions ? options.topCapSubdivisions : capDetail, 1);
  const capsBottomSegments = Math.max(options.bottomCapSubdivisions ? options.bottomCapSubdivisions : capDetail, 1);
  const alpha = Math.acos((radiusBottom - radiusTop) / height);
  let indices = [];
  const vertices = [];
  const normals = [];
  const uvs = [];
  let index = 0;
  const indexArray = [], halfHeight = heightMinusCaps * 0.5;
  const pi2 = Math.PI * 0.5;
  let x, y;
  const normal = Vector3.Zero();
  const vertex = Vector3.Zero();
  const cosAlpha = Math.cos(alpha);
  const sinAlpha = Math.sin(alpha);
  const coneLength = new Vector2(radiusTop * sinAlpha, halfHeight + radiusTop * cosAlpha).subtract(new Vector2(radiusBottom * sinAlpha, -halfHeight + radiusBottom * cosAlpha)).length();
  const vl = radiusTop * alpha + coneLength + radiusBottom * (pi2 - alpha);
  let v = 0;
  for (y = 0;y <= capsTopSegments; y++) {
    const indexRow = [];
    const a = pi2 - alpha * (y / capsTopSegments);
    v += radiusTop * alpha / capsTopSegments;
    const cosA = Math.cos(a);
    const sinA = Math.sin(a);
    const _radius = cosA * radiusTop;
    for (x = 0;x <= radialSegments; x++) {
      const u = x / radialSegments;
      const theta = u * thetaLength + thetaStart;
      const sinTheta = Math.sin(theta);
      const cosTheta = Math.cos(theta);
      vertex.x = _radius * sinTheta;
      vertex.y = halfHeight + sinA * radiusTop;
      vertex.z = _radius * cosTheta;
      vertices.push(vertex.x, vertex.y, vertex.z);
      normal.set(cosA * sinTheta, sinA, cosA * cosTheta);
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(u, useOpenGLOrientationForUV ? v / vl : 1 - v / vl);
      indexRow.push(index);
      index++;
    }
    indexArray.push(indexRow);
  }
  const coneHeight = height - radiusTop - radiusBottom + cosAlpha * radiusTop - cosAlpha * radiusBottom;
  const slope = sinAlpha * (radiusBottom - radiusTop) / coneHeight;
  for (y = 1;y <= heightSegments; y++) {
    const indexRow = [];
    v += coneLength / heightSegments;
    const _radius = sinAlpha * (y * (radiusBottom - radiusTop) / heightSegments + radiusTop);
    for (x = 0;x <= radialSegments; x++) {
      const u = x / radialSegments;
      const theta = u * thetaLength + thetaStart;
      const sinTheta = Math.sin(theta);
      const cosTheta = Math.cos(theta);
      vertex.x = _radius * sinTheta;
      vertex.y = halfHeight + cosAlpha * radiusTop - y * coneHeight / heightSegments;
      vertex.z = _radius * cosTheta;
      vertices.push(vertex.x, vertex.y, vertex.z);
      normal.set(sinTheta, slope, cosTheta).normalize();
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(u, useOpenGLOrientationForUV ? v / vl : 1 - v / vl);
      indexRow.push(index);
      index++;
    }
    indexArray.push(indexRow);
  }
  for (y = 1;y <= capsBottomSegments; y++) {
    const indexRow = [];
    const a = pi2 - alpha - (Math.PI - alpha) * (y / capsBottomSegments);
    v += radiusBottom * alpha / capsBottomSegments;
    const cosA = Math.cos(a);
    const sinA = Math.sin(a);
    const _radius = cosA * radiusBottom;
    for (x = 0;x <= radialSegments; x++) {
      const u = x / radialSegments;
      const theta = u * thetaLength + thetaStart;
      const sinTheta = Math.sin(theta);
      const cosTheta = Math.cos(theta);
      vertex.x = _radius * sinTheta;
      vertex.y = -halfHeight + sinA * radiusBottom;
      vertex.z = _radius * cosTheta;
      vertices.push(vertex.x, vertex.y, vertex.z);
      normal.set(cosA * sinTheta, sinA, cosA * cosTheta);
      normals.push(normal.x, normal.y, normal.z);
      uvs.push(u, useOpenGLOrientationForUV ? v / vl : 1 - v / vl);
      indexRow.push(index);
      index++;
    }
    indexArray.push(indexRow);
  }
  for (x = 0;x < radialSegments; x++) {
    for (y = 0;y < capsTopSegments + heightSegments + capsBottomSegments; y++) {
      const i1 = indexArray[y][x];
      const i2 = indexArray[y + 1][x];
      const i3 = indexArray[y + 1][x + 1];
      const i4 = indexArray[y][x + 1];
      indices.push(i1);
      indices.push(i2);
      indices.push(i4);
      indices.push(i2);
      indices.push(i3);
      indices.push(i4);
    }
  }
  indices = indices.reverse();
  if (options.orientation && !options.orientation.equals(Vector3.Up())) {
    const m = new Matrix;
    options.orientation.clone().scale(Math.PI * 0.5).cross(Vector3.Up()).toQuaternion().toRotationMatrix(m);
    const v2 = Vector3.Zero();
    for (let i = 0;i < vertices.length; i += 3) {
      v2.set(vertices[i], vertices[i + 1], vertices[i + 2]);
      Vector3.TransformCoordinatesToRef(v2.clone(), m, v2);
      vertices[i] = v2.x;
      vertices[i + 1] = v2.y;
      vertices[i + 2] = v2.z;
    }
  }
  const vDat = new VertexData;
  vDat.positions = vertices;
  vDat.normals = normals;
  vDat.uvs = uvs;
  vDat.indices = indices;
  return vDat;
}
function CreateCapsule(name151, options = {
  orientation: Vector3.Up(),
  subdivisions: 2,
  tessellation: 16,
  height: 1,
  radius: 0.25,
  capSubdivisions: 6,
  updatable: false
}, scene = null) {
  const capsule = new Mesh(name151, scene);
  const vertexData = CreateCapsuleVertexData(options);
  vertexData.applyToMesh(capsule, options.updatable);
  return capsule;
}
Mesh.CreateCapsule = (name151, options, scene) => {
  return CreateCapsule(name151, options, scene);
};
VertexData.CreateCapsule = CreateCapsuleVertexData;

// node_modules/@babylonjs/core/Debug/physicsViewer.js
init_logger();

// node_modules/@babylonjs/core/Meshes/Builders/ribbonBuilder.js
init_math_vector();
init_buffer();
init_compatibilityOptions();
function CreateRibbonVertexData(options) {
  let pathArray = options.pathArray;
  const closeArray = options.closeArray || false;
  const closePath = options.closePath || false;
  const invertUV = options.invertUV || false;
  const defaultOffset = Math.floor(pathArray[0].length / 2);
  let offset = options.offset || defaultOffset;
  offset = offset > defaultOffset ? defaultOffset : Math.floor(offset);
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const customUV = options.uvs;
  const customColors = options.colors;
  const positions = [];
  const indices = [];
  const normals = [];
  const uvs = [];
  const us = [];
  const vs = [];
  const uTotalDistance = [];
  const vTotalDistance = [];
  let minlg;
  const lg = [];
  const idx = [];
  let p;
  let i;
  let j;
  if (pathArray.length < 2) {
    const ar1 = [];
    const ar2 = [];
    for (i = 0;i < pathArray[0].length - offset; i++) {
      ar1.push(pathArray[0][i]);
      ar2.push(pathArray[0][i + offset]);
    }
    pathArray = [ar1, ar2];
  }
  let idc = 0;
  const closePathCorr = closePath ? 1 : 0;
  const closeArrayCorr = closeArray ? 1 : 0;
  let path;
  let l;
  minlg = pathArray[0].length;
  let vectlg;
  let dist;
  for (p = 0;p < pathArray.length + closeArrayCorr; p++) {
    uTotalDistance[p] = 0;
    us[p] = [0];
    path = p === pathArray.length ? pathArray[0] : pathArray[p];
    l = path.length;
    minlg = minlg < l ? minlg : l;
    j = 0;
    while (j < l) {
      positions.push(path[j].x, path[j].y, path[j].z);
      if (j > 0) {
        vectlg = path[j].subtract(path[j - 1]).length();
        dist = vectlg + uTotalDistance[p];
        us[p].push(dist);
        uTotalDistance[p] = dist;
      }
      j++;
    }
    if (closePath) {
      j--;
      positions.push(path[0].x, path[0].y, path[0].z);
      vectlg = path[j].subtract(path[0]).length();
      dist = vectlg + uTotalDistance[p];
      us[p].push(dist);
      uTotalDistance[p] = dist;
    }
    lg[p] = l + closePathCorr;
    idx[p] = idc;
    idc += l + closePathCorr;
  }
  let path1;
  let path2;
  let vertex1 = null;
  let vertex2 = null;
  for (i = 0;i < minlg + closePathCorr; i++) {
    vTotalDistance[i] = 0;
    vs[i] = [0];
    for (p = 0;p < pathArray.length - 1 + closeArrayCorr; p++) {
      path1 = pathArray[p];
      path2 = p === pathArray.length - 1 ? pathArray[0] : pathArray[p + 1];
      if (i === minlg) {
        vertex1 = path1[0];
        vertex2 = path2[0];
      } else {
        vertex1 = path1[i];
        vertex2 = path2[i];
      }
      vectlg = vertex2.subtract(vertex1).length();
      dist = vectlg + vTotalDistance[i];
      vs[i].push(dist);
      vTotalDistance[i] = dist;
    }
  }
  let u;
  let v;
  if (customUV) {
    for (p = 0;p < customUV.length; p++) {
      uvs.push(customUV[p].x, useOpenGLOrientationForUV ? 1 - customUV[p].y : customUV[p].y);
    }
  } else {
    for (p = 0;p < pathArray.length + closeArrayCorr; p++) {
      for (i = 0;i < minlg + closePathCorr; i++) {
        u = uTotalDistance[p] != 0 ? us[p][i] / uTotalDistance[p] : 0;
        v = vTotalDistance[i] != 0 ? vs[i][p] / vTotalDistance[i] : 0;
        if (invertUV) {
          uvs.push(v, u);
        } else {
          uvs.push(u, useOpenGLOrientationForUV ? 1 - v : v);
        }
      }
    }
  }
  p = 0;
  let pi = 0;
  let l1 = lg[p] - 1;
  let l2 = lg[p + 1] - 1;
  let min = l1 < l2 ? l1 : l2;
  let shft = idx[1] - idx[0];
  const path1nb = lg.length - 1;
  while (pi <= min && p < path1nb) {
    indices.push(pi, pi + shft, pi + 1);
    indices.push(pi + shft + 1, pi + 1, pi + shft);
    pi += 1;
    if (pi === min) {
      p++;
      shft = idx[p + 1] - idx[p];
      l1 = lg[p] - 1;
      l2 = lg[p + 1] - 1;
      pi = idx[p];
      min = l1 < l2 ? l1 + pi : l2 + pi;
    }
  }
  VertexData.ComputeNormals(positions, indices, normals);
  if (closePath) {
    let indexFirst = 0;
    let indexLast = 0;
    for (p = 0;p < pathArray.length; p++) {
      indexFirst = idx[p] * 3;
      if (p + 1 < pathArray.length) {
        indexLast = (idx[p + 1] - 1) * 3;
      } else {
        indexLast = normals.length - 3;
      }
      normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
      normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
      normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
      const l3 = Math.sqrt(normals[indexFirst] * normals[indexFirst] + normals[indexFirst + 1] * normals[indexFirst + 1] + normals[indexFirst + 2] * normals[indexFirst + 2]);
      normals[indexFirst] /= l3;
      normals[indexFirst + 1] /= l3;
      normals[indexFirst + 2] /= l3;
      normals[indexLast] = normals[indexFirst];
      normals[indexLast + 1] = normals[indexFirst + 1];
      normals[indexLast + 2] = normals[indexFirst + 2];
    }
  }
  if (closeArray) {
    let indexFirst = idx[0] * 3;
    let indexLast = idx[pathArray.length] * 3;
    for (i = 0;i < minlg + closePathCorr; i++) {
      normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
      normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
      normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
      const l3 = Math.sqrt(normals[indexFirst] * normals[indexFirst] + normals[indexFirst + 1] * normals[indexFirst + 1] + normals[indexFirst + 2] * normals[indexFirst + 2]);
      normals[indexFirst] /= l3;
      normals[indexFirst + 1] /= l3;
      normals[indexFirst + 2] /= l3;
      normals[indexLast] = normals[indexFirst];
      normals[indexLast + 1] = normals[indexFirst + 1];
      normals[indexLast + 2] = normals[indexFirst + 2];
      indexFirst += 3;
      indexLast += 3;
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  let colors = null;
  if (customColors) {
    colors = new Float32Array(customColors.length * 4);
    for (let c = 0;c < customColors.length; c++) {
      colors[c * 4] = customColors[c].r;
      colors[c * 4 + 1] = customColors[c].g;
      colors[c * 4 + 2] = customColors[c].b;
      colors[c * 4 + 3] = customColors[c].a;
    }
  }
  const vertexData = new VertexData;
  const positions32 = new Float32Array(positions);
  const normals32 = new Float32Array(normals);
  const uvs32 = new Float32Array(uvs);
  vertexData.indices = indices;
  vertexData.positions = positions32;
  vertexData.normals = normals32;
  vertexData.uvs = uvs32;
  if (colors) {
    vertexData.set(colors, VertexBuffer.ColorKind);
  }
  if (closePath) {
    vertexData._idx = idx;
  }
  return vertexData;
}
function CreateRibbon(name151, options, scene = null) {
  const pathArray = options.pathArray;
  const closeArray = options.closeArray;
  const closePath = options.closePath;
  const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  const instance = options.instance;
  const updatable = options.updatable;
  if (instance) {
    const minimum = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE);
    const maximum = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE);
    const positionFunction = (positions2) => {
      let minlg = pathArray[0].length;
      const mesh = instance;
      let i = 0;
      const ns = mesh._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1;
      for (let si = 1;si <= ns; ++si) {
        for (let p = 0;p < pathArray.length; ++p) {
          const path = pathArray[p];
          const l = path.length;
          minlg = minlg < l ? minlg : l;
          for (let j = 0;j < minlg; ++j) {
            const pathPoint = path[j];
            positions2[i] = pathPoint.x;
            positions2[i + 1] = pathPoint.y;
            positions2[i + 2] = pathPoint.z;
            minimum.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
            maximum.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
            i += 3;
          }
          if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
            const pathPoint = path[0];
            positions2[i] = pathPoint.x;
            positions2[i + 1] = pathPoint.y;
            positions2[i + 2] = pathPoint.z;
            i += 3;
          }
        }
      }
    };
    const positions = instance.getVerticesData(VertexBuffer.PositionKind);
    positionFunction(positions);
    if (instance.hasBoundingInfo) {
      instance.getBoundingInfo().reConstruct(minimum, maximum, instance._worldMatrix);
    } else {
      instance.buildBoundingInfo(minimum, maximum, instance._worldMatrix);
    }
    instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
    if (options.colors) {
      const colors = instance.getVerticesData(VertexBuffer.ColorKind);
      for (let c = 0, colorIndex = 0;c < options.colors.length; c++, colorIndex += 4) {
        const color = options.colors[c];
        colors[colorIndex] = color.r;
        colors[colorIndex + 1] = color.g;
        colors[colorIndex + 2] = color.b;
        colors[colorIndex + 3] = color.a;
      }
      instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false);
    }
    if (options.uvs) {
      const uvs = instance.getVerticesData(VertexBuffer.UVKind);
      for (let i = 0;i < options.uvs.length; i++) {
        uvs[i * 2] = options.uvs[i].x;
        uvs[i * 2 + 1] = useOpenGLOrientationForUV ? 1 - options.uvs[i].y : options.uvs[i].y;
      }
      instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false);
    }
    if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
      const indices = instance.getIndices();
      const normals = instance.getVerticesData(VertexBuffer.NormalKind);
      const params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
      VertexData.ComputeNormals(positions, indices, normals, params);
      if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
        let indexFirst = 0;
        let indexLast = 0;
        for (let p = 0;p < pathArray.length; p++) {
          indexFirst = instance._creationDataStorage.idx[p] * 3;
          if (p + 1 < pathArray.length) {
            indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
          } else {
            indexLast = normals.length - 3;
          }
          normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
          normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
          normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
          normals[indexLast] = normals[indexFirst];
          normals[indexLast + 1] = normals[indexFirst + 1];
          normals[indexLast + 2] = normals[indexFirst + 2];
        }
      }
      if (!instance.areNormalsFrozen) {
        instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
      }
    }
    return instance;
  } else {
    const ribbon = new Mesh(name151, scene);
    ribbon._originalBuilderSideOrientation = sideOrientation;
    ribbon._creationDataStorage = new _CreationDataStorage;
    const vertexData = CreateRibbonVertexData(options);
    if (closePath) {
      ribbon._creationDataStorage.idx = vertexData._idx;
    }
    ribbon._creationDataStorage.closePath = closePath;
    ribbon._creationDataStorage.closeArray = closeArray;
    vertexData.applyToMesh(ribbon, updatable);
    return ribbon;
  }
}
VertexData.CreateRibbon = CreateRibbonVertexData;
Mesh.CreateRibbon = (name151, pathArray, closeArray = false, closePath, offset, scene, updatable = false, sideOrientation, instance) => {
  return CreateRibbon(name151, {
    pathArray,
    closeArray,
    closePath,
    offset,
    updatable,
    sideOrientation,
    instance
  }, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/discBuilder.js
init_compatibilityOptions();
function CreateDiscVertexData(options) {
  const positions = [];
  const indices = [];
  const normals = [];
  const uvs = [];
  const radius = options.radius || 0.5;
  const tessellation = options.tessellation || 64;
  const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  positions.push(0, 0, 0);
  uvs.push(0.5, 0.5);
  const theta = Math.PI * 2 * arc;
  const step = arc === 1 ? theta / tessellation : theta / (tessellation - 1);
  let a = 0;
  for (let t = 0;t < tessellation; t++) {
    const x = Math.cos(a);
    const y = Math.sin(a);
    const u = (x + 1) / 2;
    const v = (1 - y) / 2;
    positions.push(radius * x, radius * y, 0);
    uvs.push(u, useOpenGLOrientationForUV ? 1 - v : v);
    a += step;
  }
  if (arc === 1) {
    positions.push(positions[3], positions[4], positions[5]);
    uvs.push(uvs[2], useOpenGLOrientationForUV ? 1 - uvs[3] : uvs[3]);
  }
  const vertexNb = positions.length / 3;
  for (let i = 1;i < vertexNb - 1; i++) {
    indices.push(i + 1, 0, i);
  }
  VertexData.ComputeNormals(positions, indices, normals);
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateDisc(name151, options = {}, scene = null) {
  const disc = new Mesh(name151, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  disc._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateDiscVertexData(options);
  vertexData.applyToMesh(disc, options.updatable);
  return disc;
}
VertexData.CreateDisc = CreateDiscVertexData;
Mesh.CreateDisc = (name151, radius, tessellation, scene = null, updatable, sideOrientation) => {
  const options = {
    radius,
    tessellation,
    sideOrientation,
    updatable
  };
  return CreateDisc(name151, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/tiledBoxBuilder.js
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Meshes/Builders/tiledPlaneBuilder.js
function CreateTiledPlaneVertexData(options) {
  const flipTile = options.pattern || Mesh.NO_FLIP;
  const tileWidth = options.tileWidth || options.tileSize || 1;
  const tileHeight = options.tileHeight || options.tileSize || 1;
  const alignH = options.alignHorizontal || 0;
  const alignV = options.alignVertical || 0;
  const width = options.width || options.size || 1;
  const tilesX = Math.floor(width / tileWidth);
  let offsetX = width - tilesX * tileWidth;
  const height = options.height || options.size || 1;
  const tilesY = Math.floor(height / tileHeight);
  let offsetY = height - tilesY * tileHeight;
  const halfWidth = tileWidth * tilesX / 2;
  const halfHeight = tileHeight * tilesY / 2;
  let adjustX = 0;
  let adjustY = 0;
  let startX = 0;
  let startY = 0;
  let endX = 0;
  let endY = 0;
  if (offsetX > 0 || offsetY > 0) {
    startX = -halfWidth;
    startY = -halfHeight;
    endX = halfWidth;
    endY = halfHeight;
    switch (alignH) {
      case Mesh.CENTER:
        offsetX /= 2;
        startX -= offsetX;
        endX += offsetX;
        break;
      case Mesh.LEFT:
        endX += offsetX;
        adjustX = -offsetX / 2;
        break;
      case Mesh.RIGHT:
        startX -= offsetX;
        adjustX = offsetX / 2;
        break;
    }
    switch (alignV) {
      case Mesh.CENTER:
        offsetY /= 2;
        startY -= offsetY;
        endY += offsetY;
        break;
      case Mesh.BOTTOM:
        endY += offsetY;
        adjustY = -offsetY / 2;
        break;
      case Mesh.TOP:
        startY -= offsetY;
        adjustY = offsetY / 2;
        break;
    }
  }
  const positions = [];
  const normals = [];
  const uvBase = [];
  uvBase[0] = [0, 0, 1, 0, 1, 1, 0, 1];
  uvBase[1] = [0, 0, 1, 0, 1, 1, 0, 1];
  if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {
    uvBase[1] = [1, 1, 0, 1, 0, 0, 1, 0];
  }
  if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {
    uvBase[1] = [1, 0, 0, 0, 0, 1, 1, 1];
  }
  if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
    uvBase[1] = [0, 1, 1, 1, 1, 0, 0, 0];
  }
  let uvs = [];
  const colors = [];
  const indices = [];
  let index = 0;
  for (let y = 0;y < tilesY; y++) {
    for (let x = 0;x < tilesX; x++) {
      positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
      positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
      positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
      positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
      indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
      if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {
        uvs = uvs.concat(uvBase[(x % 2 + y % 2) % 2]);
      } else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvs = uvs.concat(uvBase[y % 2]);
      } else {
        uvs = uvs.concat(uvBase[0]);
      }
      colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
      normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
      index += 4;
    }
  }
  if (offsetX > 0 || offsetY > 0) {
    const partialBottomRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.TOP);
    const partialTopRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.BOTTOM);
    const partialLeftCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.RIGHT);
    const partialRightCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.LEFT);
    let uvPart = [];
    let a, b, c, d;
    if (partialBottomRow && partialLeftCol) {
      positions.push(startX + adjustX, startY + adjustY, 0);
      positions.push(-halfWidth + adjustX, startY + adjustY, 0);
      positions.push(-halfWidth + adjustX, startY + offsetY + adjustY, 0);
      positions.push(startX + adjustX, startY + offsetY + adjustY, 0);
      indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
      index += 4;
      a = 1 - offsetX / tileWidth;
      b = 1 - offsetY / tileHeight;
      c = 1;
      d = 1;
      uvPart = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_ROW) {
        uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_ROW) {
        uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      uvs = uvs.concat(uvPart);
      colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
      normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
    }
    if (partialBottomRow && partialRightCol) {
      positions.push(halfWidth + adjustX, startY + adjustY, 0);
      positions.push(endX + adjustX, startY + adjustY, 0);
      positions.push(endX + adjustX, startY + offsetY + adjustY, 0);
      positions.push(halfWidth + adjustX, startY + offsetY + adjustY, 0);
      indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
      index += 4;
      a = 0;
      b = 1 - offsetY / tileHeight;
      c = offsetX / tileWidth;
      d = 1;
      uvPart = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.ROTATE_TILE && tilesX % 2 === 0) {
        uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.FLIP_TILE && tilesX % 2 === 0) {
        uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesX % 2 === 0) {
        uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      uvs = uvs.concat(uvPart);
      colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
      normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
    }
    if (partialTopRow && partialLeftCol) {
      positions.push(startX + adjustX, halfHeight + adjustY, 0);
      positions.push(-halfWidth + adjustX, halfHeight + adjustY, 0);
      positions.push(-halfWidth + adjustX, endY + adjustY, 0);
      positions.push(startX + adjustX, endY + adjustY, 0);
      indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
      index += 4;
      a = 1 - offsetX / tileWidth;
      b = 0;
      c = 1;
      d = offsetY / tileHeight;
      uvPart = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1 || flipTile === Mesh.ROTATE_TILE && tilesY % 1 === 0) {
        uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1 || flipTile === Mesh.FLIP_TILE && tilesY % 2 === 0) {
        uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1 || flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesY % 2 === 0) {
        uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      uvs = uvs.concat(uvPart);
      colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
      normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
    }
    if (partialTopRow && partialRightCol) {
      positions.push(halfWidth + adjustX, halfHeight + adjustY, 0);
      positions.push(endX + adjustX, halfHeight + adjustY, 0);
      positions.push(endX + adjustX, endY + adjustY, 0);
      positions.push(halfWidth + adjustX, endY + adjustY, 0);
      indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
      index += 4;
      a = 0;
      b = 0;
      c = offsetX / tileWidth;
      d = offsetY / tileHeight;
      uvPart = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1 || flipTile === Mesh.ROTATE_TILE && (tilesY + tilesX) % 2 === 1) {
        uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1 || flipTile === Mesh.FLIP_TILE && (tilesY + tilesX) % 2 === 1) {
        uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1 || flipTile === Mesh.FLIP_N_ROTATE_TILE && (tilesY + tilesX) % 2 === 1) {
        uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      uvs = uvs.concat(uvPart);
      colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
      normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
    }
    if (partialBottomRow) {
      const uvBaseBR = [];
      a = 0;
      b = 1 - offsetY / tileHeight;
      c = 1;
      d = 1;
      uvBaseBR[0] = [a, b, c, b, c, d, a, d];
      uvBaseBR[1] = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {
        uvBaseBR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {
        uvBaseBR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvBaseBR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      for (let x = 0;x < tilesX; x++) {
        positions.push(-halfWidth + x * tileWidth + adjustX, startY + adjustY, 0);
        positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + adjustY, 0);
        positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + offsetY + adjustY, 0);
        positions.push(-halfWidth + x * tileWidth + adjustX, startY + offsetY + adjustY, 0);
        indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
        index += 4;
        if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {
          uvs = uvs.concat(uvBaseBR[(x + 1) % 2]);
        } else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
          uvs = uvs.concat(uvBaseBR[1]);
        } else {
          uvs = uvs.concat(uvBaseBR[0]);
        }
        colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
      }
    }
    if (partialTopRow) {
      const uvBaseTR = [];
      a = 0;
      b = 0;
      c = 1;
      d = offsetY / tileHeight;
      uvBaseTR[0] = [a, b, c, b, c, d, a, d];
      uvBaseTR[1] = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {
        uvBaseTR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {
        uvBaseTR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvBaseTR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      for (let x = 0;x < tilesX; x++) {
        positions.push(-halfWidth + x * tileWidth + adjustX, endY - offsetY + adjustY, 0);
        positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY - offsetY + adjustY, 0);
        positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY + adjustY, 0);
        positions.push(-halfWidth + x * tileWidth + adjustX, endY + adjustY, 0);
        indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
        index += 4;
        if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {
          uvs = uvs.concat(uvBaseTR[(x + tilesY) % 2]);
        } else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
          uvs = uvs.concat(uvBaseTR[tilesY % 2]);
        } else {
          uvs = uvs.concat(uvBaseTR[0]);
        }
        colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
      }
    }
    if (partialLeftCol) {
      const uvBaseLC = [];
      a = 1 - offsetX / tileWidth;
      b = 0;
      c = 1;
      d = 1;
      uvBaseLC[0] = [a, b, c, b, c, d, a, d];
      uvBaseLC[1] = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {
        uvBaseLC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {
        uvBaseLC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvBaseLC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      for (let y = 0;y < tilesY; y++) {
        positions.push(startX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
        positions.push(startX + offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
        positions.push(startX + offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
        positions.push(startX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
        indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
        index += 4;
        if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {
          uvs = uvs.concat(uvBaseLC[(y + 1) % 2]);
        } else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
          uvs = uvs.concat(uvBaseLC[y % 2]);
        } else {
          uvs = uvs.concat(uvBaseLC[0]);
        }
        colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
      }
    }
    if (partialRightCol) {
      const uvBaseRC = [];
      a = 0;
      b = 0;
      c = offsetX / tileHeight;
      d = 1;
      uvBaseRC[0] = [a, b, c, b, c, d, a, d];
      uvBaseRC[1] = [a, b, c, b, c, d, a, d];
      if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {
        uvBaseRC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];
      }
      if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {
        uvBaseRC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];
      }
      if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
        uvBaseRC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];
      }
      for (let y = 0;y < tilesY; y++) {
        positions.push(endX - offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
        positions.push(endX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);
        positions.push(endX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
        positions.push(endX - offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);
        indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);
        index += 4;
        if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {
          uvs = uvs.concat(uvBaseRC[(y + tilesX) % 2]);
        } else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {
          uvs = uvs.concat(uvBaseRC[y % 2]);
        } else {
          uvs = uvs.concat(uvBaseRC[0]);
        }
        colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
      }
    }
  }
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;
  vertexData.colors = totalColors;
  return vertexData;
}
VertexData.CreateTiledPlane = CreateTiledPlaneVertexData;

// node_modules/@babylonjs/core/Meshes/Builders/tiledBoxBuilder.js
init_compatibilityOptions();
function CreateTiledBoxVertexData(options) {
  const nbFaces = 6;
  const faceUV = options.faceUV || new Array(6);
  const faceColors = options.faceColors;
  const flipTile = options.pattern || Mesh.NO_FLIP;
  const width = options.width || options.size || 1;
  const height = options.height || options.size || 1;
  const depth = options.depth || options.size || 1;
  const tileWidth = options.tileWidth || options.tileSize || 1;
  const tileHeight = options.tileHeight || options.tileSize || 1;
  const alignH = options.alignHorizontal || 0;
  const alignV = options.alignVertical || 0;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  for (let f = 0;f < nbFaces; f++) {
    if (faceUV[f] === undefined) {
      faceUV[f] = new Vector4(0, 0, 1, 1);
    }
    if (faceColors && faceColors[f] === undefined) {
      faceColors[f] = new Color4(1, 1, 1, 1);
    }
  }
  const halfWidth = width / 2;
  const halfHeight = height / 2;
  const halfDepth = depth / 2;
  const faceVertexData = [];
  for (let f = 0;f < 2; f++) {
    faceVertexData[f] = CreateTiledPlaneVertexData({
      pattern: flipTile,
      tileWidth,
      tileHeight,
      width,
      height,
      alignVertical: alignV,
      alignHorizontal: alignH,
      sideOrientation
    });
  }
  for (let f = 2;f < 4; f++) {
    faceVertexData[f] = CreateTiledPlaneVertexData({
      pattern: flipTile,
      tileWidth,
      tileHeight,
      width: depth,
      height,
      alignVertical: alignV,
      alignHorizontal: alignH,
      sideOrientation
    });
  }
  let baseAlignV = alignV;
  if (alignV === Mesh.BOTTOM) {
    baseAlignV = Mesh.TOP;
  } else if (alignV === Mesh.TOP) {
    baseAlignV = Mesh.BOTTOM;
  }
  for (let f = 4;f < 6; f++) {
    faceVertexData[f] = CreateTiledPlaneVertexData({
      pattern: flipTile,
      tileWidth,
      tileHeight,
      width,
      height: depth,
      alignVertical: baseAlignV,
      alignHorizontal: alignH,
      sideOrientation
    });
  }
  let positions = [];
  let normals = [];
  let uvs = [];
  let indices = [];
  const colors = [];
  const facePositions = [];
  const faceNormals = [];
  const newFaceUV = [];
  let lu = 0;
  let li = 0;
  for (let f = 0;f < nbFaces; f++) {
    const len = faceVertexData[f].positions.length;
    facePositions[f] = [];
    faceNormals[f] = [];
    for (let p = 0;p < len / 3; p++) {
      facePositions[f].push(new Vector3(faceVertexData[f].positions[3 * p], faceVertexData[f].positions[3 * p + 1], faceVertexData[f].positions[3 * p + 2]));
      faceNormals[f].push(new Vector3(faceVertexData[f].normals[3 * p], faceVertexData[f].normals[3 * p + 1], faceVertexData[f].normals[3 * p + 2]));
    }
    lu = faceVertexData[f].uvs.length;
    newFaceUV[f] = [];
    for (let i = 0;i < lu; i += 2) {
      newFaceUV[f][i] = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * faceVertexData[f].uvs[i];
      newFaceUV[f][i + 1] = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * faceVertexData[f].uvs[i + 1];
      if (useOpenGLOrientationForUV) {
        newFaceUV[f][i + 1] = 1 - newFaceUV[f][i + 1];
      }
    }
    uvs = uvs.concat(newFaceUV[f]);
    indices = indices.concat(faceVertexData[f].indices.map((x) => x + li));
    li += facePositions[f].length;
    if (faceColors) {
      for (let c = 0;c < 4; c++) {
        colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
      }
    }
  }
  const vec0 = new Vector3(0, 0, halfDepth);
  const mtrx0 = Matrix.RotationY(Math.PI);
  positions = facePositions[0].map((entry) => Vector3.TransformNormal(entry, mtrx0).add(vec0)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
  normals = faceNormals[0].map((entry) => Vector3.TransformNormal(entry, mtrx0)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
  positions = positions.concat(facePositions[1].map((entry) => entry.subtract(vec0)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  normals = normals.concat(faceNormals[1].map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  const vec2 = new Vector3(halfWidth, 0, 0);
  const mtrx2 = Matrix.RotationY(-Math.PI / 2);
  positions = positions.concat(facePositions[2].map((entry) => Vector3.TransformNormal(entry, mtrx2).add(vec2)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  normals = normals.concat(faceNormals[2].map((entry) => Vector3.TransformNormal(entry, mtrx2)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  const mtrx3 = Matrix.RotationY(Math.PI / 2);
  positions = positions.concat(facePositions[3].map((entry) => Vector3.TransformNormal(entry, mtrx3).subtract(vec2)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  normals = normals.concat(faceNormals[3].map((entry) => Vector3.TransformNormal(entry, mtrx3)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  const vec4 = new Vector3(0, halfHeight, 0);
  const mtrx4 = Matrix.RotationX(Math.PI / 2);
  positions = positions.concat(facePositions[4].map((entry) => Vector3.TransformNormal(entry, mtrx4).add(vec4)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  normals = normals.concat(faceNormals[4].map((entry) => Vector3.TransformNormal(entry, mtrx4)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  const mtrx5 = Matrix.RotationX(-Math.PI / 2);
  positions = positions.concat(facePositions[5].map((entry) => Vector3.TransformNormal(entry, mtrx5).subtract(vec4)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  normals = normals.concat(faceNormals[5].map((entry) => Vector3.TransformNormal(entry, mtrx5)).map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []));
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  if (faceColors) {
    const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;
    vertexData.colors = totalColors;
  }
  return vertexData;
}
VertexData.CreateTiledBox = CreateTiledBoxVertexData;

// node_modules/@babylonjs/core/Meshes/Builders/torusKnotBuilder.js
init_math_vector();
init_compatibilityOptions();
function CreateTorusKnotVertexData(options) {
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  const radius = options.radius || 2;
  const tube = options.tube || 0.5;
  const radialSegments = options.radialSegments || 32;
  const tubularSegments = options.tubularSegments || 32;
  const p = options.p || 2;
  const q = options.q || 3;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const getPos = (angle) => {
    const cu = Math.cos(angle);
    const su = Math.sin(angle);
    const quOverP = q / p * angle;
    const cs = Math.cos(quOverP);
    const tx = radius * (2 + cs) * 0.5 * cu;
    const ty = radius * (2 + cs) * su * 0.5;
    const tz = radius * Math.sin(quOverP) * 0.5;
    return new Vector3(tx, ty, tz);
  };
  let i;
  let j;
  for (i = 0;i <= radialSegments; i++) {
    const modI = i % radialSegments;
    const u = modI / radialSegments * 2 * p * Math.PI;
    const p1 = getPos(u);
    const p2 = getPos(u + 0.01);
    const tang = p2.subtract(p1);
    let n = p2.add(p1);
    const bitan = Vector3.Cross(tang, n);
    n = Vector3.Cross(bitan, tang);
    bitan.normalize();
    n.normalize();
    for (j = 0;j < tubularSegments; j++) {
      const modJ = j % tubularSegments;
      const v = modJ / tubularSegments * 2 * Math.PI;
      const cx = -tube * Math.cos(v);
      const cy = tube * Math.sin(v);
      positions.push(p1.x + cx * n.x + cy * bitan.x);
      positions.push(p1.y + cx * n.y + cy * bitan.y);
      positions.push(p1.z + cx * n.z + cy * bitan.z);
      uvs.push(i / radialSegments);
      uvs.push(useOpenGLOrientationForUV ? 1 - j / tubularSegments : j / tubularSegments);
    }
  }
  for (i = 0;i < radialSegments; i++) {
    for (j = 0;j < tubularSegments; j++) {
      const jNext = (j + 1) % tubularSegments;
      const a = i * tubularSegments + j;
      const b = (i + 1) * tubularSegments + j;
      const c = (i + 1) * tubularSegments + jNext;
      const d = i * tubularSegments + jNext;
      indices.push(d);
      indices.push(b);
      indices.push(a);
      indices.push(d);
      indices.push(c);
      indices.push(b);
    }
  }
  VertexData.ComputeNormals(positions, indices, normals);
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateTorusKnot(name151, options = {}, scene) {
  const torusKnot = new Mesh(name151, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateTorusKnotVertexData(options);
  vertexData.applyToMesh(torusKnot, options.updatable);
  return torusKnot;
}
VertexData.CreateTorusKnot = CreateTorusKnotVertexData;
Mesh.CreateTorusKnot = (name151, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) => {
  const options = {
    radius,
    tube,
    radialSegments,
    tubularSegments,
    p,
    q,
    sideOrientation,
    updatable
  };
  return CreateTorusKnot(name151, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/linesBuilder.js
init_math_vector();

// node_modules/@babylonjs/core/Meshes/linesMesh.js
init_math_color();
init_buffer();
Mesh._LinesMeshParser = (parsedMesh, scene) => {
  return LinesMesh.Parse(parsedMesh, scene);
};

class LinesMesh extends Mesh {
  _isShaderMaterial(shader154) {
    return shader154.getClassName() === "ShaderMaterial";
  }
  constructor(name155, scene = null, parent = null, source = null, doNotCloneChildren, useVertexColor, useVertexAlpha, material) {
    super(name155, scene, parent, source, doNotCloneChildren);
    this.useVertexColor = useVertexColor;
    this.useVertexAlpha = useVertexAlpha;
    this.color = new Color3(1, 1, 1);
    this.alpha = 1;
    this._shaderLanguage = 0;
    if (source) {
      this.color = source.color.clone();
      this.alpha = source.alpha;
      this.useVertexColor = source.useVertexColor;
      this.useVertexAlpha = source.useVertexAlpha;
    }
    this.intersectionThreshold = 0.1;
    const defines = [];
    const options = {
      attributes: [VertexBuffer.PositionKind],
      uniforms: ["world", "viewProjection"],
      needAlphaBlending: true,
      defines,
      useClipPlane: null,
      shaderLanguage: 0
    };
    if (!this.useVertexAlpha) {
      options.needAlphaBlending = false;
    } else {
      options.defines.push("#define VERTEXALPHA");
    }
    if (!this.useVertexColor) {
      options.uniforms.push("color");
      this._color4 = new Color4;
    } else {
      options.defines.push("#define VERTEXCOLOR");
      options.attributes.push(VertexBuffer.ColorKind);
    }
    if (material) {
      this.material = material;
    } else {
      const engine = this.getScene().getEngine();
      if (engine.isWebGPU && !LinesMesh.ForceGLSL) {
        this._shaderLanguage = 1;
      }
      options.shaderLanguage = this._shaderLanguage;
      options.extraInitializationsAsync = async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_color_vertex(), exports_color_vertex)), Promise.resolve().then(() => (init_color_fragment(), exports_color_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_color_vertex2(), exports_color_vertex2)), Promise.resolve().then(() => (init_color_fragment2(), exports_color_fragment2))]);
        }
      };
      this.material = new ShaderMaterial("colorShader", this.getScene(), "color", options, false);
      this.material.doNotSerialize = true;
    }
  }
  isReady() {
    if (!this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage || this.hasThinInstances)) {
      return false;
    }
    return super.isReady();
  }
  getClassName() {
    return "LinesMesh";
  }
  get material() {
    return this._lineMaterial;
  }
  set material(value) {
    this._lineMaterial = value;
    this._lineMaterial.fillMode = Material.LineListDrawMode;
  }
  get checkCollisions() {
    return false;
  }
  set checkCollisions(value) {}
  _bind(_subMesh, colorEffect) {
    if (!this._geometry) {
      return this;
    }
    const indexToBind = this.isUnIndexed ? null : this._geometry.getIndexBuffer();
    if (!this._userInstancedBuffersStorage || this.hasThinInstances) {
      this._geometry._bind(colorEffect, indexToBind);
    } else {
      this._geometry._bind(colorEffect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects);
    }
    if (!this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) {
      const { r, g, b } = this.color;
      this._color4.set(r, g, b, this.alpha);
      this._lineMaterial.setColor4("color", this._color4);
    }
    return this;
  }
  _draw(subMesh, fillMode, instancesCount) {
    if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
      return this;
    }
    const engine = this.getScene().getEngine();
    if (this._unIndexed) {
      engine.drawArraysType(Material.LineListDrawMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
    } else {
      engine.drawElementsType(Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
    }
    return this;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false, doNotDisposeMaterial) {
    if (!doNotDisposeMaterial) {
      this._lineMaterial.dispose(false, false, true);
    }
    super.dispose(doNotRecurse);
  }
  clone(name155, newParent = null, doNotCloneChildren) {
    return new LinesMesh(name155, this.getScene(), newParent, this, doNotCloneChildren);
  }
  createInstance(name155) {
    const instance = new InstancedLinesMesh(name155, this);
    if (this.instancedBuffers) {
      instance.instancedBuffers = {};
      for (const key in this.instancedBuffers) {
        instance.instancedBuffers[key] = this.instancedBuffers[key];
      }
    }
    return instance;
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.color = this.color.asArray();
    serializationObject.alpha = this.alpha;
  }
  static Parse(parsedMesh, scene) {
    const result = new LinesMesh(parsedMesh.name, scene);
    result.color = Color3.FromArray(parsedMesh.color);
    result.alpha = parsedMesh.alpha;
    return result;
  }
}
LinesMesh.ForceGLSL = false;

class InstancedLinesMesh extends InstancedMesh {
  constructor(name155, source) {
    super(name155, source);
    this.intersectionThreshold = source.intersectionThreshold;
  }
  getClassName() {
    return "InstancedLinesMesh";
  }
}

// node_modules/@babylonjs/core/Meshes/Builders/linesBuilder.js
init_buffer();
init_logger();
function CreateLineSystemVertexData(options) {
  const indices = [];
  const positions = [];
  const lines = options.lines;
  const colors = options.colors;
  const vertexColors = [];
  let idx = 0;
  for (let l = 0;l < lines.length; l++) {
    const points = lines[l];
    for (let index = 0;index < points.length; index++) {
      const { x, y, z } = points[index];
      positions.push(x, y, z);
      if (colors) {
        const color = colors[l];
        const { r, g, b, a } = color[index];
        vertexColors.push(r, g, b, a);
      }
      if (index > 0) {
        indices.push(idx - 1);
        indices.push(idx);
      }
      idx++;
    }
  }
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  if (colors) {
    vertexData.colors = vertexColors;
  }
  return vertexData;
}
function CreateDashedLinesVertexData(options) {
  const dashSize = options.dashSize || 3;
  const gapSize = options.gapSize || 1;
  const dashNb = options.dashNb || 200;
  const points = options.points;
  const positions = [];
  const indices = [];
  const curvect = Vector3.Zero();
  let lg = 0;
  let nb = 0;
  let shft = 0;
  let dashshft = 0;
  let curshft = 0;
  let idx = 0;
  let i = 0;
  for (i = 0;i < points.length - 1; i++) {
    points[i + 1].subtractToRef(points[i], curvect);
    lg += curvect.length();
  }
  shft = lg / dashNb;
  dashshft = dashSize * shft / (dashSize + gapSize);
  for (i = 0;i < points.length - 1; i++) {
    points[i + 1].subtractToRef(points[i], curvect);
    nb = Math.floor(curvect.length() / shft);
    curvect.normalize();
    for (let j = 0;j < nb; j++) {
      curshft = shft * j;
      positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
      positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
      indices.push(idx, idx + 1);
      idx += 2;
    }
  }
  const vertexData = new VertexData;
  vertexData.positions = positions;
  vertexData.indices = indices;
  return vertexData;
}
function CreateLineSystem(name155, options, scene = null) {
  const instance = options.instance;
  const lines = options.lines;
  const colors = options.colors;
  if (instance) {
    const positions = instance.getVerticesData(VertexBuffer.PositionKind);
    let vertexColor;
    let lineColors;
    if (colors) {
      vertexColor = instance.getVerticesData(VertexBuffer.ColorKind);
    }
    let i = 0;
    let c = 0;
    for (let l = 0;l < lines.length; l++) {
      const points = lines[l];
      for (let p = 0;p < points.length; p++) {
        positions[i] = points[p].x;
        positions[i + 1] = points[p].y;
        positions[i + 2] = points[p].z;
        if (colors && vertexColor) {
          lineColors = colors[l];
          vertexColor[c] = lineColors[p].r;
          vertexColor[c + 1] = lineColors[p].g;
          vertexColor[c + 2] = lineColors[p].b;
          vertexColor[c + 3] = lineColors[p].a;
          c += 4;
        }
        i += 3;
      }
    }
    instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
    if (colors && vertexColor) {
      instance.updateVerticesData(VertexBuffer.ColorKind, vertexColor, false, false);
    }
    instance.refreshBoundingInfo();
    return instance;
  }
  const useVertexColor = colors ? true : false;
  const lineSystem = new LinesMesh(name155, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha, options.material);
  const vertexData = CreateLineSystemVertexData(options);
  vertexData.applyToMesh(lineSystem, options.updatable);
  return lineSystem;
}
function CreateLines(name155, options, scene = null) {
  const colors = options.colors ? [options.colors] : null;
  const lines = CreateLineSystem(name155, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors, useVertexAlpha: options.useVertexAlpha, material: options.material }, scene);
  return lines;
}
function CreateDashedLines(name155, options, scene = null) {
  const points = options.points;
  const instance = options.instance;
  const gapSize = options.gapSize || 1;
  const dashSize = options.dashSize || 3;
  if (instance) {
    const positionFunction = (positions) => {
      const curvect = Vector3.Zero();
      const nbSeg = positions.length / 6;
      let lg = 0;
      let nb = 0;
      let shft = 0;
      let dashshft = 0;
      let curshft = 0;
      let p = 0;
      let i = 0;
      let j = 0;
      for (i = 0;i < points.length - 1; i++) {
        points[i + 1].subtractToRef(points[i], curvect);
        lg += curvect.length();
      }
      shft = lg / nbSeg;
      const dashSize2 = instance._creationDataStorage.dashSize;
      const gapSize2 = instance._creationDataStorage.gapSize;
      dashshft = dashSize2 * shft / (dashSize2 + gapSize2);
      for (i = 0;i < points.length - 1; i++) {
        points[i + 1].subtractToRef(points[i], curvect);
        nb = Math.floor(curvect.length() / shft);
        curvect.normalize();
        j = 0;
        while (j < nb && p < positions.length) {
          curshft = shft * j;
          positions[p] = points[i].x + curshft * curvect.x;
          positions[p + 1] = points[i].y + curshft * curvect.y;
          positions[p + 2] = points[i].z + curshft * curvect.z;
          positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
          positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
          positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
          p += 6;
          j++;
        }
      }
      while (p < positions.length) {
        positions[p] = points[i].x;
        positions[p + 1] = points[i].y;
        positions[p + 2] = points[i].z;
        p += 3;
      }
    };
    if (options.dashNb || options.dashSize || options.gapSize || options.useVertexAlpha || options.material) {
      Logger.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored.");
    }
    instance.updateMeshPositions(positionFunction, false);
    return instance;
  }
  const dashedLines = new LinesMesh(name155, scene, null, undefined, undefined, undefined, options.useVertexAlpha, options.material);
  const vertexData = CreateDashedLinesVertexData(options);
  vertexData.applyToMesh(dashedLines, options.updatable);
  dashedLines._creationDataStorage = new _CreationDataStorage;
  dashedLines._creationDataStorage.dashSize = dashSize;
  dashedLines._creationDataStorage.gapSize = gapSize;
  return dashedLines;
}
VertexData.CreateLineSystem = CreateLineSystemVertexData;
VertexData.CreateDashedLines = CreateDashedLinesVertexData;
Mesh.CreateLines = (name155, points, scene = null, updatable = false, instance = null) => {
  const options = {
    points,
    updatable,
    instance
  };
  return CreateLines(name155, options, scene);
};
Mesh.CreateDashedLines = (name155, points, dashSize, gapSize, dashNb, scene = null, updatable, instance) => {
  const options = {
    points,
    dashSize,
    gapSize,
    dashNb,
    updatable,
    instance
  };
  return CreateDashedLines(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Meshes/polygonMesh.js
init_logger();
init_math_vector();
init_buffer();
init_math_path();
init_math_constants();
init_engineStore();

class IndexedVector2 extends Vector2 {
  constructor(original, index) {
    super(original.x, original.y);
    this.index = index;
  }
}

class PolygonPoints {
  constructor() {
    this.elements = [];
  }
  add(originalPoints) {
    const result = [];
    originalPoints.forEach((point) => {
      const newPoint = new IndexedVector2(point, this.elements.length);
      result.push(newPoint);
      this.elements.push(newPoint);
    });
    return result;
  }
  computeBounds() {
    const lmin = new Vector2(this.elements[0].x, this.elements[0].y);
    const lmax = new Vector2(this.elements[0].x, this.elements[0].y);
    this.elements.forEach((point) => {
      if (point.x < lmin.x) {
        lmin.x = point.x;
      } else if (point.x > lmax.x) {
        lmax.x = point.x;
      }
      if (point.y < lmin.y) {
        lmin.y = point.y;
      } else if (point.y > lmax.y) {
        lmax.y = point.y;
      }
    });
    return {
      min: lmin,
      max: lmax,
      width: lmax.x - lmin.x,
      height: lmax.y - lmin.y
    };
  }
}
class PolygonMeshBuilder {
  _addToepoint(points) {
    for (const p of points) {
      this._epoints.push(p.x, p.y);
    }
  }
  constructor(name155, contours, scene, earcutInjection = earcut) {
    this._points = new PolygonPoints;
    this._outlinepoints = new PolygonPoints;
    this._holes = new Array;
    this._epoints = new Array;
    this._eholes = new Array;
    this.bjsEarcut = earcutInjection;
    this._name = name155;
    this._scene = scene || EngineStore.LastCreatedScene;
    let points;
    if (contours instanceof Path2) {
      points = contours.getPoints();
    } else {
      points = contours;
    }
    this._addToepoint(points);
    this._points.add(points);
    this._outlinepoints.add(points);
    if (typeof this.bjsEarcut === "undefined") {
      Logger.Warn("Earcut was not found, the polygon will not be built.");
    }
  }
  addHole(hole) {
    this._points.add(hole);
    const holepoints = new PolygonPoints;
    holepoints.add(hole);
    this._holes.push(holepoints);
    this._eholes.push(this._epoints.length / 2);
    this._addToepoint(hole);
    return this;
  }
  build(updatable = false, depth = 0, smoothingThreshold = 2) {
    const result = new Mesh(this._name, this._scene);
    const vertexData = this.buildVertexData(depth, smoothingThreshold);
    result.setVerticesData(VertexBuffer.PositionKind, vertexData.positions, updatable);
    result.setVerticesData(VertexBuffer.NormalKind, vertexData.normals, updatable);
    result.setVerticesData(VertexBuffer.UVKind, vertexData.uvs, updatable);
    result.setIndices(vertexData.indices);
    return result;
  }
  buildVertexData(depth = 0, smoothingThreshold = 2) {
    const result = new VertexData;
    const normals = [];
    const positions = [];
    const uvs = [];
    const bounds = this._points.computeBounds();
    this._points.elements.forEach((p) => {
      normals.push(0, 1, 0);
      positions.push(p.x, 0, p.y);
      uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
    });
    const indices = [];
    const res = this.bjsEarcut(this._epoints, this._eholes, 2);
    for (let i = 0;i < res.length; i++) {
      indices.push(res[i]);
    }
    if (depth > 0) {
      const positionscount = positions.length / 3;
      this._points.elements.forEach((p) => {
        normals.push(0, -1, 0);
        positions.push(p.x, -depth, p.y);
        uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
      });
      const totalCount = indices.length;
      for (let i = 0;i < totalCount; i += 3) {
        const i0 = indices[i + 0];
        const i1 = indices[i + 1];
        const i2 = indices[i + 2];
        indices.push(i2 + positionscount);
        indices.push(i1 + positionscount);
        indices.push(i0 + positionscount);
      }
      this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold);
      this._holes.forEach((hole) => {
        this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);
      });
    }
    result.indices = indices;
    result.positions = positions;
    result.normals = normals;
    result.uvs = uvs;
    return result;
  }
  _addSide(positions, normals, uvs, indices, bounds, points, depth, flip, smoothingThreshold) {
    let startIndex = positions.length / 3;
    let ulength = 0;
    for (let i = 0;i < points.elements.length; i++) {
      const p = points.elements[i];
      const p1 = points.elements[(i + 1) % points.elements.length];
      positions.push(p.x, 0, p.y);
      positions.push(p.x, -depth, p.y);
      positions.push(p1.x, 0, p1.y);
      positions.push(p1.x, -depth, p1.y);
      const p0 = points.elements[(i + points.elements.length - 1) % points.elements.length];
      const p2 = points.elements[(i + 2) % points.elements.length];
      let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x);
      let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x);
      let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x);
      if (!flip) {
        vc = vc.scale(-1);
        vp = vp.scale(-1);
        vn = vn.scale(-1);
      }
      const vc_norm = vc.normalizeToNew();
      let vp_norm = vp.normalizeToNew();
      let vn_norm = vn.normalizeToNew();
      const dotp = Vector3.Dot(vp_norm, vc_norm);
      if (dotp > smoothingThreshold) {
        if (dotp < Epsilon - 1) {
          vp_norm = new Vector3(p.x, 0, p.y).subtract(new Vector3(p1.x, 0, p1.y)).normalize();
        } else {
          vp_norm = vp.add(vc).normalize();
        }
      } else {
        vp_norm = vc_norm;
      }
      const dotn = Vector3.Dot(vn, vc);
      if (dotn > smoothingThreshold) {
        if (dotn < Epsilon - 1) {
          vn_norm = new Vector3(p1.x, 0, p1.y).subtract(new Vector3(p.x, 0, p.y)).normalize();
        } else {
          vn_norm = vn.add(vc).normalize();
        }
      } else {
        vn_norm = vc_norm;
      }
      uvs.push(ulength / bounds.width, 0);
      uvs.push(ulength / bounds.width, 1);
      ulength += vc.length();
      uvs.push(ulength / bounds.width, 0);
      uvs.push(ulength / bounds.width, 1);
      normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
      normals.push(vp_norm.x, vp_norm.y, vp_norm.z);
      normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
      normals.push(vn_norm.x, vn_norm.y, vn_norm.z);
      if (!flip) {
        indices.push(startIndex);
        indices.push(startIndex + 1);
        indices.push(startIndex + 2);
        indices.push(startIndex + 1);
        indices.push(startIndex + 3);
        indices.push(startIndex + 2);
      } else {
        indices.push(startIndex);
        indices.push(startIndex + 2);
        indices.push(startIndex + 1);
        indices.push(startIndex + 1);
        indices.push(startIndex + 2);
        indices.push(startIndex + 3);
      }
      startIndex += 4;
    }
  }
}

// node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js
init_buffer();
init_engineStore();
init_compatibilityOptions();
function CreatePolygonVertexData(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrp) {
  const faceUV = fUV || new Array(3);
  const faceColors = fColors;
  const colors = [];
  const wrap = wrp || false;
  for (let f = 0;f < 3; f++) {
    if (faceUV[f] === undefined) {
      faceUV[f] = new Vector4(0, 0, 1, 1);
    }
    if (faceColors && faceColors[f] === undefined) {
      faceColors[f] = new Color4(1, 1, 1, 1);
    }
  }
  const positions = polygon.getVerticesData(VertexBuffer.PositionKind);
  const normals = polygon.getVerticesData(VertexBuffer.NormalKind);
  const uvs = polygon.getVerticesData(VertexBuffer.UVKind);
  const indices = polygon.getIndices();
  const startIndex = positions.length / 9;
  let disp = 0;
  let distX = 0;
  let distZ = 0;
  let dist = 0;
  let totalLen = 0;
  const cumulate = [0];
  if (wrap) {
    for (let idx2 = startIndex;idx2 < positions.length / 3; idx2 += 4) {
      distX = positions[3 * (idx2 + 2)] - positions[3 * idx2];
      distZ = positions[3 * (idx2 + 2) + 2] - positions[3 * idx2 + 2];
      dist = Math.sqrt(distX * distX + distZ * distZ);
      totalLen += dist;
      cumulate.push(totalLen);
    }
  }
  let idx = 0;
  let face = 0;
  for (let index = 0;index < normals.length; index += 3) {
    if (Math.abs(normals[index + 1]) < 0.001) {
      face = 1;
    }
    if (Math.abs(normals[index + 1] - 1) < 0.001) {
      face = 0;
    }
    if (Math.abs(normals[index + 1] + 1) < 0.001) {
      face = 2;
    }
    idx = index / 3;
    if (face === 1) {
      disp = idx - startIndex;
      if (disp % 4 < 1.5) {
        if (wrap) {
          uvs[2 * idx] = faceUV[face].x + (faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)] / totalLen;
        } else {
          uvs[2 * idx] = faceUV[face].x;
        }
      } else {
        if (wrap) {
          uvs[2 * idx] = faceUV[face].x + (faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1] / totalLen;
        } else {
          uvs[2 * idx] = faceUV[face].z;
        }
      }
      if (disp % 2 === 0) {
        uvs[2 * idx + 1] = useOpenGLOrientationForUV ? 1 - faceUV[face].w : faceUV[face].w;
      } else {
        uvs[2 * idx + 1] = useOpenGLOrientationForUV ? 1 - faceUV[face].y : faceUV[face].y;
      }
    } else {
      uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
      uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
      if (useOpenGLOrientationForUV) {
        uvs[2 * idx + 1] = 1 - uvs[2 * idx + 1];
      }
    }
    if (faceColors) {
      colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  if (faceColors) {
    const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;
    vertexData.colors = totalColors;
  }
  return vertexData;
}
function CreatePolygon(name155, options, scene = null, earcutInjection = earcut) {
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  const shape = options.shape;
  const holes = options.holes || [];
  const depth = options.depth || 0;
  const smoothingThreshold = options.smoothingThreshold || 2;
  const contours = [];
  let hole = [];
  for (let i = 0;i < shape.length; i++) {
    contours[i] = new Vector2(shape[i].x, shape[i].z);
  }
  const epsilon = 0.00000001;
  if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
    contours.pop();
  }
  const polygonTriangulation = new PolygonMeshBuilder(name155, contours, scene || EngineStore.LastCreatedScene, earcutInjection);
  for (let hNb = 0;hNb < holes.length; hNb++) {
    hole = [];
    for (let hPoint = 0;hPoint < holes[hNb].length; hPoint++) {
      hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
    }
    polygonTriangulation.addHole(hole);
  }
  const polygon = polygonTriangulation.build(false, depth, smoothingThreshold);
  polygon._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreatePolygonVertexData(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap);
  vertexData.applyToMesh(polygon, options.updatable);
  return polygon;
}
function ExtrudePolygon(name155, options, scene = null, earcutInjection = earcut) {
  return CreatePolygon(name155, options, scene, earcutInjection);
}
VertexData.CreatePolygon = CreatePolygonVertexData;
Mesh.CreatePolygon = (name155, shape, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {
  const options = {
    shape,
    holes,
    updatable,
    sideOrientation
  };
  return CreatePolygon(name155, options, scene, earcutInjection);
};
Mesh.ExtrudePolygon = (name155, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {
  const options = {
    shape,
    holes,
    depth,
    updatable,
    sideOrientation
  };
  return ExtrudePolygon(name155, options, scene, earcutInjection);
};

// node_modules/@babylonjs/core/Meshes/Builders/shapeBuilder.js
init_math_vector();
init_math_path();
function ExtrudeShape(name155, options, scene = null) {
  const path = options.path;
  const shape = options.shape;
  const scale = options.scale || 1;
  const rotation = options.rotation || 0;
  const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;
  const updatable = options.updatable;
  const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  const instance = options.instance || null;
  const invertUV = options.invertUV || false;
  const closeShape = options.closeShape || false;
  const closePath = options.closePath || false;
  const capFunction = options.capFunction || null;
  return _ExtrudeShapeGeneric(name155, shape, path, scale, rotation, null, null, closePath, closeShape, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null, options.firstNormal || null, options.adjustFrame ? true : false, capFunction);
}
function ExtrudeShapeCustom(name155, options, scene = null) {
  const path = options.path;
  const shape = options.shape;
  const scaleFunction = options.scaleFunction || (() => {
    return 1;
  });
  const rotationFunction = options.rotationFunction || (() => {
    return 0;
  });
  const ribbonCloseArray = options.closePath || options.ribbonCloseArray || false;
  const ribbonClosePath = options.closeShape || options.ribbonClosePath || false;
  const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;
  const updatable = options.updatable;
  const firstNormal = options.firstNormal || null;
  const adjustFrame = options.adjustFrame || false;
  const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  const instance = options.instance;
  const invertUV = options.invertUV || false;
  const capFunction = options.capFunction || null;
  return _ExtrudeShapeGeneric(name155, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null, firstNormal, adjustFrame, capFunction || null);
}
function _ExtrudeShapeGeneric(name155, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs, firstNormal, adjustFrame, capFunction) {
  const extrusionPathArray = (shape2, curve2, path3D2, shapePaths, scale2, rotation2, scaleFunction2, rotateFunction2, cap2, custom2, adjustFrame2) => {
    const tangents = path3D2.getTangents();
    const normals = path3D2.getNormals();
    const binormals = path3D2.getBinormals();
    const distances = path3D2.getDistances();
    if (adjustFrame2) {
      for (let i = 0;i < tangents.length; i++) {
        if (tangents[i].x == 0 && tangents[i].y == 0 && tangents[i].z == 0) {
          tangents[i].copyFrom(tangents[i - 1]);
        }
        if (normals[i].x == 0 && normals[i].y == 0 && normals[i].z == 0) {
          normals[i].copyFrom(normals[i - 1]);
        }
        if (binormals[i].x == 0 && binormals[i].y == 0 && binormals[i].z == 0) {
          binormals[i].copyFrom(binormals[i - 1]);
        }
        if (i > 0) {
          let v = tangents[i - 1];
          if (Vector3.Dot(v, tangents[i]) < 0) {
            tangents[i].scaleInPlace(-1);
          }
          v = normals[i - 1];
          if (Vector3.Dot(v, normals[i]) < 0) {
            normals[i].scaleInPlace(-1);
          }
          v = binormals[i - 1];
          if (Vector3.Dot(v, binormals[i]) < 0) {
            binormals[i].scaleInPlace(-1);
          }
        }
      }
    }
    let angle = 0;
    const returnScale = () => {
      return scale2 !== null ? scale2 : 1;
    };
    const returnRotation = () => {
      return rotation2 !== null ? rotation2 : 0;
    };
    const rotate = custom2 && rotateFunction2 ? rotateFunction2 : returnRotation;
    const scl = custom2 && scaleFunction2 ? scaleFunction2 : returnScale;
    let index = cap2 === Mesh.NO_CAP || cap2 === Mesh.CAP_END ? 0 : 2;
    const rotationMatrix = TmpVectors.Matrix[0];
    for (let i = 0;i < curve2.length; i++) {
      const shapePath = [];
      const angleStep = rotate(i, distances[i]);
      const scaleRatio = scl(i, distances[i]);
      Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
      for (let p = 0;p < shape2.length; p++) {
        const planed = tangents[i].scale(shape2[p].z).add(normals[i].scale(shape2[p].x)).add(binormals[i].scale(shape2[p].y));
        const rotated = Vector3.Zero();
        Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
        rotated.scaleInPlace(scaleRatio).addInPlace(curve2[i]);
        shapePath[p] = rotated;
      }
      shapePaths[index] = shapePath;
      angle += angleStep;
      index++;
    }
    const defaultCapPath = (shapePath) => {
      const pointCap = Array();
      const barycenter = Vector3.Zero();
      let i;
      for (i = 0;i < shapePath.length; i++) {
        barycenter.addInPlace(shapePath[i]);
      }
      barycenter.scaleInPlace(1 / shapePath.length);
      for (i = 0;i < shapePath.length; i++) {
        pointCap.push(barycenter);
      }
      return pointCap;
    };
    const capPath = capFunction || defaultCapPath;
    switch (cap2) {
      case Mesh.NO_CAP:
        break;
      case Mesh.CAP_START:
        shapePaths[0] = capPath(shapePaths[2]);
        shapePaths[1] = shapePaths[2];
        break;
      case Mesh.CAP_END:
        shapePaths[index] = shapePaths[index - 1];
        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
        break;
      case Mesh.CAP_ALL:
        shapePaths[0] = capPath(shapePaths[2]);
        shapePaths[1] = shapePaths[2];
        shapePaths[index] = shapePaths[index - 1];
        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
        break;
      default:
        break;
    }
    return shapePaths;
  };
  let path3D;
  let pathArray;
  if (instance) {
    const storage = instance._creationDataStorage;
    path3D = firstNormal ? storage.path3D.update(curve, firstNormal) : storage.path3D.update(curve);
    pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom, adjustFrame);
    instance = CreateRibbon("", { pathArray, closeArray: false, closePath: false, offset: 0, updatable: false, sideOrientation: 0, instance }, scene || undefined);
    return instance;
  }
  path3D = firstNormal ? new Path3D(curve, firstNormal) : new Path3D(curve);
  const newShapePaths = new Array;
  cap = cap < 0 || cap > 3 ? 0 : cap;
  pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame);
  const extrudedGeneric = CreateRibbon(name155, {
    pathArray,
    closeArray: rbCA,
    closePath: rbCP,
    updatable: updtbl,
    sideOrientation: side,
    invertUV,
    frontUVs: frontUVs || undefined,
    backUVs: backUVs || undefined
  }, scene);
  extrudedGeneric._creationDataStorage.pathArray = pathArray;
  extrudedGeneric._creationDataStorage.path3D = path3D;
  extrudedGeneric._creationDataStorage.cap = cap;
  return extrudedGeneric;
}
Mesh.ExtrudeShape = (name155, shape, path, scale, rotation, cap, scene = null, updatable, sideOrientation, instance) => {
  const options = {
    shape,
    path,
    scale,
    rotation,
    cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,
    sideOrientation,
    instance,
    updatable
  };
  return ExtrudeShape(name155, options, scene);
};
Mesh.ExtrudeShapeCustom = (name155, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) => {
  const options = {
    shape,
    path,
    scaleFunction,
    rotationFunction,
    ribbonCloseArray,
    ribbonClosePath,
    cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,
    sideOrientation,
    instance,
    updatable
  };
  return ExtrudeShapeCustom(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/latheBuilder.js
init_math_vector();
function CreateLathe(name155, options, scene = null) {
  const arc = options.arc ? options.arc <= 0 || options.arc > 1 ? 1 : options.arc : 1;
  const closed = options.closed === undefined ? true : options.closed;
  const shape = options.shape;
  const radius = options.radius || 1;
  const tessellation = options.tessellation || 64;
  const clip = options.clip || 0;
  const updatable = options.updatable;
  const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  const cap = options.cap || Mesh.NO_CAP;
  const pi2 = Math.PI * 2;
  const paths2 = [];
  const invertUV = options.invertUV || false;
  let i = 0;
  let p = 0;
  const step = pi2 / tessellation * arc;
  let rotated;
  let path;
  for (i = 0;i <= tessellation - clip; i++) {
    path = [];
    if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) {
      path.push(new Vector3(0, shape[0].y, 0));
      path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
    }
    for (p = 0;p < shape.length; p++) {
      rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
      path.push(rotated);
    }
    if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) {
      path.push(new Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
      path.push(new Vector3(0, shape[shape.length - 1].y, 0));
    }
    paths2.push(path);
  }
  const lathe = CreateRibbon(name155, { pathArray: paths2, closeArray: closed, sideOrientation, updatable, invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  return lathe;
}
Mesh.CreateLathe = (name155, shape, radius, tessellation, scene, updatable, sideOrientation) => {
  const options = {
    shape,
    radius,
    tessellation,
    sideOrientation,
    updatable
  };
  return CreateLathe(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/tubeBuilder.js
init_math_vector();
init_math_path();
function CreateTube(name155, options, scene = null) {
  const path = options.path;
  let instance = options.instance;
  let radius = 1;
  if (options.radius !== undefined) {
    radius = options.radius;
  } else if (instance) {
    radius = instance._creationDataStorage.radius;
  }
  const tessellation = options.tessellation || 64 | 0;
  const radiusFunction = options.radiusFunction || null;
  let cap = options.cap || Mesh.NO_CAP;
  const invertUV = options.invertUV || false;
  const updatable = options.updatable;
  const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  options.arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  const tubePathArray = (path2, path3D2, circlePaths, radius2, tessellation2, radiusFunction2, cap2, arc) => {
    const tangents = path3D2.getTangents();
    const normals = path3D2.getNormals();
    const distances = path3D2.getDistances();
    const pi2 = Math.PI * 2;
    const step = pi2 / tessellation2 * arc;
    const returnRadius = () => radius2;
    const radiusFunctionFinal = radiusFunction2 || returnRadius;
    let circlePath;
    let rad;
    let normal;
    let rotated;
    const rotationMatrix = TmpVectors.Matrix[0];
    let index = cap2 === Mesh.NO_CAP || cap2 === Mesh.CAP_END ? 0 : 2;
    for (let i = 0;i < path2.length; i++) {
      rad = radiusFunctionFinal(i, distances[i]);
      circlePath = Array();
      normal = normals[i];
      for (let t = 0;t < tessellation2; t++) {
        Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
        rotated = circlePath[t] ? circlePath[t] : Vector3.Zero();
        Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
        rotated.scaleInPlace(rad).addInPlace(path2[i]);
        circlePath[t] = rotated;
      }
      circlePaths[index] = circlePath;
      index++;
    }
    const capPath = (nbPoints, pathIndex) => {
      const pointCap = Array();
      for (let i = 0;i < nbPoints; i++) {
        pointCap.push(path2[pathIndex]);
      }
      return pointCap;
    };
    switch (cap2) {
      case Mesh.NO_CAP:
        break;
      case Mesh.CAP_START:
        circlePaths[0] = capPath(tessellation2, 0);
        circlePaths[1] = circlePaths[2].slice(0);
        break;
      case Mesh.CAP_END:
        circlePaths[index] = circlePaths[index - 1].slice(0);
        circlePaths[index + 1] = capPath(tessellation2, path2.length - 1);
        break;
      case Mesh.CAP_ALL:
        circlePaths[0] = capPath(tessellation2, 0);
        circlePaths[1] = circlePaths[2].slice(0);
        circlePaths[index] = circlePaths[index - 1].slice(0);
        circlePaths[index + 1] = capPath(tessellation2, path2.length - 1);
        break;
      default:
        break;
    }
    return circlePaths;
  };
  let path3D;
  let pathArray;
  if (instance) {
    const storage = instance._creationDataStorage;
    const arc = options.arc || storage.arc;
    path3D = storage.path3D.update(path);
    pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
    instance = CreateRibbon("", { pathArray, instance });
    storage.path3D = path3D;
    storage.pathArray = pathArray;
    storage.arc = arc;
    storage.radius = radius;
    return instance;
  }
  path3D = new Path3D(path);
  const newPathArray = new Array;
  cap = cap < 0 || cap > 3 ? 0 : cap;
  pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  const tube = CreateRibbon(name155, {
    pathArray,
    closePath: true,
    closeArray: false,
    updatable,
    sideOrientation,
    invertUV,
    frontUVs: options.frontUVs,
    backUVs: options.backUVs
  }, scene);
  tube._creationDataStorage.pathArray = pathArray;
  tube._creationDataStorage.path3D = path3D;
  tube._creationDataStorage.tessellation = tessellation;
  tube._creationDataStorage.cap = cap;
  tube._creationDataStorage.arc = options.arc;
  tube._creationDataStorage.radius = radius;
  return tube;
}
Mesh.CreateTube = (name155, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) => {
  const options = {
    path,
    radius,
    tessellation,
    radiusFunction,
    arc: 1,
    cap,
    updatable,
    sideOrientation,
    instance
  };
  return CreateTube(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/polyhedronBuilder.js
init_math_vector();
init_math_color();
init_compatibilityOptions();
function CreatePolyhedronVertexData(options) {
  const polyhedra = [];
  polyhedra[0] = {
    vertex: [
      [0, 0, 1.732051],
      [1.632993, 0, -0.5773503],
      [-0.8164966, 1.414214, -0.5773503],
      [-0.8164966, -1.414214, -0.5773503]
    ],
    face: [
      [0, 1, 2],
      [0, 2, 3],
      [0, 3, 1],
      [1, 3, 2]
    ]
  };
  polyhedra[1] = {
    vertex: [
      [0, 0, 1.414214],
      [1.414214, 0, 0],
      [0, 1.414214, 0],
      [-1.414214, 0, 0],
      [0, -1.414214, 0],
      [0, 0, -1.414214]
    ],
    face: [
      [0, 1, 2],
      [0, 2, 3],
      [0, 3, 4],
      [0, 4, 1],
      [1, 4, 5],
      [1, 5, 2],
      [2, 5, 3],
      [3, 5, 4]
    ]
  };
  polyhedra[2] = {
    vertex: [
      [0, 0, 1.070466],
      [0.7136442, 0, 0.7978784],
      [-0.3568221, 0.618034, 0.7978784],
      [-0.3568221, -0.618034, 0.7978784],
      [0.7978784, 0.618034, 0.3568221],
      [0.7978784, -0.618034, 0.3568221],
      [-0.9341724, 0.381966, 0.3568221],
      [0.1362939, 1, 0.3568221],
      [0.1362939, -1, 0.3568221],
      [-0.9341724, -0.381966, 0.3568221],
      [0.9341724, 0.381966, -0.3568221],
      [0.9341724, -0.381966, -0.3568221],
      [-0.7978784, 0.618034, -0.3568221],
      [-0.1362939, 1, -0.3568221],
      [-0.1362939, -1, -0.3568221],
      [-0.7978784, -0.618034, -0.3568221],
      [0.3568221, 0.618034, -0.7978784],
      [0.3568221, -0.618034, -0.7978784],
      [-0.7136442, 0, -0.7978784],
      [0, 0, -1.070466]
    ],
    face: [
      [0, 1, 4, 7, 2],
      [0, 2, 6, 9, 3],
      [0, 3, 8, 5, 1],
      [1, 5, 11, 10, 4],
      [2, 7, 13, 12, 6],
      [3, 9, 15, 14, 8],
      [4, 10, 16, 13, 7],
      [5, 8, 14, 17, 11],
      [6, 12, 18, 15, 9],
      [10, 11, 17, 19, 16],
      [12, 13, 16, 19, 18],
      [14, 15, 18, 19, 17]
    ]
  };
  polyhedra[3] = {
    vertex: [
      [0, 0, 1.175571],
      [1.051462, 0, 0.5257311],
      [0.3249197, 1, 0.5257311],
      [-0.8506508, 0.618034, 0.5257311],
      [-0.8506508, -0.618034, 0.5257311],
      [0.3249197, -1, 0.5257311],
      [0.8506508, 0.618034, -0.5257311],
      [0.8506508, -0.618034, -0.5257311],
      [-0.3249197, 1, -0.5257311],
      [-1.051462, 0, -0.5257311],
      [-0.3249197, -1, -0.5257311],
      [0, 0, -1.175571]
    ],
    face: [
      [0, 1, 2],
      [0, 2, 3],
      [0, 3, 4],
      [0, 4, 5],
      [0, 5, 1],
      [1, 5, 7],
      [1, 7, 6],
      [1, 6, 2],
      [2, 6, 8],
      [2, 8, 3],
      [3, 8, 9],
      [3, 9, 4],
      [4, 9, 10],
      [4, 10, 5],
      [5, 10, 7],
      [6, 7, 11],
      [6, 11, 8],
      [7, 10, 11],
      [8, 11, 9],
      [9, 11, 10]
    ]
  };
  polyhedra[4] = {
    vertex: [
      [0, 0, 1.070722],
      [0.7148135, 0, 0.7971752],
      [-0.104682, 0.7071068, 0.7971752],
      [-0.6841528, 0.2071068, 0.7971752],
      [-0.104682, -0.7071068, 0.7971752],
      [0.6101315, 0.7071068, 0.5236279],
      [1.04156, 0.2071068, 0.1367736],
      [0.6101315, -0.7071068, 0.5236279],
      [-0.3574067, 1, 0.1367736],
      [-0.7888348, -0.5, 0.5236279],
      [-0.9368776, 0.5, 0.1367736],
      [-0.3574067, -1, 0.1367736],
      [0.3574067, 1, -0.1367736],
      [0.9368776, -0.5, -0.1367736],
      [0.7888348, 0.5, -0.5236279],
      [0.3574067, -1, -0.1367736],
      [-0.6101315, 0.7071068, -0.5236279],
      [-1.04156, -0.2071068, -0.1367736],
      [-0.6101315, -0.7071068, -0.5236279],
      [0.104682, 0.7071068, -0.7971752],
      [0.6841528, -0.2071068, -0.7971752],
      [0.104682, -0.7071068, -0.7971752],
      [-0.7148135, 0, -0.7971752],
      [0, 0, -1.070722]
    ],
    face: [
      [0, 2, 3],
      [1, 6, 5],
      [4, 9, 11],
      [7, 15, 13],
      [8, 16, 10],
      [12, 14, 19],
      [17, 22, 18],
      [20, 21, 23],
      [0, 1, 5, 2],
      [0, 3, 9, 4],
      [0, 4, 7, 1],
      [1, 7, 13, 6],
      [2, 5, 12, 8],
      [2, 8, 10, 3],
      [3, 10, 17, 9],
      [4, 11, 15, 7],
      [5, 6, 14, 12],
      [6, 13, 20, 14],
      [8, 12, 19, 16],
      [9, 17, 18, 11],
      [10, 16, 22, 17],
      [11, 18, 21, 15],
      [13, 15, 21, 20],
      [14, 20, 23, 19],
      [16, 19, 23, 22],
      [18, 22, 23, 21]
    ]
  };
  polyhedra[5] = {
    vertex: [
      [0, 0, 1.322876],
      [1.309307, 0, 0.1889822],
      [-0.9819805, 0.8660254, 0.1889822],
      [0.1636634, -1.299038, 0.1889822],
      [0.3273268, 0.8660254, -0.9449112],
      [-0.8183171, -0.4330127, -0.9449112]
    ],
    face: [
      [0, 3, 1],
      [2, 4, 5],
      [0, 1, 4, 2],
      [0, 2, 5, 3],
      [1, 3, 5, 4]
    ]
  };
  polyhedra[6] = {
    vertex: [
      [0, 0, 1.159953],
      [1.013464, 0, 0.5642542],
      [-0.3501431, 0.9510565, 0.5642542],
      [-0.7715208, -0.6571639, 0.5642542],
      [0.6633206, 0.9510565, -0.03144481],
      [0.8682979, -0.6571639, -0.3996071],
      [-1.121664, 0.2938926, -0.03144481],
      [-0.2348831, -1.063314, -0.3996071],
      [0.5181548, 0.2938926, -0.9953061],
      [-0.5850262, -0.112257, -0.9953061]
    ],
    face: [
      [0, 1, 4, 2],
      [0, 2, 6, 3],
      [1, 5, 8, 4],
      [3, 6, 9, 7],
      [5, 7, 9, 8],
      [0, 3, 7, 5, 1],
      [2, 4, 8, 9, 6]
    ]
  };
  polyhedra[7] = {
    vertex: [
      [0, 0, 1.118034],
      [0.8944272, 0, 0.6708204],
      [-0.2236068, 0.8660254, 0.6708204],
      [-0.7826238, -0.4330127, 0.6708204],
      [0.6708204, 0.8660254, 0.2236068],
      [1.006231, -0.4330127, -0.2236068],
      [-1.006231, 0.4330127, 0.2236068],
      [-0.6708204, -0.8660254, -0.2236068],
      [0.7826238, 0.4330127, -0.6708204],
      [0.2236068, -0.8660254, -0.6708204],
      [-0.8944272, 0, -0.6708204],
      [0, 0, -1.118034]
    ],
    face: [
      [0, 1, 4, 2],
      [0, 2, 6, 3],
      [1, 5, 8, 4],
      [3, 6, 10, 7],
      [5, 9, 11, 8],
      [7, 10, 11, 9],
      [0, 3, 7, 9, 5, 1],
      [2, 4, 8, 11, 10, 6]
    ]
  };
  polyhedra[8] = {
    vertex: [
      [-0.729665, 0.670121, 0.319155],
      [-0.655235, -0.29213, -0.754096],
      [-0.093922, -0.607123, 0.537818],
      [0.702196, 0.595691, 0.485187],
      [0.776626, -0.36656, -0.588064]
    ],
    face: [
      [1, 4, 2],
      [0, 1, 2],
      [3, 0, 2],
      [4, 3, 2],
      [4, 1, 0, 3]
    ]
  };
  polyhedra[9] = {
    vertex: [
      [-0.868849, -0.100041, 0.61257],
      [-0.329458, 0.976099, 0.28078],
      [-0.26629, -0.013796, -0.477654],
      [-0.13392, -1.034115, 0.229829],
      [0.738834, 0.707117, -0.307018],
      [0.859683, -0.535264, -0.338508]
    ],
    face: [
      [3, 0, 2],
      [5, 3, 2],
      [4, 5, 2],
      [1, 4, 2],
      [0, 1, 2],
      [0, 3, 5, 4, 1]
    ]
  };
  polyhedra[10] = {
    vertex: [
      [-0.610389, 0.243975, 0.531213],
      [-0.187812, -0.48795, -0.664016],
      [-0.187812, 0.9759, -0.664016],
      [0.187812, -0.9759, 0.664016],
      [0.798201, 0.243975, 0.132803]
    ],
    face: [
      [1, 3, 0],
      [3, 4, 0],
      [3, 1, 4],
      [0, 2, 1],
      [0, 4, 2],
      [2, 4, 1]
    ]
  };
  polyhedra[11] = {
    vertex: [
      [-1.028778, 0.392027, -0.048786],
      [-0.640503, -0.646161, 0.621837],
      [-0.125162, -0.395663, -0.540059],
      [0.004683, 0.888447, -0.651988],
      [0.125161, 0.395663, 0.540059],
      [0.632925, -0.791376, 0.433102],
      [1.031672, 0.157063, -0.354165]
    ],
    face: [
      [3, 2, 0],
      [2, 1, 0],
      [2, 5, 1],
      [0, 4, 3],
      [0, 1, 4],
      [4, 1, 5],
      [2, 3, 6],
      [3, 4, 6],
      [5, 2, 6],
      [4, 5, 6]
    ]
  };
  polyhedra[12] = {
    vertex: [
      [-0.669867, 0.334933, -0.529576],
      [-0.669867, 0.334933, 0.529577],
      [-0.4043, 1.212901, 0],
      [-0.334933, -0.669867, -0.529576],
      [-0.334933, -0.669867, 0.529577],
      [0.334933, 0.669867, -0.529576],
      [0.334933, 0.669867, 0.529577],
      [0.4043, -1.212901, 0],
      [0.669867, -0.334933, -0.529576],
      [0.669867, -0.334933, 0.529577]
    ],
    face: [
      [8, 9, 7],
      [6, 5, 2],
      [3, 8, 7],
      [5, 0, 2],
      [4, 3, 7],
      [0, 1, 2],
      [9, 4, 7],
      [1, 6, 2],
      [9, 8, 5, 6],
      [8, 3, 0, 5],
      [3, 4, 1, 0],
      [4, 9, 6, 1]
    ]
  };
  polyhedra[13] = {
    vertex: [
      [-0.931836, 0.219976, -0.264632],
      [-0.636706, 0.318353, 0.692816],
      [-0.613483, -0.735083, -0.264632],
      [-0.326545, 0.979634, 0],
      [-0.318353, -0.636706, 0.692816],
      [-0.159176, 0.477529, -0.856368],
      [0.159176, -0.477529, -0.856368],
      [0.318353, 0.636706, 0.692816],
      [0.326545, -0.979634, 0],
      [0.613482, 0.735082, -0.264632],
      [0.636706, -0.318353, 0.692816],
      [0.931835, -0.219977, -0.264632]
    ],
    face: [
      [11, 10, 8],
      [7, 9, 3],
      [6, 11, 8],
      [9, 5, 3],
      [2, 6, 8],
      [5, 0, 3],
      [4, 2, 8],
      [0, 1, 3],
      [10, 4, 8],
      [1, 7, 3],
      [10, 11, 9, 7],
      [11, 6, 5, 9],
      [6, 2, 0, 5],
      [2, 4, 1, 0],
      [4, 10, 7, 1]
    ]
  };
  polyhedra[14] = {
    vertex: [
      [-0.93465, 0.300459, -0.271185],
      [-0.838689, -0.260219, -0.516017],
      [-0.711319, 0.717591, 0.128359],
      [-0.710334, -0.156922, 0.080946],
      [-0.599799, 0.556003, -0.725148],
      [-0.503838, -0.004675, -0.969981],
      [-0.487004, 0.26021, 0.48049],
      [-0.460089, -0.750282, -0.512622],
      [-0.376468, 0.973135, -0.325605],
      [-0.331735, -0.646985, 0.084342],
      [-0.254001, 0.831847, 0.530001],
      [-0.125239, -0.494738, -0.966586],
      [0.029622, 0.027949, 0.730817],
      [0.056536, -0.982543, -0.262295],
      [0.08085, 1.087391, 0.076037],
      [0.125583, -0.532729, 0.485984],
      [0.262625, 0.599586, 0.780328],
      [0.391387, -0.726999, -0.716259],
      [0.513854, -0.868287, 0.139347],
      [0.597475, 0.85513, 0.326364],
      [0.641224, 0.109523, 0.783723],
      [0.737185, -0.451155, 0.538891],
      [0.848705, -0.612742, -0.314616],
      [0.976075, 0.365067, 0.32976],
      [1.072036, -0.19561, 0.084927]
    ],
    face: [
      [15, 18, 21],
      [12, 20, 16],
      [6, 10, 2],
      [3, 0, 1],
      [9, 7, 13],
      [2, 8, 4, 0],
      [0, 4, 5, 1],
      [1, 5, 11, 7],
      [7, 11, 17, 13],
      [13, 17, 22, 18],
      [18, 22, 24, 21],
      [21, 24, 23, 20],
      [20, 23, 19, 16],
      [16, 19, 14, 10],
      [10, 14, 8, 2],
      [15, 9, 13, 18],
      [12, 15, 21, 20],
      [6, 12, 16, 10],
      [3, 6, 2, 0],
      [9, 3, 1, 7],
      [9, 15, 12, 6, 3],
      [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]
    ]
  };
  const type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  const size = options.size;
  const sizeX = options.sizeX || size || 1;
  const sizeY = options.sizeY || size || 1;
  const sizeZ = options.sizeZ || size || 1;
  const data = options.custom || polyhedra[type];
  const nbfaces = data.face.length;
  const faceUV = options.faceUV || new Array(nbfaces);
  const faceColors = options.faceColors;
  const flat = options.flat === undefined ? true : options.flat;
  const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;
  const positions = [];
  const indices = [];
  const normals = [];
  const uvs = [];
  const colors = [];
  let index = 0;
  let faceIdx = 0;
  const indexes = [];
  let i = 0;
  let f = 0;
  let u, v, ang, x, y, tmp;
  if (flat) {
    for (f = 0;f < nbfaces; f++) {
      if (faceColors && faceColors[f] === undefined) {
        faceColors[f] = new Color4(1, 1, 1, 1);
      }
      if (faceUV && faceUV[f] === undefined) {
        faceUV[f] = new Vector4(0, 0, 1, 1);
      }
    }
  }
  if (!flat) {
    for (i = 0;i < data.vertex.length; i++) {
      positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
      uvs.push(0, useOpenGLOrientationForUV ? 1 : 0);
    }
    for (f = 0;f < nbfaces; f++) {
      for (i = 0;i < data.face[f].length - 2; i++) {
        indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
      }
    }
  } else {
    for (f = 0;f < nbfaces; f++) {
      const fl = data.face[f].length;
      ang = 2 * Math.PI / fl;
      x = 0.5 * Math.tan(ang / 2);
      y = 0.5;
      for (i = 0;i < fl; i++) {
        positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
        indexes.push(index);
        index++;
        u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
        v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
        uvs.push(u, useOpenGLOrientationForUV ? 1 - v : v);
        tmp = x * Math.cos(ang) - y * Math.sin(ang);
        y = x * Math.sin(ang) + y * Math.cos(ang);
        x = tmp;
        if (faceColors) {
          colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
        }
      }
      for (i = 0;i < fl - 2; i++) {
        indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
      }
      faceIdx += fl;
    }
  }
  VertexData.ComputeNormals(positions, indices, normals);
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.positions = positions;
  vertexData.indices = indices;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  if (faceColors && flat) {
    vertexData.colors = colors;
  }
  return vertexData;
}
function CreatePolyhedron(name155, options = {}, scene = null) {
  const polyhedron = new Mesh(name155, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreatePolyhedronVertexData(options);
  vertexData.applyToMesh(polyhedron, options.updatable);
  return polyhedron;
}
VertexData.CreatePolyhedron = CreatePolyhedronVertexData;
Mesh.CreatePolyhedron = (name155, options, scene) => {
  return CreatePolyhedron(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/icoSphereBuilder.js
init_math_vector();
init_compatibilityOptions();
function CreateIcoSphereVertexData(options) {
  const sideOrientation = options.sideOrientation || VertexData.DEFAULTSIDE;
  const radius = options.radius || 1;
  const flat = options.flat === undefined ? true : options.flat;
  const subdivisions = (options.subdivisions || 4) | 0;
  const radiusX = options.radiusX || radius;
  const radiusY = options.radiusY || radius;
  const radiusZ = options.radiusZ || radius;
  const t = (1 + Math.sqrt(5)) / 2;
  const icoVertices = [
    -1,
    t,
    -0,
    1,
    t,
    0,
    -1,
    -t,
    0,
    1,
    -t,
    0,
    0,
    -1,
    -t,
    0,
    1,
    -t,
    0,
    -1,
    t,
    0,
    1,
    t,
    t,
    0,
    1,
    t,
    0,
    -1,
    -t,
    0,
    1,
    -t,
    0,
    -1
  ];
  const ico_indices = [
    0,
    11,
    5,
    0,
    5,
    1,
    0,
    1,
    7,
    0,
    7,
    10,
    12,
    22,
    23,
    1,
    5,
    20,
    5,
    11,
    4,
    23,
    22,
    13,
    22,
    18,
    6,
    7,
    1,
    8,
    14,
    21,
    4,
    14,
    4,
    2,
    16,
    13,
    6,
    15,
    6,
    19,
    3,
    8,
    9,
    4,
    21,
    5,
    13,
    17,
    23,
    6,
    13,
    22,
    19,
    6,
    18,
    9,
    8,
    1
  ];
  const vertices_unalias_id = [
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    0,
    2,
    3,
    3,
    3,
    4,
    7,
    8,
    9,
    9,
    10,
    11
  ];
  const ico_vertexuv = [
    5,
    1,
    3,
    1,
    6,
    4,
    0,
    0,
    5,
    3,
    4,
    2,
    2,
    2,
    4,
    0,
    2,
    0,
    1,
    1,
    6,
    0,
    6,
    2,
    0,
    4,
    3,
    3,
    4,
    4,
    3,
    1,
    4,
    2,
    4,
    4,
    0,
    2,
    1,
    1,
    2,
    2,
    3,
    3,
    1,
    3,
    2,
    4
  ];
  const ustep = 138 / 1024;
  const vstep = 239 / 1024;
  const uoffset = 60 / 1024;
  const voffset = 26 / 1024;
  const island_u_offset = -40 / 1024;
  const island_v_offset = 20 / 1024;
  const island = [
    0,
    0,
    0,
    0,
    1,
    0,
    0,
    1,
    1,
    0,
    0,
    0,
    1,
    1,
    0,
    0,
    1,
    1,
    1,
    0
  ];
  const indices = [];
  const positions = [];
  const normals = [];
  const uvs = [];
  let current_indice = 0;
  const face_vertex_pos = new Array(3);
  const face_vertex_uv = new Array(3);
  let v012;
  for (v012 = 0;v012 < 3; v012++) {
    face_vertex_pos[v012] = Vector3.Zero();
    face_vertex_uv[v012] = Vector2.Zero();
  }
  for (let face = 0;face < 20; face++) {
    for (v012 = 0;v012 < 3; v012++) {
      const v_id = ico_indices[3 * face + v012];
      face_vertex_pos[v012].copyFromFloats(icoVertices[3 * vertices_unalias_id[v_id]], icoVertices[3 * vertices_unalias_id[v_id] + 1], icoVertices[3 * vertices_unalias_id[v_id] + 2]);
      face_vertex_pos[v012].normalize();
      face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
    }
    const interp_vertex = (i1, i2, c1, c2) => {
      const pos_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
      const pos_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
      const pos_interp = subdivisions === i2 ? face_vertex_pos[2] : Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
      pos_interp.normalize();
      let vertex_normal;
      if (flat) {
        const centroid_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
        const centroid_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
        vertex_normal = Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
      } else {
        vertex_normal = new Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
      }
      vertex_normal.x /= radiusX;
      vertex_normal.y /= radiusY;
      vertex_normal.z /= radiusZ;
      vertex_normal.normalize();
      const uv_x0 = Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
      const uv_x1 = Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
      const uv_interp = subdivisions === i2 ? face_vertex_uv[2] : Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
      positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
      normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
      uvs.push(uv_interp.x, useOpenGLOrientationForUV ? 1 - uv_interp.y : uv_interp.y);
      indices.push(current_indice);
      current_indice++;
    };
    for (let i2 = 0;i2 < subdivisions; i2++) {
      for (let i1 = 0;i1 + i2 < subdivisions; i1++) {
        interp_vertex(i1, i2, i1 + 1 / 3, i2 + 1 / 3);
        interp_vertex(i1 + 1, i2, i1 + 1 / 3, i2 + 1 / 3);
        interp_vertex(i1, i2 + 1, i1 + 1 / 3, i2 + 1 / 3);
        if (i1 + i2 + 1 < subdivisions) {
          interp_vertex(i1 + 1, i2, i1 + 2 / 3, i2 + 2 / 3);
          interp_vertex(i1 + 1, i2 + 1, i1 + 2 / 3, i2 + 2 / 3);
          interp_vertex(i1, i2 + 1, i1 + 2 / 3, i2 + 2 / 3);
        }
      }
    }
  }
  VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  const vertexData = new VertexData;
  vertexData.indices = indices;
  vertexData.positions = positions;
  vertexData.normals = normals;
  vertexData.uvs = uvs;
  return vertexData;
}
function CreateIcoSphere(name155, options = {}, scene = null) {
  const sphere = new Mesh(name155, scene);
  options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
  sphere._originalBuilderSideOrientation = options.sideOrientation;
  const vertexData = CreateIcoSphereVertexData(options);
  vertexData.applyToMesh(sphere, options.updatable);
  return sphere;
}
VertexData.CreateIcoSphere = CreateIcoSphereVertexData;
Mesh.CreateIcoSphere = (name155, options, scene) => {
  return CreateIcoSphere(name155, options, scene);
};

// node_modules/@babylonjs/core/Meshes/Builders/decalBuilder.js
init_math_vector();
init_buffer();
init_compatibilityOptions();
var xpAxis = new Vector3(1, 0, 0);
var xnAxis = new Vector3(-1, 0, 0);
var ypAxis = new Vector3(0, 1, 0);
var ynAxis = new Vector3(0, -1, 0);
var zpAxis = new Vector3(0, 0, 1);
var znAxis = new Vector3(0, 0, -1);

class DecalVertex {
  constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero(), vertexIdx = 0, vertexIdxForBones = 0, localPositionOverride = null, localNormalOverride = null, matrixIndicesOverride = null, matrixWeightsOverride = null) {
    this.position = position;
    this.normal = normal;
    this.uv = uv;
    this.vertexIdx = vertexIdx;
    this.vertexIdxForBones = vertexIdxForBones;
    this.localPositionOverride = localPositionOverride;
    this.localNormalOverride = localNormalOverride;
    this.matrixIndicesOverride = matrixIndicesOverride;
    this.matrixWeightsOverride = matrixWeightsOverride;
  }
  clone() {
    return new DecalVertex(this.position.clone(), this.normal.clone(), this.uv.clone(), this.vertexIdx, this.vertexIdxForBones, this.localPositionOverride?.slice(), this.localNormalOverride?.slice(), this.matrixIndicesOverride?.slice(), this.matrixWeightsOverride?.slice());
  }
}
function CreateDecal(name155, sourceMesh, options) {
  const hasSkeleton = !!sourceMesh.skeleton;
  const useLocalComputation = options.localMode || hasSkeleton;
  const indices = sourceMesh.getIndices();
  const positions = hasSkeleton ? sourceMesh.getPositionData(true, true) : sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  const normals = hasSkeleton ? sourceMesh.getNormalsData(true, true) : sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  const localPositions = useLocalComputation ? hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.PositionKind) : positions : null;
  const localNormals = useLocalComputation ? hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.NormalKind) : normals : null;
  const uvs = sourceMesh.getVerticesData(VertexBuffer.UVKind);
  const matIndices = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesKind) : null;
  const matWeights = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsKind) : null;
  const matIndicesExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  const matWeightsExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  const position = options.position || Vector3.Zero();
  let normal = options.normal || Vector3.Up();
  const size = options.size || Vector3.One();
  const angle = options.angle || 0;
  if (!normal) {
    const target = new Vector3(0, 0, 1);
    const camera2 = sourceMesh.getScene().activeCamera;
    const cameraWorldTarget = Vector3.TransformCoordinates(target, camera2.getWorldMatrix());
    normal = camera2.globalPosition.subtract(cameraWorldTarget);
  }
  const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  const pitch = Math.atan2(normal.y, len);
  const vertexData = new VertexData;
  vertexData.indices = [];
  vertexData.positions = [];
  vertexData.normals = [];
  vertexData.uvs = [];
  vertexData.matricesIndices = hasSkeleton ? [] : null;
  vertexData.matricesWeights = hasSkeleton ? [] : null;
  vertexData.matricesIndicesExtra = matIndicesExtra ? [] : null;
  vertexData.matricesWeightsExtra = matWeightsExtra ? [] : null;
  let currentVertexDataIndex = 0;
  const extractDecalVector3 = (indexId, transformMatrix) => {
    const result = new DecalVertex;
    if (!indices || !positions || !normals) {
      return result;
    }
    const vertexId = indices[indexId];
    result.vertexIdx = vertexId * 3;
    result.vertexIdxForBones = vertexId * 4;
    result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
    Vector3.TransformCoordinatesToRef(result.position, transformMatrix, result.position);
    result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
    Vector3.TransformNormalToRef(result.normal, transformMatrix, result.normal);
    if (options.captureUVS && uvs) {
      const v = uvs[vertexId * 2 + 1];
      result.uv = new Vector2(uvs[vertexId * 2], useOpenGLOrientationForUV ? 1 - v : v);
    }
    return result;
  };
  const emptyArray = [0, 0, 0, 0];
  const clip = (vertices, axis) => {
    if (vertices.length === 0) {
      return vertices;
    }
    const clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
    const indexOf = (arr, val, start, num) => {
      for (let i = 0;i < num; ++i) {
        if (arr[start + i] === val) {
          return start + i;
        }
      }
      return -1;
    };
    const clipVertices = (v0, v1) => {
      const clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
      let indices2 = emptyArray;
      let weights = emptyArray;
      if (matIndices && matWeights) {
        const mat0Index = v0.matrixIndicesOverride ? 0 : v0.vertexIdxForBones;
        const v0Indices = v0.matrixIndicesOverride ?? matIndices;
        const v0Weights = v0.matrixWeightsOverride ?? matWeights;
        const mat1Index = v1.matrixIndicesOverride ? 0 : v1.vertexIdxForBones;
        const v1Indices = v1.matrixIndicesOverride ?? matIndices;
        const v1Weights = v1.matrixWeightsOverride ?? matWeights;
        indices2 = [0, 0, 0, 0];
        weights = [0, 0, 0, 0];
        let index = 0;
        for (let i = 0;i < 4; ++i) {
          if (v0Weights[mat0Index + i] > 0) {
            const idx = indexOf(v1Indices, v0Indices[mat0Index + i], mat1Index, 4);
            indices2[index] = v0Indices[mat0Index + i];
            weights[index] = Lerp(v0Weights[mat0Index + i], idx >= 0 ? v1Weights[idx] : 0, clipFactor);
            index++;
          }
        }
        for (let i = 0;i < 4 && index < 4; ++i) {
          const ind = v1Indices[mat1Index + i];
          if (indexOf(v0Indices, ind, mat0Index, 4) !== -1)
            continue;
          indices2[index] = ind;
          weights[index] = Lerp(0, v1Weights[mat1Index + i], clipFactor);
          index++;
        }
        const sumw = weights[0] + weights[1] + weights[2] + weights[3];
        weights[0] /= sumw;
        weights[1] /= sumw;
        weights[2] /= sumw;
        weights[3] /= sumw;
      }
      const v0LocalPositionX = v0.localPositionOverride ? v0.localPositionOverride[0] : localPositions?.[v0.vertexIdx] ?? 0;
      const v0LocalPositionY = v0.localPositionOverride ? v0.localPositionOverride[1] : localPositions?.[v0.vertexIdx + 1] ?? 0;
      const v0LocalPositionZ = v0.localPositionOverride ? v0.localPositionOverride[2] : localPositions?.[v0.vertexIdx + 2] ?? 0;
      const v1LocalPositionX = v1.localPositionOverride ? v1.localPositionOverride[0] : localPositions?.[v1.vertexIdx] ?? 0;
      const v1LocalPositionY = v1.localPositionOverride ? v1.localPositionOverride[1] : localPositions?.[v1.vertexIdx + 1] ?? 0;
      const v1LocalPositionZ = v1.localPositionOverride ? v1.localPositionOverride[2] : localPositions?.[v1.vertexIdx + 2] ?? 0;
      const v0LocalNormalX = v0.localNormalOverride ? v0.localNormalOverride[0] : localNormals?.[v0.vertexIdx] ?? 0;
      const v0LocalNormalY = v0.localNormalOverride ? v0.localNormalOverride[1] : localNormals?.[v0.vertexIdx + 1] ?? 0;
      const v0LocalNormalZ = v0.localNormalOverride ? v0.localNormalOverride[2] : localNormals?.[v0.vertexIdx + 2] ?? 0;
      const v1LocalNormalX = v1.localNormalOverride ? v1.localNormalOverride[0] : localNormals?.[v1.vertexIdx] ?? 0;
      const v1LocalNormalY = v1.localNormalOverride ? v1.localNormalOverride[1] : localNormals?.[v1.vertexIdx + 1] ?? 0;
      const v1LocalNormalZ = v1.localNormalOverride ? v1.localNormalOverride[2] : localNormals?.[v1.vertexIdx + 2] ?? 0;
      const interpNormalX = v0LocalNormalX + (v1LocalNormalX - v0LocalNormalX) * clipFactor;
      const interpNormalY = v0LocalNormalY + (v1LocalNormalY - v0LocalNormalY) * clipFactor;
      const interpNormalZ = v0LocalNormalZ + (v1LocalNormalZ - v0LocalNormalZ) * clipFactor;
      const norm = Math.sqrt(interpNormalX * interpNormalX + interpNormalY * interpNormalY + interpNormalZ * interpNormalZ);
      return new DecalVertex(Vector3.Lerp(v0.position, v1.position, clipFactor), Vector3.Lerp(v0.normal, v1.normal, clipFactor).normalize(), Vector2.Lerp(v0.uv, v1.uv, clipFactor), -1, -1, localPositions ? [
        v0LocalPositionX + (v1LocalPositionX - v0LocalPositionX) * clipFactor,
        v0LocalPositionY + (v1LocalPositionY - v0LocalPositionY) * clipFactor,
        v0LocalPositionZ + (v1LocalPositionZ - v0LocalPositionZ) * clipFactor
      ] : null, localNormals ? [interpNormalX / norm, interpNormalY / norm, interpNormalZ / norm] : null, indices2, weights);
    };
    let clipResult = null;
    if (vertices.length > 3) {
      clipResult = [];
    }
    for (let index = 0;index < vertices.length; index += 3) {
      let total = 0;
      let nV1 = null;
      let nV2 = null;
      let nV3 = null;
      let nV4 = null;
      const d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
      const d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
      const d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
      const v1Out = d1 > 0;
      const v2Out = d2 > 0;
      const v3Out = d3 > 0;
      total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
      switch (total) {
        case 0:
          if (vertices.length > 3) {
            clipResult.push(vertices[index]);
            clipResult.push(vertices[index + 1]);
            clipResult.push(vertices[index + 2]);
          } else {
            clipResult = vertices;
          }
          break;
        case 1:
          clipResult = clipResult ?? new Array;
          if (v1Out) {
            nV1 = vertices[index + 1];
            nV2 = vertices[index + 2];
            nV3 = clipVertices(vertices[index], nV1);
            nV4 = clipVertices(vertices[index], nV2);
          }
          if (v2Out) {
            nV1 = vertices[index];
            nV2 = vertices[index + 2];
            nV3 = clipVertices(vertices[index + 1], nV1);
            nV4 = clipVertices(vertices[index + 1], nV2);
            clipResult.push(nV3);
            clipResult.push(nV2.clone());
            clipResult.push(nV1.clone());
            clipResult.push(nV2.clone());
            clipResult.push(nV3.clone());
            clipResult.push(nV4);
            break;
          }
          if (v3Out) {
            nV1 = vertices[index];
            nV2 = vertices[index + 1];
            nV3 = clipVertices(vertices[index + 2], nV1);
            nV4 = clipVertices(vertices[index + 2], nV2);
          }
          if (nV1 && nV2 && nV3 && nV4) {
            clipResult.push(nV1.clone());
            clipResult.push(nV2.clone());
            clipResult.push(nV3);
            clipResult.push(nV4);
            clipResult.push(nV3.clone());
            clipResult.push(nV2.clone());
          }
          break;
        case 2:
          clipResult = clipResult ?? new Array;
          if (!v1Out) {
            nV1 = vertices[index].clone();
            nV2 = clipVertices(nV1, vertices[index + 1]);
            nV3 = clipVertices(nV1, vertices[index + 2]);
            clipResult.push(nV1);
            clipResult.push(nV2);
            clipResult.push(nV3);
          }
          if (!v2Out) {
            nV1 = vertices[index + 1].clone();
            nV2 = clipVertices(nV1, vertices[index + 2]);
            nV3 = clipVertices(nV1, vertices[index]);
            clipResult.push(nV1);
            clipResult.push(nV2);
            clipResult.push(nV3);
          }
          if (!v3Out) {
            nV1 = vertices[index + 2].clone();
            nV2 = clipVertices(nV1, vertices[index]);
            nV3 = clipVertices(nV1, vertices[index + 1]);
            clipResult.push(nV1);
            clipResult.push(nV2);
            clipResult.push(nV3);
          }
          break;
        case 3:
          break;
      }
    }
    return clipResult;
  };
  const sourceMeshAsMesh = sourceMesh instanceof Mesh ? sourceMesh : null;
  const matrixData = sourceMeshAsMesh?._thinInstanceDataStorage.matrixData;
  const numMatrices = sourceMeshAsMesh?.thinInstanceCount || 1;
  const thinInstanceMatrix = TmpVectors.Matrix[0];
  thinInstanceMatrix.copyFrom(Matrix.IdentityReadOnly);
  for (let m = 0;m < numMatrices; ++m) {
    if (sourceMeshAsMesh?.hasThinInstances && matrixData) {
      const ofst = m * 16;
      thinInstanceMatrix.setRowFromFloats(0, matrixData[ofst + 0], matrixData[ofst + 1], matrixData[ofst + 2], matrixData[ofst + 3]);
      thinInstanceMatrix.setRowFromFloats(1, matrixData[ofst + 4], matrixData[ofst + 5], matrixData[ofst + 6], matrixData[ofst + 7]);
      thinInstanceMatrix.setRowFromFloats(2, matrixData[ofst + 8], matrixData[ofst + 9], matrixData[ofst + 10], matrixData[ofst + 11]);
      thinInstanceMatrix.setRowFromFloats(3, matrixData[ofst + 12], matrixData[ofst + 13], matrixData[ofst + 14], matrixData[ofst + 15]);
    }
    const decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
    const inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
    const meshWorldMatrix = sourceMesh.getWorldMatrix();
    const transformMatrix = thinInstanceMatrix.multiply(meshWorldMatrix).multiply(inverseDecalWorldMatrix);
    const oneFaceVertices = new Array(3);
    for (let index = 0;index < indices.length; index += 3) {
      let faceVertices = oneFaceVertices;
      faceVertices[0] = extractDecalVector3(index, transformMatrix);
      faceVertices[1] = extractDecalVector3(index + 1, transformMatrix);
      faceVertices[2] = extractDecalVector3(index + 2, transformMatrix);
      if (options.cullBackFaces) {
        if (-faceVertices[0].normal.z <= 0 && -faceVertices[1].normal.z <= 0 && -faceVertices[2].normal.z <= 0) {
          continue;
        }
      }
      faceVertices = clip(faceVertices, xpAxis);
      if (!faceVertices)
        continue;
      faceVertices = clip(faceVertices, xnAxis);
      if (!faceVertices)
        continue;
      faceVertices = clip(faceVertices, ypAxis);
      if (!faceVertices)
        continue;
      faceVertices = clip(faceVertices, ynAxis);
      if (!faceVertices)
        continue;
      faceVertices = clip(faceVertices, zpAxis);
      if (!faceVertices)
        continue;
      faceVertices = clip(faceVertices, znAxis);
      if (!faceVertices)
        continue;
      for (let vIndex = 0;vIndex < faceVertices.length; vIndex++) {
        const vertex = faceVertices[vIndex];
        vertexData.indices.push(currentVertexDataIndex);
        if (useLocalComputation) {
          if (vertex.localPositionOverride) {
            vertexData.positions[currentVertexDataIndex * 3] = vertex.localPositionOverride[0];
            vertexData.positions[currentVertexDataIndex * 3 + 1] = vertex.localPositionOverride[1];
            vertexData.positions[currentVertexDataIndex * 3 + 2] = vertex.localPositionOverride[2];
          } else if (localPositions) {
            vertexData.positions[currentVertexDataIndex * 3] = localPositions[vertex.vertexIdx];
            vertexData.positions[currentVertexDataIndex * 3 + 1] = localPositions[vertex.vertexIdx + 1];
            vertexData.positions[currentVertexDataIndex * 3 + 2] = localPositions[vertex.vertexIdx + 2];
          }
          if (vertex.localNormalOverride) {
            vertexData.normals[currentVertexDataIndex * 3] = vertex.localNormalOverride[0];
            vertexData.normals[currentVertexDataIndex * 3 + 1] = vertex.localNormalOverride[1];
            vertexData.normals[currentVertexDataIndex * 3 + 2] = vertex.localNormalOverride[2];
          } else if (localNormals) {
            vertexData.normals[currentVertexDataIndex * 3] = localNormals[vertex.vertexIdx];
            vertexData.normals[currentVertexDataIndex * 3 + 1] = localNormals[vertex.vertexIdx + 1];
            vertexData.normals[currentVertexDataIndex * 3 + 2] = localNormals[vertex.vertexIdx + 2];
          }
        } else {
          vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
          vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
        }
        if (vertexData.matricesIndices && vertexData.matricesWeights) {
          if (vertex.matrixIndicesOverride) {
            vertexData.matricesIndices[currentVertexDataIndex * 4] = vertex.matrixIndicesOverride[0];
            vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = vertex.matrixIndicesOverride[1];
            vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = vertex.matrixIndicesOverride[2];
            vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = vertex.matrixIndicesOverride[3];
          } else {
            if (matIndices) {
              vertexData.matricesIndices[currentVertexDataIndex * 4] = matIndices[vertex.vertexIdxForBones];
              vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = matIndices[vertex.vertexIdxForBones + 1];
              vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = matIndices[vertex.vertexIdxForBones + 2];
              vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = matIndices[vertex.vertexIdxForBones + 3];
            }
            if (matIndicesExtra && vertexData.matricesIndicesExtra) {
              vertexData.matricesIndicesExtra[currentVertexDataIndex * 4] = matIndicesExtra[vertex.vertexIdxForBones];
              vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 1] = matIndicesExtra[vertex.vertexIdxForBones + 1];
              vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 2] = matIndicesExtra[vertex.vertexIdxForBones + 2];
              vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 3] = matIndicesExtra[vertex.vertexIdxForBones + 3];
            }
          }
          if (vertex.matrixWeightsOverride) {
            vertexData.matricesWeights[currentVertexDataIndex * 4] = vertex.matrixWeightsOverride[0];
            vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = vertex.matrixWeightsOverride[1];
            vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = vertex.matrixWeightsOverride[2];
            vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = vertex.matrixWeightsOverride[3];
          } else {
            if (matWeights) {
              vertexData.matricesWeights[currentVertexDataIndex * 4] = matWeights[vertex.vertexIdxForBones];
              vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = matWeights[vertex.vertexIdxForBones + 1];
              vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = matWeights[vertex.vertexIdxForBones + 2];
              vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = matWeights[vertex.vertexIdxForBones + 3];
            }
            if (matWeightsExtra && vertexData.matricesWeightsExtra) {
              vertexData.matricesWeightsExtra[currentVertexDataIndex * 4] = matWeightsExtra[vertex.vertexIdxForBones];
              vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 1] = matWeightsExtra[vertex.vertexIdxForBones + 1];
              vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 2] = matWeightsExtra[vertex.vertexIdxForBones + 2];
              vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 3] = matWeightsExtra[vertex.vertexIdxForBones + 3];
            }
          }
        }
        if (!options.captureUVS) {
          vertexData.uvs.push(0.5 + vertex.position.x / size.x);
          const v = 0.5 + vertex.position.y / size.y;
          vertexData.uvs.push(useOpenGLOrientationForUV ? 1 - v : v);
        } else {
          vertex.uv.toArray(vertexData.uvs, currentVertexDataIndex * 2);
        }
        currentVertexDataIndex++;
      }
    }
  }
  if (vertexData.indices.length === 0)
    vertexData.indices = null;
  if (vertexData.positions.length === 0)
    vertexData.positions = null;
  if (vertexData.normals.length === 0)
    vertexData.normals = null;
  if (vertexData.uvs.length === 0)
    vertexData.uvs = null;
  if (vertexData.matricesIndices?.length === 0)
    vertexData.matricesIndices = null;
  if (vertexData.matricesWeights?.length === 0)
    vertexData.matricesWeights = null;
  if (vertexData.matricesIndicesExtra?.length === 0)
    vertexData.matricesIndicesExtra = null;
  if (vertexData.matricesWeightsExtra?.length === 0)
    vertexData.matricesWeightsExtra = null;
  const decal = new Mesh(name155, sourceMesh.getScene());
  vertexData.applyToMesh(decal);
  if (useLocalComputation) {
    decal.skeleton = sourceMesh.skeleton;
    decal.parent = sourceMesh;
  } else {
    decal.position = position.clone();
    decal.rotation = new Vector3(pitch, yaw, angle);
  }
  decal.computeWorldMatrix(true);
  decal.refreshBoundingInfo(true, true);
  return decal;
}
Mesh.CreateDecal = (name155, sourceMesh, position, normal, size, angle) => {
  const options = {
    position,
    normal,
    size,
    angle
  };
  return CreateDecal(name155, sourceMesh, options);
};

// node_modules/@babylonjs/core/Meshes/Builders/geodesicBuilder.js
init_logger();

// node_modules/@babylonjs/core/Meshes/geodesicMesh.js
init_math_vector();
init_math_constants();

// node_modules/@babylonjs/core/Maths/math.isovector.js
init_logger();
init_math_vector();

// node_modules/@babylonjs/core/Meshes/Builders/goldbergBuilder.js
init_math_vector();
init_math_color();
init_logger();

// node_modules/@babylonjs/core/Meshes/goldbergMesh.js
init_math_vector();
init_buffer();
init_math_color();
init_logger();
Mesh._GoldbergMeshParser = (parsedMesh, scene) => {
  return GoldbergMesh.Parse(parsedMesh, scene);
};

class GoldbergMesh extends Mesh {
  constructor() {
    super(...arguments);
    this.goldbergData = {
      faceColors: [],
      faceCenters: [],
      faceZaxis: [],
      faceXaxis: [],
      faceYaxis: [],
      nbSharedFaces: 0,
      nbUnsharedFaces: 0,
      nbFaces: 0,
      nbFacesAtPole: 0,
      adjacentFaces: []
    };
  }
  relatedGoldbergFace(poleOrShared, fromPole) {
    if (fromPole === undefined) {
      if (poleOrShared > this.goldbergData.nbUnsharedFaces - 1) {
        Logger.Warn("Maximum number of unshared faces used");
        poleOrShared = this.goldbergData.nbUnsharedFaces - 1;
      }
      return this.goldbergData.nbUnsharedFaces + poleOrShared;
    }
    if (poleOrShared > 11) {
      Logger.Warn("Last pole used");
      poleOrShared = 11;
    }
    if (fromPole > this.goldbergData.nbFacesAtPole - 1) {
      Logger.Warn("Maximum number of faces at a pole used");
      fromPole = this.goldbergData.nbFacesAtPole - 1;
    }
    return 12 + poleOrShared * this.goldbergData.nbFacesAtPole + fromPole;
  }
  _changeGoldbergFaceColors(colorRange) {
    for (let i = 0;i < colorRange.length; i++) {
      const min = colorRange[i][0];
      const max = colorRange[i][1];
      const col = colorRange[i][2];
      for (let f = min;f < max + 1; f++) {
        this.goldbergData.faceColors[f] = col;
      }
    }
    const newCols = [];
    for (let f = 0;f < 12; f++) {
      for (let i = 0;i < 5; i++) {
        newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);
      }
    }
    for (let f = 12;f < this.goldbergData.faceColors.length; f++) {
      for (let i = 0;i < 6; i++) {
        newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);
      }
    }
    return newCols;
  }
  setGoldbergFaceColors(colorRange) {
    const newCols = this._changeGoldbergFaceColors(colorRange);
    this.setVerticesData(VertexBuffer.ColorKind, newCols);
  }
  updateGoldbergFaceColors(colorRange) {
    const newCols = this._changeGoldbergFaceColors(colorRange);
    this.updateVerticesData(VertexBuffer.ColorKind, newCols);
  }
  _changeGoldbergFaceUVs(uvRange) {
    const uvs = this.getVerticesData(VertexBuffer.UVKind);
    for (let i = 0;i < uvRange.length; i++) {
      const min = uvRange[i][0];
      const max = uvRange[i][1];
      const center = uvRange[i][2];
      const radius = uvRange[i][3];
      const angle = uvRange[i][4];
      const points5 = [];
      const points6 = [];
      let u;
      let v;
      for (let p = 0;p < 5; p++) {
        u = center.x + radius * Math.cos(angle + p * Math.PI / 2.5);
        v = center.y + radius * Math.sin(angle + p * Math.PI / 2.5);
        if (u < 0) {
          u = 0;
        }
        if (u > 1) {
          u = 1;
        }
        points5.push(u, v);
      }
      for (let p = 0;p < 6; p++) {
        u = center.x + radius * Math.cos(angle + p * Math.PI / 3);
        v = center.y + radius * Math.sin(angle + p * Math.PI / 3);
        if (u < 0) {
          u = 0;
        }
        if (u > 1) {
          u = 1;
        }
        points6.push(u, v);
      }
      for (let f = min;f < Math.min(12, max + 1); f++) {
        for (let p = 0;p < 5; p++) {
          uvs[10 * f + 2 * p] = points5[2 * p];
          uvs[10 * f + 2 * p + 1] = points5[2 * p + 1];
        }
      }
      for (let f = Math.max(12, min);f < max + 1; f++) {
        for (let p = 0;p < 6; p++) {
          uvs[12 * f - 24 + 2 * p] = points6[2 * p];
          uvs[12 * f - 23 + 2 * p] = points6[2 * p + 1];
        }
      }
    }
    return uvs;
  }
  setGoldbergFaceUVs(uvRange) {
    const newUVs = this._changeGoldbergFaceUVs(uvRange);
    this.setVerticesData(VertexBuffer.UVKind, newUVs);
  }
  updateGoldbergFaceUVs(uvRange) {
    const newUVs = this._changeGoldbergFaceUVs(uvRange);
    this.updateVerticesData(VertexBuffer.UVKind, newUVs);
  }
  placeOnGoldbergFaceAt(mesh, face, position) {
    const orientation = Vector3.RotationFromAxis(this.goldbergData.faceXaxis[face], this.goldbergData.faceYaxis[face], this.goldbergData.faceZaxis[face]);
    mesh.rotation = orientation;
    mesh.position = this.goldbergData.faceCenters[face].add(this.goldbergData.faceXaxis[face].scale(position.x)).add(this.goldbergData.faceYaxis[face].scale(position.y)).add(this.goldbergData.faceZaxis[face].scale(position.z));
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.type = "GoldbergMesh";
    const goldbergData = {};
    goldbergData.adjacentFaces = this.goldbergData.adjacentFaces;
    goldbergData.nbSharedFaces = this.goldbergData.nbSharedFaces;
    goldbergData.nbUnsharedFaces = this.goldbergData.nbUnsharedFaces;
    goldbergData.nbFaces = this.goldbergData.nbFaces;
    goldbergData.nbFacesAtPole = this.goldbergData.nbFacesAtPole;
    if (this.goldbergData.faceColors) {
      goldbergData.faceColors = [];
      for (const color of this.goldbergData.faceColors) {
        goldbergData.faceColors.push(color.asArray());
      }
    }
    if (this.goldbergData.faceCenters) {
      goldbergData.faceCenters = [];
      for (const vector of this.goldbergData.faceCenters) {
        goldbergData.faceCenters.push(vector.asArray());
      }
    }
    if (this.goldbergData.faceZaxis) {
      goldbergData.faceZaxis = [];
      for (const vector of this.goldbergData.faceZaxis) {
        goldbergData.faceZaxis.push(vector.asArray());
      }
    }
    if (this.goldbergData.faceYaxis) {
      goldbergData.faceYaxis = [];
      for (const vector of this.goldbergData.faceYaxis) {
        goldbergData.faceYaxis.push(vector.asArray());
      }
    }
    if (this.goldbergData.faceXaxis) {
      goldbergData.faceXaxis = [];
      for (const vector of this.goldbergData.faceXaxis) {
        goldbergData.faceXaxis.push(vector.asArray());
      }
    }
    serializationObject.goldbergData = goldbergData;
  }
  static Parse(parsedMesh, scene) {
    const goldbergData = parsedMesh.goldbergData;
    goldbergData.faceColors = goldbergData.faceColors.map((el) => Color4.FromArray(el));
    goldbergData.faceCenters = goldbergData.faceCenters.map((el) => Vector3.FromArray(el));
    goldbergData.faceZaxis = goldbergData.faceZaxis.map((el) => Vector3.FromArray(el));
    goldbergData.faceXaxis = goldbergData.faceXaxis.map((el) => Vector3.FromArray(el));
    goldbergData.faceYaxis = goldbergData.faceYaxis.map((el) => Vector3.FromArray(el));
    const goldberg = new GoldbergMesh(parsedMesh.name, scene);
    goldberg.goldbergData = goldbergData;
    return goldberg;
  }
}

// node_modules/@babylonjs/core/Meshes/Builders/goldbergBuilder.js
init_compatibilityOptions();

// node_modules/@babylonjs/core/Meshes/Builders/textBuilder.js
init_math_path();
init_math_vector();
class ShapePath {
  constructor(resolution) {
    this._paths = [];
    this._tempPaths = [];
    this._holes = [];
    this._resolution = resolution;
  }
  moveTo(x, y) {
    this._currentPath = new Path2(x, y);
    this._tempPaths.push(this._currentPath);
  }
  lineTo(x, y) {
    this._currentPath.addLineTo(x, y);
  }
  quadraticCurveTo(cpx, cpy, x, y) {
    this._currentPath.addQuadraticCurveTo(cpx, cpy, x, y, this._resolution);
  }
  bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) {
    this._currentPath.addBezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y, this._resolution);
  }
  extractHoles() {
    for (const path of this._tempPaths) {
      if (path.area() > 0) {
        this._holes.push(path);
      } else {
        this._paths.push(path);
      }
    }
    if (!this._paths.length && this._holes.length) {
      const temp = this._holes;
      this._holes = this._paths;
      this._paths = temp;
    }
    this._tempPaths.length = 0;
  }
  get paths() {
    return this._paths;
  }
  get holes() {
    return this._holes;
  }
}
function CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData) {
  const glyph = fontData.glyphs[char] || fontData.glyphs["?"];
  if (!glyph) {
    return null;
  }
  const shapePath = new ShapePath(resolution);
  if (glyph.o) {
    const outline = glyph.o.split(" ");
    for (let i = 0, l = outline.length;i < l; ) {
      const action2 = outline[i++];
      switch (action2) {
        case "m": {
          const x = parseInt(outline[i++]) * scale + offsetX;
          const y = parseInt(outline[i++]) * scale + offsetY;
          shapePath.moveTo(x, y);
          break;
        }
        case "l": {
          const x = parseInt(outline[i++]) * scale + offsetX;
          const y = parseInt(outline[i++]) * scale + offsetY;
          shapePath.lineTo(x, y);
          break;
        }
        case "q": {
          const cpx = parseInt(outline[i++]) * scale + offsetX;
          const cpy = parseInt(outline[i++]) * scale + offsetY;
          const cpx1 = parseInt(outline[i++]) * scale + offsetX;
          const cpy1 = parseInt(outline[i++]) * scale + offsetY;
          shapePath.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
          break;
        }
        case "b": {
          const cpx = parseInt(outline[i++]) * scale + offsetX;
          const cpy = parseInt(outline[i++]) * scale + offsetY;
          const cpx1 = parseInt(outline[i++]) * scale + offsetX;
          const cpy1 = parseInt(outline[i++]) * scale + offsetY;
          const cpx2 = parseInt(outline[i++]) * scale + offsetX;
          const cpy2 = parseInt(outline[i++]) * scale + offsetY;
          shapePath.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
          break;
        }
      }
    }
  }
  shapePath.extractHoles();
  return { offsetX: glyph.ha * scale, shapePath };
}
function CreateTextShapePaths(text, size, resolution, fontData) {
  const chars = Array.from(text);
  const scale = size / fontData.resolution;
  const line_height = (fontData.boundingBox.yMax - fontData.boundingBox.yMin + fontData.underlineThickness) * scale;
  const shapePaths = [];
  let offsetX = 0, offsetY = 0;
  for (let i = 0;i < chars.length; i++) {
    const char = chars[i];
    if (char === `
`) {
      offsetX = 0;
      offsetY -= line_height;
    } else {
      const ret = CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData);
      if (ret) {
        offsetX += ret.offsetX;
        shapePaths.push(ret.shapePath);
      }
    }
  }
  return shapePaths;
}

// node_modules/@babylonjs/core/Debug/physicsViewer.js
init_math_constants();
// node_modules/@babylonjs/core/Debug/rayHelper.js
init_math_vector();
// node_modules/@babylonjs/core/Debug/skeletonViewer.js
init_math_vector();
init_math_color();
init_buffer();
init_effect();
init_logger();

class SkeletonViewer {
  static CreateBoneWeightShader(options, scene) {
    const skeleton2 = options.skeleton;
    const colorBase = options.colorBase ?? Color3.Black();
    const colorZero = options.colorZero ?? Color3.Blue();
    const colorQuarter = options.colorQuarter ?? Color3.Green();
    const colorHalf = options.colorHalf ?? Color3.Yellow();
    const colorFull = options.colorFull ?? Color3.Red();
    const targetBoneIndex = options.targetBoneIndex ?? 0;
    Effect.ShadersStore["boneWeights:" + skeleton2.name + "VertexShader"] = `precision highp float;

        attribute vec3 position;
        attribute vec2 uv;

        uniform mat4 view;
        uniform mat4 projection;
        uniform mat4 worldViewProjection;

        #include<bonesDeclaration>
        #if NUM_BONE_INFLUENCERS == 0
            attribute vec4 matricesIndices;
            attribute vec4 matricesWeights;
        #endif
        #include<bakedVertexAnimationDeclaration>

        #include<instancesDeclaration>

        varying vec3 vColor;

        uniform vec3 colorBase;
        uniform vec3 colorZero;
        uniform vec3 colorQuarter;
        uniform vec3 colorHalf;
        uniform vec3 colorFull;

        uniform float targetBoneIndex;

        void main() {
            vec3 positionUpdated = position;

            #include<instancesVertex>
            #include<bonesVertex>
            #include<bakedVertexAnimation>

            vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);

            vec3 color = colorBase;
            float totalWeight = 0.;
            if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){
                totalWeight += matricesWeights[0];
            }
            if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){
                totalWeight += matricesWeights[1];
            }
            if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){
                totalWeight += matricesWeights[2];
            }
            if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){
                totalWeight += matricesWeights[3];
            }

            color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));
            color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));
            color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));
            color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));
            vColor = color;

        gl_Position = projection * view * worldPos;
        }`;
    Effect.ShadersStore["boneWeights:" + skeleton2.name + "FragmentShader"] = `
            precision highp float;
            varying vec3 vPosition;

            varying vec3 vColor;

            void main() {
                vec4 color = vec4(vColor, 1.0);
                gl_FragColor = color;
            }
        `;
    const shader154 = new ShaderMaterial("boneWeight:" + skeleton2.name, scene, {
      vertex: "boneWeights:" + skeleton2.name,
      fragment: "boneWeights:" + skeleton2.name
    }, {
      attributes: ["position", "normal", "matricesIndices", "matricesWeights"],
      uniforms: [
        "world",
        "worldView",
        "worldViewProjection",
        "view",
        "projection",
        "viewProjection",
        "colorBase",
        "colorZero",
        "colorQuarter",
        "colorHalf",
        "colorFull",
        "targetBoneIndex"
      ]
    });
    shader154.setColor3("colorBase", colorBase);
    shader154.setColor3("colorZero", colorZero);
    shader154.setColor3("colorQuarter", colorQuarter);
    shader154.setColor3("colorHalf", colorHalf);
    shader154.setColor3("colorFull", colorFull);
    shader154.setFloat("targetBoneIndex", targetBoneIndex);
    shader154.getClassName = () => {
      return "BoneWeightShader";
    };
    shader154.transparencyMode = Material.MATERIAL_OPAQUE;
    return shader154;
  }
  static CreateSkeletonMapShader(options, scene) {
    const skeleton2 = options.skeleton;
    const colorMap = options.colorMap ?? [
      {
        color: new Color3(1, 0.38, 0.18),
        location: 0
      },
      {
        color: new Color3(0.59, 0.18, 1),
        location: 0.2
      },
      {
        color: new Color3(0.59, 1, 0.18),
        location: 0.4
      },
      {
        color: new Color3(1, 0.87, 0.17),
        location: 0.6
      },
      {
        color: new Color3(1, 0.17, 0.42),
        location: 0.8
      },
      {
        color: new Color3(0.17, 0.68, 1),
        location: 1
      }
    ];
    const bufferWidth = skeleton2.bones.length + 1;
    const colorMapBuffer = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene);
    const shader154 = new ShaderMaterial("boneWeights:" + skeleton2.name, scene, {
      vertexSource: `precision highp float;

            attribute vec3 position;
            attribute vec2 uv;

            uniform mat4 view;
            uniform mat4 projection;
            uniform mat4 worldViewProjection;
            uniform float colorMap[` + skeleton2.bones.length * 4 + `];

            #include<bonesDeclaration>
            #if NUM_BONE_INFLUENCERS == 0
                attribute vec4 matricesIndices;
                attribute vec4 matricesWeights;
            #endif
            #include<bakedVertexAnimationDeclaration>
            #include<instancesDeclaration>

            varying vec3 vColor;

            void main() {
                vec3 positionUpdated = position;

                #include<instancesVertex>
                #include<bonesVertex>
                #include<bakedVertexAnimation>

                vec3 color = vec3(0.);
                bool first = true;

                for (int i = 0; i < 4; i++) {
                    int boneIdx = int(matricesIndices[i]);
                    float boneWgt = matricesWeights[i];

                    vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);

                    if (boneWgt > 0.) {
                        if (first) {
                            first = false;
                            color = c;
                        } else {
                            color = mix(color, c, boneWgt);
                        }
                    }
                }

                vColor = color;

                vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);

                gl_Position = projection * view * worldPos;
            }`,
      fragmentSource: `
            precision highp float;
            varying vec3 vColor;

            void main() {
                vec4 color = vec4( vColor, 1.0 );
                gl_FragColor = color;
            }
            `
    }, {
      attributes: ["position", "normal", "matricesIndices", "matricesWeights"],
      uniforms: ["world", "worldView", "worldViewProjection", "view", "projection", "viewProjection", "colorMap"]
    });
    shader154.setFloats("colorMap", colorMapBuffer);
    shader154.getClassName = () => {
      return "SkeletonMapShader";
    };
    shader154.transparencyMode = Material.MATERIAL_OPAQUE;
    return shader154;
  }
  static _CreateBoneMapColorBuffer(size, colorMap, scene) {
    const tempGrad = new DynamicTexture("temp", { width: size, height: 1 }, scene, false);
    const ctx = tempGrad.getContext();
    const grad = ctx.createLinearGradient(0, 0, size, 0);
    colorMap.forEach((stop) => {
      grad.addColorStop(stop.location, stop.color.toHexString());
    });
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, size, 1);
    tempGrad.update();
    const buffer2 = [];
    const data = ctx.getImageData(0, 0, size, 1).data;
    const rUnit = 1 / 255;
    for (let i = 0;i < data.length; i++) {
      buffer2.push(data[i] * rUnit);
    }
    tempGrad.dispose();
    return buffer2;
  }
  get scene() {
    return this._scene;
  }
  get utilityLayer() {
    return this._utilityLayer;
  }
  get isReady() {
    return this._ready;
  }
  set ready(value) {
    this._ready = value;
  }
  get debugMesh() {
    return this._debugMesh;
  }
  set debugMesh(value) {
    this._debugMesh = value;
  }
  get displayMode() {
    return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;
  }
  set displayMode(value) {
    if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
      value = SkeletonViewer.DISPLAY_LINES;
    }
    this.options.displayMode = value;
  }
  constructor(skeleton2, mesh, scene, autoUpdateBonesMatrices = true, renderingGroupId = 3, options = {}) {
    this.skeleton = skeleton2;
    this.mesh = mesh;
    this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
    this.renderingGroupId = renderingGroupId;
    this.options = options;
    this.color = Color3.White();
    this._debugLines = new Array;
    this._localAxes = null;
    this._isEnabled = true;
    this._obs = null;
    this._scene = scene;
    this._ready = false;
    options.pauseAnimations = options.pauseAnimations ?? true;
    options.returnToRest = options.returnToRest ?? false;
    options.displayMode = options.displayMode ?? SkeletonViewer.DISPLAY_LINES;
    options.displayOptions = options.displayOptions ?? {};
    options.displayOptions.midStep = options.displayOptions.midStep ?? 0.235;
    options.displayOptions.midStepFactor = options.displayOptions.midStepFactor ?? 0.155;
    options.displayOptions.sphereBaseSize = options.displayOptions.sphereBaseSize ?? 0.15;
    options.displayOptions.sphereScaleUnit = options.displayOptions.sphereScaleUnit ?? 2;
    options.displayOptions.sphereFactor = options.displayOptions.sphereFactor ?? 0.865;
    options.displayOptions.spurFollowsChild = options.displayOptions.spurFollowsChild ?? false;
    options.displayOptions.showLocalAxes = options.displayOptions.showLocalAxes ?? false;
    options.displayOptions.localAxesSize = options.displayOptions.localAxesSize ?? 0.075;
    options.computeBonesUsingShaders = options.computeBonesUsingShaders ?? true;
    options.useAllBones = options.useAllBones ?? true;
    this._boneIndices = new Set;
    if (!options.useAllBones) {
      const initialMeshBoneIndices = mesh?.getVerticesData(VertexBuffer.MatricesIndicesKind);
      const initialMeshBoneWeights = mesh?.getVerticesData(VertexBuffer.MatricesWeightsKind);
      if (initialMeshBoneIndices && initialMeshBoneWeights) {
        for (let i = 0;i < initialMeshBoneIndices.length; ++i) {
          const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i];
          if (weight !== 0) {
            this._boneIndices.add(index);
          }
        }
      }
    }
    this._utilityLayer = new UtilityLayerRenderer(this._scene, false);
    this._utilityLayer.pickUtilitySceneFirst = false;
    this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
    let displayMode = this.options.displayMode || 0;
    if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
      displayMode = SkeletonViewer.DISPLAY_LINES;
    }
    this.displayMode = displayMode;
    this.update();
    this._bindObs();
  }
  _bindObs() {
    switch (this.displayMode) {
      case SkeletonViewer.DISPLAY_LINES: {
        this._obs = this.scene.onBeforeRenderObservable.add(() => {
          this._displayLinesUpdate();
        });
        break;
      }
    }
  }
  update() {
    switch (this.displayMode) {
      case SkeletonViewer.DISPLAY_LINES: {
        this._displayLinesUpdate();
        break;
      }
      case SkeletonViewer.DISPLAY_SPHERES: {
        this._buildSpheresAndSpurs(true);
        break;
      }
      case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {
        this._buildSpheresAndSpurs(false);
        break;
      }
    }
    this._buildLocalAxes();
  }
  set isEnabled(value) {
    if (this.isEnabled === value) {
      return;
    }
    this._isEnabled = value;
    if (this.debugMesh) {
      this.debugMesh.setEnabled(value);
    }
    if (value && !this._obs) {
      this._bindObs();
    } else if (!value && this._obs) {
      this.scene.onBeforeRenderObservable.remove(this._obs);
      this._obs = null;
    }
  }
  get isEnabled() {
    return this._isEnabled;
  }
  _getBonePosition(position, bone2, meshMat, x = 0, y = 0, z = 0) {
    const tmat = TmpVectors.Matrix[0];
    const parentBone = bone2.getParent();
    tmat.copyFrom(bone2.getLocalMatrix());
    if (x !== 0 || y !== 0 || z !== 0) {
      const tmat2 = TmpVectors.Matrix[1];
      Matrix.IdentityToRef(tmat2);
      tmat2.setTranslationFromFloats(x, y, z);
      tmat2.multiplyToRef(tmat, tmat);
    }
    if (parentBone) {
      tmat.multiplyToRef(parentBone.getAbsoluteMatrix(), tmat);
    }
    tmat.multiplyToRef(meshMat, tmat);
    position.x = tmat.m[12];
    position.y = tmat.m[13];
    position.z = tmat.m[14];
  }
  _getLinesForBonesWithLength(bones, mesh) {
    const len = bones.length;
    let matrix;
    let meshPos;
    if (mesh) {
      matrix = mesh.getWorldMatrix();
      meshPos = mesh.position;
    } else {
      matrix = new Matrix;
      meshPos = bones[0].position;
    }
    let idx = 0;
    for (let i = 0;i < len; i++) {
      const bone2 = bones[i];
      let points = this._debugLines[idx];
      if (bone2._index === -1 || !this._boneIndices.has(bone2.getIndex()) && !this.options.useAllBones) {
        continue;
      }
      if (!points) {
        points = [Vector3.Zero(), Vector3.Zero()];
        this._debugLines[idx] = points;
      }
      this._getBonePosition(points[0], bone2, matrix);
      this._getBonePosition(points[1], bone2, matrix, 0, bone2.length, 0);
      points[0].subtractInPlace(meshPos);
      points[1].subtractInPlace(meshPos);
      idx++;
    }
  }
  _getLinesForBonesNoLength(bones) {
    const len = bones.length;
    let boneNum = 0;
    const mesh = this.mesh;
    let transformNode;
    let meshPos;
    if (mesh) {
      transformNode = mesh;
      meshPos = mesh.position;
    } else {
      transformNode = new TransformNode("");
      meshPos = bones[0].position;
    }
    for (let i = len - 1;i >= 0; i--) {
      const childBone = bones[i];
      const parentBone = childBone.getParent();
      if (!parentBone || !this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones) {
        continue;
      }
      let points = this._debugLines[boneNum];
      if (!points) {
        points = [Vector3.Zero(), Vector3.Zero()];
        this._debugLines[boneNum] = points;
      }
      childBone.getAbsolutePositionToRef(transformNode, points[0]);
      parentBone.getAbsolutePositionToRef(transformNode, points[1]);
      points[0].subtractInPlace(meshPos);
      points[1].subtractInPlace(meshPos);
      boneNum++;
    }
    if (!mesh) {
      transformNode.dispose();
    }
  }
  _revert(animationState) {
    if (this.options.pauseAnimations) {
      this.scene.animationsEnabled = animationState;
      this.utilityLayer.utilityLayerScene.animationsEnabled = animationState;
    }
  }
  _getAbsoluteBindPoseToRef(bone2, matrix) {
    if (bone2 === null || bone2._index === -1) {
      matrix.copyFrom(Matrix.Identity());
      return;
    }
    this._getAbsoluteBindPoseToRef(bone2.getParent(), matrix);
    bone2.getBindMatrix().multiplyToRef(matrix, matrix);
    return;
  }
  _createSpur(anchorPoint, bone2, childPoint, childBone, displayOptions, utilityLayerScene) {
    const dir = childPoint.subtract(anchorPoint);
    const h = dir.length();
    const up = dir.normalize().scale(h);
    const midStep = displayOptions.midStep || 0.165;
    const midStepFactor = displayOptions.midStepFactor || 0.215;
    const up0 = up.scale(midStep);
    const spur = ExtrudeShapeCustom("skeletonViewer", {
      shape: [new Vector3(1, -1, 0), new Vector3(1, 1, 0), new Vector3(-1, 1, 0), new Vector3(-1, -1, 0), new Vector3(1, -1, 0)],
      path: [Vector3.Zero(), up0, up],
      scaleFunction: (i) => {
        switch (i) {
          case 0:
          case 2:
            return 0;
          case 1:
            return h * midStepFactor;
        }
        return 0;
      },
      sideOrientation: Mesh.DEFAULTSIDE,
      updatable: false
    }, utilityLayerScene);
    const numVertices = spur.getTotalVertices();
    const mwk = [], mik = [];
    for (let i = 0;i < numVertices; i++) {
      mwk.push(1, 0, 0, 0);
      if (childBone && displayOptions.spurFollowsChild && i > 9) {
        mik.push(childBone.getIndex(), 0, 0, 0);
      } else {
        mik.push(bone2.getIndex(), 0, 0, 0);
      }
    }
    spur.position = anchorPoint.clone();
    spur.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
    spur.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
    spur.convertToFlatShadedMesh();
    return spur;
  }
  _getBoundingSphereForBone(boneIndex) {
    if (!this.mesh) {
      return null;
    }
    const positions = this.mesh.getVerticesData(VertexBuffer.PositionKind);
    const indices = this.mesh.getIndices();
    const boneWeights = this.mesh.getVerticesData(VertexBuffer.MatricesWeightsKind);
    const boneIndices = this.mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);
    if (!positions || !indices || !boneWeights || !boneIndices) {
      return null;
    }
    const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    let found = 0;
    for (let i = 0;i < indices.length; ++i) {
      const vertexIndex = indices[i];
      for (let b = 0;b < 4; ++b) {
        const bIndex = boneIndices[vertexIndex * 4 + b];
        const bWeight = boneWeights[vertexIndex * 4 + b];
        if (bIndex === boneIndex && bWeight > 0.00001) {
          Vector3.FromArrayToRef(positions, vertexIndex * 3, TmpVectors.Vector3[0]);
          min.minimizeInPlace(TmpVectors.Vector3[0]);
          max.maximizeInPlace(TmpVectors.Vector3[0]);
          found++;
          break;
        }
      }
    }
    return found > 1 ? {
      center: Vector3.Center(min, max),
      radius: Vector3.Distance(min, max) / 2
    } : null;
  }
  _buildSpheresAndSpurs(spheresOnly = true) {
    if (this._debugMesh) {
      this._debugMesh.dispose();
      this._debugMesh = null;
      this.ready = false;
    }
    this._ready = false;
    const utilityLayerScene = this.utilityLayer?.utilityLayerScene;
    const bones = this.skeleton.bones;
    const spheres = [];
    const spurs = [];
    const animationState = this.scene.animationsEnabled;
    try {
      if (this.options.pauseAnimations) {
        this.scene.animationsEnabled = false;
        utilityLayerScene.animationsEnabled = false;
      }
      if (this.options.returnToRest) {
        this.skeleton.returnToRest();
      }
      if (this.autoUpdateBonesMatrices) {
        this.skeleton.computeAbsoluteMatrices();
      }
      let longestBoneLength = Number.NEGATIVE_INFINITY;
      const displayOptions = this.options.displayOptions || {};
      for (let i = 0;i < bones.length; i++) {
        const bone2 = bones[i];
        if (bone2._index === -1 || !this._boneIndices.has(bone2.getIndex()) && !this.options.useAllBones) {
          continue;
        }
        const boneAbsoluteBindPoseTransform = new Matrix;
        this._getAbsoluteBindPoseToRef(bone2, boneAbsoluteBindPoseTransform);
        const anchorPoint = new Vector3;
        boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint);
        if (bone2.children.length > 0) {
          bone2.children.forEach((bc) => {
            const childAbsoluteBindPoseTransform = new Matrix;
            bc.getLocalMatrix().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteBindPoseTransform);
            const childPoint = new Vector3;
            childAbsoluteBindPoseTransform.decompose(undefined, undefined, childPoint);
            const distanceFromParent = Vector3.Distance(anchorPoint, childPoint);
            if (distanceFromParent > longestBoneLength) {
              longestBoneLength = distanceFromParent;
            }
            if (spheresOnly) {
              return;
            }
            spurs.push(this._createSpur(anchorPoint, bone2, childPoint, bc, displayOptions, utilityLayerScene));
          });
        } else {
          const boundingSphere2 = this._getBoundingSphereForBone(bone2.getIndex());
          if (boundingSphere2) {
            if (boundingSphere2.radius > longestBoneLength) {
              longestBoneLength = boundingSphere2.radius;
            }
            if (!spheresOnly) {
              let childPoint;
              const parentBone = bone2.getParent();
              if (parentBone) {
                this._getAbsoluteBindPoseToRef(parentBone, boneAbsoluteBindPoseTransform);
                boneAbsoluteBindPoseTransform.decompose(undefined, undefined, TmpVectors.Vector3[0]);
                childPoint = anchorPoint.subtract(TmpVectors.Vector3[0]).normalize().scale(boundingSphere2.radius).add(anchorPoint);
              } else {
                childPoint = boundingSphere2.center.subtract(anchorPoint).normalize().scale(boundingSphere2.radius).add(anchorPoint);
              }
              spurs.push(this._createSpur(anchorPoint, bone2, childPoint, null, displayOptions, utilityLayerScene));
            }
          }
        }
        const sphereBaseSize = displayOptions.sphereBaseSize || 0.2;
        const sphere = CreateSphere("skeletonViewer", {
          segments: 6,
          diameter: sphereBaseSize,
          updatable: true
        }, utilityLayerScene);
        const numVertices = sphere.getTotalVertices();
        const mwk = [], mik = [];
        for (let i2 = 0;i2 < numVertices; i2++) {
          mwk.push(1, 0, 0, 0);
          mik.push(bone2.getIndex(), 0, 0, 0);
        }
        sphere.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
        sphere.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
        sphere.position = anchorPoint.clone();
        spheres.push([sphere, bone2]);
      }
      const sphereScaleUnit = displayOptions.sphereScaleUnit || 2;
      const sphereFactor = displayOptions.sphereFactor || 0.85;
      const meshes = [];
      for (let i = 0;i < spheres.length; i++) {
        const [sphere, bone2] = spheres[i];
        const scale = 1 / (sphereScaleUnit / longestBoneLength);
        let _stepsOut = 0;
        let _b = bone2;
        while (_b.getParent() && _b.getParent().getIndex() !== -1) {
          _stepsOut++;
          _b = _b.getParent();
        }
        sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));
        meshes.push(sphere);
      }
      this.debugMesh = Mesh.MergeMeshes(meshes.concat(spurs), true, true);
      if (this.debugMesh) {
        this.debugMesh.renderingGroupId = this.renderingGroupId;
        this.debugMesh.skeleton = this.skeleton;
        this.debugMesh.parent = this.mesh;
        this.debugMesh.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
        this.debugMesh.alwaysSelectAsActiveMesh = true;
      }
      const light = this.utilityLayer._getSharedGizmoLight();
      light.intensity = 0.7;
      this._revert(animationState);
      this.ready = true;
    } catch (err) {
      Logger.Error(err);
      this._revert(animationState);
      this.dispose();
    }
  }
  _buildLocalAxes() {
    if (this._localAxes) {
      this._localAxes.dispose();
    }
    this._localAxes = null;
    const displayOptions = this.options.displayOptions || {};
    if (!displayOptions.showLocalAxes) {
      return;
    }
    const targetScene = this._utilityLayer.utilityLayerScene;
    const size = displayOptions.localAxesSize || 0.075;
    const lines = [];
    const colors = [];
    const red = new Color4(1, 0, 0, 1);
    const green = new Color4(0, 1, 0, 1);
    const blue = new Color4(0, 0, 1, 1);
    const mwk = [];
    const mik = [];
    const vertsPerBone = 6;
    for (const i in this.skeleton.bones) {
      const bone2 = this.skeleton.bones[i];
      if (bone2._index === -1 || !this._boneIndices.has(bone2.getIndex()) && !this.options.useAllBones) {
        continue;
      }
      const boneAbsoluteBindPoseTransform = new Matrix;
      const boneOrigin = new Vector3;
      this._getAbsoluteBindPoseToRef(bone2, boneAbsoluteBindPoseTransform);
      boneAbsoluteBindPoseTransform.decompose(undefined, TmpVectors.Quaternion[0], boneOrigin);
      const m = new Matrix;
      TmpVectors.Quaternion[0].toRotationMatrix(m);
      const boneAxisX = Vector3.TransformCoordinates(new Vector3(0 + size, 0, 0), m);
      const boneAxisY = Vector3.TransformCoordinates(new Vector3(0, 0 + size, 0), m);
      const boneAxisZ = Vector3.TransformCoordinates(new Vector3(0, 0, 0 + size), m);
      const axisX = [boneOrigin, boneOrigin.add(boneAxisX)];
      const axisY = [boneOrigin, boneOrigin.add(boneAxisY)];
      const axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)];
      const linePoints = [axisX, axisY, axisZ];
      const lineColors = [
        [red, red],
        [green, green],
        [blue, blue]
      ];
      lines.push(...linePoints);
      colors.push(...lineColors);
      for (let j = 0;j < vertsPerBone; j++) {
        mwk.push(1, 0, 0, 0);
        mik.push(bone2.getIndex(), 0, 0, 0);
      }
    }
    this._localAxes = CreateLineSystem("localAxes", { lines, colors, updatable: true }, targetScene);
    this._localAxes.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);
    this._localAxes.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);
    this._localAxes.skeleton = this.skeleton;
    this._localAxes.renderingGroupId = this.renderingGroupId + 1;
    this._localAxes.parent = this.mesh;
    this._localAxes.computeBonesUsingShaders = this.options.computeBonesUsingShaders ?? true;
  }
  _displayLinesUpdate() {
    if (!this._utilityLayer) {
      return;
    }
    if (this.autoUpdateBonesMatrices) {
      this.skeleton.computeAbsoluteMatrices();
    }
    if (this.skeleton.bones[0].length === undefined) {
      this._getLinesForBonesNoLength(this.skeleton.bones);
    } else {
      this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh);
    }
    const targetScene = this._utilityLayer.utilityLayerScene;
    if (targetScene) {
      if (!this._debugMesh) {
        this._debugMesh = CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
        this._debugMesh.renderingGroupId = this.renderingGroupId;
      } else {
        CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
      }
      if (this.mesh) {
        this._debugMesh.position.copyFrom(this.mesh.position);
      } else {
        this._debugMesh.position.copyFrom(this.skeleton.bones[0].position);
      }
      this._debugMesh.color = this.color;
    }
  }
  changeDisplayMode(mode) {
    const wasEnabled = this.isEnabled ? true : false;
    if (this.displayMode !== mode) {
      this.isEnabled = false;
      if (this._debugMesh) {
        this._debugMesh.dispose();
        this._debugMesh = null;
        this.ready = false;
      }
      this.displayMode = mode;
      this.update();
      this._bindObs();
      this.isEnabled = wasEnabled;
    }
  }
  changeDisplayOptions(option, value) {
    const wasEnabled = this.isEnabled ? true : false;
    this.options.displayOptions[option] = value;
    this.isEnabled = false;
    if (this._debugMesh) {
      this._debugMesh.dispose();
      this._debugMesh = null;
      this.ready = false;
    }
    this.update();
    this._bindObs();
    this.isEnabled = wasEnabled;
  }
  dispose() {
    this.isEnabled = false;
    if (this._debugMesh) {
      this._debugMesh.dispose();
      this._debugMesh = null;
    }
    if (this._utilityLayer) {
      this._utilityLayer.dispose();
      this._utilityLayer = null;
    }
    this.ready = false;
  }
}
SkeletonViewer.DISPLAY_LINES = 0;
SkeletonViewer.DISPLAY_SPHERES = 1;
SkeletonViewer.DISPLAY_SPHERE_AND_SPURS = 2;
// node_modules/@babylonjs/core/Debug/directionalLightFrustumViewer.js
init_math_color();
init_math_vector();
// node_modules/@babylonjs/core/DeviceInput/index.js
init_deviceEnums();
init_deviceSource();
init_deviceSourceManager();
// node_modules/@babylonjs/core/Engines/constants.js
class Constants {
}
Constants.AUTOSAMPLERSUFFIX = "Sampler";
Constants.DISABLEUA = "#define DISABLE_UNIFORMITY_ANALYSIS";
Constants.ALPHA_DISABLE = 0;
Constants.ALPHA_ADD = 1;
Constants.ALPHA_COMBINE = 2;
Constants.ALPHA_SUBTRACT = 3;
Constants.ALPHA_MULTIPLY = 4;
Constants.ALPHA_MAXIMIZED = 5;
Constants.ALPHA_ONEONE = 6;
Constants.ALPHA_PREMULTIPLIED = 7;
Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
Constants.ALPHA_INTERPOLATE = 9;
Constants.ALPHA_SCREENMODE = 10;
Constants.ALPHA_ONEONE_ONEONE = 11;
Constants.ALPHA_ALPHATOCOLOR = 12;
Constants.ALPHA_REVERSEONEMINUS = 13;
Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14;
Constants.ALPHA_ONEONE_ONEZERO = 15;
Constants.ALPHA_EXCLUSION = 16;
Constants.ALPHA_LAYER_ACCUMULATE = 17;
Constants.ALPHA_EQUATION_ADD = 0;
Constants.ALPHA_EQUATION_SUBSTRACT = 1;
Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2;
Constants.ALPHA_EQUATION_MAX = 3;
Constants.ALPHA_EQUATION_MIN = 4;
Constants.ALPHA_EQUATION_DARKEN = 5;
Constants.DELAYLOADSTATE_NONE = 0;
Constants.DELAYLOADSTATE_LOADED = 1;
Constants.DELAYLOADSTATE_LOADING = 2;
Constants.DELAYLOADSTATE_NOTLOADED = 4;
Constants.NEVER = 512;
Constants.ALWAYS = 519;
Constants.LESS = 513;
Constants.EQUAL = 514;
Constants.LEQUAL = 515;
Constants.GREATER = 516;
Constants.GEQUAL = 518;
Constants.NOTEQUAL = 517;
Constants.KEEP = 7680;
Constants.ZERO = 0;
Constants.REPLACE = 7681;
Constants.INCR = 7682;
Constants.DECR = 7683;
Constants.INVERT = 5386;
Constants.INCR_WRAP = 34055;
Constants.DECR_WRAP = 34056;
Constants.TEXTURE_CLAMP_ADDRESSMODE = 0;
Constants.TEXTURE_WRAP_ADDRESSMODE = 1;
Constants.TEXTURE_MIRROR_ADDRESSMODE = 2;
Constants.TEXTURE_CREATIONFLAG_STORAGE = 1;
Constants.TEXTUREFORMAT_ALPHA = 0;
Constants.TEXTUREFORMAT_LUMINANCE = 1;
Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
Constants.TEXTUREFORMAT_RGB = 4;
Constants.TEXTUREFORMAT_RGBA = 5;
Constants.TEXTUREFORMAT_RED = 6;
Constants.TEXTUREFORMAT_R = 6;
Constants.TEXTUREFORMAT_R16_UNORM = 33322;
Constants.TEXTUREFORMAT_RG16_UNORM = 33324;
Constants.TEXTUREFORMAT_RGB16_UNORM = 32852;
Constants.TEXTUREFORMAT_RGBA16_UNORM = 32859;
Constants.TEXTUREFORMAT_R16_SNORM = 36760;
Constants.TEXTUREFORMAT_RG16_SNORM = 36761;
Constants.TEXTUREFORMAT_RGB16_SNORM = 36762;
Constants.TEXTUREFORMAT_RGBA16_SNORM = 36763;
Constants.TEXTUREFORMAT_RG = 7;
Constants.TEXTUREFORMAT_RED_INTEGER = 8;
Constants.TEXTUREFORMAT_R_INTEGER = 8;
Constants.TEXTUREFORMAT_RG_INTEGER = 9;
Constants.TEXTUREFORMAT_RGB_INTEGER = 10;
Constants.TEXTUREFORMAT_RGBA_INTEGER = 11;
Constants.TEXTUREFORMAT_BGRA = 12;
Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13;
Constants.TEXTUREFORMAT_DEPTH32_FLOAT = 14;
Constants.TEXTUREFORMAT_DEPTH16 = 15;
Constants.TEXTUREFORMAT_DEPTH24 = 16;
Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17;
Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18;
Constants.TEXTUREFORMAT_STENCIL8 = 19;
Constants.TEXTUREFORMAT_UNDEFINED = 4294967295;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493;
Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495;
Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777;
Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840;
Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196;
Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493;
Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495;
Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496;
Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497;
Constants.TEXTURETYPE_UNSIGNED_BYTE = 0;
Constants.TEXTURETYPE_UNSIGNED_INT = 0;
Constants.TEXTURETYPE_FLOAT = 1;
Constants.TEXTURETYPE_HALF_FLOAT = 2;
Constants.TEXTURETYPE_BYTE = 3;
Constants.TEXTURETYPE_SHORT = 4;
Constants.TEXTURETYPE_UNSIGNED_SHORT = 5;
Constants.TEXTURETYPE_INT = 6;
Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7;
Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
Constants.TEXTURETYPE_UNDEFINED = 16;
Constants.TEXTURE_2D = 3553;
Constants.TEXTURE_2D_ARRAY = 35866;
Constants.TEXTURE_CUBE_MAP = 34067;
Constants.TEXTURE_CUBE_MAP_ARRAY = 3735928559;
Constants.TEXTURE_3D = 32879;
Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1;
Constants.TEXTURE_NEAREST_NEAREST = 1;
Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
Constants.TEXTURE_LINEAR_LINEAR = 2;
Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
Constants.TEXTURE_NEAREST_LINEAR = 7;
Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
Constants.TEXTURE_LINEAR_NEAREST = 12;
Constants.TEXTURE_EXPLICIT_MODE = 0;
Constants.TEXTURE_SPHERICAL_MODE = 1;
Constants.TEXTURE_PLANAR_MODE = 2;
Constants.TEXTURE_CUBIC_MODE = 3;
Constants.TEXTURE_PROJECTION_MODE = 4;
Constants.TEXTURE_SKYBOX_MODE = 5;
Constants.TEXTURE_INVCUBIC_MODE = 6;
Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7;
Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096;
Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64;
Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16;
Constants.TEXTURE_FILTERING_QUALITY_LOW = 8;
Constants.SCALEMODE_FLOOR = 1;
Constants.SCALEMODE_NEAREST = 2;
Constants.SCALEMODE_CEILING = 3;
Constants.MATERIAL_TextureDirtyFlag = 1;
Constants.MATERIAL_LightDirtyFlag = 2;
Constants.MATERIAL_FresnelDirtyFlag = 4;
Constants.MATERIAL_AttributesDirtyFlag = 8;
Constants.MATERIAL_MiscDirtyFlag = 16;
Constants.MATERIAL_PrePassDirtyFlag = 32;
Constants.MATERIAL_ImageProcessingDirtyFlag = 64;
Constants.MATERIAL_AllDirtyFlag = 127;
Constants.MATERIAL_TriangleFillMode = 0;
Constants.MATERIAL_WireFrameFillMode = 1;
Constants.MATERIAL_PointFillMode = 2;
Constants.MATERIAL_PointListDrawMode = 3;
Constants.MATERIAL_LineListDrawMode = 4;
Constants.MATERIAL_LineLoopDrawMode = 5;
Constants.MATERIAL_LineStripDrawMode = 6;
Constants.MATERIAL_TriangleStripDrawMode = 7;
Constants.MATERIAL_TriangleFanDrawMode = 8;
Constants.MATERIAL_ClockWiseSideOrientation = 0;
Constants.MATERIAL_CounterClockWiseSideOrientation = 1;
Constants.ACTION_NothingTrigger = 0;
Constants.ACTION_OnPickTrigger = 1;
Constants.ACTION_OnLeftPickTrigger = 2;
Constants.ACTION_OnRightPickTrigger = 3;
Constants.ACTION_OnCenterPickTrigger = 4;
Constants.ACTION_OnPickDownTrigger = 5;
Constants.ACTION_OnDoublePickTrigger = 6;
Constants.ACTION_OnPickUpTrigger = 7;
Constants.ACTION_OnPickOutTrigger = 16;
Constants.ACTION_OnLongPressTrigger = 8;
Constants.ACTION_OnPointerOverTrigger = 9;
Constants.ACTION_OnPointerOutTrigger = 10;
Constants.ACTION_OnEveryFrameTrigger = 11;
Constants.ACTION_OnIntersectionEnterTrigger = 12;
Constants.ACTION_OnIntersectionExitTrigger = 13;
Constants.ACTION_OnKeyDownTrigger = 14;
Constants.ACTION_OnKeyUpTrigger = 15;
Constants.PARTICLES_BILLBOARDMODE_Y = 2;
Constants.PARTICLES_BILLBOARDMODE_ALL = 7;
Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8;
Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9;
Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0;
Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
Constants.SCENELOADER_NO_LOGGING = 0;
Constants.SCENELOADER_MINIMAL_LOGGING = 1;
Constants.SCENELOADER_SUMMARY_LOGGING = 2;
Constants.SCENELOADER_DETAILED_LOGGING = 3;
Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0;
Constants.PREPASS_POSITION_TEXTURE_TYPE = 1;
Constants.PREPASS_VELOCITY_TEXTURE_TYPE = 2;
Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3;
Constants.PREPASS_COLOR_TEXTURE_TYPE = 4;
Constants.PREPASS_DEPTH_TEXTURE_TYPE = 5;
Constants.PREPASS_NORMAL_TEXTURE_TYPE = 6;
Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7;
Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE = 8;
Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE = 9;
Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE = 10;
Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE = 11;
Constants.PREPASS_ALBEDO_TEXTURE_TYPE = 12;
Constants.BUFFER_CREATIONFLAG_READ = 1;
Constants.BUFFER_CREATIONFLAG_WRITE = 2;
Constants.BUFFER_CREATIONFLAG_READWRITE = 3;
Constants.BUFFER_CREATIONFLAG_UNIFORM = 4;
Constants.BUFFER_CREATIONFLAG_VERTEX = 8;
Constants.BUFFER_CREATIONFLAG_INDEX = 16;
Constants.BUFFER_CREATIONFLAG_STORAGE = 32;
Constants.BUFFER_CREATIONFLAG_INDIRECT = 64;
Constants.RENDERPASS_MAIN = 0;
Constants.INPUT_ALT_KEY = 18;
Constants.INPUT_CTRL_KEY = 17;
Constants.INPUT_META_KEY1 = 91;
Constants.INPUT_META_KEY2 = 92;
Constants.INPUT_META_KEY3 = 93;
Constants.INPUT_SHIFT_KEY = 16;
Constants.SNAPSHOTRENDERING_STANDARD = 0;
Constants.SNAPSHOTRENDERING_FAST = 1;
Constants.PERSPECTIVE_CAMERA = 0;
Constants.ORTHOGRAPHIC_CAMERA = 1;
Constants.FOVMODE_VERTICAL_FIXED = 0;
Constants.FOVMODE_HORIZONTAL_FIXED = 1;
Constants.RIG_MODE_NONE = 0;
Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Constants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
Constants.RIG_MODE_VR = 20;
Constants.RIG_MODE_CUSTOM = 22;
Constants.MAX_SUPPORTED_UV_SETS = 6;
Constants.GL_ALPHA_EQUATION_ADD = 32774;
Constants.GL_ALPHA_EQUATION_MIN = 32775;
Constants.GL_ALPHA_EQUATION_MAX = 32776;
Constants.GL_ALPHA_EQUATION_SUBTRACT = 32778;
Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 32779;
Constants.GL_ALPHA_FUNCTION_SRC = 768;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 769;
Constants.GL_ALPHA_FUNCTION_SRC_ALPHA = 770;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 771;
Constants.GL_ALPHA_FUNCTION_DST_ALPHA = 772;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 773;
Constants.GL_ALPHA_FUNCTION_DST_COLOR = 774;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 775;
Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 776;
Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 32769;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 32770;
Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 32771;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 32772;
Constants.GL_ALPHA_FUNCTION_SRC1_COLOR = 35065;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR = 35066;
Constants.GL_ALPHA_FUNCTION_SRC1_ALPHA = 34185;
Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA = 35067;
Constants.SnippetUrl = "https://snippet.babylonjs.com";
Constants.FOGMODE_NONE = 0;
Constants.FOGMODE_EXP = 1;
Constants.FOGMODE_EXP2 = 2;
Constants.FOGMODE_LINEAR = 3;
Constants.BYTE = 5120;
Constants.UNSIGNED_BYTE = 5121;
Constants.SHORT = 5122;
Constants.UNSIGNED_SHORT = 5123;
Constants.INT = 5124;
Constants.UNSIGNED_INT = 5125;
Constants.FLOAT = 5126;
Constants.PositionKind = "position";
Constants.NormalKind = "normal";
Constants.TangentKind = "tangent";
Constants.UVKind = "uv";
Constants.UV2Kind = "uv2";
Constants.UV3Kind = "uv3";
Constants.UV4Kind = "uv4";
Constants.UV5Kind = "uv5";
Constants.UV6Kind = "uv6";
Constants.ColorKind = "color";
Constants.ColorInstanceKind = "instanceColor";
Constants.MatricesIndicesKind = "matricesIndices";
Constants.MatricesWeightsKind = "matricesWeights";
Constants.MatricesIndicesExtraKind = "matricesIndicesExtra";
Constants.MatricesWeightsExtraKind = "matricesWeightsExtra";
Constants.ANIMATIONTYPE_FLOAT = 0;
Constants.ANIMATIONTYPE_VECTOR3 = 1;
Constants.ANIMATIONTYPE_QUATERNION = 2;
Constants.ANIMATIONTYPE_MATRIX = 3;
Constants.ANIMATIONTYPE_COLOR3 = 4;
Constants.ANIMATIONTYPE_COLOR4 = 7;
Constants.ANIMATIONTYPE_VECTOR2 = 5;
Constants.ANIMATIONTYPE_SIZE = 6;
Constants.ShadowMinZ = 0;
Constants.ShadowMaxZ = 1e4;

// node_modules/@babylonjs/core/Engines/index.js
init_abstractEngine();
init_thinEngine();
init_engine();
init_engineStore();

// node_modules/@babylonjs/core/Engines/nullEngine.js
init_logger();
init_engine();
init_internalTexture();
init_dataBuffer();
init_performanceConfigurator();
init_renderTargetWrapper();
// node_modules/@babylonjs/core/Engines/AbstractEngine/index.js
init_abstractEngine_cubeTexture();
init_abstractEngine_loadingScreen();
init_abstractEngine_dom();
init_abstractEngine_states();

// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.timeQuery.js
init_abstractEngine();
init_perfCounter();
AbstractEngine.prototype.getGPUFrameTimeCounter = function() {
  if (!this._gpuFrameTime) {
    this._gpuFrameTime = new PerfCounter;
  }
  return this._gpuFrameTime;
};
AbstractEngine.prototype.captureGPUFrameTime = function(value) {};
// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.query.js
init_abstractEngine();

class _OcclusionDataStorage {
  constructor() {
    this.occlusionInternalRetryCounter = 0;
    this.isOcclusionQueryInProgress = false;
    this.isOccluded = false;
    this.occlusionRetryCount = -1;
    this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
    this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
    this.forceRenderingWhenOccluded = false;
  }
}
AbstractEngine.prototype.createQuery = function() {
  return null;
};
AbstractEngine.prototype.deleteQuery = function(query) {
  return this;
};
AbstractEngine.prototype.isQueryResultAvailable = function(query) {
  return false;
};
AbstractEngine.prototype.getQueryResult = function(query) {
  return 0;
};
AbstractEngine.prototype.beginOcclusionQuery = function(algorithmType, query) {
  return false;
};
AbstractEngine.prototype.endOcclusionQuery = function(algorithmType) {
  return this;
};
Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  get: function() {
    return this._occlusionDataStorage.isOcclusionQueryInProgress;
  },
  set: function(value) {
    this._occlusionDataStorage.isOcclusionQueryInProgress = value;
  },
  enumerable: false,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "_occlusionDataStorage", {
  get: function() {
    if (!this.__occlusionDataStorage) {
      this.__occlusionDataStorage = new _OcclusionDataStorage;
    }
    return this.__occlusionDataStorage;
  },
  enumerable: false,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  get: function() {
    return this._occlusionDataStorage.isOccluded;
  },
  set: function(value) {
    this._occlusionDataStorage.isOccluded = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  get: function() {
    return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  },
  set: function(value) {
    this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "occlusionType", {
  get: function() {
    return this._occlusionDataStorage.occlusionType;
  },
  set: function(value) {
    this._occlusionDataStorage.occlusionType = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "occlusionRetryCount", {
  get: function() {
    return this._occlusionDataStorage.occlusionRetryCount;
  },
  set: function(value) {
    this._occlusionDataStorage.occlusionRetryCount = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(AbstractMesh.prototype, "forceRenderingWhenOccluded", {
  get: function() {
    return this._occlusionDataStorage.forceRenderingWhenOccluded;
  },
  set: function(value) {
    this._occlusionDataStorage.forceRenderingWhenOccluded = value;
  },
  enumerable: true,
  configurable: true
});
AbstractMesh.prototype._checkOcclusionQuery = function() {
  const dataStorage = this._occlusionDataStorage;
  if (dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
    dataStorage.isOccluded = false;
    return false;
  }
  const engine = this.getEngine();
  if (!engine.getCaps().supportOcclusionQuery) {
    dataStorage.isOccluded = false;
    return false;
  }
  if (!engine.isQueryResultAvailable) {
    dataStorage.isOccluded = false;
    return false;
  }
  if (this.isOcclusionQueryInProgress && this._occlusionQuery !== null && this._occlusionQuery !== undefined) {
    const isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
    if (isOcclusionQueryAvailable) {
      const occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
      dataStorage.isOcclusionQueryInProgress = false;
      dataStorage.occlusionInternalRetryCounter = 0;
      dataStorage.isOccluded = occlusionQueryResult > 0 ? false : true;
    } else {
      dataStorage.occlusionInternalRetryCounter++;
      if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
        dataStorage.isOcclusionQueryInProgress = false;
        dataStorage.occlusionInternalRetryCounter = 0;
        dataStorage.isOccluded = dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
      } else {
        return dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
      }
    }
  }
  const scene = this.getScene();
  if (scene.getBoundingBoxRenderer) {
    const occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
    if (this._occlusionQuery === null) {
      this._occlusionQuery = engine.createQuery();
    }
    if (this._occlusionQuery && engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery)) {
      occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
      engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
      this._occlusionDataStorage.isOcclusionQueryInProgress = true;
    }
  }
  return dataStorage.isOccluded;
};

// node_modules/@babylonjs/core/Engines/AbstractEngine/index.js
init_abstractEngine_renderPass();
init_abstractEngine_texture();
init_abstractEngine_alpha();

// node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.views.js
init_observable();
init_abstractEngine();
var _onBeforeViewRenderObservable = new Observable;
var _onAfterViewRenderObservable = new Observable;
Object.defineProperty(AbstractEngine.prototype, "onBeforeViewRenderObservable", {
  get: function() {
    return _onBeforeViewRenderObservable;
  }
});
Object.defineProperty(AbstractEngine.prototype, "onAfterViewRenderObservable", {
  get: function() {
    return _onAfterViewRenderObservable;
  }
});
Object.defineProperty(AbstractEngine.prototype, "inputElement", {
  get: function() {
    return this._inputElement;
  },
  set: function(value) {
    if (this._inputElement !== value) {
      this._inputElement = value;
      this._onEngineViewChanged?.();
    }
  }
});
AbstractEngine.prototype.getInputElement = function() {
  return this.inputElement || this.getRenderingCanvas();
};
AbstractEngine.prototype.registerView = function(canvas, camera2, clearBeforeCopy) {
  if (!this.views) {
    this.views = [];
  }
  for (const view of this.views) {
    if (view.target === canvas) {
      return view;
    }
  }
  const masterCanvas = this.getRenderingCanvas();
  if (masterCanvas) {
    canvas.width = masterCanvas.width;
    canvas.height = masterCanvas.height;
  }
  const newView = { target: canvas, camera: camera2, clearBeforeCopy, enabled: true, id: (Math.random() * 1e5).toFixed() };
  this.views.push(newView);
  if (camera2 && !Array.isArray(camera2)) {
    camera2.onDisposeObservable.add(() => {
      this.unRegisterView(canvas);
    });
  }
  return newView;
};
AbstractEngine.prototype.unRegisterView = function(canvas) {
  if (!this.views || this.views.length === 0) {
    return this;
  }
  for (const view of this.views) {
    if (view.target === canvas) {
      const index = this.views.indexOf(view);
      if (index !== -1) {
        this.views.splice(index, 1);
      }
      break;
    }
  }
  return this;
};
AbstractEngine.prototype._renderViewStep = function(view) {
  const canvas = view.target;
  const context = canvas.getContext("2d");
  if (!context) {
    return true;
  }
  const parent = this.getRenderingCanvas();
  _onBeforeViewRenderObservable.notifyObservers(view);
  const camera2 = view.camera;
  let previewCamera = null;
  let previewCameras = null;
  let scene = null;
  if (camera2) {
    scene = Array.isArray(camera2) ? camera2[0].getScene() : camera2.getScene();
    previewCamera = scene.activeCamera;
    previewCameras = scene.activeCameras;
    if (Array.isArray(camera2)) {
      scene.activeCameras = camera2;
    } else {
      scene.activeCamera = camera2;
      scene.activeCameras = null;
    }
  }
  this.activeView = view;
  if (view.customResize) {
    view.customResize(canvas);
  } else {
    const width = Math.floor(canvas.clientWidth / this._hardwareScalingLevel);
    const height = Math.floor(canvas.clientHeight / this._hardwareScalingLevel);
    const dimsChanged = width !== canvas.width || parent.width !== canvas.width || height !== canvas.height || parent.height !== canvas.height;
    if (canvas.clientWidth && canvas.clientHeight && dimsChanged) {
      canvas.width = width;
      canvas.height = height;
      this.setSize(width, height);
    }
  }
  if (!parent.width || !parent.height) {
    return false;
  }
  this._renderFrame();
  this.flushFramebuffer();
  if (view.clearBeforeCopy) {
    context.clearRect(0, 0, parent.width, parent.height);
  }
  context.drawImage(parent, 0, 0);
  if (scene) {
    scene.activeCameras = previewCameras;
    scene.activeCamera = previewCamera;
  }
  _onAfterViewRenderObservable.notifyObservers(view);
  return true;
};
AbstractEngine.prototype._renderViews = function() {
  if (!this.views || this.views.length === 0) {
    return false;
  }
  const parent = this.getRenderingCanvas();
  if (!parent) {
    return false;
  }
  let inputElementView;
  for (const view of this.views) {
    if (!view.enabled) {
      continue;
    }
    const canvas = view.target;
    if (canvas === this.inputElement) {
      inputElementView = view;
      continue;
    }
    if (!this._renderViewStep(view)) {
      return false;
    }
  }
  if (inputElementView) {
    if (!this._renderViewStep(inputElementView)) {
      return false;
    }
  }
  this.activeView = null;
  return true;
};
// node_modules/@babylonjs/core/Engines/Extensions/index.js
init_engine_alpha();

// node_modules/@babylonjs/core/Engines/Extensions/engine.debugging.js
init_abstractEngine();
AbstractEngine.prototype._debugPushGroup = function(groupName, targetObject) {};
AbstractEngine.prototype._debugPopGroup = function(targetObject) {};
AbstractEngine.prototype._debugInsertMarker = function(text, targetObject) {};
AbstractEngine.prototype._debugFlushPendingCommands = function() {};
// node_modules/@babylonjs/core/Engines/Extensions/engine.query.js
init_thinEngine();

// node_modules/@babylonjs/core/Instrumentation/timeToken.js
class _TimeToken {
  constructor() {
    this._timeElapsedQueryEnded = false;
  }
}

// node_modules/@babylonjs/core/Engines/Extensions/engine.query.js
ThinEngine.prototype.createQuery = function() {
  const query = this._gl.createQuery();
  if (!query) {
    throw new Error("Unable to create Occlusion Query");
  }
  return query;
};
ThinEngine.prototype.deleteQuery = function(query) {
  this._gl.deleteQuery(query);
  return this;
};
ThinEngine.prototype.isQueryResultAvailable = function(query) {
  return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
};
ThinEngine.prototype.getQueryResult = function(query) {
  return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
};
ThinEngine.prototype.beginOcclusionQuery = function(algorithmType, query) {
  const glAlgorithm = this._getGlAlgorithmType(algorithmType);
  this._gl.beginQuery(glAlgorithm, query);
  return true;
};
ThinEngine.prototype.endOcclusionQuery = function(algorithmType) {
  const glAlgorithm = this._getGlAlgorithmType(algorithmType);
  this._gl.endQuery(glAlgorithm);
  return this;
};
ThinEngine.prototype._createTimeQuery = function() {
  const timerQuery = this.getCaps().timerQuery;
  if (timerQuery.createQueryEXT) {
    return timerQuery.createQueryEXT();
  }
  return this.createQuery();
};
ThinEngine.prototype._deleteTimeQuery = function(query) {
  const timerQuery = this.getCaps().timerQuery;
  if (timerQuery.deleteQueryEXT) {
    timerQuery.deleteQueryEXT(query);
    return;
  }
  this.deleteQuery(query);
};
ThinEngine.prototype._getTimeQueryResult = function(query) {
  const timerQuery = this.getCaps().timerQuery;
  if (timerQuery.getQueryObjectEXT) {
    return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  }
  return this.getQueryResult(query);
};
ThinEngine.prototype._getTimeQueryAvailability = function(query) {
  const timerQuery = this.getCaps().timerQuery;
  if (timerQuery.getQueryObjectEXT) {
    return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  }
  return this.isQueryResultAvailable(query);
};
ThinEngine.prototype.startTimeQuery = function() {
  const caps = this.getCaps();
  const timerQuery = caps.timerQuery;
  if (!timerQuery) {
    return null;
  }
  const token = new _TimeToken;
  this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  if (caps.canUseTimestampForTimerQuery) {
    token._startTimeQuery = this._createTimeQuery();
    if (token._startTimeQuery) {
      timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
    }
  } else {
    if (this._currentNonTimestampToken) {
      return this._currentNonTimestampToken;
    }
    token._timeElapsedQuery = this._createTimeQuery();
    if (token._timeElapsedQuery) {
      if (timerQuery.beginQueryEXT) {
        timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
      } else {
        this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
      }
    }
    this._currentNonTimestampToken = token;
  }
  return token;
};
ThinEngine.prototype.endTimeQuery = function(token) {
  const caps = this.getCaps();
  const timerQuery = caps.timerQuery;
  if (!timerQuery || !token) {
    return -1;
  }
  if (caps.canUseTimestampForTimerQuery) {
    if (!token._startTimeQuery) {
      return -1;
    }
    if (!token._endTimeQuery) {
      token._endTimeQuery = this._createTimeQuery();
      if (token._endTimeQuery) {
        timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
      }
    }
  } else if (!token._timeElapsedQueryEnded) {
    if (!token._timeElapsedQuery) {
      return -1;
    }
    if (timerQuery.endQueryEXT) {
      timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
    } else {
      this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
      this._currentNonTimestampToken = null;
    }
    token._timeElapsedQueryEnded = true;
  }
  const disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  let available = false;
  if (token._endTimeQuery) {
    available = this._getTimeQueryAvailability(token._endTimeQuery);
  } else if (token._timeElapsedQuery) {
    available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  }
  if (available && !disjoint) {
    let result = 0;
    if (caps.canUseTimestampForTimerQuery) {
      if (!token._startTimeQuery || !token._endTimeQuery) {
        return -1;
      }
      const timeStart = this._getTimeQueryResult(token._startTimeQuery);
      const timeEnd = this._getTimeQueryResult(token._endTimeQuery);
      result = timeEnd - timeStart;
      this._deleteTimeQuery(token._startTimeQuery);
      this._deleteTimeQuery(token._endTimeQuery);
      token._startTimeQuery = null;
      token._endTimeQuery = null;
    } else {
      if (!token._timeElapsedQuery) {
        return -1;
      }
      result = this._getTimeQueryResult(token._timeElapsedQuery);
      this._deleteTimeQuery(token._timeElapsedQuery);
      token._timeElapsedQuery = null;
      token._timeElapsedQueryEnded = false;
    }
    return result;
  }
  return -1;
};
ThinEngine.prototype.captureGPUFrameTime = function(value) {
  if (value === this._captureGPUFrameTime) {
    return;
  }
  this._captureGPUFrameTime = value;
  if (value) {
    const gpuFrameTime = this.getGPUFrameTimeCounter();
    this._onBeginFrameObserver = this.onBeginFrameObservable.add(() => {
      if (!this._gpuFrameTimeToken) {
        this._gpuFrameTimeToken = this.startTimeQuery();
      }
    });
    this._onEndFrameObserver = this.onEndFrameObservable.add(() => {
      if (!this._gpuFrameTimeToken) {
        return;
      }
      const time = this.endTimeQuery(this._gpuFrameTimeToken);
      if (time > -1) {
        this._gpuFrameTimeToken = null;
        gpuFrameTime.fetchNewFrame();
        gpuFrameTime.addCount(time, true);
      }
    });
  } else {
    this.onBeginFrameObservable.remove(this._onBeginFrameObserver);
    this._onBeginFrameObserver = null;
    this.onEndFrameObservable.remove(this._onEndFrameObserver);
    this._onEndFrameObserver = null;
  }
};
ThinEngine.prototype._getGlAlgorithmType = function(algorithmType) {
  return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
};
// node_modules/@babylonjs/core/Engines/Extensions/engine.transformFeedback.js
init_engine();
Engine.prototype.createTransformFeedback = function() {
  const transformFeedback = this._gl.createTransformFeedback();
  if (!transformFeedback) {
    throw new Error("Unable to create Transform Feedback");
  }
  return transformFeedback;
};
Engine.prototype.deleteTransformFeedback = function(value) {
  this._gl.deleteTransformFeedback(value);
};
Engine.prototype.bindTransformFeedback = function(value) {
  this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
};
Engine.prototype.beginTransformFeedback = function(usePoints = true) {
  this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
};
Engine.prototype.endTransformFeedback = function() {
  this._gl.endTransformFeedback();
};
Engine.prototype.setTranformFeedbackVaryings = function(program, value) {
  this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
};
Engine.prototype.bindTransformFeedbackBuffer = function(value) {
  this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null);
};
Engine.prototype.readTransformFeedbackBuffer = function(target) {
  this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, target);
};

// node_modules/@babylonjs/core/Engines/Extensions/index.js
init_engine_rawTexture();

// node_modules/@babylonjs/core/Engines/Extensions/engine.videoTexture.js
init_thinEngine();
ThinEngine.prototype.updateVideoTexture = function(texture, video, invertY) {
  if (!texture || texture._isDisabled) {
    return;
  }
  const glformat = this._getInternalFormat(texture.format);
  const internalFormat = this._getRGBABufferInternalSizedFormat(0, texture.format);
  const wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  this._unpackFlipY(!invertY);
  try {
    if (this._videoTextureSupported === undefined) {
      this._gl.getError();
      this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);
      if (this._gl.getError() !== 0) {
        this._videoTextureSupported = false;
      } else {
        this._videoTextureSupported = true;
      }
    }
    if (!this._videoTextureSupported) {
      if (!texture._workingCanvas) {
        texture._workingCanvas = this.createCanvas(texture.width, texture.height);
        const context = texture._workingCanvas.getContext("2d");
        if (!context) {
          throw new Error("Unable to get 2d context");
        }
        texture._workingContext = context;
        texture._workingCanvas.width = texture.width;
        texture._workingCanvas.height = texture.height;
      }
      texture._workingContext.clearRect(0, 0, texture.width, texture.height);
      texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
      this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
    } else {
      this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);
    }
    if (texture.generateMipMaps) {
      this._gl.generateMipmap(this._gl.TEXTURE_2D);
    }
    if (!wasPreviouslyBound) {
      this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
    }
    texture.isReady = true;
  } catch (ex) {
    texture._isDisabled = true;
  }
};
// node_modules/@babylonjs/core/Engines/Extensions/engine.multiRender.js
init_internalTexture();
init_logger();
init_thinEngine();
ThinEngine.prototype.restoreSingleAttachment = function() {
  const gl = this._gl;
  this.bindAttachments([gl.BACK]);
};
ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function() {
  const gl = this._gl;
  this.bindAttachments([gl.COLOR_ATTACHMENT0]);
};
ThinEngine.prototype.buildTextureLayout = function(textureStatus) {
  const gl = this._gl;
  const result = [];
  for (let i = 0;i < textureStatus.length; i++) {
    if (textureStatus[i]) {
      result.push(gl["COLOR_ATTACHMENT" + i]);
    } else {
      result.push(gl.NONE);
    }
  }
  return result;
};
ThinEngine.prototype.bindAttachments = function(attachments) {
  const gl = this._gl;
  gl.drawBuffers(attachments);
};
ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {
  this._currentRenderTarget = null;
  if (!rtWrapper.disableAutomaticMSAAResolve) {
    this.resolveMultiFramebuffer(rtWrapper);
  }
  if (!disableGenerateMipMaps) {
    this.generateMipMapsMultiFramebuffer(rtWrapper);
  }
  if (onBeforeUnbind) {
    if (rtWrapper._MSAAFramebuffer) {
      this._bindUnboundFramebuffer(rtWrapper._framebuffer);
    }
    onBeforeUnbind();
  }
  this._bindUnboundFramebuffer(null);
};
ThinEngine.prototype.createMultipleRenderTarget = function(size, options, initializeBuffers = true) {
  let generateMipMaps = false;
  let generateDepthBuffer = true;
  let generateStencilBuffer = false;
  let generateDepthTexture = false;
  let depthTextureFormat = undefined;
  let textureCount = 1;
  let samples = 1;
  const defaultType = 0;
  const defaultSamplingMode = 3;
  const defaultUseSRGBBuffer = false;
  const defaultFormat = 5;
  const defaultTarget = 3553;
  let types = [];
  let samplingModes = [];
  let useSRGBBuffers = [];
  let formats = [];
  let targets = [];
  let faceIndex = [];
  let layerIndex = [];
  let layers = [];
  let labels = [];
  let dontCreateTextures = false;
  const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);
  if (options !== undefined) {
    generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
    generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
    generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
    generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
    textureCount = options.textureCount ?? 1;
    samples = options.samples ?? samples;
    types = options.types || types;
    samplingModes = options.samplingModes || samplingModes;
    useSRGBBuffers = options.useSRGBBuffers || useSRGBBuffers;
    formats = options.formats || formats;
    targets = options.targetTypes || targets;
    faceIndex = options.faceIndex || faceIndex;
    layerIndex = options.layerIndex || layerIndex;
    layers = options.layerCounts || layers;
    labels = options.labels || labels;
    dontCreateTextures = options.dontCreateTextures ?? false;
    if (this.webGLVersion > 1 && (options.depthTextureFormat === 13 || options.depthTextureFormat === 17 || options.depthTextureFormat === 16 || options.depthTextureFormat === 14 || options.depthTextureFormat === 18)) {
      depthTextureFormat = options.depthTextureFormat;
    }
  }
  if (depthTextureFormat === undefined) {
    depthTextureFormat = generateStencilBuffer ? 13 : 14;
  }
  const gl = this._gl;
  const currentFramebuffer = this._currentFramebuffer;
  const framebuffer = gl.createFramebuffer();
  this._bindUnboundFramebuffer(framebuffer);
  const width = size.width ?? size;
  const height = size.height ?? size;
  const textures = [];
  const attachments = [];
  const useStencilTexture = this.webGLVersion > 1 && (depthTextureFormat === 13 || depthTextureFormat === 17 || depthTextureFormat === 18);
  rtWrapper.label = options?.label ?? "MultiRenderTargetWrapper";
  rtWrapper._framebuffer = framebuffer;
  rtWrapper._generateDepthBuffer = generateDepthTexture || generateDepthBuffer;
  rtWrapper._generateStencilBuffer = generateDepthTexture ? useStencilTexture : generateStencilBuffer;
  rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, width, height, 1, depthTextureFormat);
  rtWrapper._attachments = attachments;
  for (let i = 0;i < textureCount; i++) {
    let samplingMode = samplingModes[i] || defaultSamplingMode;
    let type = types[i] || defaultType;
    let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer;
    const format = formats[i] || defaultFormat;
    const target = targets[i] || defaultTarget;
    const layerCount = layers[i] ?? 1;
    if (type === 1 && !this._caps.textureFloatLinearFiltering) {
      samplingMode = 1;
    } else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
      samplingMode = 1;
    }
    const filters = this._getSamplingParameters(samplingMode, generateMipMaps);
    if (type === 1 && !this._caps.textureFloat) {
      type = 0;
      Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
    }
    useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU);
    const isWebGL2 = this.webGLVersion > 1;
    const attachment = gl[isWebGL2 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
    attachments.push(attachment);
    if (target === -1 || dontCreateTextures) {
      continue;
    }
    const texture = new InternalTexture(this, 6);
    textures[i] = texture;
    gl.activeTexture(gl["TEXTURE" + i]);
    gl.bindTexture(target, texture._hardwareTexture.underlyingResource);
    gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag);
    gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min);
    gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);
    const internalFormat = this._getInternalFormat(format);
    const webGLTextureType = this._getWebGLTextureType(type);
    if (isWebGL2 && (target === 35866 || target === 32879)) {
      if (target === 35866) {
        texture.is2DArray = true;
      } else {
        texture.is3D = true;
      }
      texture.baseDepth = texture.depth = layerCount;
      gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null);
    } else if (target === 34067) {
      for (let i2 = 0;i2 < 6; i2++) {
        gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);
      }
      texture.isCube = true;
    } else {
      gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);
    }
    if (generateMipMaps) {
      gl.generateMipmap(target);
    }
    this._bindTextureDirectly(target, null);
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.width = width;
    texture.height = height;
    texture.isReady = true;
    texture.samples = 1;
    texture.generateMipMaps = generateMipMaps;
    texture.samplingMode = samplingMode;
    texture.type = type;
    texture._useSRGBBuffer = useSRGBBuffer;
    texture.format = format;
    texture.label = labels[i] ?? rtWrapper.label + "-Texture" + i;
    this._internalTexturesCache.push(texture);
  }
  if (generateDepthTexture && this._caps.depthTextureExtension && !dontCreateTextures) {
    const depthTexture = new InternalTexture(this, 14);
    let depthTextureType = 5;
    let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16;
    let glDepthTextureFormat = gl.DEPTH_COMPONENT;
    let glDepthTextureType = gl.UNSIGNED_SHORT;
    let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;
    if (this.webGLVersion < 2) {
      glDepthTextureInternalFormat = gl.DEPTH_COMPONENT;
    } else {
      if (depthTextureFormat === 14) {
        depthTextureType = 1;
        glDepthTextureType = gl.FLOAT;
        glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F;
      } else if (depthTextureFormat === 18) {
        depthTextureType = 0;
        glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
        glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8;
        glDepthTextureFormat = gl.DEPTH_STENCIL;
        glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;
      } else if (depthTextureFormat === 16) {
        depthTextureType = 0;
        glDepthTextureType = gl.UNSIGNED_INT;
        glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24;
        glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;
      } else if (depthTextureFormat === 13 || depthTextureFormat === 17) {
        depthTextureType = 12;
        glDepthTextureType = gl.UNSIGNED_INT_24_8;
        glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8;
        glDepthTextureFormat = gl.DEPTH_STENCIL;
        glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;
      }
    }
    this._bindTextureDirectly(gl.TEXTURE_2D, depthTexture, true);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texImage2D(gl.TEXTURE_2D, 0, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0);
    this._bindTextureDirectly(gl.TEXTURE_2D, null);
    rtWrapper._depthStencilTexture = depthTexture;
    rtWrapper._depthStencilTextureWithStencil = useStencilTexture;
    depthTexture.baseWidth = width;
    depthTexture.baseHeight = height;
    depthTexture.width = width;
    depthTexture.height = height;
    depthTexture.isReady = true;
    depthTexture.samples = 1;
    depthTexture.generateMipMaps = generateMipMaps;
    depthTexture.samplingMode = 1;
    depthTexture.format = depthTextureFormat;
    depthTexture.type = depthTextureType;
    depthTexture.label = rtWrapper.label + "-DepthStencil";
    textures[textureCount] = depthTexture;
    this._internalTexturesCache.push(depthTexture);
  }
  rtWrapper.setTextures(textures);
  if (initializeBuffers) {
    gl.drawBuffers(attachments);
  }
  this._bindUnboundFramebuffer(currentFramebuffer);
  rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);
  this.resetTextureCache();
  if (!dontCreateTextures) {
    this.updateMultipleRenderTargetTextureSampleCount(rtWrapper, samples, initializeBuffers);
  } else if (samples > 1) {
    const framebuffer2 = gl.createFramebuffer();
    if (!framebuffer2) {
      throw new Error("Unable to create multi sampled framebuffer");
    }
    rtWrapper._samples = samples;
    rtWrapper._MSAAFramebuffer = framebuffer2;
    if (textureCount > 0 && initializeBuffers) {
      this._bindUnboundFramebuffer(framebuffer2);
      gl.drawBuffers(attachments);
      this._bindUnboundFramebuffer(currentFramebuffer);
    }
  }
  return rtWrapper;
};
ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(rtWrapper, samples, initializeBuffers = true) {
  if (this.webGLVersion < 2 || !rtWrapper) {
    return 1;
  }
  if (rtWrapper.samples === samples) {
    return samples;
  }
  const gl = this._gl;
  samples = Math.min(samples, this.getCaps().maxMSAASamples);
  if (rtWrapper._depthStencilBuffer) {
    gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);
    rtWrapper._depthStencilBuffer = null;
  }
  if (rtWrapper._MSAAFramebuffer) {
    gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);
    rtWrapper._MSAAFramebuffer = null;
  }
  const count = rtWrapper._attachments.length;
  for (let i = 0;i < count; i++) {
    const texture = rtWrapper.textures[i];
    const hardwareTexture = texture._hardwareTexture;
    hardwareTexture?.releaseMSAARenderBuffers();
  }
  if (samples > 1 && typeof gl.renderbufferStorageMultisample === "function") {
    const framebuffer = gl.createFramebuffer();
    if (!framebuffer) {
      throw new Error("Unable to create multi sampled framebuffer");
    }
    rtWrapper._MSAAFramebuffer = framebuffer;
    this._bindUnboundFramebuffer(framebuffer);
    const attachments = [];
    for (let i = 0;i < count; i++) {
      const texture = rtWrapper.textures[i];
      const hardwareTexture = texture._hardwareTexture;
      const attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
      const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), attachment);
      if (!colorRenderbuffer) {
        throw new Error("Unable to create multi sampled framebuffer");
      }
      hardwareTexture.addMSAARenderBuffer(colorRenderbuffer);
      texture.samples = samples;
      attachments.push(attachment);
    }
    if (initializeBuffers) {
      gl.drawBuffers(attachments);
    }
  } else {
    this._bindUnboundFramebuffer(rtWrapper._framebuffer);
  }
  const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : undefined;
  rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat);
  this._bindUnboundFramebuffer(null);
  rtWrapper._samples = samples;
  return samples;
};
ThinEngine.prototype.generateMipMapsMultiFramebuffer = function(texture) {
  const rtWrapper = texture;
  const gl = this._gl;
  if (!rtWrapper.isMulti) {
    return;
  }
  for (let i = 0;i < rtWrapper._attachments.length; i++) {
    const texture2 = rtWrapper.textures[i];
    if (texture2?.generateMipMaps && !texture2?.isCube && !texture2?.is3D) {
      this._bindTextureDirectly(gl.TEXTURE_2D, texture2, true);
      gl.generateMipmap(gl.TEXTURE_2D);
      this._bindTextureDirectly(gl.TEXTURE_2D, null);
    }
  }
};
ThinEngine.prototype.resolveMultiFramebuffer = function(texture) {
  const rtWrapper = texture;
  const gl = this._gl;
  if (!rtWrapper._MSAAFramebuffer || !rtWrapper.isMulti) {
    return;
  }
  let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0;
  bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0;
  bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0;
  const attachments = rtWrapper._attachments;
  const count = attachments.length;
  gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer);
  for (let i = 0;i < count; i++) {
    const texture2 = rtWrapper.textures[i];
    for (let j = 0;j < count; j++) {
      attachments[j] = gl.NONE;
    }
    attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
    gl.readBuffer(attachments[i]);
    gl.drawBuffers(attachments);
    gl.blitFramebuffer(0, 0, texture2.width, texture2.height, 0, 0, texture2.width, texture2.height, bufferBits, gl.NEAREST);
  }
  for (let i = 0;i < count; i++) {
    attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  }
  gl.drawBuffers(attachments);
  gl.bindFramebuffer(this._gl.FRAMEBUFFER, rtWrapper._MSAAFramebuffer);
};

// node_modules/@babylonjs/core/Engines/Extensions/index.js
init_engine_cubeTexture();
init_engine_prefilteredCubeTexture();
init_engine_renderTarget();
init_engine_renderTargetCube();
init_engine_renderTargetTexture();
init_engine_uniformBuffer();
init_engine_dynamicBuffer();
init_engine_readTexture();

// node_modules/@babylonjs/core/Engines/Extensions/engine.computeShader.js
init_thinEngine();
init_abstractEngine();
var ComputeBindingType;
(function(ComputeBindingType2) {
  ComputeBindingType2[ComputeBindingType2["Texture"] = 0] = "Texture";
  ComputeBindingType2[ComputeBindingType2["StorageTexture"] = 1] = "StorageTexture";
  ComputeBindingType2[ComputeBindingType2["UniformBuffer"] = 2] = "UniformBuffer";
  ComputeBindingType2[ComputeBindingType2["StorageBuffer"] = 3] = "StorageBuffer";
  ComputeBindingType2[ComputeBindingType2["TextureWithoutSampler"] = 4] = "TextureWithoutSampler";
  ComputeBindingType2[ComputeBindingType2["Sampler"] = 5] = "Sampler";
  ComputeBindingType2[ComputeBindingType2["ExternalTexture"] = 6] = "ExternalTexture";
  ComputeBindingType2[ComputeBindingType2["DataBuffer"] = 7] = "DataBuffer";
})(ComputeBindingType || (ComputeBindingType = {}));
ThinEngine.prototype.createComputeEffect = function(baseName, options) {
  throw new Error("createComputeEffect: This engine does not support compute shaders!");
};
ThinEngine.prototype.createComputePipelineContext = function() {
  throw new Error("createComputePipelineContext: This engine does not support compute shaders!");
};
ThinEngine.prototype.createComputeContext = function() {
  return;
};
ThinEngine.prototype.computeDispatch = function(effect, context, bindings, x, y, z, bindingsMapping) {
  throw new Error("computeDispatch: This engine does not support compute shaders!");
};
ThinEngine.prototype.computeDispatchIndirect = function(effect, context, bindings, buffer2, offset, bindingsMapping) {
  throw new Error("computeDispatchIndirect: This engine does not support compute shaders!");
};
ThinEngine.prototype.areAllComputeEffectsReady = function() {
  return true;
};
ThinEngine.prototype.releaseComputeEffects = function() {};
ThinEngine.prototype._prepareComputePipelineContext = function(pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) {};
ThinEngine.prototype._rebuildComputeEffects = function() {};
AbstractEngine.prototype._executeWhenComputeStateIsCompiled = function(pipelineContext, action2) {
  action2(null);
};
ThinEngine.prototype._releaseComputeEffect = function(effect) {};
ThinEngine.prototype._deleteComputePipelineContext = function(pipelineContext) {};
// node_modules/@babylonjs/core/Engines/Extensions/engine.textureSelector.js
init_engine();
function transformTextureUrl(url) {
  const excludeFn = (entry) => {
    const strRegExPattern = "\\b" + entry + "\\b";
    return url && (url === entry || url.match(new RegExp(strRegExPattern, "g")));
  };
  if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(excludeFn)) {
    return url;
  }
  const lastDot = url.lastIndexOf(".");
  const lastQuestionMark = url.lastIndexOf("?");
  const querystring = lastQuestionMark > -1 ? url.substring(lastQuestionMark, url.length) : "";
  return (lastDot > -1 ? url.substring(0, lastDot) : url) + this._textureFormatInUse + querystring;
}
Object.defineProperty(Engine.prototype, "texturesSupported", {
  get: function() {
    const texturesSupported = [];
    if (this._caps.astc) {
      texturesSupported.push("-astc.ktx");
    }
    if (this._caps.s3tc) {
      texturesSupported.push("-dxt.ktx");
    }
    if (this._caps.pvrtc) {
      texturesSupported.push("-pvrtc.ktx");
    }
    if (this._caps.etc2) {
      texturesSupported.push("-etc2.ktx");
    }
    if (this._caps.etc1) {
      texturesSupported.push("-etc1.ktx");
    }
    return texturesSupported;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  get: function() {
    return this._textureFormatInUse || null;
  },
  enumerable: true,
  configurable: true
});
Engine.prototype.setCompressedTextureExclusions = function(skippedFiles) {
  this._excludedCompressedTextures = skippedFiles;
};
Engine.prototype.setTextureFormatToUse = function(formatsAvailable) {
  const texturesSupported = this.texturesSupported;
  for (let i = 0, len1 = texturesSupported.length;i < len1; i++) {
    for (let j = 0, len2 = formatsAvailable.length;j < len2; j++) {
      if (texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
        this._transformTextureUrl = transformTextureUrl.bind(this);
        return this._textureFormatInUse = texturesSupported[i];
      }
    }
  }
  this._textureFormatInUse = "";
  this._transformTextureUrl = null;
  return null;
};
// node_modules/@babylonjs/core/Engines/Native/nativeDataStream.js
class NativeDataStream {
  constructor() {
    const buffer2 = new ArrayBuffer(NativeDataStream.DEFAULT_BUFFER_SIZE);
    this._uint32s = new Uint32Array(buffer2);
    this._int32s = new Int32Array(buffer2);
    this._float32s = new Float32Array(buffer2);
    this._length = NativeDataStream.DEFAULT_BUFFER_SIZE / 4;
    this._position = 0;
    this._nativeDataStream = new _native.NativeDataStream(() => {
      this._flush();
    });
  }
  writeUint32(value) {
    this._flushIfNecessary(1);
    this._uint32s[this._position++] = value;
  }
  writeInt32(value) {
    this._flushIfNecessary(1);
    this._int32s[this._position++] = value;
  }
  writeFloat32(value) {
    this._flushIfNecessary(1);
    this._float32s[this._position++] = value;
  }
  writeUint32Array(values) {
    this._flushIfNecessary(1 + values.length);
    this._uint32s[this._position++] = values.length;
    this._uint32s.set(values, this._position);
    this._position += values.length;
  }
  writeInt32Array(values) {
    this._flushIfNecessary(1 + values.length);
    this._uint32s[this._position++] = values.length;
    this._int32s.set(values, this._position);
    this._position += values.length;
  }
  writeFloat32Array(values) {
    this._flushIfNecessary(1 + values.length);
    this._uint32s[this._position++] = values.length;
    this._float32s.set(values, this._position);
    this._position += values.length;
  }
  writeNativeData(handle) {
    this._flushIfNecessary(handle.length);
    this._uint32s.set(handle, this._position);
    this._position += handle.length;
  }
  writeBoolean(value) {
    this.writeUint32(value ? 1 : 0);
  }
  _flushIfNecessary(required) {
    if (this._position + required > this._length) {
      this._flush();
    }
  }
  _flush() {
    this._nativeDataStream.writeBuffer(this._uint32s.buffer, this._position);
    this._position = 0;
  }
}
NativeDataStream.DEFAULT_BUFFER_SIZE = 65536;
// node_modules/@babylonjs/core/Engines/nativeEngine.js
init_engine();
init_internalTexture();
init_texture();
init_dataBuffer();
init_tools();
init_observable();
init_environmentTextureTools();
init_logger();
init_thinEngine();
init_engineStore();

// node_modules/@babylonjs/core/Engines/Processors/shaderCodeInliner.js
init_logger();

// node_modules/@babylonjs/core/Misc/codeStringParsingTools.js
function ExtractBetweenMarkers(markerOpen, markerClose, block, startIndex) {
  let currPos = startIndex, openMarkers = 0, waitForChar = "";
  while (currPos < block.length) {
    const currChar = block.charAt(currPos);
    if (!waitForChar) {
      switch (currChar) {
        case markerOpen:
          openMarkers++;
          break;
        case markerClose:
          openMarkers--;
          break;
        case '"':
        case "'":
        case "`":
          waitForChar = currChar;
          break;
        case "/":
          if (currPos + 1 < block.length) {
            const nextChar = block.charAt(currPos + 1);
            if (nextChar === "/") {
              waitForChar = `
`;
            } else if (nextChar === "*") {
              waitForChar = "*/";
            }
          }
          break;
      }
    } else {
      if (currChar === waitForChar) {
        if (waitForChar === '"' || waitForChar === "'") {
          block.charAt(currPos - 1) !== "\\" && (waitForChar = "");
        } else {
          waitForChar = "";
        }
      } else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) {
        block.charAt(currPos + 1) === "/" && (waitForChar = "");
        if (waitForChar === "") {
          currPos++;
        }
      }
    }
    currPos++;
    if (openMarkers === 0) {
      break;
    }
  }
  return openMarkers === 0 ? currPos - 1 : -1;
}
function SkipWhitespaces(s, index) {
  while (index < s.length) {
    const c = s[index];
    if (c !== " " && c !== `
` && c !== "\r" && c !== "\t" && c !== `
` && c !== "\xA0") {
      break;
    }
    index++;
  }
  return index;
}
function IsIdentifierChar(c) {
  const v = c.charCodeAt(0);
  return v >= 48 && v <= 57 || v >= 65 && v <= 90 || v >= 97 && v <= 122 || v == 95;
}
function RemoveComments(block) {
  let currPos = 0, waitForChar = "", inComments = false;
  const s = [];
  while (currPos < block.length) {
    const currChar = block.charAt(currPos);
    if (!waitForChar) {
      switch (currChar) {
        case '"':
        case "'":
        case "`":
          waitForChar = currChar;
          break;
        case "/":
          if (currPos + 1 < block.length) {
            const nextChar = block.charAt(currPos + 1);
            if (nextChar === "/") {
              waitForChar = `
`;
              inComments = true;
            } else if (nextChar === "*") {
              waitForChar = "*/";
              inComments = true;
            }
          }
          break;
      }
      if (!inComments) {
        s.push(currChar);
      }
    } else {
      if (currChar === waitForChar) {
        if (waitForChar === '"' || waitForChar === "'") {
          block.charAt(currPos - 1) !== "\\" && (waitForChar = "");
          s.push(currChar);
        } else {
          waitForChar = "";
          inComments = false;
        }
      } else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) {
        block.charAt(currPos + 1) === "/" && (waitForChar = "");
        if (waitForChar === "") {
          inComments = false;
          currPos++;
        }
      } else {
        if (!inComments) {
          s.push(currChar);
        }
      }
    }
    currPos++;
  }
  return s.join("");
}
function FindBackward(s, index, c, c2) {
  while (index >= 0 && s.charAt(index) !== c && (!c2 || s.charAt(index) !== c2)) {
    index--;
  }
  return index;
}
function EscapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function InjectStartingAndEndingCode(code, mainFuncDecl, startingCode, endingCode) {
  let idx = code.indexOf(mainFuncDecl);
  if (idx < 0) {
    return code;
  }
  if (startingCode) {
    while (idx++ < code.length && code.charAt(idx) != "{") {}
    if (idx < code.length) {
      const part1 = code.substring(0, idx + 1);
      const part2 = code.substring(idx + 1);
      code = part1 + startingCode + part2;
    }
  }
  if (endingCode) {
    const lastClosingCurly = code.lastIndexOf("}");
    code = code.substring(0, lastClosingCurly);
    code += endingCode + `
}`;
  }
  return code;
}

// node_modules/@babylonjs/core/Engines/Processors/shaderCodeInliner.js
class ShaderCodeInliner {
  get code() {
    return this._sourceCode;
  }
  constructor(sourceCode, numMaxIterations = 20) {
    this.debug = false;
    this._sourceCode = sourceCode;
    this._numMaxIterations = numMaxIterations;
    this._functionDescr = [];
    this.inlineToken = "#define inline";
  }
  processCode() {
    if (this.debug) {
      Logger.Log(`Start inlining process (code size=${this._sourceCode.length})...`);
    }
    this._collectFunctions();
    this._processInlining(this._numMaxIterations);
    if (this.debug) {
      Logger.Log("End of inlining process.");
    }
  }
  _collectFunctions() {
    let startIndex = 0;
    while (startIndex < this._sourceCode.length) {
      const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex);
      if (inlineTokenIndex < 0) {
        break;
      }
      const funcParamsStartIndex = this._sourceCode.indexOf("(", inlineTokenIndex + this.inlineToken.length);
      if (funcParamsStartIndex < 0) {
        if (this.debug) {
          Logger.Warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`);
        }
        startIndex = inlineTokenIndex + this.inlineToken.length;
        continue;
      }
      const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));
      if (!funcNameMatch) {
        if (this.debug) {
          Logger.Warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`);
        }
        startIndex = inlineTokenIndex + this.inlineToken.length;
        continue;
      }
      const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]];
      const funcParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, funcParamsStartIndex);
      if (funcParamsEndIndex < 0) {
        if (this.debug) {
          Logger.Warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`);
        }
        startIndex = inlineTokenIndex + this.inlineToken.length;
        continue;
      }
      const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex);
      const funcBodyStartIndex = SkipWhitespaces(this._sourceCode, funcParamsEndIndex + 1);
      if (funcBodyStartIndex === this._sourceCode.length) {
        if (this.debug) {
          Logger.Warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`);
        }
        startIndex = inlineTokenIndex + this.inlineToken.length;
        continue;
      }
      const funcBodyEndIndex = ExtractBetweenMarkers("{", "}", this._sourceCode, funcBodyStartIndex);
      if (funcBodyEndIndex < 0) {
        if (this.debug) {
          Logger.Warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`);
        }
        startIndex = inlineTokenIndex + this.inlineToken.length;
        continue;
      }
      const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1);
      const params = RemoveComments(funcParams).split(",");
      const paramNames = [];
      for (let p = 0;p < params.length; ++p) {
        const param = params[p].trim();
        const idx = param.lastIndexOf(" ");
        if (idx >= 0) {
          paramNames.push(param.substring(idx + 1));
        }
      }
      if (funcType !== "void") {
        paramNames.push("return");
      }
      this._functionDescr.push({
        name: funcName,
        type: funcType,
        parameters: paramNames,
        body: funcBody,
        callIndex: 0
      });
      startIndex = funcBodyEndIndex + 1;
      const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : "";
      const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : "";
      this._sourceCode = partBefore + partAfter;
      startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex;
    }
    if (this.debug) {
      Logger.Log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=${this._functionDescr}`);
    }
  }
  _processInlining(numMaxIterations = 20) {
    while (numMaxIterations-- >= 0) {
      if (!this._replaceFunctionCallsByCode()) {
        break;
      }
    }
    if (this.debug) {
      Logger.Log(`numMaxIterations is ${numMaxIterations} after inlining process`);
    }
    return numMaxIterations >= 0;
  }
  _replaceFunctionCallsByCode() {
    let doAgain = false;
    for (const func of this._functionDescr) {
      const { name: name155, type, parameters, body } = func;
      let startIndex = 0;
      while (startIndex < this._sourceCode.length) {
        const functionCallIndex = this._sourceCode.indexOf(name155, startIndex);
        if (functionCallIndex < 0) {
          break;
        }
        if (functionCallIndex === 0 || IsIdentifierChar(this._sourceCode.charAt(functionCallIndex - 1))) {
          startIndex = functionCallIndex + name155.length;
          continue;
        }
        const callParamsStartIndex = SkipWhitespaces(this._sourceCode, functionCallIndex + name155.length);
        if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== "(") {
          startIndex = functionCallIndex + name155.length;
          continue;
        }
        const callParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, callParamsStartIndex);
        if (callParamsEndIndex < 0) {
          if (this.debug) {
            Logger.Warn(`Could not extract the parameters of the function call. Function '${name155}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`);
          }
          startIndex = functionCallIndex + name155.length;
          continue;
        }
        const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex);
        const splitParameterCall = (s) => {
          const parameters2 = [];
          let curIdx = 0, startParamIdx = 0;
          while (curIdx < s.length) {
            if (s.charAt(curIdx) === "(") {
              const idx2 = ExtractBetweenMarkers("(", ")", s, curIdx);
              if (idx2 < 0) {
                return null;
              }
              curIdx = idx2;
            } else if (s.charAt(curIdx) === ",") {
              parameters2.push(s.substring(startParamIdx, curIdx));
              startParamIdx = curIdx + 1;
            }
            curIdx++;
          }
          if (startParamIdx < curIdx) {
            parameters2.push(s.substring(startParamIdx, curIdx));
          }
          return parameters2;
        };
        const params = splitParameterCall(RemoveComments(callParams));
        if (params === null) {
          if (this.debug) {
            Logger.Warn(`Invalid function call: can't extract the parameters of the function call. Function '${name155}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}, callParams=` + callParams);
          }
          startIndex = functionCallIndex + name155.length;
          continue;
        }
        const paramNames = [];
        for (let p = 0;p < params.length; ++p) {
          const param = params[p].trim();
          paramNames.push(param);
        }
        const retParamName = type !== "void" ? name155 + "_" + func.callIndex++ : null;
        if (retParamName) {
          paramNames.push(retParamName + " =");
        }
        if (paramNames.length !== parameters.length) {
          if (this.debug) {
            Logger.Warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${name155}' (type=${type}). function parameters=${parameters}, call parameters=${paramNames}`);
          }
          startIndex = functionCallIndex + name155.length;
          continue;
        }
        startIndex = callParamsEndIndex + 1;
        const funcBody = this._replaceNames(body, parameters, paramNames);
        let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : "";
        const partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : "";
        if (retParamName) {
          const injectDeclarationIndex = FindBackward(this._sourceCode, functionCallIndex - 1, `
`, "{");
          partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1);
          const partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex);
          this._sourceCode = partBefore + type + " " + retParamName + `;
` + funcBody + `
` + partBetween + retParamName + partAfter;
          if (this.debug) {
            Logger.Log(`Replace function call by code. Function '${name155}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}, call parameters=${paramNames}`);
          }
        } else {
          this._sourceCode = partBefore + funcBody + partAfter;
          startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex);
          if (this.debug) {
            Logger.Log(`Replace function call by code. Function '${name155}' (type=${type}). functionCallIndex=${functionCallIndex}, call parameters=${paramNames}`);
          }
        }
        doAgain = true;
      }
    }
    return doAgain;
  }
  _replaceNames(code, sources, destinations) {
    for (let i = 0;i < sources.length; ++i) {
      const source = new RegExp(EscapeRegExp(sources[i]), "g"), sourceLen = sources[i].length, destination = destinations[i];
      code = code.replace(source, (match, ...args) => {
        const offset = args[0];
        if (IsIdentifierChar(code.charAt(offset - 1)) || IsIdentifierChar(code.charAt(offset + sourceLen))) {
          return sources[i];
        }
        return destination;
      });
    }
    return code;
  }
}
ShaderCodeInliner._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/;

// node_modules/@babylonjs/core/Engines/Native/nativeShaderProcessors.js
var varyingRegex2 = /(flat\s)?\s*varying\s*.*/;

class NativeShaderProcessor {
  constructor() {
    this.shaderLanguage = 0;
  }
  initializeShaders(processingContext) {
    this._nativeProcessingContext = processingContext;
    if (this._nativeProcessingContext) {
      this._nativeProcessingContext.remappedAttributeNames = {};
      this._nativeProcessingContext.injectInVertexMain = "";
    }
  }
  attributeProcessor(attribute) {
    if (!this._nativeProcessingContext) {
      return attribute.replace("attribute", "in");
    }
    const attribRegex = /\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm;
    const match = attribRegex.exec(attribute);
    if (match !== null) {
      const attributeType = match[1];
      const name155 = match[2];
      const numComponents = this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[name155];
      if (numComponents !== undefined) {
        const newType = numComponents < 0 ? numComponents === -1 ? "int" : "ivec" + -numComponents : numComponents === 1 ? "uint" : "uvec" + numComponents;
        const newName = `_int_${name155}_`;
        attribute = attribute.replace(match[0], `in ${newType} ${newName}; ${attributeType} ${name155};`);
        this._nativeProcessingContext.injectInVertexMain += `${name155} = ${attributeType}(${newName});
`;
        this._nativeProcessingContext.remappedAttributeNames[name155] = newName;
      } else {
        attribute = attribute.replace(match[0], `in ${attributeType} ${name155};`);
      }
    }
    return attribute;
  }
  varyingCheck(varying, _isFragment) {
    return varyingRegex2.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 {
      if (this._nativeProcessingContext?.injectInVertexMain) {
        code = InjectStartingAndEndingCode(code, "void main", this._nativeProcessingContext.injectInVertexMain);
      }
      const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
      if (hasMultiviewExtension) {
        return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + code;
      }
    }
    return code;
  }
}

// node_modules/@babylonjs/core/Engines/Native/nativePipelineContext.js
class NativePipelineContext {
  get isReady() {
    if (this.compilationError) {
      const message = this.compilationError.message;
      throw new Error("SHADER ERROR" + (typeof message === "string" ? `
` + message : ""));
    }
    return this.isCompiled;
  }
  _getVertexShaderCode() {
    return null;
  }
  _getFragmentShaderCode() {
    return null;
  }
  constructor(engine, isAsync, shaderProcessingContext) {
    this.isCompiled = false;
    this.vertexBufferKindToType = {};
    this._valueCache = {};
    this._engine = engine;
    this.isAsync = isAsync;
    this.shaderProcessingContext = shaderProcessingContext;
  }
  _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {
    const engine = this._engine;
    if (engine.supportsUniformBuffers) {
      for (const name155 in uniformBuffersNames) {
        effect.bindUniformBlock(name155, uniformBuffersNames[name155]);
      }
    }
    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((name155, index2) => {
      samplers[name155] = index2;
    });
    attributes.push(...engine.getAttributes(this, attributesNames));
  }
  setEngine(engine) {
    this._engine = engine;
  }
  dispose() {
    this._uniforms = {};
  }
  _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 = [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 = [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 = [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);
  }
  setFloatArray(uniformName, array) {
    this._valueCache[uniformName] = null;
    this._engine.setFloatArray(this._uniforms[uniformName], array);
  }
  setFloatArray2(uniformName, array) {
    this._valueCache[uniformName] = null;
    this._engine.setFloatArray2(this._uniforms[uniformName], array);
  }
  setFloatArray3(uniformName, array) {
    this._valueCache[uniformName] = null;
    this._engine.setFloatArray3(this._uniforms[uniformName], array);
  }
  setFloatArray4(uniformName, array) {
    this._valueCache[uniformName] = null;
    this._engine.setFloatArray4(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;
    }
  }
  setBool(uniformName, bool) {
    const cache = this._valueCache[uniformName];
    if (cache !== undefined && cache === bool) {
      return;
    }
    if (this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0)) {
      this._valueCache[uniformName] = bool ? 1 : 0;
    }
  }
  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;
      }
    }
  }
}

// node_modules/@babylonjs/core/Engines/Native/nativeRenderTargetWrapper.js
init_renderTargetWrapper();

class NativeRenderTargetWrapper extends RenderTargetWrapper {
  get _framebuffer() {
    return this.__framebuffer;
  }
  set _framebuffer(framebuffer) {
    if (this.__framebuffer) {
      this._engine._releaseFramebufferObjects(this.__framebuffer);
    }
    this.__framebuffer = framebuffer;
  }
  get _framebufferDepthStencil() {
    return this.__framebufferDepthStencil;
  }
  set _framebufferDepthStencil(framebufferDepthStencil) {
    if (this.__framebufferDepthStencil) {
      this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil);
    }
    this.__framebufferDepthStencil = framebufferDepthStencil;
  }
  constructor(isMulti, isCube, size, engine) {
    super(isMulti, isCube, size, engine);
    this.__framebuffer = null;
    this.__framebufferDepthStencil = null;
    this._engine = engine;
  }
  dispose(disposeOnlyFramebuffers = false) {
    this._framebuffer = null;
    this._framebufferDepthStencil = null;
    super.dispose(disposeOnlyFramebuffers);
  }
}

// node_modules/@babylonjs/core/Engines/Native/nativeHardwareTexture.js
class NativeHardwareTexture {
  get underlyingResource() {
    return this._nativeTexture;
  }
  constructor(existingTexture, engine) {
    this._engine = engine;
    this.set(existingTexture);
  }
  setUsage() {}
  set(hardwareTexture) {
    this._nativeTexture = hardwareTexture;
  }
  reset() {
    this._nativeTexture = null;
  }
  release() {
    if (this._nativeTexture) {
      this._engine.deleteTexture(this._nativeTexture);
    }
    this.reset();
  }
}

// node_modules/@babylonjs/core/Engines/Native/nativeHelpers.js
init_error();
init_buffer();
function getNativeTextureFormat(format, type) {
  switch (format) {
    case 15:
      return _native.Engine.TEXTURE_FORMAT_D16;
    case 16:
      return _native.Engine.TEXTURE_FORMAT_D24;
    case 13:
      return _native.Engine.TEXTURE_FORMAT_D24S8;
    case 14:
      return _native.Engine.TEXTURE_FORMAT_D32F;
    case 36492:
      return _native.Engine.TEXTURE_FORMAT_BC7;
    case 36494:
      return _native.Engine.TEXTURE_FORMAT_BC6H;
    case 33779:
      return _native.Engine.TEXTURE_FORMAT_BC3;
    case 33778:
      return _native.Engine.TEXTURE_FORMAT_BC2;
    case 33777:
      return _native.Engine.TEXTURE_FORMAT_BC1;
    case 33776:
      return _native.Engine.TEXTURE_FORMAT_BC1;
    case 37808:
      return _native.Engine.TEXTURE_FORMAT_ASTC4x4;
    case 36196:
      return _native.Engine.TEXTURE_FORMAT_ETC1;
    case 37492:
      return _native.Engine.TEXTURE_FORMAT_ETC2;
    case 37496:
      return _native.Engine.TEXTURE_FORMAT_ETC2A;
    case 4: {
      switch (type) {
        case 0:
          return _native.Engine.TEXTURE_FORMAT_RGB8;
        case 3:
          return _native.Engine.TEXTURE_FORMAT_RGB8S;
        case 6:
          return _native.Engine.TEXTURE_FORMAT_RGB8I;
        case 7:
          return _native.Engine.TEXTURE_FORMAT_RGB8U;
      }
      break;
    }
    case 5: {
      switch (type) {
        case 0:
          return _native.Engine.TEXTURE_FORMAT_RGBA8;
        case 1:
          return _native.Engine.TEXTURE_FORMAT_RGBA32F;
        case 2:
          return _native.Engine.TEXTURE_FORMAT_RGBA16F;
        case 3:
          return _native.Engine.TEXTURE_FORMAT_RGBA8S;
        case 4:
          return _native.Engine.TEXTURE_FORMAT_RGBA16I;
        case 5:
          return _native.Engine.TEXTURE_FORMAT_RGBA16U;
        case 6:
          return _native.Engine.TEXTURE_FORMAT_RGBA32I;
        case 7:
          return _native.Engine.TEXTURE_FORMAT_RGBA32U;
      }
      break;
    }
    case 6: {
      switch (type) {
        case 0:
          return _native.Engine.TEXTURE_FORMAT_R8;
        case 1:
          return _native.Engine.TEXTURE_FORMAT_R32F;
        case 2:
          return _native.Engine.TEXTURE_FORMAT_R16F;
        case 3:
          return _native.Engine.TEXTURE_FORMAT_R8S;
        case 4:
          return _native.Engine.TEXTURE_FORMAT_R16S;
        case 5:
          return _native.Engine.TEXTURE_FORMAT_R16U;
        case 6:
          return _native.Engine.TEXTURE_FORMAT_R32I;
        case 7:
          return _native.Engine.TEXTURE_FORMAT_R32U;
      }
      break;
    }
    case 7: {
      switch (type) {
        case 0:
          return _native.Engine.TEXTURE_FORMAT_RG8;
        case 1:
          return _native.Engine.TEXTURE_FORMAT_RG32F;
        case 2:
          return _native.Engine.TEXTURE_FORMAT_RG16F;
        case 3:
          return _native.Engine.TEXTURE_FORMAT_RG8S;
        case 4:
          return _native.Engine.TEXTURE_FORMAT_RG16S;
        case 5:
          return _native.Engine.TEXTURE_FORMAT_RG16U;
        case 6:
          return _native.Engine.TEXTURE_FORMAT_RG32I;
        case 7:
          return _native.Engine.TEXTURE_FORMAT_RG32U;
      }
      break;
    }
    case 12: {
      switch (type) {
        case 0:
          return _native.Engine.TEXTURE_FORMAT_BGRA8;
      }
      break;
    }
  }
  throw new RuntimeError(`Unsupported texture format or type: format ${format}, type ${type}.`, ErrorCodes.UnsupportedTextureError);
}
function getNativeSamplingMode(samplingMode) {
  switch (samplingMode) {
    case 1:
      return _native.Engine.TEXTURE_NEAREST_NEAREST;
    case 2:
      return _native.Engine.TEXTURE_LINEAR_LINEAR;
    case 3:
      return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
    case 4:
      return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
    case 5:
      return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
    case 6:
      return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
    case 7:
      return _native.Engine.TEXTURE_NEAREST_LINEAR;
    case 8:
      return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;
    case 9:
      return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
    case 10:
      return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
    case 11:
      return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;
    case 12:
      return _native.Engine.TEXTURE_LINEAR_NEAREST;
    default:
      throw new Error(`Unsupported sampling mode: ${samplingMode}.`);
  }
}
function getNativeAddressMode(wrapMode) {
  switch (wrapMode) {
    case 1:
      return _native.Engine.ADDRESS_MODE_WRAP;
    case 0:
      return _native.Engine.ADDRESS_MODE_CLAMP;
    case 2:
      return _native.Engine.ADDRESS_MODE_MIRROR;
    default:
      throw new Error("Unexpected wrap mode: " + wrapMode + ".");
  }
}
function getNativeStencilFunc(func) {
  switch (func) {
    case 513:
      return _native.Engine.STENCIL_TEST_LESS;
    case 515:
      return _native.Engine.STENCIL_TEST_LEQUAL;
    case 514:
      return _native.Engine.STENCIL_TEST_EQUAL;
    case 518:
      return _native.Engine.STENCIL_TEST_GEQUAL;
    case 516:
      return _native.Engine.STENCIL_TEST_GREATER;
    case 517:
      return _native.Engine.STENCIL_TEST_NOTEQUAL;
    case 512:
      return _native.Engine.STENCIL_TEST_NEVER;
    case 519:
      return _native.Engine.STENCIL_TEST_ALWAYS;
    default:
      throw new Error(`Unsupported stencil func mode: ${func}.`);
  }
}
function getNativeStencilOpFail(opFail) {
  switch (opFail) {
    case 7680:
      return _native.Engine.STENCIL_OP_FAIL_S_KEEP;
    case 0:
      return _native.Engine.STENCIL_OP_FAIL_S_ZERO;
    case 7681:
      return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;
    case 7682:
      return _native.Engine.STENCIL_OP_FAIL_S_INCR;
    case 7683:
      return _native.Engine.STENCIL_OP_FAIL_S_DECR;
    case 5386:
      return _native.Engine.STENCIL_OP_FAIL_S_INVERT;
    case 34055:
      return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;
    case 34056:
      return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;
    default:
      throw new Error(`Unsupported stencil OpFail mode: ${opFail}.`);
  }
}
function getNativeStencilDepthFail(depthFail) {
  switch (depthFail) {
    case 7680:
      return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;
    case 0:
      return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;
    case 7681:
      return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;
    case 7682:
      return _native.Engine.STENCIL_OP_FAIL_Z_INCR;
    case 7683:
      return _native.Engine.STENCIL_OP_FAIL_Z_DECR;
    case 5386:
      return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;
    case 34055:
      return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;
    case 34056:
      return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;
    default:
      throw new Error(`Unsupported stencil depthFail mode: ${depthFail}.`);
  }
}
function getNativeStencilDepthPass(opPass) {
  switch (opPass) {
    case 7680:
      return _native.Engine.STENCIL_OP_PASS_Z_KEEP;
    case 0:
      return _native.Engine.STENCIL_OP_PASS_Z_ZERO;
    case 7681:
      return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;
    case 7682:
      return _native.Engine.STENCIL_OP_PASS_Z_INCR;
    case 7683:
      return _native.Engine.STENCIL_OP_PASS_Z_DECR;
    case 5386:
      return _native.Engine.STENCIL_OP_PASS_Z_INVERT;
    case 34055:
      return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;
    case 34056:
      return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;
    default:
      throw new Error(`Unsupported stencil opPass mode: ${opPass}.`);
  }
}
function getNativeAlphaMode(mode) {
  switch (mode) {
    case 0:
      return _native.Engine.ALPHA_DISABLE;
    case 1:
      return _native.Engine.ALPHA_ADD;
    case 2:
      return _native.Engine.ALPHA_COMBINE;
    case 3:
      return _native.Engine.ALPHA_SUBTRACT;
    case 4:
      return _native.Engine.ALPHA_MULTIPLY;
    case 5:
      return _native.Engine.ALPHA_MAXIMIZED;
    case 6:
      return _native.Engine.ALPHA_ONEONE;
    case 7:
      return _native.Engine.ALPHA_PREMULTIPLIED;
    case 8:
      return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
    case 9:
      return _native.Engine.ALPHA_INTERPOLATE;
    case 10:
      return _native.Engine.ALPHA_SCREENMODE;
    default:
      throw new Error(`Unsupported alpha mode: ${mode}.`);
  }
}
function getNativeAttribType(type) {
  switch (type) {
    case VertexBuffer.BYTE:
      return _native.Engine.ATTRIB_TYPE_INT8;
    case VertexBuffer.UNSIGNED_BYTE:
      return _native.Engine.ATTRIB_TYPE_UINT8;
    case VertexBuffer.SHORT:
      return _native.Engine.ATTRIB_TYPE_INT16;
    case VertexBuffer.UNSIGNED_SHORT:
      return _native.Engine.ATTRIB_TYPE_UINT16;
    case VertexBuffer.FLOAT:
      return _native.Engine.ATTRIB_TYPE_FLOAT;
    default:
      throw new Error(`Unsupported attribute type: ${type}.`);
  }
}

// node_modules/@babylonjs/core/Buffers/buffer.nonFloatVertexBuffers.js
var vertexBufferKindForNonFloatProcessing = {
  [VertexBuffer.PositionKind]: true,
  [VertexBuffer.NormalKind]: true,
  [VertexBuffer.TangentKind]: true,
  [VertexBuffer.UVKind]: true,
  [VertexBuffer.UV2Kind]: true,
  [VertexBuffer.UV3Kind]: true,
  [VertexBuffer.UV4Kind]: true,
  [VertexBuffer.UV5Kind]: true,
  [VertexBuffer.UV6Kind]: true,
  [VertexBuffer.ColorKind]: true,
  [VertexBuffer.ColorInstanceKind]: true,
  [VertexBuffer.MatricesIndicesKind]: true,
  [VertexBuffer.MatricesWeightsKind]: true,
  [VertexBuffer.MatricesIndicesExtraKind]: true,
  [VertexBuffer.MatricesWeightsExtraKind]: true
};
function isSignedType(type) {
  switch (type) {
    case VertexBuffer.BYTE:
    case VertexBuffer.SHORT:
    case VertexBuffer.INT:
    case VertexBuffer.FLOAT:
      return true;
    case VertexBuffer.UNSIGNED_BYTE:
    case VertexBuffer.UNSIGNED_SHORT:
    case VertexBuffer.UNSIGNED_INT:
      return false;
    default:
      throw new Error(`Invalid type '${type}'`);
  }
}
function checkNonFloatVertexBuffers(vertexBuffers, effect) {
  const engine = effect.getEngine();
  const pipelineContext = effect._pipelineContext;
  if (!pipelineContext?.vertexBufferKindToType) {
    return;
  }
  let shaderProcessingContext = null;
  for (const kind in vertexBuffers) {
    const currentVertexBuffer = vertexBuffers[kind];
    if (!currentVertexBuffer || !vertexBufferKindForNonFloatProcessing[kind]) {
      continue;
    }
    const currentVertexBufferType = currentVertexBuffer.normalized ? VertexBuffer.FLOAT : currentVertexBuffer.type;
    const vertexBufferType = pipelineContext.vertexBufferKindToType[kind];
    if (currentVertexBufferType !== VertexBuffer.FLOAT && vertexBufferType === undefined || vertexBufferType !== undefined && vertexBufferType !== currentVertexBufferType) {
      if (!shaderProcessingContext) {
        shaderProcessingContext = engine._getShaderProcessingContext(effect.shaderLanguage, false);
      }
      pipelineContext.vertexBufferKindToType[kind] = currentVertexBufferType;
      if (currentVertexBufferType !== VertexBuffer.FLOAT) {
        shaderProcessingContext.vertexBufferKindToNumberOfComponents[kind] = VertexBuffer.DeduceStride(kind);
        if (isSignedType(currentVertexBufferType)) {
          shaderProcessingContext.vertexBufferKindToNumberOfComponents[kind] *= -1;
        }
      }
    }
  }
  if (shaderProcessingContext) {
    const parallelShaderCompile = engine._caps.parallelShaderCompile;
    engine._caps.parallelShaderCompile = undefined;
    effect._processShaderCodeAsync(null, engine._features._checkNonFloatVertexBuffersDontRecreatePipelineContext, shaderProcessingContext);
    engine._caps.parallelShaderCompile = parallelShaderCompile;
  }
}

// node_modules/@babylonjs/core/Engines/Native/nativeShaderProcessingContext.js
class NativeShaderProcessingContext {
  constructor() {
    this.vertexBufferKindToNumberOfComponents = {};
    this.remappedAttributeNames = {};
    this.injectInVertexMain = "";
  }
}

// node_modules/@babylonjs/core/Engines/nativeEngine.js
init_textureLoaderManager();
var onNativeObjectInitialized = new Observable;
if (typeof self !== "undefined" && !Object.prototype.hasOwnProperty.call(self, "_native")) {
  let __native;
  Object.defineProperty(self, "_native", {
    get: () => __native,
    set: (value) => {
      __native = value;
      if (__native) {
        onNativeObjectInitialized.notifyObservers(__native);
      }
    }
  });
}
function AcquireNativeObjectAsync() {
  return new Promise((resolve3) => {
    if (typeof _native === "undefined") {
      onNativeObjectInitialized.addOnce((nativeObject) => resolve3(nativeObject));
    } else {
      resolve3(_native);
    }
  });
}
async function RegisterNativeTypeAsync(typeName, constructor) {
  (await AcquireNativeObjectAsync())[typeName] = constructor;
}

class NativeDataBuffer extends DataBuffer {
}

class CommandBufferEncoder {
  constructor(_engine) {
    this._engine = _engine;
    this._pending = new Array;
    this._isCommandBufferScopeActive = false;
    this._commandStream = NativeEngine._createNativeDataStream();
    this._engine.setCommandDataStream(this._commandStream);
  }
  beginCommandScope() {
    if (this._isCommandBufferScopeActive) {
      throw new Error("Command scope already active.");
    }
    this._isCommandBufferScopeActive = true;
  }
  endCommandScope() {
    if (!this._isCommandBufferScopeActive) {
      throw new Error("Command scope is not active.");
    }
    this._isCommandBufferScopeActive = false;
    this._submit();
  }
  startEncodingCommand(command) {
    this._commandStream.writeNativeData(command);
  }
  encodeCommandArgAsUInt32(commandArg) {
    this._commandStream.writeUint32(commandArg);
  }
  encodeCommandArgAsUInt32s(commandArg) {
    this._commandStream.writeUint32Array(commandArg);
  }
  encodeCommandArgAsInt32(commandArg) {
    this._commandStream.writeInt32(commandArg);
  }
  encodeCommandArgAsInt32s(commandArg) {
    this._commandStream.writeInt32Array(commandArg);
  }
  encodeCommandArgAsFloat32(commandArg) {
    this._commandStream.writeFloat32(commandArg);
  }
  encodeCommandArgAsFloat32s(commandArg) {
    this._commandStream.writeFloat32Array(commandArg);
  }
  encodeCommandArgAsNativeData(commandArg) {
    this._commandStream.writeNativeData(commandArg);
    this._pending.push(commandArg);
  }
  finishEncodingCommand() {
    if (!this._isCommandBufferScopeActive) {
      this._submit();
    }
  }
  _submit() {
    this._engine.submitCommands();
    this._pending.length = 0;
  }
}
var remappedAttributesNames = [];

class NativeEngine extends Engine {
  setHardwareScalingLevel(level) {
    super.setHardwareScalingLevel(level);
    this._engine.setHardwareScalingLevel(level);
  }
  constructor(options = {}) {
    super(null, false, undefined, options.adaptToDeviceRatio);
    this._engine = new _native.Engine({
      version: Engine.Version,
      nonFloatVertexBuffers: true
    });
    this._camera = _native.Camera ? new _native.Camera : null;
    this._commandBufferEncoder = new CommandBufferEncoder(this._engine);
    this._frameStats = { gpuTimeNs: Number.NaN };
    this._boundBuffersVertexArray = null;
    this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL;
    this._stencilTest = false;
    this._stencilMask = 255;
    this._stencilFunc = 519;
    this._stencilFuncRef = 0;
    this._stencilFuncMask = 255;
    this._stencilOpStencilFail = 7680;
    this._stencilOpDepthFail = 7680;
    this._stencilOpStencilDepthPass = 7681;
    this._zOffset = 0;
    this._zOffsetUnits = 0;
    this._depthWrite = true;
    this._fillModeWarningDisplayed = false;
    if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) {
      throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);
    }
    if (this._engine.setDeviceLostCallback) {
      this._engine.setDeviceLostCallback(() => {
        this.onContextLostObservable.notifyObservers(this);
        this._contextWasLost = true;
        this._restoreEngineAfterContextLost();
      });
    }
    this._webGLVersion = 2;
    this.disableUniformBuffers = true;
    this._shaderPlatformName = "NATIVE";
    this._caps = {
      maxTexturesImageUnits: 16,
      maxVertexTextureImageUnits: 16,
      maxCombinedTexturesImageUnits: 32,
      maxTextureSize: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,
      maxCubemapTextureSize: 512,
      maxRenderTextureSize: 512,
      maxVertexAttribs: 16,
      maxVaryingVectors: 16,
      maxDrawBuffers: 8,
      maxFragmentUniformVectors: 16,
      maxVertexUniformVectors: 16,
      standardDerivatives: true,
      astc: null,
      pvrtc: null,
      etc1: null,
      etc2: null,
      bptc: null,
      maxAnisotropy: 16,
      uintIndices: true,
      fragmentDepthSupported: false,
      highPrecisionShaderSupported: true,
      colorBufferFloat: false,
      supportFloatTexturesResolve: false,
      rg11b10ufColorRenderable: false,
      textureFloat: true,
      textureFloatLinearFiltering: true,
      textureFloatRender: true,
      textureHalfFloat: true,
      textureHalfFloatLinearFiltering: true,
      textureHalfFloatRender: true,
      textureLOD: true,
      texelFetch: false,
      drawBuffersExtension: false,
      depthTextureExtension: false,
      vertexArrayObject: true,
      instancedArrays: true,
      supportOcclusionQuery: false,
      canUseTimestampForTimerQuery: false,
      blendMinMax: false,
      maxMSAASamples: 16,
      canUseGLInstanceID: true,
      canUseGLVertexID: true,
      supportComputeShaders: false,
      supportSRGBBuffers: true,
      supportTransformFeedbacks: false,
      textureMaxLevel: false,
      texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,
      disableMorphTargetTexture: false,
      parallelShaderCompile: { COMPLETION_STATUS_KHR: 0 },
      textureNorm16: false
    };
    this._features = {
      forceBitmapOverHTMLImageElement: true,
      supportRenderAndCopyToLodForFloatTextures: false,
      supportDepthStencilTexture: false,
      supportShadowSamplers: false,
      uniformBufferHardCheckMatrix: false,
      allowTexturePrefiltering: false,
      trackUbosInFrame: false,
      checkUbosContentBeforeUpload: false,
      supportCSM: false,
      basisNeedsPOT: false,
      support3DTextures: false,
      needTypeSuffixInShaderConstants: false,
      supportMSAA: true,
      supportSSAO2: false,
      supportIBLShadows: false,
      supportExtendedTextureFormats: false,
      supportSwitchCaseInShader: false,
      supportSyncTextureRead: false,
      needsInvertingBitmap: true,
      useUBOBindingCache: true,
      needShaderCodeInlining: true,
      needToAlwaysBindUniformBuffers: false,
      supportRenderPasses: true,
      supportSpriteInstancing: false,
      forceVertexBufferStrideAndOffsetMultiple4Bytes: true,
      _checkNonFloatVertexBuffersDontRecreatePipelineContext: false,
      _collectUbosUpdatedInFrame: false
    };
    Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
    Tools.LoadScript = function(scriptUrl, onSuccess, onError, scriptId) {
      Tools.LoadFile(scriptUrl, (data) => {
        Function(data).apply(null);
        if (onSuccess) {
          onSuccess();
        }
      }, undefined, undefined, false, (request, exception) => {
        if (onError) {
          onError("LoadScript Error", exception);
        }
      });
    };
    if (typeof URL === "undefined") {
      window.URL = {
        createObjectURL: function() {},
        revokeObjectURL: function() {}
      };
    }
    if (typeof Blob === "undefined") {
      window.Blob = function(v) {
        return v;
      };
    }
    if (!Array.prototype.flat) {
      Object.defineProperty(Array.prototype, "flat", {
        configurable: true,
        value: function flat() {
          const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);
          return depth ? Array.prototype.reduce.call(this, function(acc, cur) {
            if (Array.isArray(cur)) {
              acc.push.apply(acc, flat.call(cur, depth - 1));
            } else {
              acc.push(cur);
            }
            return acc;
          }, []) : Array.prototype.slice.call(this);
        },
        writable: true
      });
    }
    const devicePixelRatio = window ? window.devicePixelRatio || 1 : 1;
    this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1 / devicePixelRatio : 1;
    this._engine.setHardwareScalingLevel(this._hardwareScalingLevel);
    this._lastDevicePixelRatio = devicePixelRatio;
    this.resize();
    const currentDepthFunction = this.getDepthFunction();
    if (currentDepthFunction) {
      this.setDepthFunction(currentDepthFunction);
    }
    this._shaderProcessor = new NativeShaderProcessor;
    this.onNewSceneAddedObservable.add((scene) => {
      const originalRender = scene.render;
      scene.render = (...args) => {
        this._commandBufferEncoder.beginCommandScope();
        originalRender.apply(scene, args);
        this._commandBufferEncoder.endCommandScope();
      };
    });
  }
  dispose() {
    super.dispose();
    if (this._boundBuffersVertexArray) {
      this._deleteVertexArray(this._boundBuffersVertexArray);
    }
    this._engine.dispose();
  }
  static _createNativeDataStream() {
    return new NativeDataStream;
  }
  _queueNewFrame(bindedRenderFunction, requester) {
    if (requester.requestAnimationFrame && requester !== window) {
      requester.requestAnimationFrame(bindedRenderFunction);
    } else {
      this._engine.requestAnimationFrame(bindedRenderFunction);
    }
    return 0;
  }
  _restoreEngineAfterContextLost() {
    this._clearEmptyResources();
    const depthTest = this._depthCullingState.depthTest;
    const depthFunc = this._depthCullingState.depthFunc;
    const depthMask = this._depthCullingState.depthMask;
    const stencilTest = this._stencilState.stencilTest;
    this._rebuildGraphicsResources();
    this._depthCullingState.depthTest = depthTest;
    this._depthCullingState.depthFunc = depthFunc;
    this._depthCullingState.depthMask = depthMask;
    this._stencilState.stencilTest = stencilTest;
    this._flagContextRestored();
  }
  _bindUnboundFramebuffer(framebuffer) {
    if (this._currentFramebuffer !== framebuffer) {
      if (this._currentFramebuffer) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER);
        this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer);
        this._commandBufferEncoder.finishEncodingCommand();
      }
      if (framebuffer) {
        this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER);
        this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);
        this._commandBufferEncoder.finishEncodingCommand();
      }
      this._currentFramebuffer = framebuffer;
    }
  }
  getHostDocument() {
    return null;
  }
  clear(color, backBuffer, depth, stencil = false) {
    if (this.useReverseDepthBuffer) {
      throw new Error("reverse depth buffer is not currently implemented");
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(1);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(0);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  createIndexBuffer(indices, updateable, _label) {
    const data = this._normalizeIndexData(indices);
    const buffer2 = new NativeDataBuffer;
    buffer2.references = 1;
    buffer2.is32Bits = data.BYTES_PER_ELEMENT === 4;
    if (data.byteLength) {
      buffer2.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer2.is32Bits, updateable ?? false);
    }
    return buffer2;
  }
  createVertexBuffer(vertices, updateable, _label) {
    const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices);
    const buffer2 = new NativeDataBuffer;
    buffer2.references = 1;
    if (data.byteLength) {
      buffer2.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable ?? false);
    }
    return buffer2;
  }
  _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
    if (!effect._checkedNonFloatVertexBuffers) {
      checkNonFloatVertexBuffers(vertexBuffers, effect);
      effect._checkedNonFloatVertexBuffers = true;
    }
    if (indexBuffer) {
      this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
    }
    const attributes = effect.getAttributesNames();
    for (let index = 0;index < attributes.length; index++) {
      const location2 = effect.getAttributeLocation(index);
      if (location2 >= 0) {
        const kind = attributes[index];
        let vertexBuffer = null;
        if (overrideVertexBuffers) {
          vertexBuffer = overrideVertexBuffers[kind];
        }
        if (!vertexBuffer) {
          vertexBuffer = vertexBuffers[kind];
        }
        if (vertexBuffer) {
          const buffer2 = vertexBuffer.effectiveBuffer;
          if (buffer2 && buffer2.nativeVertexBuffer) {
            this._engine.recordVertexBuffer(vertexArray, buffer2.nativeVertexBuffer, location2, vertexBuffer.effectiveByteOffset, vertexBuffer.effectiveByteStride, vertexBuffer.getSize(), getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor());
          }
        }
      }
    }
  }
  bindBuffers(vertexBuffers, indexBuffer, effect) {
    if (this._boundBuffersVertexArray) {
      this._deleteVertexArray(this._boundBuffersVertexArray);
    }
    this._boundBuffersVertexArray = this._engine.createVertexArray();
    this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);
    this.bindVertexArrayObject(this._boundBuffersVertexArray);
  }
  recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
    const vertexArray = this._engine.createVertexArray();
    this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers);
    return vertexArray;
  }
  _deleteVertexArray(vertexArray) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  bindVertexArrayObject(vertexArray) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  releaseVertexArrayObject(vertexArray) {
    this._deleteVertexArray(vertexArray);
  }
  getAttributes(pipelineContext, attributesNames) {
    const nativePipelineContext = pipelineContext;
    const nativeShaderProcessingContext = nativePipelineContext.shaderProcessingContext;
    remappedAttributesNames.length = 0;
    for (let index = 0;index < attributesNames.length; index++) {
      const origAttributeName = attributesNames[index];
      const attributeName = nativeShaderProcessingContext.remappedAttributeNames[origAttributeName] ?? origAttributeName;
      remappedAttributesNames[index] = attributeName;
    }
    return this._engine.getAttributes(nativePipelineContext.program, remappedAttributesNames);
  }
  _checkSupportedFillMode(fillMode) {
    if (fillMode == 5 || fillMode == 8) {
      if (!this._fillModeWarningDisplayed) {
        Logger.Warn("Line Loop and Triangle Fan are not supported fill modes with Babylon Native. Elements with these fill mode will not be visible.");
        this._fillModeWarningDisplayed = true;
      }
      return false;
    }
    return true;
  }
  drawElementsType(fillMode, indexStart, indexCount, instancesCount) {
    if (!this._checkSupportedFillMode(fillMode)) {
      return;
    }
    this._drawCalls.addCount(1, false);
    if (instancesCount && _native.Engine.COMMAND_DRAWINDEXEDINSTANCED) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount);
    } else {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);
    }
    this._commandBufferEncoder.finishEncodingCommand();
  }
  drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {
    if (!this._checkSupportedFillMode(fillMode)) {
      return;
    }
    this._drawCalls.addCount(1, false);
    if (instancesCount && _native.Engine.COMMAND_DRAWINSTANCED) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount);
    } else {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);
    }
    this._commandBufferEncoder.finishEncodingCommand();
  }
  createPipelineContext(shaderProcessingContext) {
    const isAsync = !!(this._caps.parallelShaderCompile && this._engine.createProgramAsync);
    return new NativePipelineContext(this, isAsync, shaderProcessingContext);
  }
  createMaterialContext() {
    return;
  }
  createDrawContext() {
    return;
  }
  _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines, _transformFeedbackVaryings, _key, onReady) {
    if (createAsRaw) {
      this.createRawShaderProgram();
    } else {
      this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines);
    }
    onReady();
  }
  _getShaderProcessingContext(_shaderLanguage) {
    return new NativeShaderProcessingContext;
  }
  _executeWhenRenderingStateIsCompiled(pipelineContext, action2) {
    const nativePipelineContext = pipelineContext;
    if (nativePipelineContext.isAsync) {
      if (nativePipelineContext.onCompiled) {
        const oldHandler = nativePipelineContext.onCompiled;
        nativePipelineContext.onCompiled = () => {
          oldHandler();
          action2();
        };
      } else {
        nativePipelineContext.onCompiled = action2;
      }
    } else {
      action2();
    }
  }
  createRawShaderProgram() {
    throw new Error("Not Supported");
  }
  createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) {
    const nativePipelineContext = pipelineContext;
    this.onBeforeShaderCompilationObservable.notifyObservers(this);
    const vertexInliner = new ShaderCodeInliner(vertexCode);
    vertexInliner.processCode();
    vertexCode = vertexInliner.code;
    const fragmentInliner = new ShaderCodeInliner(fragmentCode);
    fragmentInliner.processCode();
    fragmentCode = fragmentInliner.code;
    vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines);
    fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines);
    const onSuccess = () => {
      nativePipelineContext.isCompiled = true;
      nativePipelineContext.onCompiled?.();
      this.onAfterShaderCompilationObservable.notifyObservers(this);
    };
    if (pipelineContext.isAsync) {
      nativePipelineContext.program = this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => {
        nativePipelineContext.compilationError = error;
      });
    } else {
      try {
        nativePipelineContext.program = this._engine.createProgram(vertexCode, fragmentCode);
        onSuccess();
      } catch (e) {
        const message = e?.message;
        throw new Error("SHADER ERROR" + (typeof message === "string" ? `
` + message : ""));
      }
    }
    return nativePipelineContext.program;
  }
  inlineShaderCode(code) {
    const sci = new ShaderCodeInliner(code);
    sci.debug = false;
    sci.processCode();
    return sci.code;
  }
  _setProgram(program) {
    if (this._currentProgram !== program) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(program);
      this._commandBufferEncoder.finishEncodingCommand();
      this._currentProgram = program;
    }
  }
  _deletePipelineContext(pipelineContext) {
    const nativePipelineContext = pipelineContext;
    if (nativePipelineContext && nativePipelineContext.program) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.program);
      this._commandBufferEncoder.finishEncodingCommand();
    }
  }
  getUniforms(pipelineContext, uniformsNames) {
    const nativePipelineContext = pipelineContext;
    return this._engine.getUniforms(nativePipelineContext.program, uniformsNames);
  }
  bindUniformBlock(pipelineContext, blockName, index) {
    throw new Error("Not Implemented");
  }
  bindSamplers(effect) {
    const nativePipelineContext = effect.getPipelineContext();
    this._setProgram(nativePipelineContext.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;
  }
  getRenderWidth(useScreen = false) {
    if (!useScreen && this._currentRenderTarget) {
      return this._currentRenderTarget.width;
    }
    return this._engine.getRenderWidth();
  }
  getRenderHeight(useScreen = false) {
    if (!useScreen && this._currentRenderTarget) {
      return this._currentRenderTarget.height;
    }
    return this._engine.getRenderHeight();
  }
  setViewport(viewport, requiredWidth, requiredHeight) {
    this._cachedViewport = viewport;
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  enableScissor(x, y, width, height) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(width);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(height);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  disableScissor() {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  setStateCullFaceType(_cullBackFaces, _force) {
    throw new Error("setStateCullFaceType: Not Implemented");
  }
  setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {
    this._zOffset = zOffset;
    this._zOffsetUnits = zOffsetUnits;
    if (this._zOffset !== 0) {
      Tools.Warn("zOffset is not supported in Native engine.");
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(this.cullBackFaces ?? cullBackFaces ?? true ? 1 : 0);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  getInputElementClientRect() {
    const rect = {
      bottom: this.getRenderHeight(),
      height: this.getRenderHeight(),
      left: 0,
      right: this.getRenderWidth(),
      top: 0,
      width: this.getRenderWidth(),
      x: 0,
      y: 0,
      toJSON: () => {}
    };
    return rect;
  }
  setZOffset(value) {
    if (value !== this._zOffset) {
      this._zOffset = value;
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET);
      this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);
      this._commandBufferEncoder.finishEncodingCommand();
    }
  }
  getZOffset() {
    return this._zOffset;
  }
  setZOffsetUnits(value) {
    if (value !== this._zOffsetUnits) {
      this._zOffsetUnits = value;
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS);
      this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);
      this._commandBufferEncoder.finishEncodingCommand();
    }
  }
  getZOffsetUnits() {
    return this._zOffsetUnits;
  }
  setDepthBuffer(enable) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  getDepthWrite() {
    return this._depthWrite;
  }
  getDepthFunction() {
    switch (this._currentDepthTest) {
      case _native.Engine.DEPTH_TEST_NEVER:
        return 512;
      case _native.Engine.DEPTH_TEST_ALWAYS:
        return 519;
      case _native.Engine.DEPTH_TEST_GREATER:
        return 516;
      case _native.Engine.DEPTH_TEST_GEQUAL:
        return 518;
      case _native.Engine.DEPTH_TEST_NOTEQUAL:
        return 517;
      case _native.Engine.DEPTH_TEST_EQUAL:
        return 514;
      case _native.Engine.DEPTH_TEST_LESS:
        return 513;
      case _native.Engine.DEPTH_TEST_LEQUAL:
        return 515;
    }
    return null;
  }
  setDepthFunction(depthFunc) {
    let nativeDepthFunc = 0;
    switch (depthFunc) {
      case 512:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER;
        break;
      case 519:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS;
        break;
      case 516:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER;
        break;
      case 518:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL;
        break;
      case 517:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL;
        break;
      case 514:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL;
        break;
      case 513:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS;
        break;
      case 515:
        nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL;
        break;
    }
    this._currentDepthTest = nativeDepthFunc;
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  setDepthWrite(enable) {
    this._depthWrite = enable;
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));
    this._commandBufferEncoder.finishEncodingCommand();
  }
  setColorWrite(enable) {
    this._colorWrite = enable;
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));
    this._commandBufferEncoder.finishEncodingCommand();
  }
  getColorWrite() {
    return this._colorWrite;
  }
  applyStencil() {
    this._setStencil(this._stencilMask, getNativeStencilOpFail(this._stencilOpStencilFail), getNativeStencilDepthFail(this._stencilOpDepthFail), getNativeStencilDepthPass(this._stencilOpStencilDepthPass), getNativeStencilFunc(this._stencilFunc), this._stencilFuncRef);
  }
  _setStencil(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(mask);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(func);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(ref);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  setStencilBuffer(enable) {
    this._stencilTest = enable;
    if (enable) {
      this.applyStencil();
    } else {
      this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0);
    }
  }
  getStencilBuffer() {
    return this._stencilTest;
  }
  getStencilOperationPass() {
    return this._stencilOpStencilDepthPass;
  }
  setStencilOperationPass(operation) {
    this._stencilOpStencilDepthPass = operation;
    this.applyStencil();
  }
  setStencilMask(mask) {
    this._stencilMask = mask;
    this.applyStencil();
  }
  setStencilFunction(stencilFunc) {
    this._stencilFunc = stencilFunc;
    this.applyStencil();
  }
  setStencilFunctionReference(reference) {
    this._stencilFuncRef = reference;
    this.applyStencil();
  }
  setStencilFunctionMask(mask) {
    this._stencilFuncMask = mask;
  }
  setStencilOperationFail(operation) {
    this._stencilOpStencilFail = operation;
    this.applyStencil();
  }
  setStencilOperationDepthFail(operation) {
    this._stencilOpDepthFail = operation;
    this.applyStencil();
  }
  getStencilMask() {
    return this._stencilMask;
  }
  getStencilFunction() {
    return this._stencilFunc;
  }
  getStencilFunctionReference() {
    return this._stencilFuncRef;
  }
  getStencilFunctionMask() {
    return this._stencilFuncMask;
  }
  getStencilOperationFail() {
    return this._stencilOpStencilFail;
  }
  getStencilOperationDepthFail() {
    return this._stencilOpDepthFail;
  }
  setAlphaConstants(r, g, b, a) {
    throw new Error("Setting alpha blend constant color not yet implemented.");
  }
  setAlphaMode(mode, noDepthWriteChange = false) {
    if (this._alphaMode === mode) {
      return;
    }
    const nativeMode = getNativeAlphaMode(mode);
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode);
    this._commandBufferEncoder.finishEncodingCommand();
    if (!noDepthWriteChange) {
      this.setDepthWrite(mode === 0);
    }
    this._alphaMode = mode;
  }
  setInt(uniform, int) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsInt32(int);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setIntArray(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setIntArray2(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setIntArray3(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setIntArray4(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloatArray(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloatArray2(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloatArray3(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloatArray4(uniform, array) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setArray(uniform, array) {
    if (!uniform) {
      return false;
    }
    return this.setFloatArray(uniform, new Float32Array(array));
  }
  setArray2(uniform, array) {
    if (!uniform) {
      return false;
    }
    return this.setFloatArray2(uniform, new Float32Array(array));
  }
  setArray3(uniform, array) {
    if (!uniform) {
      return false;
    }
    return this.setFloatArray3(uniform, new Float32Array(array));
  }
  setArray4(uniform, array) {
    if (!uniform) {
      return false;
    }
    return this.setFloatArray4(uniform, new Float32Array(array));
  }
  setMatrices(uniform, matrices) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setMatrix3x3(uniform, matrix) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setMatrix2x2(uniform, matrix) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloat(uniform, value) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(value);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloat2(uniform, x, y) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloat3(uniform, x, y, z) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(z);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setFloat4(uniform, x, y, z, w) {
    if (!uniform) {
      return false;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(z);
    this._commandBufferEncoder.encodeCommandArgAsFloat32(w);
    this._commandBufferEncoder.finishEncodingCommand();
    return true;
  }
  setColor3(uniform, color3) {
    if (!uniform) {
      return false;
    }
    this.setFloat3(uniform, color3.r, color3.g, color3.b);
    return true;
  }
  setColor4(uniform, color3, alpha) {
    if (!uniform) {
      return false;
    }
    this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
    return true;
  }
  wipeCaches(bruteForce) {
    if (this.preventCacheWipeBetweenFrames) {
      return;
    }
    this.resetTextureCache();
    this._currentEffect = null;
    if (bruteForce) {
      this._currentProgram = null;
      this._stencilStateComposer.reset();
      this._depthCullingState.reset();
      this._alphaState.reset();
    }
    this._cachedVertexBuffers = null;
    this._cachedIndexBuffer = null;
    this._cachedEffectForVertexBuffers = null;
  }
  _createTexture() {
    return this._engine.createTexture();
  }
  _deleteTexture(texture) {
    if (texture) {
      this._engine.deleteTexture(texture.underlyingResource);
    }
  }
  updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) {
    if (premulAlpha === undefined) {
      premulAlpha = false;
    }
    if (!!texture && !!texture._hardwareTexture) {
      const source = canvas.getCanvasTexture();
      const destination = texture._hardwareTexture.underlyingResource;
      this._engine.copyTexture(destination, source);
      texture.isReady = true;
    }
  }
  createDynamicTexture(width, height, generateMipMaps, samplingMode) {
    width = Math.max(width, 1);
    height = Math.max(height, 1);
    return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode);
  }
  createVideoElement(constraints) {
    if (this._camera) {
      return this._camera.createVideo(constraints);
    }
    return null;
  }
  updateVideoTexture(texture, video, invertY) {
    if (texture && texture._hardwareTexture && this._camera) {
      const webGLTexture = texture._hardwareTexture.underlyingResource;
      this._camera.updateVideoTexture(webGLTexture, video, invertY);
    }
  }
  createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {
    const texture = new InternalTexture(this, 3);
    texture.format = format;
    texture.generateMipMaps = generateMipMaps;
    texture.samplingMode = samplingMode;
    texture.invertY = invertY;
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.width = texture.baseWidth;
    texture.height = texture.baseHeight;
    texture._compression = compression;
    texture.type = type;
    texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);
    this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);
    if (texture._hardwareTexture) {
      const webGLTexture = texture._hardwareTexture.underlyingResource;
      const filter = getNativeSamplingMode(samplingMode);
      this._setTextureSampling(webGLTexture, filter);
    }
    this._internalTexturesCache.push(texture);
    return texture;
  }
  createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {
    const texture = new InternalTexture(this, 11);
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.baseDepth = depth;
    texture.width = width;
    texture.height = height;
    texture.depth = depth;
    texture.format = format;
    texture.type = textureType;
    texture.generateMipMaps = generateMipMaps;
    texture.samplingMode = samplingMode;
    texture.is2DArray = true;
    if (texture._hardwareTexture) {
      const nativeTexture = texture._hardwareTexture.underlyingResource;
      this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, getNativeTextureFormat(format, textureType), generateMipMaps, invertY);
      const filter = getNativeSamplingMode(samplingMode);
      this._setTextureSampling(nativeTexture, filter);
    }
    texture.isReady = true;
    this._internalTexturesCache.push(texture);
    return texture;
  }
  updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
    if (!texture) {
      return;
    }
    if (bufferView && texture._hardwareTexture) {
      const underlyingResource = texture._hardwareTexture.underlyingResource;
      this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY);
    }
    texture.isReady = true;
  }
  createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer2 = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) {
    url = url || "";
    const fromData = url.substring(0, 5) === "data:";
    const isBase64 = fromData && url.indexOf(";base64,") !== -1;
    const texture = fallback ? fallback : new InternalTexture(this, 1);
    const originalUrl = url;
    if (this._transformTextureUrl && !isBase64 && !fallback && !buffer2) {
      url = this._transformTextureUrl(url);
    }
    const lastDot = url.lastIndexOf(".");
    const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
    let loaderPromise = null;
    if (extension.endsWith(".basis") || extension.endsWith(".ktx") || extension.endsWith(".ktx2") || mimeType === "image/ktx" || mimeType === "image/ktx2") {
      loaderPromise = _GetCompatibleTextureLoader(extension);
    }
    if (scene) {
      scene.addPendingData(texture);
    }
    texture.url = url;
    texture.generateMipMaps = !noMipmap;
    texture.samplingMode = samplingMode;
    texture.invertY = invertY;
    texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap);
    if (!this.doNotHandleContextLost) {
      texture._buffer = buffer2;
    }
    let onLoadObserver = null;
    if (onLoad && !fallback) {
      onLoadObserver = texture.onLoadedObservable.add(onLoad);
    }
    if (!fallback) {
      this._internalTexturesCache.push(texture);
    }
    const onInternalError = (message, exception) => {
      if (scene) {
        scene.removePendingData(texture);
      }
      if (url === originalUrl) {
        if (onLoadObserver) {
          texture.onLoadedObservable.remove(onLoadObserver);
        }
        if (EngineStore.UseFallbackTexture) {
          this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer2, texture);
        }
        if (onError) {
          onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
        }
      } else {
        Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
        this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer2, texture, format, forcedExtension, mimeType, loaderOptions);
      }
    };
    if (loaderPromise) {
      throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
    } else {
      const onload = (data) => {
        if (!texture._hardwareTexture) {
          if (scene) {
            scene.removePendingData(texture);
          }
          return;
        }
        const underlyingResource = texture._hardwareTexture.underlyingResource;
        this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, texture._useSRGBBuffer, () => {
          texture.baseWidth = this._engine.getTextureWidth(underlyingResource);
          texture.baseHeight = this._engine.getTextureHeight(underlyingResource);
          texture.width = texture.baseWidth;
          texture.height = texture.baseHeight;
          texture.isReady = true;
          const filter = getNativeSamplingMode(samplingMode);
          this._setTextureSampling(underlyingResource, filter);
          if (scene) {
            scene.removePendingData(texture);
          }
          texture.onLoadedObservable.notifyObservers(texture);
          texture.onLoadedObservable.clear();
        }, () => {
          throw new Error("Could not load a native texture.");
        });
      };
      if (fromData && buffer2) {
        if (buffer2 instanceof ArrayBuffer) {
          onload(new Uint8Array(buffer2));
        } else if (ArrayBuffer.isView(buffer2)) {
          onload(buffer2);
        } else if (typeof buffer2 === "string") {
          onload(new Uint8Array(Tools.DecodeBase64(buffer2)));
        } else {
          throw new Error("Unsupported buffer type");
        }
      } else {
        if (isBase64) {
          onload(new Uint8Array(Tools.DecodeBase64(url)));
        } else {
          this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => {
            onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
          });
        }
      }
    }
    return texture;
  }
  wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) {
    const hardwareTexture = new NativeHardwareTexture(texture, this._engine);
    const internalTexture = new InternalTexture(this, 0, true);
    internalTexture._hardwareTexture = hardwareTexture;
    internalTexture.baseWidth = this._engine.getTextureWidth(texture);
    internalTexture.baseHeight = this._engine.getTextureHeight(texture);
    internalTexture.width = internalTexture.baseWidth;
    internalTexture.height = internalTexture.baseHeight;
    internalTexture.isReady = true;
    internalTexture.useMipMaps = hasMipMaps;
    this.updateTextureSamplingMode(samplingMode, internalTexture);
    return internalTexture;
  }
  wrapWebGLTexture() {
    throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.");
  }
  _createDepthStencilTexture(size, options, rtWrapper) {
    const generateStencil = options.generateStencil || false;
    const samples = options.samples || 1;
    const nativeRTWrapper = rtWrapper;
    const texture = new InternalTexture(this, 12);
    const width = size.width ?? size;
    const height = size.height ?? size;
    const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, generateStencil, true, samples);
    nativeRTWrapper._framebufferDepthStencil = framebuffer;
    return texture;
  }
  _releaseFramebufferObjects(framebuffer) {
    if (framebuffer) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);
      this._commandBufferEncoder.finishEncodingCommand();
    }
  }
  _createImageBitmapFromSource(imageSource, options) {
    const promise = new Promise((resolve3, reject) => {
      const image = this.createCanvasImage();
      image.onload = () => {
        try {
          const imageBitmap = this._engine.createImageBitmap(image);
          resolve3(imageBitmap);
        } catch (error) {
          reject(`Error loading image ${image.src} with exception: ${error}`);
        }
      };
      image.onerror = (error) => {
        reject(`Error loading image ${image.src} with exception: ${error}`);
      };
      image.src = imageSource;
    });
    return promise;
  }
  createImageBitmap(image, options) {
    return new Promise((resolve3, reject) => {
      if (Array.isArray(image)) {
        const arr = image;
        if (arr.length) {
          const image2 = this._engine.createImageBitmap(arr[0]);
          if (image2) {
            resolve3(image2);
            return;
          }
        }
      }
      reject(`Unsupported data for createImageBitmap.`);
    });
  }
  resizeImageBitmap(image, bufferWidth, bufferHeight) {
    return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight);
  }
  createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer2 = 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 = this._getUseSRGBBuffer(useSRGBBuffer, !!noMipmap);
    if (!this._doNotHandleContextLost) {
      texture._extension = forcedExtension;
      texture._files = files;
      texture._buffer = buffer2;
    }
    const lastDot = rootUrl.lastIndexOf(".");
    const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "";
    if (extension === ".env") {
      const onloaddata = (data) => {
        const info = GetEnvInfo(data);
        texture.width = info.width;
        texture.height = info.width;
        UploadEnvSpherical(texture, info);
        const specularInfo = info.specular;
        if (!specularInfo) {
          throw new Error(`Nothing else parsed so far`);
        }
        texture._lodGenerationScale = specularInfo.lodGenerationScale;
        const imageData = CreateRadianceImageDataArrayBufferViews(data, info);
        texture.format = 5;
        texture.type = 0;
        texture.generateMipMaps = true;
        texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
        texture._isRGBD = true;
        texture.invertY = true;
        this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, texture._useSRGBBuffer, () => {
          texture.isReady = true;
          if (onLoad) {
            onLoad();
          }
        }, () => {
          throw new Error("Could not load a native cube texture.");
        });
      };
      if (buffer2) {
        onloaddata(buffer2);
      } else if (files && files.length === 6) {
        throw new Error(`Multi-file loading not allowed on env files.`);
      } else {
        const onInternalError = (request, exception) => {
          if (onError && request) {
            onError(request.status + " " + request.statusText, exception);
          }
        };
        this._loadFile(rootUrl, (data) => {
          onloaddata(new Uint8Array(data, 0, data.byteLength));
        }, undefined, undefined, true, onInternalError);
      }
    } else {
      if (!files || files.length !== 6) {
        throw new Error("Cannot load cubemap because 6 files were not defined");
      }
      const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];
      Promise.all(reorderedFiles.map((file) => this._loadFileAsync(file, undefined, true).then((data) => new Uint8Array(data, 0, data.byteLength)))).then((data) => {
        return new Promise((resolve3, reject) => {
          this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, texture._useSRGBBuffer, resolve3, reject);
        });
      }).then(() => {
        texture.isReady = true;
        if (onLoad) {
          onLoad();
        }
      }, (error) => {
        if (onError) {
          onError(`Failed to load cubemap: ${error.message}`, error);
        }
      });
    }
    this._internalTexturesCache.push(texture);
    return texture;
  }
  _createHardwareTexture() {
    return new NativeHardwareTexture(this._createTexture(), this._engine);
  }
  _createHardwareRenderTargetWrapper(isMulti, isCube, size) {
    const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this);
    this._renderTargetWrapperCache.push(rtWrapper);
    return rtWrapper;
  }
  _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = 0) {
    let generateMipMaps = false;
    let type = 0;
    let samplingMode = 3;
    let format = 5;
    let useSRGBBuffer = false;
    let samples = 1;
    let label;
    if (options !== undefined && typeof options === "object") {
      generateMipMaps = !!options.generateMipMaps;
      type = options.type === undefined ? 0 : options.type;
      samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;
      format = options.format === undefined ? 5 : options.format;
      useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer;
      samples = options.samples ?? 1;
      label = options.label;
    } else {
      generateMipMaps = !!options;
    }
    useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);
    if (type === 1 && !this._caps.textureFloatLinearFiltering) {
      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 texture = new InternalTexture(this, source);
    const width = size.width ?? size;
    const height = size.height ?? size;
    const layers = size.layers || 0;
    if (layers !== 0) {
      throw new Error("Texture layers are not supported in Babylon Native");
    }
    const nativeTexture = texture._hardwareTexture.underlyingResource;
    const nativeTextureFormat = getNativeTextureFormat(format, type);
    this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer, samples);
    this._setTextureSampling(nativeTexture, getNativeSamplingMode(samplingMode));
    texture._useSRGBBuffer = useSRGBBuffer;
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.width = width;
    texture.height = height;
    texture.depth = layers;
    texture.isReady = true;
    texture.samples = samples;
    texture.generateMipMaps = generateMipMaps;
    texture.samplingMode = samplingMode;
    texture.type = type;
    texture.format = format;
    texture.label = label;
    this._internalTexturesCache.push(texture);
    return texture;
  }
  createRenderTargetTexture(size, options) {
    const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);
    let generateDepthBuffer = true;
    let generateStencilBuffer = false;
    let noColorAttachment = false;
    let colorAttachment = undefined;
    let samples = 1;
    if (options !== undefined && typeof options === "object") {
      generateDepthBuffer = options.generateDepthBuffer ?? true;
      generateStencilBuffer = !!options.generateStencilBuffer;
      noColorAttachment = !!options.noColorAttachment;
      colorAttachment = options.colorAttachment;
      samples = options.samples ?? 1;
    }
    const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, 5));
    const width = size.width ?? size;
    const height = size.height ?? size;
    const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer, samples);
    rtWrapper._framebuffer = framebuffer;
    rtWrapper._generateDepthBuffer = generateDepthBuffer;
    rtWrapper._generateStencilBuffer = generateStencilBuffer;
    rtWrapper._samples = samples;
    rtWrapper.setTextures(texture);
    return rtWrapper;
  }
  updateRenderTargetTextureSampleCount(rtWrapper, samples) {
    Logger.Warn("Updating render target sample count is not currently supported");
    return rtWrapper.samples;
  }
  updateTextureSamplingMode(samplingMode, texture) {
    if (texture._hardwareTexture) {
      const filter = getNativeSamplingMode(samplingMode);
      this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter);
    }
    texture.samplingMode = samplingMode;
  }
  bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
    const nativeRTWrapper = texture;
    if (this._currentRenderTarget) {
      this.unBindFramebuffer(this._currentRenderTarget);
    }
    this._currentRenderTarget = texture;
    if (faceIndex) {
      throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
    }
    if (requiredWidth || requiredHeight) {
      throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
    }
    if (nativeRTWrapper._framebufferDepthStencil) {
      this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil);
    } else {
      this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer);
    }
  }
  unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {
    this._currentRenderTarget = null;
    if (onBeforeUnbind) {
      onBeforeUnbind();
    }
    this._bindUnboundFramebuffer(null);
  }
  createDynamicVertexBuffer(data) {
    return this.createVertexBuffer(data, true);
  }
  updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) {
    const buffer2 = indexBuffer;
    const data = this._normalizeIndexData(indices);
    buffer2.is32Bits = data.BYTES_PER_ELEMENT === 4;
    this._engine.updateDynamicIndexBuffer(buffer2.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset);
  }
  updateDynamicVertexBuffer(vertexBuffer, data, byteOffset = 0, byteLength) {
    const buffer2 = vertexBuffer;
    const dataView = data instanceof Array ? new Float32Array(data) : data instanceof ArrayBuffer ? new Uint8Array(data) : data;
    const byteView = new Uint8Array(dataView.buffer, dataView.byteOffset, byteLength ?? dataView.byteLength);
    this._engine.updateDynamicVertexBuffer(buffer2.nativeVertexBuffer, byteView.buffer, byteView.byteOffset, byteView.byteLength, byteOffset);
  }
  _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) {
    const uniform = this._boundUniforms[channel];
    if (!uniform) {
      return false;
    }
    if (!texture) {
      if (this._boundTexturesCache[channel] != null) {
        this._activeChannel = channel;
        this._boundTexturesCache[channel] = null;
        this._unsetNativeTexture(uniform);
      }
      return false;
    }
    if (texture.video) {
      this._activeChannel = 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;
    }
    this._activeChannel = channel;
    if (!internalTexture || !internalTexture._hardwareTexture) {
      return false;
    }
    this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, getNativeAddressMode(texture.wrapU), getNativeAddressMode(texture.wrapV), getNativeAddressMode(texture.wrapR));
    this._updateAnisotropicLevel(texture);
    this._setNativeTexture(uniform, internalTexture._hardwareTexture.underlyingResource);
    return true;
  }
  _setTextureSampling(texture, filter) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(filter);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV);
    this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  _setNativeTexture(uniform, texture) {
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  _unsetNativeTexture(uniform) {
    if (!_native.Engine.COMMAND_UNSETTEXTURE) {
      return;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE);
    this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  _updateAnisotropicLevel(texture) {
    const internalTexture = texture.getInternalTexture();
    const value = texture.anisotropicFilteringLevel;
    if (!internalTexture || !internalTexture._hardwareTexture) {
      return;
    }
    if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource);
      this._commandBufferEncoder.encodeCommandArgAsUInt32(value);
      this._commandBufferEncoder.finishEncodingCommand();
      internalTexture._cachedAnisotropicFilteringLevel = value;
    }
  }
  _bindTexture(channel, texture) {
    const uniform = this._boundUniforms[channel];
    if (!uniform) {
      return;
    }
    if (texture && texture._hardwareTexture) {
      const underlyingResource = texture._hardwareTexture.underlyingResource;
      this._setNativeTexture(uniform, underlyingResource);
    } else {
      this._unsetNativeTexture(uniform);
    }
  }
  unbindAllTextures() {
    if (!_native.Engine.COMMAND_DISCARDALLTEXTURES) {
      return;
    }
    this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES);
    this._commandBufferEncoder.finishEncodingCommand();
  }
  _deleteBuffer(buffer2) {
    if (buffer2.nativeIndexBuffer) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer2.nativeIndexBuffer);
      this._commandBufferEncoder.finishEncodingCommand();
      delete buffer2.nativeIndexBuffer;
    }
    if (buffer2.nativeVertexBuffer) {
      this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER);
      this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer2.nativeVertexBuffer);
      this._commandBufferEncoder.finishEncodingCommand();
      delete buffer2.nativeVertexBuffer;
    }
  }
  createCanvas(width, height) {
    if (!_native.Canvas) {
      throw new Error("Native Canvas plugin not available.");
    }
    const canvas = new _native.Canvas;
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
  createCanvasImage() {
    if (!_native.Canvas) {
      throw new Error("Native Canvas plugin not available.");
    }
    const image = new _native.Image;
    return image;
  }
  createCanvasPath2D(d) {
    if (!_native.Canvas) {
      throw new Error("Native Canvas plugin not available.");
    }
    const path2d = new _native.Path2D(d);
    return path2d;
  }
  updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {
    throw new Error("updateTextureData not implemented.");
  }
  _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) {
    throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
  }
  _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) {
    throw new Error("_uploadDataToTextureDirectly not implemented.");
  }
  _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {
    throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  }
  _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {
    throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  }
  getFontOffset(font) {
    const result = { ascent: 0, height: 0, descent: 0 };
    return result;
  }
  flushFramebuffer() {}
  _readTexturePixels(texture, width, height, faceIndex, level, buffer2, _flushRenderer, _noDataConversion, x, y) {
    if (faceIndex !== undefined && faceIndex !== -1) {
      throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`);
    }
    return this._engine.readTexture(texture._hardwareTexture?.underlyingResource, level ?? 0, x ?? 0, y ?? 0, width, height, buffer2?.buffer ?? null, buffer2?.byteOffset ?? 0, buffer2?.byteLength ?? 0).then((rawBuffer) => {
      if (!buffer2) {
        buffer2 = new Uint8Array(rawBuffer);
      }
      return buffer2;
    });
  }
  startTimeQuery() {
    if (!this._gpuFrameTimeToken) {
      this._gpuFrameTimeToken = new _TimeToken;
    }
    return this._gpuFrameTimeToken;
  }
  endTimeQuery(token) {
    this._engine.populateFrameStats?.(this._frameStats);
    return this._frameStats.gpuTimeNs;
  }
}
NativeEngine.PROTOCOL_VERSION = 8;

// node_modules/@babylonjs/core/Engines/Native/validatedNativeDataStream.js
NativeEngine._createNativeDataStream = function() {
  if (_native.NativeDataStream.VALIDATION_ENABLED) {
    return new ValidatedNativeDataStream;
  } else {
    return new NativeDataStream;
  }
};

class ValidatedNativeDataStream extends NativeDataStream {
  constructor() {
    super();
  }
  writeUint32(value) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32);
    super.writeUint32(value);
  }
  writeInt32(value) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32);
    super.writeInt32(value);
  }
  writeFloat32(value) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32);
    super.writeFloat32(value);
  }
  writeUint32Array(values) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY);
    super.writeUint32Array(values);
  }
  writeInt32Array(values) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY);
    super.writeInt32Array(values);
  }
  writeFloat32Array(values) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY);
    super.writeFloat32Array(values);
  }
  writeNativeData(handle) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA);
    super.writeNativeData(handle);
  }
  writeBoolean(value) {
    super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN);
    super.writeBoolean(value);
  }
}
// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.alpha.js
init_abstractEngine();
init_abstractEngine_alpha();

// node_modules/@babylonjs/core/Engines/thinWebGPUEngine.js
init_abstractEngine();
init_logger();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuTextureHelper.js
class WebGPUTextureHelper {
  static ComputeNumMipmapLevels(width, height) {
    return ILog2(Math.max(width, height)) + 1;
  }
  static GetTextureTypeFromFormat(format) {
    switch (format) {
      case "r8unorm":
      case "r8uint":
      case "rg8unorm":
      case "rg8uint":
      case "rgba8unorm":
      case "rgba8unorm-srgb":
      case "rgba8uint":
      case "bgra8unorm":
      case "bgra8unorm-srgb":
      case "rgb10a2uint":
      case "rgb10a2unorm":
      case "rgb9e5ufloat":
      case "rg11b10ufloat":
      case "bc7-rgba-unorm":
      case "bc7-rgba-unorm-srgb":
      case "bc6h-rgb-ufloat":
      case "bc5-rg-unorm":
      case "bc3-rgba-unorm":
      case "bc3-rgba-unorm-srgb":
      case "bc2-rgba-unorm":
      case "bc2-rgba-unorm-srgb":
      case "bc4-r-unorm":
      case "bc1-rgba-unorm":
      case "bc1-rgba-unorm-srgb":
      case "etc2-rgb8unorm":
      case "etc2-rgb8unorm-srgb":
      case "etc2-rgb8a1unorm":
      case "etc2-rgb8a1unorm-srgb":
      case "etc2-rgba8unorm":
      case "etc2-rgba8unorm-srgb":
      case "eac-r11unorm":
      case "eac-rg11unorm":
      case "astc-4x4-unorm":
      case "astc-4x4-unorm-srgb":
      case "astc-5x4-unorm":
      case "astc-5x4-unorm-srgb":
      case "astc-5x5-unorm":
      case "astc-5x5-unorm-srgb":
      case "astc-6x5-unorm":
      case "astc-6x5-unorm-srgb":
      case "astc-6x6-unorm":
      case "astc-6x6-unorm-srgb":
      case "astc-8x5-unorm":
      case "astc-8x5-unorm-srgb":
      case "astc-8x6-unorm":
      case "astc-8x6-unorm-srgb":
      case "astc-8x8-unorm":
      case "astc-8x8-unorm-srgb":
      case "astc-10x5-unorm":
      case "astc-10x5-unorm-srgb":
      case "astc-10x6-unorm":
      case "astc-10x6-unorm-srgb":
      case "astc-10x8-unorm":
      case "astc-10x8-unorm-srgb":
      case "astc-10x10-unorm":
      case "astc-10x10-unorm-srgb":
      case "astc-12x10-unorm":
      case "astc-12x10-unorm-srgb":
      case "astc-12x12-unorm":
      case "astc-12x12-unorm-srgb":
      case "stencil8":
        return 0;
      case "r8snorm":
      case "r8sint":
      case "rg8snorm":
      case "rg8sint":
      case "rgba8snorm":
      case "rgba8sint":
      case "bc6h-rgb-float":
      case "bc5-rg-snorm":
      case "bc4-r-snorm":
      case "eac-r11snorm":
      case "eac-rg11snorm":
        return 3;
      case "r16uint":
      case "r16unorm":
      case "rg16unorm":
      case "rgba16unorm":
      case "rg16uint":
      case "rgba16uint":
      case "depth16unorm":
        return 5;
      case "r16sint":
      case "r16snorm":
      case "rg16snorm":
      case "rgba16snorm":
      case "rg16sint":
      case "rgba16sint":
        return 4;
      case "r16float":
      case "rg16float":
      case "rgba16float":
        return 2;
      case "r32uint":
      case "rg32uint":
      case "rgba32uint":
        return 7;
      case "r32sint":
      case "rg32sint":
      case "rgba32sint":
        return 7;
      case "r32float":
      case "rg32float":
      case "rgba32float":
      case "depth32float":
      case "depth32float-stencil8":
      case "depth24plus":
      case "depth24plus-stencil8":
        return 1;
    }
    return 0;
  }
  static GetBlockInformationFromFormat(format) {
    switch (format) {
      case "r8unorm":
      case "r8snorm":
      case "r8uint":
      case "r8sint":
        return { width: 1, height: 1, length: 1 };
      case "r16uint":
      case "r16sint":
      case "r16unorm":
      case "rg16unorm":
      case "rgba16unorm":
      case "r16snorm":
      case "rg16snorm":
      case "rgba16snorm":
      case "r16float":
      case "rg8unorm":
      case "rg8snorm":
      case "rg8uint":
      case "rg8sint":
        return { width: 1, height: 1, length: 2 };
      case "r32uint":
      case "r32sint":
      case "r32float":
      case "rg16uint":
      case "rg16sint":
      case "rg16float":
      case "rgba8unorm":
      case "rgba8unorm-srgb":
      case "rgba8snorm":
      case "rgba8uint":
      case "rgba8sint":
      case "bgra8unorm":
      case "bgra8unorm-srgb":
      case "rgb9e5ufloat":
      case "rgb10a2uint":
      case "rgb10a2unorm":
      case "rg11b10ufloat":
        return { width: 1, height: 1, length: 4 };
      case "rg32uint":
      case "rg32sint":
      case "rg32float":
      case "rgba16uint":
      case "rgba16sint":
      case "rgba16float":
        return { width: 1, height: 1, length: 8 };
      case "rgba32uint":
      case "rgba32sint":
      case "rgba32float":
        return { width: 1, height: 1, length: 16 };
      case "stencil8":
        throw "No fixed size for Stencil8 format!";
      case "depth16unorm":
        return { width: 1, height: 1, length: 2 };
      case "depth24plus":
        throw "No fixed size for Depth24Plus format!";
      case "depth24plus-stencil8":
        throw "No fixed size for Depth24PlusStencil8 format!";
      case "depth32float":
        return { width: 1, height: 1, length: 4 };
      case "depth32float-stencil8":
        return { width: 1, height: 1, length: 5 };
      case "bc7-rgba-unorm":
      case "bc7-rgba-unorm-srgb":
      case "bc6h-rgb-ufloat":
      case "bc6h-rgb-float":
      case "bc5-rg-unorm":
      case "bc5-rg-snorm":
      case "bc3-rgba-unorm":
      case "bc3-rgba-unorm-srgb":
      case "bc2-rgba-unorm":
      case "bc2-rgba-unorm-srgb":
        return { width: 4, height: 4, length: 16 };
      case "bc4-r-unorm":
      case "bc4-r-snorm":
      case "bc1-rgba-unorm":
      case "bc1-rgba-unorm-srgb":
        return { width: 4, height: 4, length: 8 };
      case "etc2-rgb8unorm":
      case "etc2-rgb8unorm-srgb":
      case "etc2-rgb8a1unorm":
      case "etc2-rgb8a1unorm-srgb":
      case "eac-r11unorm":
      case "eac-r11snorm":
        return { width: 4, height: 4, length: 8 };
      case "etc2-rgba8unorm":
      case "etc2-rgba8unorm-srgb":
      case "eac-rg11unorm":
      case "eac-rg11snorm":
        return { width: 4, height: 4, length: 16 };
      case "astc-4x4-unorm":
      case "astc-4x4-unorm-srgb":
        return { width: 4, height: 4, length: 16 };
      case "astc-5x4-unorm":
      case "astc-5x4-unorm-srgb":
        return { width: 5, height: 4, length: 16 };
      case "astc-5x5-unorm":
      case "astc-5x5-unorm-srgb":
        return { width: 5, height: 5, length: 16 };
      case "astc-6x5-unorm":
      case "astc-6x5-unorm-srgb":
        return { width: 6, height: 5, length: 16 };
      case "astc-6x6-unorm":
      case "astc-6x6-unorm-srgb":
        return { width: 6, height: 6, length: 16 };
      case "astc-8x5-unorm":
      case "astc-8x5-unorm-srgb":
        return { width: 8, height: 5, length: 16 };
      case "astc-8x6-unorm":
      case "astc-8x6-unorm-srgb":
        return { width: 8, height: 6, length: 16 };
      case "astc-8x8-unorm":
      case "astc-8x8-unorm-srgb":
        return { width: 8, height: 8, length: 16 };
      case "astc-10x5-unorm":
      case "astc-10x5-unorm-srgb":
        return { width: 10, height: 5, length: 16 };
      case "astc-10x6-unorm":
      case "astc-10x6-unorm-srgb":
        return { width: 10, height: 6, length: 16 };
      case "astc-10x8-unorm":
      case "astc-10x8-unorm-srgb":
        return { width: 10, height: 8, length: 16 };
      case "astc-10x10-unorm":
      case "astc-10x10-unorm-srgb":
        return { width: 10, height: 10, length: 16 };
      case "astc-12x10-unorm":
      case "astc-12x10-unorm-srgb":
        return { width: 12, height: 10, length: 16 };
      case "astc-12x12-unorm":
      case "astc-12x12-unorm-srgb":
        return { width: 12, height: 12, length: 16 };
    }
    return { width: 1, height: 1, length: 4 };
  }
  static IsHardwareTexture(texture) {
    return !!texture.release;
  }
  static IsInternalTexture(texture) {
    return !!texture.dispose;
  }
  static IsImageBitmap(imageBitmap) {
    return imageBitmap.close !== undefined;
  }
  static IsImageBitmapArray(imageBitmap) {
    return Array.isArray(imageBitmap) && imageBitmap[0].close !== undefined;
  }
  static IsCompressedFormat(format) {
    switch (format) {
      case "bc7-rgba-unorm-srgb":
      case "bc7-rgba-unorm":
      case "bc6h-rgb-float":
      case "bc6h-rgb-ufloat":
      case "bc5-rg-snorm":
      case "bc5-rg-unorm":
      case "bc4-r-snorm":
      case "bc4-r-unorm":
      case "bc3-rgba-unorm-srgb":
      case "bc3-rgba-unorm":
      case "bc2-rgba-unorm-srgb":
      case "bc2-rgba-unorm":
      case "bc1-rgba-unorm-srgb":
      case "bc1-rgba-unorm":
      case "etc2-rgb8unorm":
      case "etc2-rgb8unorm-srgb":
      case "etc2-rgb8a1unorm":
      case "etc2-rgb8a1unorm-srgb":
      case "etc2-rgba8unorm":
      case "etc2-rgba8unorm-srgb":
      case "eac-r11unorm":
      case "eac-r11snorm":
      case "eac-rg11unorm":
      case "eac-rg11snorm":
      case "astc-4x4-unorm":
      case "astc-4x4-unorm-srgb":
      case "astc-5x4-unorm":
      case "astc-5x4-unorm-srgb":
      case "astc-5x5-unorm":
      case "astc-5x5-unorm-srgb":
      case "astc-6x5-unorm":
      case "astc-6x5-unorm-srgb":
      case "astc-6x6-unorm":
      case "astc-6x6-unorm-srgb":
      case "astc-8x5-unorm":
      case "astc-8x5-unorm-srgb":
      case "astc-8x6-unorm":
      case "astc-8x6-unorm-srgb":
      case "astc-8x8-unorm":
      case "astc-8x8-unorm-srgb":
      case "astc-10x5-unorm":
      case "astc-10x5-unorm-srgb":
      case "astc-10x6-unorm":
      case "astc-10x6-unorm-srgb":
      case "astc-10x8-unorm":
      case "astc-10x8-unorm-srgb":
      case "astc-10x10-unorm":
      case "astc-10x10-unorm-srgb":
      case "astc-12x10-unorm":
      case "astc-12x10-unorm-srgb":
      case "astc-12x12-unorm":
      case "astc-12x12-unorm-srgb":
        return true;
    }
    return false;
  }
  static GetWebGPUTextureFormat(type, format, useSRGBBuffer = false) {
    switch (format) {
      case 15:
        return "depth16unorm";
      case 16:
        return "depth24plus";
      case 13:
        return "depth24plus-stencil8";
      case 14:
        return "depth32float";
      case 18:
        return "depth32float-stencil8";
      case 19:
        return "stencil8";
      case 36492:
        return useSRGBBuffer ? "bc7-rgba-unorm-srgb" : "bc7-rgba-unorm";
      case 36495:
        return "bc6h-rgb-ufloat";
      case 36494:
        return "bc6h-rgb-float";
      case 33779:
        return useSRGBBuffer ? "bc3-rgba-unorm-srgb" : "bc3-rgba-unorm";
      case 33778:
        return useSRGBBuffer ? "bc2-rgba-unorm-srgb" : "bc2-rgba-unorm";
      case 33777:
      case 33776:
        return useSRGBBuffer ? "bc1-rgba-unorm-srgb" : "bc1-rgba-unorm";
      case 37808:
        return useSRGBBuffer ? "astc-4x4-unorm-srgb" : "astc-4x4-unorm";
      case 36196:
      case 37492:
        return useSRGBBuffer ? "etc2-rgb8unorm-srgb" : "etc2-rgb8unorm";
      case 37496:
        return useSRGBBuffer ? "etc2-rgba8unorm-srgb" : "etc2-rgba8unorm";
    }
    switch (type) {
      case 3:
        switch (format) {
          case 6:
            return "r8snorm";
          case 7:
            return "rg8snorm";
          case 4:
            throw "RGB format not supported in WebGPU";
          case 8:
            return "r8sint";
          case 9:
            return "rg8sint";
          case 10:
            throw "RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba8sint";
          default:
            return "rgba8snorm";
        }
      case 0:
        switch (format) {
          case 6:
            return "r8unorm";
          case 7:
            return "rg8unorm";
          case 4:
            throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
          case 5:
            return useSRGBBuffer ? "rgba8unorm-srgb" : "rgba8unorm";
          case 12:
            return useSRGBBuffer ? "bgra8unorm-srgb" : "bgra8unorm";
          case 8:
            return "r8uint";
          case 9:
            return "rg8uint";
          case 10:
            throw "RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba8uint";
          case 0:
            throw "TEXTUREFORMAT_ALPHA format not supported in WebGPU";
          case 1:
            throw "TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";
          case 2:
            throw "TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";
          default:
            return "rgba8unorm";
        }
      case 4:
        switch (format) {
          case 8:
            return "r16sint";
          case 9:
            return "rg16sint";
          case 10:
            throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba16sint";
          default:
            return "rgba16sint";
        }
      case 5:
        switch (format) {
          case 8:
            return "r16uint";
          case 9:
            return "rg16uint";
          case 10:
            throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba16uint";
          default:
            return "rgba16uint";
        }
      case 6:
        switch (format) {
          case 8:
            return "r32sint";
          case 9:
            return "rg32sint";
          case 10:
            throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba32sint";
          default:
            return "rgba32sint";
        }
      case 7:
        switch (format) {
          case 8:
            return "r32uint";
          case 9:
            return "rg32uint";
          case 10:
            throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
          case 11:
            return "rgba32uint";
          default:
            return "rgba32uint";
        }
      case 1:
        switch (format) {
          case 6:
            return "r32float";
          case 7:
            return "rg32float";
          case 4:
            throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
          case 5:
            return "rgba32float";
          default:
            return "rgba32float";
        }
      case 2:
        switch (format) {
          case 6:
            return "r16float";
          case 7:
            return "rg16float";
          case 4:
            throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
          case 5:
            return "rgba16float";
          default:
            return "rgba16float";
        }
      case 10:
        throw "TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";
      case 13:
        switch (format) {
          case 5:
            return "rg11b10ufloat";
          case 11:
            throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";
          default:
            return "rg11b10ufloat";
        }
      case 14:
        switch (format) {
          case 5:
            return "rgb9e5ufloat";
          case 11:
            throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";
          default:
            return "rgb9e5ufloat";
        }
      case 8:
        throw "TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";
      case 9:
        throw "TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";
      case 11:
        switch (format) {
          case 5:
            return "rgb10a2unorm";
          case 11:
            return "rgb10a2uint";
          default:
            return "rgb10a2unorm";
        }
    }
    return useSRGBBuffer ? "rgba8unorm-srgb" : "rgba8unorm";
  }
  static GetNumChannelsFromWebGPUTextureFormat(format) {
    switch (format) {
      case "r8unorm":
      case "r8snorm":
      case "r8uint":
      case "r8sint":
      case "bc4-r-unorm":
      case "bc4-r-snorm":
      case "r16uint":
      case "r16sint":
      case "depth16unorm":
      case "r16float":
      case "r16unorm":
      case "r16snorm":
      case "r32uint":
      case "r32sint":
      case "r32float":
      case "depth32float":
      case "stencil8":
      case "depth24plus":
      case "eac-r11unorm":
      case "eac-r11snorm":
        return 1;
      case "rg8unorm":
      case "rg8snorm":
      case "rg8uint":
      case "rg8sint":
      case "depth32float-stencil8":
      case "bc5-rg-unorm":
      case "bc5-rg-snorm":
      case "rg16uint":
      case "rg16sint":
      case "rg16float":
      case "rg16unorm":
      case "rg16snorm":
      case "rg32uint":
      case "rg32sint":
      case "rg32float":
      case "depth24plus-stencil8":
      case "eac-rg11unorm":
      case "eac-rg11snorm":
        return 2;
      case "rgb9e5ufloat":
      case "rg11b10ufloat":
      case "bc6h-rgb-ufloat":
      case "bc6h-rgb-float":
      case "etc2-rgb8unorm":
      case "etc2-rgb8unorm-srgb":
        return 3;
      case "rgba8unorm":
      case "rgba8unorm-srgb":
      case "rgba8snorm":
      case "rgba8uint":
      case "rgba8sint":
      case "bgra8unorm":
      case "bgra8unorm-srgb":
      case "rgba16unorm":
      case "rgba16snorm":
      case "rgb10a2uint":
      case "rgb10a2unorm":
      case "bc7-rgba-unorm":
      case "bc7-rgba-unorm-srgb":
      case "bc3-rgba-unorm":
      case "bc3-rgba-unorm-srgb":
      case "bc2-rgba-unorm":
      case "bc2-rgba-unorm-srgb":
      case "bc1-rgba-unorm":
      case "bc1-rgba-unorm-srgb":
      case "rgba16uint":
      case "rgba16sint":
      case "rgba16float":
      case "rgba32uint":
      case "rgba32sint":
      case "rgba32float":
      case "etc2-rgb8a1unorm":
      case "etc2-rgb8a1unorm-srgb":
      case "etc2-rgba8unorm":
      case "etc2-rgba8unorm-srgb":
      case "astc-4x4-unorm":
      case "astc-4x4-unorm-srgb":
      case "astc-5x4-unorm":
      case "astc-5x4-unorm-srgb":
      case "astc-5x5-unorm":
      case "astc-5x5-unorm-srgb":
      case "astc-6x5-unorm":
      case "astc-6x5-unorm-srgb":
      case "astc-6x6-unorm":
      case "astc-6x6-unorm-srgb":
      case "astc-8x5-unorm":
      case "astc-8x5-unorm-srgb":
      case "astc-8x6-unorm":
      case "astc-8x6-unorm-srgb":
      case "astc-8x8-unorm":
      case "astc-8x8-unorm-srgb":
      case "astc-10x5-unorm":
      case "astc-10x5-unorm-srgb":
      case "astc-10x6-unorm":
      case "astc-10x6-unorm-srgb":
      case "astc-10x8-unorm":
      case "astc-10x8-unorm-srgb":
      case "astc-10x10-unorm":
      case "astc-10x10-unorm-srgb":
      case "astc-12x10-unorm":
      case "astc-12x10-unorm-srgb":
      case "astc-12x12-unorm":
      case "astc-12x12-unorm-srgb":
        return 4;
    }
    throw `Unknown format ${format}!`;
  }
  static HasStencilAspect(format) {
    switch (format) {
      case "stencil8":
      case "depth32float-stencil8":
      case "depth24plus-stencil8":
        return true;
    }
    return false;
  }
  static HasDepthAndStencilAspects(format) {
    switch (format) {
      case "depth32float-stencil8":
      case "depth24plus-stencil8":
        return true;
    }
    return false;
  }
  static GetDepthFormatOnly(format) {
    switch (format) {
      case "depth16unorm":
        return "depth16unorm";
      case "depth24plus":
        return "depth24plus";
      case "depth24plus-stencil8":
        return "depth24plus";
      case "depth32float":
        return "depth32float";
      case "depth32float-stencil8":
        return "depth32float";
    }
    return format;
  }
  static GetSample(sampleCount) {
    return sampleCount > 1 ? 4 : 1;
  }
}

// node_modules/@babylonjs/core/Engines/thinWebGPUEngine.js
init_webgpuPerfCounter();

class ThinWebGPUEngine extends AbstractEngine {
  constructor() {
    super(...arguments);
    this.dbgShowShaderCode = false;
    this.dbgSanityChecks = true;
    this.dbgVerboseLogsNumFrames = 10;
    this.dbgLogIfNotDrawWrapper = true;
    this.dbgShowEmptyEnableEffectCalls = true;
    this.dbgVerboseLogsForFirstFrames = false;
    this._currentRenderPass = null;
    this._snapshotRenderingMode = 0;
    this._timestampIndex = 0;
    this._debugStackRenderPass = [];
  }
  get enableGPUTimingMeasurements() {
    return this._timestampQuery.enable;
  }
  set enableGPUTimingMeasurements(enable) {
    if (this._timestampQuery.enable === enable) {
      return;
    }
    this.gpuTimeInFrameForMainPass = enable ? new WebGPUPerfCounter : undefined;
    this._timestampQuery.enable = enable;
  }
  _currentPassIsMainPass() {
    return this._currentRenderTarget === null;
  }
  _endCurrentRenderPass() {
    if (!this._currentRenderPass) {
      return 0;
    }
    if (this._debugStackRenderPass.length !== 0) {
      for (let i = 0;i < this._debugStackRenderPass.length; ++i) {
        this._currentRenderPass.popDebugGroup();
      }
    }
    const currentPassIndex = this._currentPassIsMainPass() ? 2 : 1;
    if (!this._snapshotRendering.endRenderPass(this._currentRenderPass) && !this.compatibilityMode) {
      this._bundleList.run(this._currentRenderPass);
      this._bundleList.reset();
    }
    this._currentRenderPass.end();
    this._timestampQuery.endPass(this._timestampIndex, this._currentRenderTarget && this._currentRenderTarget.gpuTimeInFrame ? this._currentRenderTarget.gpuTimeInFrame : this.gpuTimeInFrameForMainPass);
    this._timestampIndex += 2;
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log("frame #" + this._count + " - " + (currentPassIndex === 2 ? "main" : "render target") + " end pass" + (currentPassIndex === 1 ? " - internalTexture.uniqueId=" + this._currentRenderTarget?.texture?.uniqueId : ""));
      }
    }
    this._debugPopGroup?.(0);
    this._currentRenderPass = null;
    return currentPassIndex;
  }
  _generateMipmaps(texture, commandEncoder) {
    commandEncoder = commandEncoder ?? this._renderEncoder;
    const gpuHardwareTexture = texture._hardwareTexture;
    if (!gpuHardwareTexture) {
      return;
    }
    if (commandEncoder === this._renderEncoder) {
      this._endCurrentRenderPass();
    }
    const format = texture._hardwareTexture.format;
    const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height);
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log("frame #" + this._count + " - generate mipmaps - width=" + texture.width + ", height=" + texture.height + ", isCube=" + texture.isCube + ", command encoder=" + (commandEncoder === this._renderEncoder ? "render" : "copy"));
      }
    }
    if (texture.isCube) {
      this._textureHelper.generateCubeMipmaps(gpuHardwareTexture, format, mipmapCount, commandEncoder);
    } else {
      this._textureHelper.generateMipmaps(gpuHardwareTexture, format, mipmapCount, 0, texture.is3D, commandEncoder);
    }
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.alpha.js
ThinWebGPUEngine.prototype.setAlphaMode = function(mode, noDepthWriteChange = false) {
  if (this._alphaMode === mode && (mode === 0 && !this._alphaState.alphaBlend || mode !== 0 && this._alphaState.alphaBlend)) {
    if (!noDepthWriteChange) {
      const depthMask = mode === 0;
      if (this.depthCullingState.depthMask !== depthMask) {
        this.setDepthWrite(depthMask);
        this._cacheRenderPipeline.setDepthWriteEnabled(depthMask);
      }
    }
    return;
  }
  switch (mode) {
    case 0:
      this._alphaState.alphaBlend = false;
      break;
    case 7:
      this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 8:
      this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);
      this._alphaState.alphaBlend = true;
      break;
    case 2:
      this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 6:
      this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 1:
      this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 3:
      this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 4:
      this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 5:
      this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 9:
      this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772);
      this._alphaState.alphaBlend = true;
      break;
    case 10:
      this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771);
      this._alphaState.alphaBlend = true;
      break;
    case 11:
      this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 12:
      this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0);
      this._alphaState.alphaBlend = true;
      break;
    case 13:
      this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771);
      this._alphaState.alphaBlend = true;
      break;
    case 14:
      this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);
      this._alphaState.alphaBlend = true;
      break;
    case 15:
      this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0);
      this._alphaState.alphaBlend = true;
      break;
    case 16:
      this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1);
      this._alphaState.alphaBlend = true;
      break;
    case 17:
      this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771);
      this._alphaState.alphaBlend = true;
      break;
  }
  if (!noDepthWriteChange) {
    this.setDepthWrite(mode === 0);
    this._cacheRenderPipeline.setDepthWriteEnabled(mode === 0);
  }
  this._alphaMode = mode;
  this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);
  this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);
};
ThinWebGPUEngine.prototype.setAlphaEquation = function(equation) {
  AbstractEngine.prototype.setAlphaEquation.call(this, equation);
  this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.computeShader.js
init_logger();

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_logger();
init_math();
init_internalTexture();
init_effect();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuConstants.js
var PowerPreference;
(function(PowerPreference2) {
  PowerPreference2["LowPower"] = "low-power";
  PowerPreference2["HighPerformance"] = "high-performance";
})(PowerPreference || (PowerPreference = {}));
var FeatureName;
(function(FeatureName2) {
  FeatureName2["DepthClipControl"] = "depth-clip-control";
  FeatureName2["Depth32FloatStencil8"] = "depth32float-stencil8";
  FeatureName2["TextureCompressionBC"] = "texture-compression-bc";
  FeatureName2["TextureCompressionBCSliced3D"] = "texture-compression-bc-sliced-3d";
  FeatureName2["TextureCompressionETC2"] = "texture-compression-etc2";
  FeatureName2["TextureCompressionASTC"] = "texture-compression-astc";
  FeatureName2["TextureCompressionASTCSliced3D"] = "texture-compression-astc-sliced-3d";
  FeatureName2["TimestampQuery"] = "timestamp-query";
  FeatureName2["IndirectFirstInstance"] = "indirect-first-instance";
  FeatureName2["ShaderF16"] = "shader-f16";
  FeatureName2["RG11B10UFloatRenderable"] = "rg11b10ufloat-renderable";
  FeatureName2["BGRA8UnormStorage"] = "bgra8unorm-storage";
  FeatureName2["Float32Filterable"] = "float32-filterable";
  FeatureName2["Float32Blendable"] = "float32-blendable";
  FeatureName2["ClipDistances"] = "clip-distances";
  FeatureName2["DualSourceBlending"] = "dual-source-blending";
})(FeatureName || (FeatureName = {}));
var BufferMapState;
(function(BufferMapState2) {
  BufferMapState2["Unmapped"] = "unmapped";
  BufferMapState2["Pending"] = "pending";
  BufferMapState2["Mapped"] = "mapped";
})(BufferMapState || (BufferMapState = {}));
var BufferUsage;
(function(BufferUsage2) {
  BufferUsage2[BufferUsage2["MapRead"] = 1] = "MapRead";
  BufferUsage2[BufferUsage2["MapWrite"] = 2] = "MapWrite";
  BufferUsage2[BufferUsage2["CopySrc"] = 4] = "CopySrc";
  BufferUsage2[BufferUsage2["CopyDst"] = 8] = "CopyDst";
  BufferUsage2[BufferUsage2["Index"] = 16] = "Index";
  BufferUsage2[BufferUsage2["Vertex"] = 32] = "Vertex";
  BufferUsage2[BufferUsage2["Uniform"] = 64] = "Uniform";
  BufferUsage2[BufferUsage2["Storage"] = 128] = "Storage";
  BufferUsage2[BufferUsage2["Indirect"] = 256] = "Indirect";
  BufferUsage2[BufferUsage2["QueryResolve"] = 512] = "QueryResolve";
})(BufferUsage || (BufferUsage = {}));
var MapMode;
(function(MapMode2) {
  MapMode2[MapMode2["Read"] = 1] = "Read";
  MapMode2[MapMode2["Write"] = 2] = "Write";
})(MapMode || (MapMode = {}));
var TextureDimension;
(function(TextureDimension2) {
  TextureDimension2["E1d"] = "1d";
  TextureDimension2["E2d"] = "2d";
  TextureDimension2["E3d"] = "3d";
})(TextureDimension || (TextureDimension = {}));
var TextureUsage;
(function(TextureUsage2) {
  TextureUsage2[TextureUsage2["CopySrc"] = 1] = "CopySrc";
  TextureUsage2[TextureUsage2["CopyDst"] = 2] = "CopyDst";
  TextureUsage2[TextureUsage2["TextureBinding"] = 4] = "TextureBinding";
  TextureUsage2[TextureUsage2["StorageBinding"] = 8] = "StorageBinding";
  TextureUsage2[TextureUsage2["RenderAttachment"] = 16] = "RenderAttachment";
})(TextureUsage || (TextureUsage = {}));
var TextureViewDimension;
(function(TextureViewDimension2) {
  TextureViewDimension2["E1d"] = "1d";
  TextureViewDimension2["E2d"] = "2d";
  TextureViewDimension2["E2dArray"] = "2d-array";
  TextureViewDimension2["Cube"] = "cube";
  TextureViewDimension2["CubeArray"] = "cube-array";
  TextureViewDimension2["E3d"] = "3d";
})(TextureViewDimension || (TextureViewDimension = {}));
var TextureAspect;
(function(TextureAspect2) {
  TextureAspect2["All"] = "all";
  TextureAspect2["StencilOnly"] = "stencil-only";
  TextureAspect2["DepthOnly"] = "depth-only";
})(TextureAspect || (TextureAspect = {}));
var TextureFormat;
(function(TextureFormat2) {
  TextureFormat2["R8Unorm"] = "r8unorm";
  TextureFormat2["R8Snorm"] = "r8snorm";
  TextureFormat2["R8Uint"] = "r8uint";
  TextureFormat2["R8Sint"] = "r8sint";
  TextureFormat2["R16Uint"] = "r16uint";
  TextureFormat2["R16Sint"] = "r16sint";
  TextureFormat2["R16Float"] = "r16float";
  TextureFormat2["RG8Unorm"] = "rg8unorm";
  TextureFormat2["RG8Snorm"] = "rg8snorm";
  TextureFormat2["RG8Uint"] = "rg8uint";
  TextureFormat2["RG8Sint"] = "rg8sint";
  TextureFormat2["R16Unorm"] = "r16unorm";
  TextureFormat2["R16Snorm"] = "r16snorm";
  TextureFormat2["RG16Unorm"] = "rg16unorm";
  TextureFormat2["RG16Snorm"] = "rg16snorm";
  TextureFormat2["RGBA16Unorm"] = "rgba16unorm";
  TextureFormat2["RGBA16Snorm"] = "rgba16snorm";
  TextureFormat2["R32Uint"] = "r32uint";
  TextureFormat2["R32Sint"] = "r32sint";
  TextureFormat2["R32Float"] = "r32float";
  TextureFormat2["RG16Uint"] = "rg16uint";
  TextureFormat2["RG16Sint"] = "rg16sint";
  TextureFormat2["RG16Float"] = "rg16float";
  TextureFormat2["RGBA8Unorm"] = "rgba8unorm";
  TextureFormat2["RGBA8UnormSRGB"] = "rgba8unorm-srgb";
  TextureFormat2["RGBA8Snorm"] = "rgba8snorm";
  TextureFormat2["RGBA8Uint"] = "rgba8uint";
  TextureFormat2["RGBA8Sint"] = "rgba8sint";
  TextureFormat2["BGRA8Unorm"] = "bgra8unorm";
  TextureFormat2["BGRA8UnormSRGB"] = "bgra8unorm-srgb";
  TextureFormat2["RGB9E5UFloat"] = "rgb9e5ufloat";
  TextureFormat2["RGB10A2UINT"] = "rgb10a2uint";
  TextureFormat2["RGB10A2Unorm"] = "rgb10a2unorm";
  TextureFormat2["RG11B10UFloat"] = "rg11b10ufloat";
  TextureFormat2["RG32Uint"] = "rg32uint";
  TextureFormat2["RG32Sint"] = "rg32sint";
  TextureFormat2["RG32Float"] = "rg32float";
  TextureFormat2["RGBA16Uint"] = "rgba16uint";
  TextureFormat2["RGBA16Sint"] = "rgba16sint";
  TextureFormat2["RGBA16Float"] = "rgba16float";
  TextureFormat2["RGBA32Uint"] = "rgba32uint";
  TextureFormat2["RGBA32Sint"] = "rgba32sint";
  TextureFormat2["RGBA32Float"] = "rgba32float";
  TextureFormat2["Stencil8"] = "stencil8";
  TextureFormat2["Depth16Unorm"] = "depth16unorm";
  TextureFormat2["Depth24Plus"] = "depth24plus";
  TextureFormat2["Depth24PlusStencil8"] = "depth24plus-stencil8";
  TextureFormat2["Depth32Float"] = "depth32float";
  TextureFormat2["BC1RGBAUnorm"] = "bc1-rgba-unorm";
  TextureFormat2["BC1RGBAUnormSRGB"] = "bc1-rgba-unorm-srgb";
  TextureFormat2["BC2RGBAUnorm"] = "bc2-rgba-unorm";
  TextureFormat2["BC2RGBAUnormSRGB"] = "bc2-rgba-unorm-srgb";
  TextureFormat2["BC3RGBAUnorm"] = "bc3-rgba-unorm";
  TextureFormat2["BC3RGBAUnormSRGB"] = "bc3-rgba-unorm-srgb";
  TextureFormat2["BC4RUnorm"] = "bc4-r-unorm";
  TextureFormat2["BC4RSnorm"] = "bc4-r-snorm";
  TextureFormat2["BC5RGUnorm"] = "bc5-rg-unorm";
  TextureFormat2["BC5RGSnorm"] = "bc5-rg-snorm";
  TextureFormat2["BC6HRGBUFloat"] = "bc6h-rgb-ufloat";
  TextureFormat2["BC6HRGBFloat"] = "bc6h-rgb-float";
  TextureFormat2["BC7RGBAUnorm"] = "bc7-rgba-unorm";
  TextureFormat2["BC7RGBAUnormSRGB"] = "bc7-rgba-unorm-srgb";
  TextureFormat2["ETC2RGB8Unorm"] = "etc2-rgb8unorm";
  TextureFormat2["ETC2RGB8UnormSRGB"] = "etc2-rgb8unorm-srgb";
  TextureFormat2["ETC2RGB8A1Unorm"] = "etc2-rgb8a1unorm";
  TextureFormat2["ETC2RGB8A1UnormSRGB"] = "etc2-rgb8a1unorm-srgb";
  TextureFormat2["ETC2RGBA8Unorm"] = "etc2-rgba8unorm";
  TextureFormat2["ETC2RGBA8UnormSRGB"] = "etc2-rgba8unorm-srgb";
  TextureFormat2["EACR11Unorm"] = "eac-r11unorm";
  TextureFormat2["EACR11Snorm"] = "eac-r11snorm";
  TextureFormat2["EACRG11Unorm"] = "eac-rg11unorm";
  TextureFormat2["EACRG11Snorm"] = "eac-rg11snorm";
  TextureFormat2["ASTC4x4Unorm"] = "astc-4x4-unorm";
  TextureFormat2["ASTC4x4UnormSRGB"] = "astc-4x4-unorm-srgb";
  TextureFormat2["ASTC5x4Unorm"] = "astc-5x4-unorm";
  TextureFormat2["ASTC5x4UnormSRGB"] = "astc-5x4-unorm-srgb";
  TextureFormat2["ASTC5x5Unorm"] = "astc-5x5-unorm";
  TextureFormat2["ASTC5x5UnormSRGB"] = "astc-5x5-unorm-srgb";
  TextureFormat2["ASTC6x5Unorm"] = "astc-6x5-unorm";
  TextureFormat2["ASTC6x5UnormSRGB"] = "astc-6x5-unorm-srgb";
  TextureFormat2["ASTC6x6Unorm"] = "astc-6x6-unorm";
  TextureFormat2["ASTC6x6UnormSRGB"] = "astc-6x6-unorm-srgb";
  TextureFormat2["ASTC8x5Unorm"] = "astc-8x5-unorm";
  TextureFormat2["ASTC8x5UnormSRGB"] = "astc-8x5-unorm-srgb";
  TextureFormat2["ASTC8x6Unorm"] = "astc-8x6-unorm";
  TextureFormat2["ASTC8x6UnormSRGB"] = "astc-8x6-unorm-srgb";
  TextureFormat2["ASTC8x8Unorm"] = "astc-8x8-unorm";
  TextureFormat2["ASTC8x8UnormSRGB"] = "astc-8x8-unorm-srgb";
  TextureFormat2["ASTC10x5Unorm"] = "astc-10x5-unorm";
  TextureFormat2["ASTC10x5UnormSRGB"] = "astc-10x5-unorm-srgb";
  TextureFormat2["ASTC10x6Unorm"] = "astc-10x6-unorm";
  TextureFormat2["ASTC10x6UnormSRGB"] = "astc-10x6-unorm-srgb";
  TextureFormat2["ASTC10x8Unorm"] = "astc-10x8-unorm";
  TextureFormat2["ASTC10x8UnormSRGB"] = "astc-10x8-unorm-srgb";
  TextureFormat2["ASTC10x10Unorm"] = "astc-10x10-unorm";
  TextureFormat2["ASTC10x10UnormSRGB"] = "astc-10x10-unorm-srgb";
  TextureFormat2["ASTC12x10Unorm"] = "astc-12x10-unorm";
  TextureFormat2["ASTC12x10UnormSRGB"] = "astc-12x10-unorm-srgb";
  TextureFormat2["ASTC12x12Unorm"] = "astc-12x12-unorm";
  TextureFormat2["ASTC12x12UnormSRGB"] = "astc-12x12-unorm-srgb";
  TextureFormat2["Depth32FloatStencil8"] = "depth32float-stencil8";
})(TextureFormat || (TextureFormat = {}));
var AddressMode;
(function(AddressMode2) {
  AddressMode2["ClampToEdge"] = "clamp-to-edge";
  AddressMode2["Repeat"] = "repeat";
  AddressMode2["MirrorRepeat"] = "mirror-repeat";
})(AddressMode || (AddressMode = {}));
var FilterMode;
(function(FilterMode2) {
  FilterMode2["Nearest"] = "nearest";
  FilterMode2["Linear"] = "linear";
})(FilterMode || (FilterMode = {}));
var MipmapFilterMode;
(function(MipmapFilterMode2) {
  MipmapFilterMode2["Nearest"] = "nearest";
  MipmapFilterMode2["Linear"] = "linear";
})(MipmapFilterMode || (MipmapFilterMode = {}));
var CompareFunction;
(function(CompareFunction2) {
  CompareFunction2["Never"] = "never";
  CompareFunction2["Less"] = "less";
  CompareFunction2["Equal"] = "equal";
  CompareFunction2["LessEqual"] = "less-equal";
  CompareFunction2["Greater"] = "greater";
  CompareFunction2["NotEqual"] = "not-equal";
  CompareFunction2["GreaterEqual"] = "greater-equal";
  CompareFunction2["Always"] = "always";
})(CompareFunction || (CompareFunction = {}));
var ShaderStage;
(function(ShaderStage2) {
  ShaderStage2[ShaderStage2["Vertex"] = 1] = "Vertex";
  ShaderStage2[ShaderStage2["Fragment"] = 2] = "Fragment";
  ShaderStage2[ShaderStage2["Compute"] = 4] = "Compute";
})(ShaderStage || (ShaderStage = {}));
var BufferBindingType;
(function(BufferBindingType2) {
  BufferBindingType2["Uniform"] = "uniform";
  BufferBindingType2["Storage"] = "storage";
  BufferBindingType2["ReadOnlyStorage"] = "read-only-storage";
})(BufferBindingType || (BufferBindingType = {}));
var SamplerBindingType;
(function(SamplerBindingType2) {
  SamplerBindingType2["Filtering"] = "filtering";
  SamplerBindingType2["NonFiltering"] = "non-filtering";
  SamplerBindingType2["Comparison"] = "comparison";
})(SamplerBindingType || (SamplerBindingType = {}));
var TextureSampleType;
(function(TextureSampleType2) {
  TextureSampleType2["Float"] = "float";
  TextureSampleType2["UnfilterableFloat"] = "unfilterable-float";
  TextureSampleType2["Depth"] = "depth";
  TextureSampleType2["Sint"] = "sint";
  TextureSampleType2["Uint"] = "uint";
})(TextureSampleType || (TextureSampleType = {}));
var StorageTextureAccess;
(function(StorageTextureAccess2) {
  StorageTextureAccess2["WriteOnly"] = "write-only";
  StorageTextureAccess2["ReadOnly"] = "read-only";
  StorageTextureAccess2["ReadWrite"] = "read-write";
})(StorageTextureAccess || (StorageTextureAccess = {}));
var CompilationMessageType;
(function(CompilationMessageType2) {
  CompilationMessageType2["Error"] = "error";
  CompilationMessageType2["Warning"] = "warning";
  CompilationMessageType2["Info"] = "info";
})(CompilationMessageType || (CompilationMessageType = {}));
var PipelineErrorReason;
(function(PipelineErrorReason2) {
  PipelineErrorReason2["Validation"] = "validation";
  PipelineErrorReason2["Internal"] = "internal";
})(PipelineErrorReason || (PipelineErrorReason = {}));
var AutoLayoutMode;
(function(AutoLayoutMode2) {
  AutoLayoutMode2["Auto"] = "auto";
})(AutoLayoutMode || (AutoLayoutMode = {}));
var PrimitiveTopology;
(function(PrimitiveTopology2) {
  PrimitiveTopology2["PointList"] = "point-list";
  PrimitiveTopology2["LineList"] = "line-list";
  PrimitiveTopology2["LineStrip"] = "line-strip";
  PrimitiveTopology2["TriangleList"] = "triangle-list";
  PrimitiveTopology2["TriangleStrip"] = "triangle-strip";
})(PrimitiveTopology || (PrimitiveTopology = {}));
var FrontFace;
(function(FrontFace2) {
  FrontFace2["CCW"] = "ccw";
  FrontFace2["CW"] = "cw";
})(FrontFace || (FrontFace = {}));
var CullMode;
(function(CullMode2) {
  CullMode2["None"] = "none";
  CullMode2["Front"] = "front";
  CullMode2["Back"] = "back";
})(CullMode || (CullMode = {}));
var ColorWrite;
(function(ColorWrite2) {
  ColorWrite2[ColorWrite2["Red"] = 1] = "Red";
  ColorWrite2[ColorWrite2["Green"] = 2] = "Green";
  ColorWrite2[ColorWrite2["Blue"] = 4] = "Blue";
  ColorWrite2[ColorWrite2["Alpha"] = 8] = "Alpha";
  ColorWrite2[ColorWrite2["All"] = 15] = "All";
})(ColorWrite || (ColorWrite = {}));
var BlendFactor;
(function(BlendFactor2) {
  BlendFactor2["Zero"] = "zero";
  BlendFactor2["One"] = "one";
  BlendFactor2["Src"] = "src";
  BlendFactor2["OneMinusSrc"] = "one-minus-src";
  BlendFactor2["SrcAlpha"] = "src-alpha";
  BlendFactor2["OneMinusSrcAlpha"] = "one-minus-src-alpha";
  BlendFactor2["Dst"] = "dst";
  BlendFactor2["OneMinusDst"] = "one-minus-dst";
  BlendFactor2["DstAlpha"] = "dst-alpha";
  BlendFactor2["OneMinusDstAlpha"] = "one-minus-dst-alpha";
  BlendFactor2["SrcAlphaSaturated"] = "src-alpha-saturated";
  BlendFactor2["Constant"] = "constant";
  BlendFactor2["OneMinusConstant"] = "one-minus-constant";
  BlendFactor2["Src1"] = "src1";
  BlendFactor2["OneMinusSrc1"] = "one-minus-src1";
  BlendFactor2["Src1Alpha"] = "src1-alpha";
  BlendFactor2["OneMinusSrc1Alpha"] = "one-minus-src1-alpha";
})(BlendFactor || (BlendFactor = {}));
var BlendOperation;
(function(BlendOperation2) {
  BlendOperation2["Add"] = "add";
  BlendOperation2["Subtract"] = "subtract";
  BlendOperation2["ReverseSubtract"] = "reverse-subtract";
  BlendOperation2["Min"] = "min";
  BlendOperation2["Max"] = "max";
})(BlendOperation || (BlendOperation = {}));
var StencilOperation;
(function(StencilOperation2) {
  StencilOperation2["Keep"] = "keep";
  StencilOperation2["Zero"] = "zero";
  StencilOperation2["Replace"] = "replace";
  StencilOperation2["Invert"] = "invert";
  StencilOperation2["IncrementClamp"] = "increment-clamp";
  StencilOperation2["DecrementClamp"] = "decrement-clamp";
  StencilOperation2["IncrementWrap"] = "increment-wrap";
  StencilOperation2["DecrementWrap"] = "decrement-wrap";
})(StencilOperation || (StencilOperation = {}));
var IndexFormat;
(function(IndexFormat2) {
  IndexFormat2["Uint16"] = "uint16";
  IndexFormat2["Uint32"] = "uint32";
})(IndexFormat || (IndexFormat = {}));
var VertexFormat;
(function(VertexFormat2) {
  VertexFormat2["Uint8x2"] = "uint8x2";
  VertexFormat2["Uint8x4"] = "uint8x4";
  VertexFormat2["Sint8x2"] = "sint8x2";
  VertexFormat2["Sint8x4"] = "sint8x4";
  VertexFormat2["Unorm8x2"] = "unorm8x2";
  VertexFormat2["Unorm8x4"] = "unorm8x4";
  VertexFormat2["Snorm8x2"] = "snorm8x2";
  VertexFormat2["Snorm8x4"] = "snorm8x4";
  VertexFormat2["Uint16x2"] = "uint16x2";
  VertexFormat2["Uint16x4"] = "uint16x4";
  VertexFormat2["Sint16x2"] = "sint16x2";
  VertexFormat2["Sint16x4"] = "sint16x4";
  VertexFormat2["Unorm16x2"] = "unorm16x2";
  VertexFormat2["Unorm16x4"] = "unorm16x4";
  VertexFormat2["Snorm16x2"] = "snorm16x2";
  VertexFormat2["Snorm16x4"] = "snorm16x4";
  VertexFormat2["Float16x2"] = "float16x2";
  VertexFormat2["Float16x4"] = "float16x4";
  VertexFormat2["Float32"] = "float32";
  VertexFormat2["Float32x2"] = "float32x2";
  VertexFormat2["Float32x3"] = "float32x3";
  VertexFormat2["Float32x4"] = "float32x4";
  VertexFormat2["Uint32"] = "uint32";
  VertexFormat2["Uint32x2"] = "uint32x2";
  VertexFormat2["Uint32x3"] = "uint32x3";
  VertexFormat2["Uint32x4"] = "uint32x4";
  VertexFormat2["Sint32"] = "sint32";
  VertexFormat2["Sint32x2"] = "sint32x2";
  VertexFormat2["Sint32x3"] = "sint32x3";
  VertexFormat2["Sint32x4"] = "sint32x4";
  VertexFormat2["UNORM10x10x10x2"] = "unorm10-10-10-2";
})(VertexFormat || (VertexFormat = {}));
var VertexStepMode;
(function(VertexStepMode2) {
  VertexStepMode2["Vertex"] = "vertex";
  VertexStepMode2["Instance"] = "instance";
})(VertexStepMode || (VertexStepMode = {}));
var ComputePassTimestampLocation;
(function(ComputePassTimestampLocation2) {
  ComputePassTimestampLocation2["Beginning"] = "beginning";
  ComputePassTimestampLocation2["End"] = "end";
})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));
var RenderPassTimestampLocation;
(function(RenderPassTimestampLocation2) {
  RenderPassTimestampLocation2["Beginning"] = "beginning";
  RenderPassTimestampLocation2["End"] = "end";
})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));
var LoadOp;
(function(LoadOp2) {
  LoadOp2["Load"] = "load";
  LoadOp2["Clear"] = "clear";
})(LoadOp || (LoadOp = {}));
var StoreOp;
(function(StoreOp2) {
  StoreOp2["Store"] = "store";
  StoreOp2["Discard"] = "discard";
})(StoreOp || (StoreOp = {}));
var QueryType;
(function(QueryType2) {
  QueryType2["Occlusion"] = "occlusion";
  QueryType2["Timestamp"] = "timestamp";
})(QueryType || (QueryType = {}));
var CanvasAlphaMode;
(function(CanvasAlphaMode2) {
  CanvasAlphaMode2["Opaque"] = "opaque";
  CanvasAlphaMode2["Premultiplied"] = "premultiplied";
})(CanvasAlphaMode || (CanvasAlphaMode = {}));
var CanvasToneMappingMode;
(function(CanvasToneMappingMode2) {
  CanvasToneMappingMode2["Standard"] = "standard";
  CanvasToneMappingMode2["Extended"] = "extended";
})(CanvasToneMappingMode || (CanvasToneMappingMode = {}));
var DeviceLostReason;
(function(DeviceLostReason2) {
  DeviceLostReason2["Unknown"] = "unknown";
  DeviceLostReason2["Destroyed"] = "destroyed";
})(DeviceLostReason || (DeviceLostReason = {}));
var ErrorFilter;
(function(ErrorFilter2) {
  ErrorFilter2["Validation"] = "validation";
  ErrorFilter2["OutOfMemory"] = "out-of-memory";
  ErrorFilter2["Internal"] = "internal";
})(ErrorFilter || (ErrorFilter = {}));

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_buffer();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuPipelineContext.js
init_uniformBuffer();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessor.js
class WebGPUShaderProcessor {
  constructor() {
    this.shaderLanguage = 0;
  }
  _addUniformToLeftOverUBO(name155, uniformType, preProcessors) {
    let length = 0;
    [name155, uniformType, length] = this._getArraySize(name155, uniformType, preProcessors);
    for (let i = 0;i < this._webgpuProcessingContext.leftOverUniforms.length; i++) {
      if (this._webgpuProcessingContext.leftOverUniforms[i].name === name155) {
        return;
      }
    }
    this._webgpuProcessingContext.leftOverUniforms.push({
      name: name155,
      type: uniformType,
      length
    });
  }
  _buildLeftOverUBO() {
    if (!this._webgpuProcessingContext.leftOverUniforms.length) {
      return "";
    }
    const name155 = WebGPUShaderProcessor.LeftOvertUBOName;
    let availableUBO = this._webgpuProcessingContext.availableBuffers[name155];
    if (!availableUBO) {
      availableUBO = {
        binding: this._webgpuProcessingContext.getNextFreeUBOBinding()
      };
      this._webgpuProcessingContext.availableBuffers[name155] = availableUBO;
      this._addBufferBindingDescription(name155, availableUBO, "uniform", true);
      this._addBufferBindingDescription(name155, availableUBO, "uniform", false);
    }
    return this._generateLeftOverUBOCode(name155, availableUBO);
  }
  _collectBindingNames() {
    for (let i = 0;i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {
      const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];
      if (setDefinition === undefined) {
        this._webgpuProcessingContext.bindGroupLayoutEntries[i] = [];
        continue;
      }
      for (let j = 0;j < setDefinition.length; j++) {
        const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];
        const name155 = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;
        const nameInArrayOfTexture = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].nameInArrayOfTexture;
        if (entry) {
          if (entry.texture || entry.externalTexture || entry.storageTexture) {
            this._webgpuProcessingContext.textureNames.push(nameInArrayOfTexture);
          } else if (entry.sampler) {
            this._webgpuProcessingContext.samplerNames.push(name155);
          } else if (entry.buffer) {
            this._webgpuProcessingContext.bufferNames.push(name155);
          }
        }
      }
    }
  }
  _preCreateBindGroupEntries() {
    const bindGroupEntries = this._webgpuProcessingContext.bindGroupEntries;
    for (let i = 0;i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {
      const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];
      const entries = [];
      for (let j = 0;j < setDefinition.length; j++) {
        const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];
        if (entry.sampler || entry.texture || entry.storageTexture || entry.externalTexture) {
          entries.push({
            binding: entry.binding,
            resource: undefined
          });
        } else if (entry.buffer) {
          entries.push({
            binding: entry.binding,
            resource: {
              buffer: undefined,
              offset: 0,
              size: 0
            }
          });
        }
      }
      bindGroupEntries[i] = entries;
    }
  }
  _addTextureBindingDescription(name155, textureInfo, textureIndex, dimension, format, isVertex) {
    let { groupIndex, bindingIndex } = textureInfo.textures[textureIndex];
    if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];
    }
    if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {
      let len;
      if (dimension === null) {
        len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({
          binding: bindingIndex,
          visibility: 0,
          externalTexture: {}
        });
      } else if (format) {
        len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({
          binding: bindingIndex,
          visibility: 0,
          storageTexture: {
            access: "write-only",
            format,
            viewDimension: dimension
          }
        });
      } else {
        len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({
          binding: bindingIndex,
          visibility: 0,
          texture: {
            sampleType: textureInfo.sampleType,
            viewDimension: dimension,
            multisampled: false
          }
        });
      }
      const textureName = textureInfo.isTextureArray ? name155 + textureIndex : name155;
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name: name155, index: len - 1, nameInArrayOfTexture: textureName };
    }
    bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;
    if (isVertex) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1;
    } else {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2;
    }
  }
  _addSamplerBindingDescription(name155, samplerInfo, isVertex) {
    let { groupIndex, bindingIndex } = samplerInfo.binding;
    if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];
    }
    if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {
      const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({
        binding: bindingIndex,
        visibility: 0,
        sampler: {
          type: samplerInfo.type
        }
      });
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name: name155, index: len - 1 };
    }
    bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;
    if (isVertex) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1;
    } else {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2;
    }
  }
  _addBufferBindingDescription(name155, uniformBufferInfo, bufferType, isVertex) {
    let { groupIndex, bindingIndex } = uniformBufferInfo.binding;
    if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];
    }
    if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {
      const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({
        binding: bindingIndex,
        visibility: 0,
        buffer: {
          type: bufferType
        }
      });
      this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name: name155, index: len - 1 };
    }
    bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;
    if (isVertex) {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 1;
    } else {
      this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= 2;
    }
  }
}
WebGPUShaderProcessor.LeftOvertUBOName = "LeftOver";
WebGPUShaderProcessor.InternalsUBOName = "Internals";
WebGPUShaderProcessor.UniformSizes = {
  bool: 1,
  int: 1,
  float: 1,
  vec2: 2,
  ivec2: 2,
  uvec2: 2,
  vec3: 3,
  ivec3: 3,
  uvec3: 3,
  vec4: 4,
  ivec4: 4,
  uvec4: 4,
  mat2: 4,
  mat3: 12,
  mat4: 16,
  i32: 1,
  u32: 1,
  f32: 1,
  mat2x2: 4,
  mat3x3: 12,
  mat4x4: 16,
  mat2x2f: 4,
  mat3x3f: 12,
  mat4x4f: 16,
  vec2i: 2,
  vec3i: 3,
  vec4i: 4,
  vec2u: 2,
  vec3u: 3,
  vec4u: 4,
  vec2f: 2,
  vec3f: 3,
  vec4f: 4,
  vec2h: 1,
  vec3h: 2,
  vec4h: 2
};
WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType = {
  sampler2D: "sampler2D",
  sampler2DArray: "sampler2DArray",
  sampler2DShadow: "sampler2DShadow",
  sampler2DArrayShadow: "sampler2DArrayShadow",
  samplerCube: "samplerCube",
  sampler3D: "sampler3D"
};
WebGPUShaderProcessor._TextureTypeByWebGLSamplerType = {
  sampler2D: "texture2D",
  sampler2DArray: "texture2DArray",
  sampler2DShadow: "texture2D",
  sampler2DArrayShadow: "texture2DArray",
  samplerCube: "textureCube",
  samplerCubeArray: "textureCubeArray",
  sampler3D: "texture3D"
};
WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType = {
  textureCube: "cube",
  textureCubeArray: "cube-array",
  texture2D: "2d",
  texture2DArray: "2d-array",
  texture3D: "3d"
};
WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType = {
  sampler2DShadow: "samplerShadow",
  sampler2DArrayShadow: "samplerShadow"
};
WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType = {
  samplerShadow: true,
  samplerArrayShadow: true,
  sampler: false
};

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuPipelineContext.js
class WebGPUPipelineContext {
  get isAsync() {
    return false;
  }
  get isReady() {
    if (this.stages) {
      return true;
    }
    return false;
  }
  constructor(shaderProcessingContext, engine) {
    this.bindGroupLayouts = {};
    this._name = "unnamed";
    this.shaderProcessingContext = shaderProcessingContext;
    this._leftOverUniformsByName = {};
    this.engine = engine;
    this.vertexBufferKindToType = {};
  }
  _handlesSpectorRebuildCallback() {}
  _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {
    const engine = this.engine;
    if (engine._doNotHandleContextLost) {
      effect._fragmentSourceCode = "";
      effect._vertexSourceCode = "";
    }
    const foundSamplers = this.shaderProcessingContext.availableTextures;
    let index;
    for (index = 0;index < samplerList.length; index++) {
      const name155 = samplerList[index];
      const sampler = foundSamplers[samplerList[index]];
      if (sampler == null || sampler == undefined) {
        samplerList.splice(index, 1);
        index--;
      } else {
        samplers[name155] = index;
      }
    }
    for (const attr of engine.getAttributes(this, attributesNames)) {
      attributes.push(attr);
    }
    this.buildUniformLayout();
    const attributeNamesFromEffect = [];
    const attributeLocationsFromEffect = [];
    for (index = 0;index < attributesNames.length; index++) {
      const location2 = attributes[index];
      if (location2 >= 0) {
        attributeNamesFromEffect.push(attributesNames[index]);
        attributeLocationsFromEffect.push(location2);
      }
    }
    this.shaderProcessingContext.attributeNamesFromEffect = attributeNamesFromEffect;
    this.shaderProcessingContext.attributeLocationsFromEffect = attributeLocationsFromEffect;
  }
  buildUniformLayout() {
    if (!this.shaderProcessingContext.leftOverUniforms.length) {
      return;
    }
    this.uniformBuffer?.dispose();
    this.uniformBuffer = new UniformBuffer(this.engine, undefined, undefined, "leftOver-" + this._name);
    for (const leftOverUniform of this.shaderProcessingContext.leftOverUniforms) {
      const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1");
      const size = WebGPUShaderProcessor.UniformSizes[type];
      this.uniformBuffer.addUniform(leftOverUniform.name, size, leftOverUniform.length);
      this._leftOverUniformsByName[leftOverUniform.name] = leftOverUniform.type;
    }
    this.uniformBuffer.create();
  }
  setEngine(engine) {
    this.engine = engine;
  }
  dispose() {
    if (this.uniformBuffer) {
      this.uniformBuffer.dispose();
    }
  }
  setInt(uniformName, value) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateInt(uniformName, value);
  }
  setInt2(uniformName, x, y) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateInt2(uniformName, x, y);
  }
  setInt3(uniformName, x, y, z) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateInt3(uniformName, x, y, z);
  }
  setInt4(uniformName, x, y, z, w) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateInt4(uniformName, x, y, z, w);
  }
  setIntArray(uniformName, array) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateIntArray(uniformName, array);
  }
  setIntArray2(uniformName, array) {
    this.setIntArray(uniformName, array);
  }
  setIntArray3(uniformName, array) {
    this.setIntArray(uniformName, array);
  }
  setIntArray4(uniformName, array) {
    this.setIntArray(uniformName, array);
  }
  setUInt(uniformName, value) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateUInt(uniformName, value);
  }
  setUInt2(uniformName, x, y) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateUInt2(uniformName, x, y);
  }
  setUInt3(uniformName, x, y, z) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateUInt3(uniformName, x, y, z);
  }
  setUInt4(uniformName, x, y, z, w) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateUInt4(uniformName, x, y, z, w);
  }
  setUIntArray(uniformName, array) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateUIntArray(uniformName, array);
  }
  setUIntArray2(uniformName, array) {
    this.setUIntArray(uniformName, array);
  }
  setUIntArray3(uniformName, array) {
    this.setUIntArray(uniformName, array);
  }
  setUIntArray4(uniformName, array) {
    this.setUIntArray(uniformName, array);
  }
  setArray(uniformName, array) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateArray(uniformName, array);
  }
  setArray2(uniformName, array) {
    this.setArray(uniformName, array);
  }
  setArray3(uniformName, array) {
    this.setArray(uniformName, array);
  }
  setArray4(uniformName, array) {
    this.setArray(uniformName, array);
  }
  setMatrices(uniformName, matrices) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateMatrices(uniformName, matrices);
  }
  setMatrix(uniformName, matrix) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateMatrix(uniformName, matrix);
  }
  setMatrix3x3(uniformName, matrix) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateMatrix3x3(uniformName, matrix);
  }
  setMatrix2x2(uniformName, matrix) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateMatrix2x2(uniformName, matrix);
  }
  setFloat(uniformName, value) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateFloat(uniformName, value);
  }
  setVector2(uniformName, vector2) {
    this.setFloat2(uniformName, vector2.x, vector2.y);
  }
  setFloat2(uniformName, x, y) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateFloat2(uniformName, x, y);
  }
  setVector3(uniformName, vector3) {
    this.setFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  }
  setFloat3(uniformName, x, y, z) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateFloat3(uniformName, x, y, z);
  }
  setVector4(uniformName, vector4) {
    this.setFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  }
  setQuaternion(uniformName, quaternion) {
    this.setFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  }
  setFloat4(uniformName, x, y, z, w) {
    if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {
      return;
    }
    this.uniformBuffer.updateFloat4(uniformName, x, y, z, w);
  }
  setColor3(uniformName, color3) {
    this.setFloat3(uniformName, color3.r, color3.g, color3.b);
  }
  setColor4(uniformName, color3, alpha) {
    this.setFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  }
  setDirectColor4(uniformName, color4) {
    this.setFloat4(uniformName, color4.r, color4.g, color4.b, color4.a);
  }
  _getVertexShaderCode() {
    return this.sources?.vertex;
  }
  _getFragmentShaderCode() {
    return this.sources?.fragment;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessingContext.js
var _maxGroups = 4;
var _maxBindingsPerGroup = 1 << 16;
var _typeToLocationSize = {
  mat2: 2,
  mat3: 3,
  mat4: 4,
  mat2x2: 2,
  mat3x3: 3,
  mat4x4: 4
};

class WebGPUShaderProcessingContext {
  static get KnownUBOs() {
    return WebGPUShaderProcessingContext._SimplifiedKnownBindings ? WebGPUShaderProcessingContext._SimplifiedKnownUBOs : WebGPUShaderProcessingContext._KnownUBOs;
  }
  constructor(shaderLanguage, pureMode = false) {
    this.vertexBufferKindToNumberOfComponents = {};
    this.shaderLanguage = shaderLanguage;
    this._attributeNextLocation = 0;
    this._varyingNextLocation = 0;
    this.freeGroupIndex = 0;
    this.freeBindingIndex = 0;
    this.availableVaryings = {};
    this.availableAttributes = {};
    this.availableBuffers = {};
    this.availableTextures = {};
    this.availableSamplers = {};
    this.orderedAttributes = [];
    this.bindGroupLayoutEntries = [];
    this.bindGroupLayoutEntryInfo = [];
    this.bindGroupEntries = [];
    this.bufferNames = [];
    this.textureNames = [];
    this.samplerNames = [];
    this.leftOverUniforms = [];
    if (!pureMode) {
      this._findStartingGroupBinding();
    }
  }
  _findStartingGroupBinding() {
    const knownUBOs = WebGPUShaderProcessingContext.KnownUBOs;
    const groups = [];
    for (const name155 in knownUBOs) {
      const binding = knownUBOs[name155].binding;
      if (binding.groupIndex === -1) {
        continue;
      }
      if (groups[binding.groupIndex] === undefined) {
        groups[binding.groupIndex] = binding.bindingIndex;
      } else {
        groups[binding.groupIndex] = Math.max(groups[binding.groupIndex], binding.bindingIndex);
      }
    }
    this.freeGroupIndex = groups.length - 1;
    if (this.freeGroupIndex === 0) {
      this.freeGroupIndex++;
      this.freeBindingIndex = 0;
    } else {
      this.freeBindingIndex = groups[groups.length - 1] + 1;
    }
  }
  getAttributeNextLocation(dataType, arrayLength = 0) {
    const index = this._attributeNextLocation;
    this._attributeNextLocation += (_typeToLocationSize[dataType] ?? 1) * (arrayLength || 1);
    return index;
  }
  getVaryingNextLocation(dataType, arrayLength = 0) {
    const index = this._varyingNextLocation;
    this._varyingNextLocation += (_typeToLocationSize[dataType] ?? 1) * (arrayLength || 1);
    return index;
  }
  getNextFreeUBOBinding() {
    return this._getNextFreeBinding(1);
  }
  _getNextFreeBinding(bindingCount) {
    if (this.freeBindingIndex > _maxBindingsPerGroup - bindingCount) {
      this.freeGroupIndex++;
      this.freeBindingIndex = 0;
    }
    if (this.freeGroupIndex === _maxGroups) {
      throw "Too many textures or UBOs have been declared and it is not supported in WebGPU.";
    }
    const returnValue = {
      groupIndex: this.freeGroupIndex,
      bindingIndex: this.freeBindingIndex
    };
    this.freeBindingIndex += bindingCount;
    return returnValue;
  }
}
WebGPUShaderProcessingContext._SimplifiedKnownBindings = true;
WebGPUShaderProcessingContext._SimplifiedKnownUBOs = {
  Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },
  Light0: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light1: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light2: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light3: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light4: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light5: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light6: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light7: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light8: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light9: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light10: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light11: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light12: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light13: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light14: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light15: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light16: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light17: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light18: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light19: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light20: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light21: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light22: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light23: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light24: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light25: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light26: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light27: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light28: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light29: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light30: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Light31: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Material: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Mesh: { binding: { groupIndex: -1, bindingIndex: -1 } },
  Internals: { binding: { groupIndex: -1, bindingIndex: -1 } }
};
WebGPUShaderProcessingContext._KnownUBOs = {
  Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },
  Light0: { binding: { groupIndex: 1, bindingIndex: 0 } },
  Light1: { binding: { groupIndex: 1, bindingIndex: 1 } },
  Light2: { binding: { groupIndex: 1, bindingIndex: 2 } },
  Light3: { binding: { groupIndex: 1, bindingIndex: 3 } },
  Light4: { binding: { groupIndex: 1, bindingIndex: 4 } },
  Light5: { binding: { groupIndex: 1, bindingIndex: 5 } },
  Light6: { binding: { groupIndex: 1, bindingIndex: 6 } },
  Light7: { binding: { groupIndex: 1, bindingIndex: 7 } },
  Light8: { binding: { groupIndex: 1, bindingIndex: 8 } },
  Light9: { binding: { groupIndex: 1, bindingIndex: 9 } },
  Light10: { binding: { groupIndex: 1, bindingIndex: 10 } },
  Light11: { binding: { groupIndex: 1, bindingIndex: 11 } },
  Light12: { binding: { groupIndex: 1, bindingIndex: 12 } },
  Light13: { binding: { groupIndex: 1, bindingIndex: 13 } },
  Light14: { binding: { groupIndex: 1, bindingIndex: 14 } },
  Light15: { binding: { groupIndex: 1, bindingIndex: 15 } },
  Light16: { binding: { groupIndex: 1, bindingIndex: 16 } },
  Light17: { binding: { groupIndex: 1, bindingIndex: 17 } },
  Light18: { binding: { groupIndex: 1, bindingIndex: 18 } },
  Light19: { binding: { groupIndex: 1, bindingIndex: 19 } },
  Light20: { binding: { groupIndex: 1, bindingIndex: 20 } },
  Light21: { binding: { groupIndex: 1, bindingIndex: 21 } },
  Light22: { binding: { groupIndex: 1, bindingIndex: 22 } },
  Light23: { binding: { groupIndex: 1, bindingIndex: 23 } },
  Light24: { binding: { groupIndex: 1, bindingIndex: 24 } },
  Light25: { binding: { groupIndex: 1, bindingIndex: 25 } },
  Light26: { binding: { groupIndex: 1, bindingIndex: 26 } },
  Light27: { binding: { groupIndex: 1, bindingIndex: 27 } },
  Light28: { binding: { groupIndex: 1, bindingIndex: 28 } },
  Light29: { binding: { groupIndex: 1, bindingIndex: 29 } },
  Light30: { binding: { groupIndex: 1, bindingIndex: 30 } },
  Light31: { binding: { groupIndex: 1, bindingIndex: 31 } },
  Material: { binding: { groupIndex: 2, bindingIndex: 0 } },
  Mesh: { binding: { groupIndex: 2, bindingIndex: 1 } },
  Internals: { binding: { groupIndex: 2, bindingIndex: 2 } }
};

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsGLSL.js
init_logger();
class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor {
  constructor() {
    super(...arguments);
    this._missingVaryings = [];
    this._textureArrayProcessing = [];
    this._vertexIsGLES3 = false;
    this._fragmentIsGLES3 = false;
    this.shaderLanguage = 0;
    this.parseGLES3 = true;
  }
  _getArraySize(name155, type, preProcessors) {
    let length = 0;
    const startArray = name155.indexOf("[");
    const endArray = name155.indexOf("]");
    if (startArray > 0 && endArray > 0) {
      const lengthInString = name155.substring(startArray + 1, endArray);
      length = +lengthInString;
      if (isNaN(length)) {
        length = +preProcessors[lengthInString.trim()];
      }
      name155 = name155.substring(0, startArray);
    }
    return [name155, type, length];
  }
  initializeShaders(processingContext) {
    this._webgpuProcessingContext = processingContext;
    this._missingVaryings.length = 0;
    this._textureArrayProcessing.length = 0;
    this.attributeKeywordName = undefined;
    this.varyingVertexKeywordName = undefined;
    this.varyingFragmentKeywordName = undefined;
  }
  preProcessShaderCode(code, isFragment) {
    const ubDeclaration = `// Internals UBO
uniform ${WebGPUShaderProcessor.InternalsUBOName} {
float yFactor_;
float textureOutputHeight_;
};
`;
    const alreadyInjected = code.indexOf("// Internals UBO") !== -1;
    if (isFragment) {
      this._fragmentIsGLES3 = code.indexOf("#version 3") !== -1;
      if (this._fragmentIsGLES3) {
        this.varyingFragmentKeywordName = "in";
      }
      return alreadyInjected ? code : ubDeclaration + `##INJECTCODE##
` + code;
    }
    this._vertexIsGLES3 = code.indexOf("#version 3") !== -1;
    if (this._vertexIsGLES3) {
      this.attributeKeywordName = "in";
      this.varyingVertexKeywordName = "out";
    }
    return alreadyInjected ? code : ubDeclaration + code;
  }
  varyingCheck(varying, isFragment) {
    const outRegex = /(flat\s)?\s*\bout\b/;
    const inRegex = /(flat\s)?\s*\bin\b/;
    const varyingRegex3 = /(flat\s)?\s*\bvarying\b/;
    const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex3;
    return regex.test(varying);
  }
  varyingProcessor(varying, isFragment, preProcessors) {
    this._preProcessors = preProcessors;
    const outRegex = /\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm;
    const inRegex = /\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm;
    const varyingRegex3 = /\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm;
    const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex3;
    const match = regex.exec(varying);
    if (match !== null) {
      const interpolationQualifier = match[1] ?? "";
      const varyingType = match[2];
      const name155 = match[3];
      let location2;
      if (isFragment) {
        location2 = this._webgpuProcessingContext.availableVaryings[name155];
        this._missingVaryings[location2] = "";
        if (location2 === undefined) {
          Logger.Warn(`Invalid fragment shader: The varying named "${name155}" is not declared in the vertex shader! This declaration will be ignored.`);
        }
      } else {
        location2 = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name155, varyingType, preProcessors)[2]);
        this._webgpuProcessingContext.availableVaryings[name155] = location2;
        this._missingVaryings[location2] = `layout(location = ${location2}) ${interpolationQualifier} in ${varyingType} ${name155};`;
      }
      varying = varying.replace(match[0], location2 === undefined ? "" : `layout(location = ${location2}) ${interpolationQualifier} ${isFragment ? "in" : "out"} ${varyingType} ${name155};`);
    }
    return varying;
  }
  attributeProcessor(attribute, preProcessors) {
    this._preProcessors = preProcessors;
    const inRegex = /\s*in\s+(\S+)\s+(\S+)\s*;/gm;
    const attribRegex = /\s*attribute\s+(\S+)\s+(\S+)\s*;/gm;
    const regex = this._vertexIsGLES3 ? inRegex : attribRegex;
    const match = regex.exec(attribute);
    if (match !== null) {
      const attributeType = match[1];
      const name155 = match[2];
      const location2 = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name155, attributeType, preProcessors)[2]);
      this._webgpuProcessingContext.availableAttributes[name155] = location2;
      this._webgpuProcessingContext.orderedAttributes[location2] = name155;
      const numComponents = this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[name155];
      if (numComponents !== undefined) {
        const newType = numComponents < 0 ? numComponents === -1 ? "int" : "ivec" + -numComponents : numComponents === 1 ? "uint" : "uvec" + numComponents;
        const newName = `_int_${name155}_`;
        attribute = attribute.replace(match[0], `layout(location = ${location2}) in ${newType} ${newName}; ${attributeType} ${name155} = ${attributeType}(${newName});`);
      } else {
        attribute = attribute.replace(match[0], `layout(location = ${location2}) in ${attributeType} ${name155};`);
      }
    }
    return attribute;
  }
  uniformProcessor(uniform, isFragment, preProcessors) {
    this._preProcessors = preProcessors;
    const uniformRegex = /\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm;
    const match = uniformRegex.exec(uniform);
    if (match !== null) {
      let uniformType = match[1];
      let name155 = match[2];
      if (uniformType.indexOf("sampler") === 0 || uniformType.indexOf("sampler") === 1) {
        let arraySize = 0;
        [name155, uniformType, arraySize] = this._getArraySize(name155, uniformType, preProcessors);
        let textureInfo = this._webgpuProcessingContext.availableTextures[name155];
        if (!textureInfo) {
          textureInfo = {
            autoBindSampler: true,
            isTextureArray: arraySize > 0,
            isStorageTexture: false,
            textures: [],
            sampleType: "float"
          };
          for (let i = 0;i < (arraySize || 1); ++i) {
            textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());
          }
        }
        const samplerType = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[uniformType] ?? "sampler";
        const isComparisonSampler = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[samplerType];
        const samplerBindingType = isComparisonSampler ? "comparison" : "filtering";
        const samplerName = name155 + `Sampler`;
        let samplerInfo = this._webgpuProcessingContext.availableSamplers[samplerName];
        if (!samplerInfo) {
          samplerInfo = {
            binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),
            type: samplerBindingType
          };
        }
        const componentType = uniformType.charAt(0) === "u" ? "u" : uniformType.charAt(0) === "i" ? "i" : "";
        if (componentType) {
          uniformType = uniformType.substring(1);
        }
        const sampleType = isComparisonSampler ? "depth" : componentType === "u" ? "uint" : componentType === "i" ? "sint" : "float";
        textureInfo.sampleType = sampleType;
        const isTextureArray = arraySize > 0;
        const samplerGroupIndex = samplerInfo.binding.groupIndex;
        const samplerBindingIndex = samplerInfo.binding.bindingIndex;
        const samplerFunction = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[uniformType];
        const textureType = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[uniformType];
        const textureDimension = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[textureType];
        if (!isTextureArray) {
          arraySize = 1;
          uniform = `layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${samplerType} ${samplerName};
                        layout(set = ${textureInfo.textures[0].groupIndex}, binding = ${textureInfo.textures[0].bindingIndex}) uniform ${componentType}${textureType} ${name155}Texture;
                        #define ${name155} ${componentType}${samplerFunction}(${name155}Texture, ${samplerName})`;
        } else {
          const layouts = [];
          layouts.push(`layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};`);
          uniform = `
`;
          for (let i = 0;i < arraySize; ++i) {
            const textureSetIndex = textureInfo.textures[i].groupIndex;
            const textureBindingIndex = textureInfo.textures[i].bindingIndex;
            layouts.push(`layout(set = ${textureSetIndex}, binding = ${textureBindingIndex}) uniform ${textureType} ${name155}Texture${i};`);
            uniform += `${i > 0 ? `
` : ""}#define ${name155}${i} ${componentType}${samplerFunction}(${name155}Texture${i}, ${samplerName})`;
          }
          uniform = layouts.join(`
`) + uniform;
          this._textureArrayProcessing.push(name155);
        }
        this._webgpuProcessingContext.availableTextures[name155] = textureInfo;
        this._webgpuProcessingContext.availableSamplers[samplerName] = samplerInfo;
        this._addSamplerBindingDescription(samplerName, samplerInfo, !isFragment);
        for (let i = 0;i < arraySize; ++i) {
          this._addTextureBindingDescription(name155, textureInfo, i, textureDimension, null, !isFragment);
        }
      } else {
        this._addUniformToLeftOverUBO(name155, uniformType, preProcessors);
        uniform = "";
      }
    }
    return uniform;
  }
  uniformBufferProcessor(uniformBuffer, isFragment) {
    const uboRegex = /uniform\s+(\w+)/gm;
    const match = uboRegex.exec(uniformBuffer);
    if (match !== null) {
      const name155 = match[1];
      let uniformBufferInfo = this._webgpuProcessingContext.availableBuffers[name155];
      if (!uniformBufferInfo) {
        const knownUBO = WebGPUShaderProcessingContext.KnownUBOs[name155];
        let binding;
        if (knownUBO && knownUBO.binding.groupIndex !== -1) {
          binding = knownUBO.binding;
        } else {
          binding = this._webgpuProcessingContext.getNextFreeUBOBinding();
        }
        uniformBufferInfo = { binding };
        this._webgpuProcessingContext.availableBuffers[name155] = uniformBufferInfo;
      }
      this._addBufferBindingDescription(name155, uniformBufferInfo, "uniform", !isFragment);
      uniformBuffer = uniformBuffer.replace("uniform", `layout(set = ${uniformBufferInfo.binding.groupIndex}, binding = ${uniformBufferInfo.binding.bindingIndex}) uniform`);
    }
    return uniformBuffer;
  }
  postProcessor(code, defines, isFragment, _processingContext, _parameters) {
    const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
    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 hasFragCoord = code.indexOf("gl_FragCoord") >= 0;
      const fragCoordCode = `
                glFragCoord_ = gl_FragCoord;
                if (yFactor_ == 1.) {
                    glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;
                }
            `;
      const injectCode = hasFragCoord ? `vec4 glFragCoord_;
` : "";
      const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1;
      code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
      code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
      code = code.replace(/textureCube\s*\(/g, "texture(");
      code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
      code = code.replace(/gl_FragColor/g, "glFragColor");
      code = code.replace(/gl_FragData/g, "glFragData");
      code = code.replace(/gl_FragCoord/g, "glFragCoord_");
      if (!this._fragmentIsGLES3) {
        code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : `layout(location = 0) out vec4 glFragColor;
`) + "void main(");
      } else {
        const match = /^\s*out\s+\S+\s+\S+\s*;/gm.exec(code);
        if (match !== null) {
          code = code.substring(0, match.index) + "layout(location = 0) " + code.substring(match.index);
        }
      }
      code = code.replace(/dFdy/g, "(-yFactor_)*dFdy");
      code = code.replace("##INJECTCODE##", injectCode);
      if (hasFragCoord) {
        code = InjectStartingAndEndingCode(code, "void main", fragCoordCode);
      }
    } else {
      code = code.replace(/gl_InstanceID/g, "gl_InstanceIndex");
      code = code.replace(/gl_VertexID/g, "gl_VertexIndex");
      const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
      if (hasMultiviewExtension) {
        return `#extension GL_OVR_multiview2 : require
layout (num_views = 2) in;
` + code;
      }
    }
    if (!isFragment) {
      const lastClosingCurly = code.lastIndexOf("}");
      code = code.substring(0, lastClosingCurly);
      code += `gl_Position.y *= yFactor_;
`;
      code += "}";
    }
    return code;
  }
  _applyTextureArrayProcessing(code, name155) {
    const regex = new RegExp(name155 + "\\s*\\[(.+)?\\]", "gm");
    let match = regex.exec(code);
    while (match !== null) {
      const index = match[1];
      let iindex = +index;
      if (this._preProcessors && isNaN(iindex)) {
        iindex = +this._preProcessors[index.trim()];
      }
      code = code.replace(match[0], name155 + iindex);
      match = regex.exec(code);
    }
    return code;
  }
  _generateLeftOverUBOCode(name155, uniformBufferDescription) {
    let ubo = `layout(set = ${uniformBufferDescription.binding.groupIndex}, binding = ${uniformBufferDescription.binding.bindingIndex}) uniform ${name155} {
    `;
    for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {
      if (leftOverUniform.length > 0) {
        ubo += `    ${leftOverUniform.type} ${leftOverUniform.name}[${leftOverUniform.length}];
`;
      } else {
        ubo += `    ${leftOverUniform.type} ${leftOverUniform.name};
`;
      }
    }
    ubo += `};

`;
    return ubo;
  }
  finalizeShaders(vertexCode, fragmentCode) {
    for (let i = 0;i < this._textureArrayProcessing.length; ++i) {
      const name155 = this._textureArrayProcessing[i];
      vertexCode = this._applyTextureArrayProcessing(vertexCode, name155);
      fragmentCode = this._applyTextureArrayProcessing(fragmentCode, name155);
    }
    for (let i = 0;i < this._missingVaryings.length; ++i) {
      const decl = this._missingVaryings[i];
      if (decl && decl.length > 0) {
        fragmentCode = decl + `
` + fragmentCode;
      }
    }
    const leftOverUBO = this._buildLeftOverUBO();
    vertexCode = leftOverUBO + vertexCode;
    fragmentCode = leftOverUBO + fragmentCode;
    this._collectBindingNames();
    this._preCreateBindGroupEntries();
    this._preProcessors = null;
    this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents = {};
    return { vertexCode, fragmentCode };
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsWGSL.js
init_logger();
init_bakedVertexAnimationDeclaration();
init_bakedVertexAnimation();
init_instancesDeclaration();
init_instancesVertex();
init_helperFunctions();
init_fresnelFunction();
init_meshUboDeclaration();
init_sceneUboDeclaration();
init_decalFragment();
var builtInName_frag_depth = "fragmentOutputs.fragDepth";
var leftOverVarName = "uniforms";
var internalsVarName = "internals";
var gpuTextureViewDimensionByWebGPUTextureFunction = {
  texture_1d: "1d",
  texture_2d: "2d",
  texture_2d_array: "2d-array",
  texture_3d: "3d",
  texture_cube: "cube",
  texture_cube_array: "cube-array",
  texture_multisampled_2d: "2d",
  texture_depth_2d: "2d",
  texture_depth_2d_array: "2d-array",
  texture_depth_cube: "cube",
  texture_depth_cube_array: "cube-array",
  texture_depth_multisampled_2d: "2d",
  texture_storage_1d: "1d",
  texture_storage_2d: "2d",
  texture_storage_2d_array: "2d-array",
  texture_storage_3d: "3d",
  texture_external: null
};

class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor {
  constructor() {
    super(...arguments);
    this.shaderLanguage = 1;
    this.uniformRegexp = /uniform\s+(\w+)\s*:\s*(.+)\s*;/;
    this.textureRegexp = /var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/;
    this.noPrecision = true;
    this.pureMode = false;
  }
  preProcessor(code, defines, preProcessors, isFragment, processingContext) {
    for (const key in preProcessors) {
      if (key === "__VERSION__") {
        continue;
      }
      const value = preProcessors[key];
      if (!isNaN(parseInt(value)) || !isNaN(parseFloat(value))) {
        code = `const ${key} = ${value};
` + code;
      }
    }
    return code;
  }
  _getArraySize(name155, uniformType, preProcessors) {
    let length = 0;
    const endArray = uniformType.lastIndexOf(">");
    if (uniformType.indexOf("array") >= 0 && endArray > 0) {
      let startArray = endArray;
      while (startArray > 0 && uniformType.charAt(startArray) !== " " && uniformType.charAt(startArray) !== ",") {
        startArray--;
      }
      const lengthInString = uniformType.substring(startArray + 1, endArray);
      length = +lengthInString;
      if (isNaN(length)) {
        length = +preProcessors[lengthInString.trim()];
      }
      while (startArray > 0 && (uniformType.charAt(startArray) === " " || uniformType.charAt(startArray) === ",")) {
        startArray--;
      }
      uniformType = uniformType.substring(uniformType.indexOf("<") + 1, startArray + 1);
    }
    return [name155, uniformType, length];
  }
  initializeShaders(processingContext) {
    this._webgpuProcessingContext = processingContext;
    this._attributesInputWGSL = [];
    this._attributesWGSL = [];
    this._attributesConversionCodeWGSL = [];
    this._hasNonFloatAttribute = false;
    this._varyingsWGSL = [];
    this._varyingNamesWGSL = [];
    this._stridedUniformArrays = [];
  }
  preProcessShaderCode(code) {
    const ubDeclaration = this.pureMode ? "" : `struct ${WebGPUShaderProcessor.InternalsUBOName} {
  yFactor_: f32,
  textureOutputHeight_: f32,
};
var<uniform> ${internalsVarName} : ${WebGPUShaderProcessor.InternalsUBOName};
`;
    const alreadyInjected = code.indexOf(ubDeclaration) !== -1;
    return alreadyInjected ? code : ubDeclaration + RemoveComments(code);
  }
  varyingCheck(varying) {
    const regex = /(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/;
    return regex.test(varying);
  }
  varyingProcessor(varying, isFragment, preProcessors) {
    const varyingRegex3 = /\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm;
    const match = varyingRegex3.exec(varying);
    if (match !== null) {
      const interpolationType = match[1] ?? "perspective";
      const interpolationSampling = match[2] ?? "center";
      const varyingType = match[4];
      const name155 = match[3];
      const interpolation = interpolationType === "flat" ? `@interpolate(${interpolationType})` : `@interpolate(${interpolationType}, ${interpolationSampling})`;
      let location2;
      if (isFragment) {
        location2 = this._webgpuProcessingContext.availableVaryings[name155];
        if (location2 === undefined) {
          Logger.Warn(`Invalid fragment shader: The varying named "${name155}" is not declared in the vertex shader! This declaration will be ignored.`);
        }
      } else {
        location2 = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name155, varyingType, preProcessors)[2]);
        this._webgpuProcessingContext.availableVaryings[name155] = location2;
        this._varyingsWGSL.push(`  @location(${location2}) ${interpolation} ${name155} : ${varyingType},`);
        this._varyingNamesWGSL.push(name155);
      }
      varying = "";
    }
    return varying;
  }
  attributeProcessor(attribute, preProcessors) {
    const attribRegex = /\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm;
    const match = attribRegex.exec(attribute);
    if (match !== null) {
      const attributeType = match[2];
      const name155 = match[1];
      const location2 = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name155, attributeType, preProcessors)[2]);
      this._webgpuProcessingContext.availableAttributes[name155] = location2;
      this._webgpuProcessingContext.orderedAttributes[location2] = name155;
      const numComponents = this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[name155];
      if (numComponents !== undefined) {
        const newType = numComponents < 0 ? numComponents === -1 ? "i32" : "vec" + -numComponents + "<i32>" : numComponents === 1 ? "u32" : "vec" + numComponents + "<u32>";
        const newName = `_int_${name155}_`;
        this._attributesInputWGSL.push(`@location(${location2}) ${newName} : ${newType},`);
        this._attributesWGSL.push(`${name155} : ${attributeType},`);
        this._attributesConversionCodeWGSL.push(`vertexInputs.${name155} = ${attributeType}(vertexInputs_.${newName});`);
        this._hasNonFloatAttribute = true;
      } else {
        this._attributesInputWGSL.push(`@location(${location2}) ${name155} : ${attributeType},`);
        this._attributesWGSL.push(`${name155} : ${attributeType},`);
        this._attributesConversionCodeWGSL.push(`vertexInputs.${name155} = vertexInputs_.${name155};`);
      }
      attribute = "";
    }
    return attribute;
  }
  uniformProcessor(uniform, isFragment, preProcessors) {
    const match = this.uniformRegexp.exec(uniform);
    if (match !== null) {
      const uniformType = match[2];
      const name155 = match[1];
      this._addUniformToLeftOverUBO(name155, uniformType, preProcessors);
      uniform = "";
    }
    return uniform;
  }
  textureProcessor(texture, isFragment, preProcessors) {
    const match = this.textureRegexp.exec(texture);
    if (match !== null) {
      const name155 = match[1];
      const type = match[2];
      const isArrayOfTexture = !!match[3];
      const textureFunc = match[4];
      const isStorageTexture = textureFunc.indexOf("storage") > 0;
      const componentType = match[6];
      const storageTextureFormat = isStorageTexture ? componentType.substring(0, componentType.indexOf(",")).trim() : null;
      let arraySize = isArrayOfTexture ? this._getArraySize(name155, type, preProcessors)[2] : 0;
      let textureInfo = this._webgpuProcessingContext.availableTextures[name155];
      if (!textureInfo) {
        textureInfo = {
          isTextureArray: arraySize > 0,
          isStorageTexture,
          textures: [],
          sampleType: "float"
        };
        arraySize = arraySize || 1;
        for (let i = 0;i < arraySize; ++i) {
          textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());
        }
      } else {
        arraySize = textureInfo.textures.length;
      }
      this._webgpuProcessingContext.availableTextures[name155] = textureInfo;
      const isDepthTexture = textureFunc.indexOf("depth") > 0;
      const textureDimension = gpuTextureViewDimensionByWebGPUTextureFunction[textureFunc];
      const sampleType = isDepthTexture ? "depth" : componentType === "u32" ? "uint" : componentType === "i32" ? "sint" : "float";
      textureInfo.sampleType = sampleType;
      if (textureDimension === undefined) {
        throw `Can't get the texture dimension corresponding to the texture function "${textureFunc}"!`;
      }
      for (let i = 0;i < arraySize; ++i) {
        const { groupIndex, bindingIndex } = textureInfo.textures[i];
        if (i === 0) {
          texture = `@group(${groupIndex}) @binding(${bindingIndex}) ${texture}`;
        }
        this._addTextureBindingDescription(name155, textureInfo, i, textureDimension, storageTextureFormat, !isFragment);
      }
    }
    return texture;
  }
  postProcessor(code) {
    const definePattern = /#define (.+?) (.+?)$/gm;
    let match;
    while ((match = definePattern.exec(code)) !== null) {
      code = code.replace(new RegExp(match[1], "g"), match[2]);
    }
    return code;
  }
  finalizeShaders(vertexCode, fragmentCode) {
    const fragCoordCode = fragmentCode.indexOf("fragmentInputs.position") >= 0 && !this.pureMode ? `
            if (internals.yFactor_ == 1.) {
                fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;
            }
        ` : "";
    vertexCode = this._processSamplers(vertexCode, true);
    fragmentCode = this._processSamplers(fragmentCode, false);
    vertexCode = this._processCustomBuffers(vertexCode, true);
    fragmentCode = this._processCustomBuffers(fragmentCode, false);
    const leftOverUBO = this._buildLeftOverUBO();
    vertexCode = leftOverUBO + vertexCode;
    fragmentCode = leftOverUBO + fragmentCode;
    vertexCode = vertexCode.replace(/#define (\w+)\s+(\d+\.?\d*)/g, "const $1 = $2;");
    vertexCode = vertexCode.replace(/#define /g, "//#define ");
    vertexCode = this._processStridedUniformArrays(vertexCode);
    let vertexInputs = `struct VertexInputs {
  @builtin(vertex_index) vertexIndex : u32,
  @builtin(instance_index) instanceIndex : u32,
`;
    if (this._attributesInputWGSL.length > 0) {
      vertexInputs += this._attributesInputWGSL.join(`
`);
    }
    vertexInputs += `
};
var<private> vertexInputs` + (this._hasNonFloatAttribute ? "_" : "") + ` : VertexInputs;
`;
    if (this._hasNonFloatAttribute) {
      vertexInputs += `struct VertexInputs_ {
  vertexIndex : u32, instanceIndex : u32,
`;
      vertexInputs += this._attributesWGSL.join(`
`);
      vertexInputs += `
};
var<private> vertexInputs : VertexInputs_;
`;
    }
    let vertexOutputs = `struct FragmentInputs {
  @builtin(position) position : vec4<f32>,
`;
    if (this._varyingsWGSL.length > 0) {
      vertexOutputs += this._varyingsWGSL.join(`
`);
    }
    vertexOutputs += `
};
var<private> vertexOutputs : FragmentInputs;
`;
    vertexCode = vertexInputs + vertexOutputs + vertexCode;
    let vertexMainStartingCode = `
  vertexInputs${this._hasNonFloatAttribute ? "_" : ""} = input;
`;
    if (this._hasNonFloatAttribute) {
      vertexMainStartingCode += `vertexInputs.vertexIndex = vertexInputs_.vertexIndex;
vertexInputs.instanceIndex = vertexInputs_.instanceIndex;
`;
      vertexMainStartingCode += this._attributesConversionCodeWGSL.join(`
`);
      vertexMainStartingCode += `
`;
    }
    const vertexMainEndingCode = this.pureMode ? `  return vertexOutputs;` : `  vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;
  return vertexOutputs;`;
    let needDiagnosticOff = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) !== -1;
    vertexCode = (needDiagnosticOff ? `diagnostic(off, derivative_uniformity);
` : "") + `diagnostic(off, chromium.unreachable_code);
` + InjectStartingAndEndingCode(vertexCode, "fn main", vertexMainStartingCode, vertexMainEndingCode);
    fragmentCode = fragmentCode.replace(/#define (\w+)\s+(\d+\.?\d*)/g, "const $1 = $2;");
    fragmentCode = fragmentCode.replace(/#define /g, "//#define ");
    fragmentCode = this._processStridedUniformArrays(fragmentCode);
    if (!this.pureMode) {
      fragmentCode = fragmentCode.replace(/dpdy/g, "(-internals.yFactor_)*dpdy");
    }
    let fragmentInputs = `struct FragmentInputs {
  @builtin(position) position : vec4<f32>,
  @builtin(front_facing) frontFacing : bool,
`;
    if (this._varyingsWGSL.length > 0) {
      fragmentInputs += this._varyingsWGSL.join(`
`);
    }
    fragmentInputs += `
};
var<private> fragmentInputs : FragmentInputs;
`;
    let fragmentOutputs = `struct FragmentOutputs {
`;
    const regexRoot = "fragmentOutputs\\.fragData";
    let match = fragmentCode.match(new RegExp(regexRoot + "0", "g"));
    let indexLocation = 0;
    if (match) {
      fragmentOutputs += ` @location(${indexLocation}) fragData0 : vec4<f32>,
`;
      indexLocation++;
      for (let index = 1;index < 8; index++) {
        match = fragmentCode.match(new RegExp(regexRoot + index, "g"));
        if (match) {
          fragmentOutputs += ` @location(${indexLocation}) fragData${indexLocation} : vec4<f32>,
`;
          indexLocation++;
        }
      }
      if (fragmentCode.indexOf("MRT_AND_COLOR") !== -1) {
        fragmentOutputs += `  @location(${indexLocation}) color : vec4<f32>,
`;
        indexLocation++;
      }
    }
    const regex = /oitDepthSampler/;
    match = fragmentCode.match(regex);
    if (match) {
      fragmentOutputs += ` @location(${indexLocation++}) depth : vec2<f32>,
`;
      fragmentOutputs += ` @location(${indexLocation++}) frontColor : vec4<f32>,
`;
      fragmentOutputs += ` @location(${indexLocation++}) backColor : vec4<f32>,
`;
    }
    if (indexLocation === 0) {
      fragmentOutputs += `  @location(0) color : vec4<f32>,
`;
      indexLocation++;
    }
    let hasFragDepth = false;
    let idx = 0;
    while (!hasFragDepth) {
      idx = fragmentCode.indexOf(builtInName_frag_depth, idx);
      if (idx < 0) {
        break;
      }
      const saveIndex = idx;
      hasFragDepth = true;
      while (idx > 1 && fragmentCode.charAt(idx) !== `
`) {
        if (fragmentCode.charAt(idx) === "/" && fragmentCode.charAt(idx - 1) === "/") {
          hasFragDepth = false;
          break;
        }
        idx--;
      }
      idx = saveIndex + builtInName_frag_depth.length;
    }
    if (hasFragDepth) {
      fragmentOutputs += `  @builtin(frag_depth) fragDepth: f32,
`;
    }
    fragmentOutputs += `};
var<private> fragmentOutputs : FragmentOutputs;
`;
    fragmentCode = fragmentInputs + fragmentOutputs + fragmentCode;
    const fragmentStartingCode = `  fragmentInputs = input;
  ` + fragCoordCode;
    const fragmentEndingCode = "  return fragmentOutputs;";
    needDiagnosticOff = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) !== -1;
    fragmentCode = (needDiagnosticOff ? `diagnostic(off, derivative_uniformity);
` : "") + `diagnostic(off, chromium.unreachable_code);
` + InjectStartingAndEndingCode(fragmentCode, "fn main", fragmentStartingCode, fragmentEndingCode);
    this._collectBindingNames();
    this._preCreateBindGroupEntries();
    this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents = {};
    return { vertexCode, fragmentCode };
  }
  _generateLeftOverUBOCode(name155, uniformBufferDescription) {
    let stridedArrays = "";
    let ubo = `struct ${name155} {
`;
    for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {
      const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1");
      const size = WebGPUShaderProcessor.UniformSizes[type];
      if (leftOverUniform.length > 0) {
        if (size <= 2) {
          const stridedArrayType = `${name155}_${this._stridedUniformArrays.length}_strided_arr`;
          stridedArrays += `struct ${stridedArrayType} {
                        @size(16)
                        el: ${type},
                    }`;
          this._stridedUniformArrays.push(leftOverUniform.name);
          ubo += ` @align(16) ${leftOverUniform.name} : array<${stridedArrayType}, ${leftOverUniform.length}>,
`;
        } else {
          ubo += ` ${leftOverUniform.name} : array<${leftOverUniform.type}, ${leftOverUniform.length}>,
`;
        }
      } else {
        ubo += `  ${leftOverUniform.name} : ${leftOverUniform.type},
`;
      }
    }
    ubo += `};
`;
    ubo = `${stridedArrays}
${ubo}`;
    ubo += `@group(${uniformBufferDescription.binding.groupIndex}) @binding(${uniformBufferDescription.binding.bindingIndex}) var<uniform> ${leftOverVarName} : ${name155};
`;
    return ubo;
  }
  _processSamplers(code, isVertex) {
    const samplerRegexp = /var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;
    while (true) {
      const match = samplerRegexp.exec(code);
      if (match === null) {
        break;
      }
      const name155 = match[1];
      const samplerType = match[2];
      const suffixLessLength = name155.length - `Sampler`.length;
      const textureName = name155.lastIndexOf(`Sampler`) === suffixLessLength ? name155.substring(0, suffixLessLength) : null;
      const samplerBindingType = samplerType === "sampler_comparison" ? "comparison" : "filtering";
      if (textureName) {
        const textureInfo = this._webgpuProcessingContext.availableTextures[textureName];
        if (textureInfo) {
          textureInfo.autoBindSampler = true;
        }
      }
      let samplerInfo = this._webgpuProcessingContext.availableSamplers[name155];
      if (!samplerInfo) {
        samplerInfo = {
          binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),
          type: samplerBindingType
        };
        this._webgpuProcessingContext.availableSamplers[name155] = samplerInfo;
      }
      this._addSamplerBindingDescription(name155, samplerInfo, isVertex);
      const part1 = code.substring(0, match.index);
      const insertPart = `@group(${samplerInfo.binding.groupIndex}) @binding(${samplerInfo.binding.bindingIndex}) `;
      const part2 = code.substring(match.index);
      code = part1 + insertPart + part2;
      samplerRegexp.lastIndex += insertPart.length;
    }
    return code;
  }
  _processCustomBuffers(code, isVertex) {
    const instantiateBufferRegexp = /var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;
    while (true) {
      const match = instantiateBufferRegexp.exec(code);
      if (match === null) {
        break;
      }
      const type = match[1];
      const decoration = match[3];
      let name155 = match[4];
      const structName = match[5];
      let bufferInfo = this._webgpuProcessingContext.availableBuffers[name155];
      if (!bufferInfo) {
        const knownUBO = type === "uniform" ? WebGPUShaderProcessingContext.KnownUBOs[structName] : null;
        let binding;
        if (knownUBO) {
          name155 = structName;
          binding = knownUBO.binding;
          if (binding.groupIndex === -1) {
            binding = this._webgpuProcessingContext.availableBuffers[name155]?.binding;
            if (!binding) {
              binding = this._webgpuProcessingContext.getNextFreeUBOBinding();
            }
          }
        } else {
          binding = this._webgpuProcessingContext.getNextFreeUBOBinding();
        }
        bufferInfo = { binding };
        this._webgpuProcessingContext.availableBuffers[name155] = bufferInfo;
      }
      this._addBufferBindingDescription(name155, this._webgpuProcessingContext.availableBuffers[name155], decoration === "read_write" ? "storage" : type === "storage" ? "read-only-storage" : "uniform", isVertex);
      const groupIndex = bufferInfo.binding.groupIndex;
      const bindingIndex = bufferInfo.binding.bindingIndex;
      const part1 = code.substring(0, match.index);
      const insertPart = `@group(${groupIndex}) @binding(${bindingIndex}) `;
      const part2 = code.substring(match.index);
      code = part1 + insertPart + part2;
      instantiateBufferRegexp.lastIndex += insertPart.length;
    }
    return code;
  }
  _processStridedUniformArrays(code) {
    for (const uniformArrayName of this._stridedUniformArrays) {
      code = code.replace(new RegExp(`${uniformArrayName}\\s*\\[(.*?)\\]`, "g"), `${uniformArrayName}[$1].el`);
    }
    return code;
  }
}

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_tools();
// node_modules/@babylonjs/core/Engines/WebGPU/webgpuHardwareTexture.js
class WebGPUHardwareTexture {
  get underlyingResource() {
    return this._webgpuTexture;
  }
  getMSAATexture(index) {
    return this._webgpuMSAATexture?.[index] ?? null;
  }
  setMSAATexture(texture, index) {
    if (!this._webgpuMSAATexture) {
      this._webgpuMSAATexture = [];
    }
    this._webgpuMSAATexture[index] = texture;
  }
  releaseMSAATexture(index) {
    if (this._webgpuMSAATexture) {
      if (index !== undefined) {
        this._engine._textureHelper.releaseTexture(this._webgpuMSAATexture[index]);
        delete this._webgpuMSAATexture[index];
      } else {
        for (const texture of this._webgpuMSAATexture) {
          this._engine._textureHelper.releaseTexture(texture);
        }
        this._webgpuMSAATexture = null;
      }
    }
  }
  constructor(_engine, existingTexture = null) {
    this._engine = _engine;
    this._originalFormatIsRGB = false;
    this.format = "rgba8unorm";
    this.textureUsages = 0;
    this.textureAdditionalUsages = 0;
    this._webgpuTexture = existingTexture;
    this._webgpuMSAATexture = null;
    this.view = null;
    this.viewForWriting = null;
  }
  set(hardwareTexture) {
    this._webgpuTexture = hardwareTexture;
  }
  setUsage(_textureSource, generateMipMaps, is2DArray, isCube, is3D, width, height, depth) {
    let viewDimension = "2d";
    let arrayLayerCount = 1;
    if (isCube) {
      viewDimension = is2DArray ? "cube-array" : "cube";
      arrayLayerCount = 6 * (depth || 1);
    } else if (is3D) {
      viewDimension = "3d";
      arrayLayerCount = 1;
    } else if (is2DArray) {
      viewDimension = "2d-array";
      arrayLayerCount = depth;
    }
    const format = WebGPUTextureHelper.GetDepthFormatOnly(this.format);
    const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(this.format) ? "depth-only" : "all";
    this.createView({
      label: `TextureView${is3D ? "3D" : isCube ? "Cube" : "2D"}${is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}_${generateMipMaps ? "wmips" : "womips"}_${this.format}_${viewDimension}`,
      format,
      dimension: viewDimension,
      mipLevelCount: generateMipMaps ? ILog2(Math.max(width, height)) + 1 : 1,
      baseArrayLayer: 0,
      baseMipLevel: 0,
      arrayLayerCount,
      aspect
    });
  }
  createView(descriptor, createViewForWriting = false) {
    this.view = this._webgpuTexture.createView(descriptor);
    if (createViewForWriting && descriptor) {
      const saveNumMipMaps = descriptor.mipLevelCount;
      descriptor.mipLevelCount = 1;
      this.viewForWriting = this._webgpuTexture.createView(descriptor);
      descriptor.mipLevelCount = saveNumMipMaps;
    }
  }
  reset() {
    this._webgpuTexture = null;
    this._webgpuMSAATexture = null;
    this.view = null;
    this.viewForWriting = null;
  }
  release() {
    this._webgpuTexture?.destroy();
    this.releaseMSAATexture();
    this._copyInvertYTempTexture?.destroy();
    this.reset();
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuTextureManager.js
init_shaderProcessor();
var mipmapVertexSource = `
    const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f),  vec2f(1.0f, 1.0f),  vec2f(-1.0f, -1.0f),  vec2f(1.0f, -1.0f));
    const tex = array<vec2<f32>, 4>( vec2f(0.0f, 0.0f),  vec2f(1.0f, 0.0f),  vec2f(0.0f, 1.0f),  vec2f(1.0f, 1.0f));

    varying vTex: vec2f;

    @vertex
    fn main(input : VertexInputs) -> FragmentInputs {
        vertexOutputs.vTex = tex[input.vertexIndex];
        vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);
    }
    `;
var mipmapFragmentSource = `
    var imgSampler: sampler;
    var img: texture_2d<f32>;

    varying vTex: vec2f;

    @fragment
    fn main(input: FragmentInputs) -> FragmentOutputs {
        fragmentOutputs.color = textureSample(img, imgSampler, input.vTex);
    }
    `;
var invertYPreMultiplyAlphaVertexSource = `
    const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f),  vec2f(1.0f, 1.0f),  vec2f(-1.0f, -1.0f),  vec2f(1.0f, -1.0f));
    const tex = array<vec2<f32>, 4>( vec2f(0.0f, 0.0f),  vec2f(1.0f, 0.0f),  vec2f(0.0f, 1.0f),  vec2f(1.0f, 1.0f));

    var img: texture_2d<f32>;

    #ifdef INVERTY
        varying vTextureSize: vec2f;
    #endif

    @vertex
    fn main(input : VertexInputs) -> FragmentInputs {
        #ifdef INVERTY
            vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0));
        #endif
        vertexOutputs.position =  vec4f(pos[input.vertexIndex], 0.0, 1.0);
    }
    `;
var invertYPreMultiplyAlphaFragmentSource = `
    var img: texture_2d<f32>;

    #ifdef INVERTY
        varying vTextureSize: vec2f;
    #endif

    @fragment
    fn main(input: FragmentInputs) -> FragmentOutputs {
    #ifdef INVERTY
        var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0);
    #else
        var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);
    #endif
    #ifdef PREMULTIPLYALPHA
        color = vec4f(color.rgb * color.a, color.a);
    #endif
        fragmentOutputs.color = color;
    }
    `;
var invertYPreMultiplyAlphaWithOfstVertexSource = invertYPreMultiplyAlphaVertexSource;
var invertYPreMultiplyAlphaWithOfstFragmentSource = `
    var img: texture_2d<f32>;
    uniform ofstX: f32;
    uniform ofstY: f32;
    uniform width: f32;
    uniform height: f32;

    #ifdef INVERTY
        varying vTextureSize: vec2f;
    #endif

    @fragment
    fn main(input: FragmentInputs) -> FragmentOutputs {
        if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) {
            discard;
        }
        if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) {
            discard;
        }
    #ifdef INVERTY
        var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0);
    #else
        var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);
    #endif
    #ifdef PREMULTIPLYALPHA
        color = vec4f(color.rgb * color.a, color.a);
    #endif
        fragmentOutputs.color = color;
    }
    `;
var clearVertexSource = `
    const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f),  vec2f(1.0f, 1.0f),  vec2f(-1.0f, -1.0f),  vec2f(1.0f, -1.0f));

    @vertex
    fn main(input : VertexInputs) -> FragmentInputs {
        vertexOutputs.position =  vec4f(pos[input.vertexIndex], 0.0, 1.0);
    }
    `;
var clearFragmentSource = `
    uniform color: vec4f;


    @fragment
    fn main(input: FragmentInputs) -> FragmentOutputs {
        fragmentOutputs.color = uniforms.color;
    }
    `;
var copyVideoToTextureVertexSource = `
    struct VertexOutput {
        @builtin(position) Position : vec4<f32>,
        @location(0) fragUV : vec2<f32>
    }

    @vertex
    fn main(
        @builtin(vertex_index) VertexIndex : u32
    ) -> VertexOutput {
        var pos = array<vec2<f32>, 4>(
            vec2(-1.0,  1.0),
            vec2( 1.0,  1.0),
            vec2(-1.0, -1.0),
            vec2( 1.0, -1.0)
        );
        var tex = array<vec2<f32>, 4>(
            vec2(0.0, 0.0),
            vec2(1.0, 0.0),
            vec2(0.0, 1.0),
            vec2(1.0, 1.0)
        );

        var output: VertexOutput;

        output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);
        output.fragUV = tex[VertexIndex];

        return output;
    }
    `;
var copyVideoToTextureFragmentSource = `
    @group(0) @binding(0) var videoSampler: sampler;
    @group(0) @binding(1) var videoTexture: texture_external;

    @fragment
    fn main(
        @location(0) fragUV: vec2<f32>
    ) -> @location(0) vec4<f32> {
        return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);
    }
    `;
var copyVideoToTextureInvertYFragmentSource = `
    @group(0) @binding(0) var videoSampler: sampler;
    @group(0) @binding(1) var videoTexture: texture_external;

    @fragment
    fn main(
        @location(0) fragUV: vec2<f32>
    ) -> @location(0) vec4<f32> {
        return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y));
    }
    `;
var PipelineType;
(function(PipelineType2) {
  PipelineType2[PipelineType2["MipMap"] = 0] = "MipMap";
  PipelineType2[PipelineType2["InvertYPremultiplyAlpha"] = 1] = "InvertYPremultiplyAlpha";
  PipelineType2[PipelineType2["Clear"] = 2] = "Clear";
  PipelineType2[PipelineType2["InvertYPremultiplyAlphaWithOfst"] = 3] = "InvertYPremultiplyAlphaWithOfst";
})(PipelineType || (PipelineType = {}));
var VideoPipelineType;
(function(VideoPipelineType2) {
  VideoPipelineType2[VideoPipelineType2["DontInvertY"] = 0] = "DontInvertY";
  VideoPipelineType2[VideoPipelineType2["InvertY"] = 1] = "InvertY";
})(VideoPipelineType || (VideoPipelineType = {}));
var shadersForPipelineType = [
  { vertex: mipmapVertexSource, fragment: mipmapFragmentSource },
  { vertex: invertYPreMultiplyAlphaVertexSource, fragment: invertYPreMultiplyAlphaFragmentSource },
  { vertex: clearVertexSource, fragment: clearFragmentSource },
  { vertex: invertYPreMultiplyAlphaWithOfstVertexSource, fragment: invertYPreMultiplyAlphaWithOfstFragmentSource }
];
var renderableTextureFormatToIndex = {
  "": 0,
  r8unorm: 1,
  r8uint: 2,
  r8sint: 3,
  r16uint: 4,
  r16sint: 5,
  r16float: 6,
  rg8unorm: 7,
  rg8uint: 8,
  rg8sint: 9,
  r32uint: 10,
  r32sint: 11,
  r32float: 12,
  rg16uint: 13,
  rg16sint: 14,
  rg16float: 15,
  rgba8unorm: 16,
  "rgba8unorm-srgb": 17,
  rgba8uint: 18,
  rgba8sint: 19,
  bgra8unorm: 20,
  "bgra8unorm-srgb": 21,
  rgb10a2uint: 22,
  rgb10a2unorm: 23,
  rg32uint: 24,
  rg32sint: 25,
  rg32float: 26,
  rgba16uint: 27,
  rgba16sint: 28,
  rgba16float: 29,
  rgba32uint: 30,
  rgba32sint: 31,
  rgba32float: 32,
  stencil8: 33,
  depth16unorm: 34,
  depth24plus: 35,
  "depth24plus-stencil8": 36,
  depth32float: 37,
  "depth32float-stencil8": 38,
  r16unorm: 39,
  rg16unorm: 40,
  rgba16unorm: 41,
  r16snorm: 42,
  rg16snorm: 43,
  rgba16snorm: 44
};

class WebGPUTextureManager {
  constructor(engine, device, bufferManager, enabledExtensions) {
    this._pipelines = {};
    this._compiledShaders = [];
    this._videoPipelines = {};
    this._videoCompiledShaders = [];
    this._deferredReleaseTextures = [];
    this._engine = engine;
    this._device = device;
    this._bufferManager = bufferManager;
    if (enabledExtensions.indexOf("rg11b10ufloat-renderable") !== -1) {
      const keys = Object.keys(renderableTextureFormatToIndex);
      renderableTextureFormatToIndex["rg11b10ufloat"] = renderableTextureFormatToIndex[keys[keys.length - 1]] + 1;
    }
    this._mipmapSampler = device.createSampler({ minFilter: "linear" });
    this._videoSampler = device.createSampler({ minFilter: "linear" });
    this._ubCopyWithOfst = this._bufferManager.createBuffer(4 * 4, BufferUsage.Uniform | BufferUsage.CopyDst, "UBCopyWithOffset").underlyingResource;
    this._getPipeline("rgba8unorm");
    this._getVideoPipeline("rgba8unorm");
  }
  _getPipeline(format, type = PipelineType.MipMap, params) {
    const index = type === PipelineType.MipMap ? 1 << 0 : type === PipelineType.InvertYPremultiplyAlpha ? ((params.invertY ? 1 : 0) << 1) + ((params.premultiplyAlpha ? 1 : 0) << 2) : type === PipelineType.Clear ? 1 << 3 : type === PipelineType.InvertYPremultiplyAlphaWithOfst ? ((params.invertY ? 1 : 0) << 4) + ((params.premultiplyAlpha ? 1 : 0) << 5) : 0;
    if (!this._pipelines[format]) {
      this._pipelines[format] = [];
    }
    let pipelineAndBGL = this._pipelines[format][index];
    if (!pipelineAndBGL) {
      let defines = "";
      if (type === PipelineType.InvertYPremultiplyAlpha || type === PipelineType.InvertYPremultiplyAlphaWithOfst) {
        if (params.invertY) {
          defines += `#define INVERTY
`;
        }
        if (params.premultiplyAlpha) {
          defines += `#define PREMULTIPLYALPHA
`;
        }
      }
      let modules = this._compiledShaders[index];
      if (!modules) {
        let vertexCode = shadersForPipelineType[type].vertex;
        let fragmentCode = shadersForPipelineType[type].fragment;
        const processorOptions = {
          defines: defines.split(`
`),
          indexParameters: null,
          isFragment: false,
          shouldUseHighPrecisionShader: true,
          processor: this._engine._getShaderProcessor(1),
          supportsUniformBuffers: true,
          shadersRepository: "",
          includesShadersStore: {},
          version: (this._engine.version * 100).toString(),
          platformName: this._engine.shaderPlatformName,
          processingContext: this._engine._getShaderProcessingContext(1, true),
          isNDCHalfZRange: this._engine.isNDCHalfZRange,
          useReverseDepthBuffer: this._engine.useReverseDepthBuffer
        };
        Initialize(processorOptions);
        processorOptions.processor.pureMode = true;
        Process(vertexCode, processorOptions, (migratedVertexCode) => {
          vertexCode = migratedVertexCode;
        }, this._engine);
        processorOptions.isFragment = true;
        Process(fragmentCode, processorOptions, (migratedFragmentCode) => {
          fragmentCode = migratedFragmentCode;
        }, this._engine);
        const final = Finalize(vertexCode, fragmentCode, processorOptions);
        processorOptions.processor.pureMode = false;
        const vertexModule = this._device.createShaderModule({
          label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalVertexShader_${index}`,
          code: final.vertexCode
        });
        const fragmentModule = this._device.createShaderModule({
          label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalFragmentShader_${index}`,
          code: final.fragmentCode
        });
        modules = this._compiledShaders[index] = [vertexModule, fragmentModule];
      }
      const pipeline = this._device.createRenderPipeline({
        label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalPipeline_${format}_${index}`,
        layout: "auto",
        vertex: {
          module: modules[0],
          entryPoint: "main"
        },
        fragment: {
          module: modules[1],
          entryPoint: "main",
          targets: [
            {
              format
            }
          ]
        },
        primitive: {
          topology: "triangle-strip",
          stripIndexFormat: "uint16"
        }
      });
      pipelineAndBGL = this._pipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];
    }
    return pipelineAndBGL;
  }
  _getVideoPipeline(format, type = VideoPipelineType.DontInvertY) {
    const index = type === VideoPipelineType.InvertY ? 1 << 0 : 0;
    if (!this._videoPipelines[format]) {
      this._videoPipelines[format] = [];
    }
    let pipelineAndBGL = this._videoPipelines[format][index];
    if (!pipelineAndBGL) {
      let modules = this._videoCompiledShaders[index];
      if (!modules) {
        const vertexModule = this._device.createShaderModule({
          code: copyVideoToTextureVertexSource,
          label: `BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_VertexShader`
        });
        const fragmentModule = this._device.createShaderModule({
          code: index === 0 ? copyVideoToTextureFragmentSource : copyVideoToTextureInvertYFragmentSource,
          label: `BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_FragmentShader_${index === 0 ? "DontInvertY" : "InvertY"}`
        });
        modules = this._videoCompiledShaders[index] = [vertexModule, fragmentModule];
      }
      const pipeline = this._device.createRenderPipeline({
        label: `BabylonWebGPUDevice${this._engine.uniqueId}_InternalVideoPipeline_${format}_${index === 0 ? "DontInvertY" : "InvertY"}`,
        layout: "auto",
        vertex: {
          module: modules[0],
          entryPoint: "main"
        },
        fragment: {
          module: modules[1],
          entryPoint: "main",
          targets: [
            {
              format
            }
          ]
        },
        primitive: {
          topology: "triangle-strip",
          stripIndexFormat: "uint16"
        }
      });
      pipelineAndBGL = this._videoPipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];
    }
    return pipelineAndBGL;
  }
  setCommandEncoder(encoder) {
    this._commandEncoderForCreation = encoder;
  }
  copyVideoToTexture(video, texture, format, invertY = false, commandEncoder) {
    const useOwnCommandEncoder = commandEncoder === undefined;
    const [pipeline, bindGroupLayout] = this._getVideoPipeline(format, invertY ? VideoPipelineType.InvertY : VideoPipelineType.DontInvertY);
    if (useOwnCommandEncoder) {
      commandEncoder = this._device.createCommandEncoder({});
    }
    commandEncoder.pushDebugGroup?.(`copy video to texture - invertY=${invertY}`);
    const webgpuHardwareTexture = texture._hardwareTexture;
    const renderPassDescriptor = {
      label: `BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${format}_${invertY ? "InvertY" : "DontInvertY"}${texture.label ? "_" + texture.label : ""}`,
      colorAttachments: [
        {
          view: webgpuHardwareTexture.underlyingResource.createView({
            format,
            dimension: "2d",
            mipLevelCount: 1,
            baseArrayLayer: 0,
            baseMipLevel: 0,
            arrayLayerCount: 1,
            aspect: "all"
          }),
          loadOp: "load",
          storeOp: "store"
        }
      ]
    };
    const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
    const descriptor = {
      layout: bindGroupLayout,
      entries: [
        {
          binding: 0,
          resource: this._videoSampler
        },
        {
          binding: 1,
          resource: this._device.importExternalTexture({
            source: video.underlyingResource
          })
        }
      ]
    };
    const bindGroup = this._device.createBindGroup(descriptor);
    passEncoder.setPipeline(pipeline);
    passEncoder.setBindGroup(0, bindGroup);
    passEncoder.draw(4, 1, 0, 0);
    passEncoder.end();
    commandEncoder.popDebugGroup?.();
    if (useOwnCommandEncoder) {
      this._device.queue.submit([commandEncoder.finish()]);
      commandEncoder = null;
    }
  }
  invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY = false, premultiplyAlpha = false, faceIndex = 0, mipLevel = 0, layers = 1, ofstX = 0, ofstY = 0, rectWidth = 0, rectHeight = 0, commandEncoder, allowGPUOptimization) {
    const useRect = rectWidth !== 0;
    const useOwnCommandEncoder = commandEncoder === undefined;
    const [pipeline, bindGroupLayout] = this._getPipeline(format, useRect ? PipelineType.InvertYPremultiplyAlphaWithOfst : PipelineType.InvertYPremultiplyAlpha, {
      invertY,
      premultiplyAlpha
    });
    faceIndex = Math.max(faceIndex, 0);
    if (useOwnCommandEncoder) {
      commandEncoder = this._device.createCommandEncoder({});
    }
    commandEncoder.pushDebugGroup?.(`internal process texture - invertY=${invertY} premultiplyAlpha=${premultiplyAlpha}`);
    let gpuTexture;
    if (WebGPUTextureHelper.IsHardwareTexture(gpuOrHdwTexture)) {
      gpuTexture = gpuOrHdwTexture.underlyingResource;
      if (!(invertY && !premultiplyAlpha && layers === 1 && faceIndex === 0)) {
        gpuOrHdwTexture = undefined;
      }
    } else {
      gpuTexture = gpuOrHdwTexture;
      gpuOrHdwTexture = undefined;
    }
    if (!gpuTexture) {
      return;
    }
    if (useRect) {
      this._bufferManager.setRawData(this._ubCopyWithOfst, 0, new Float32Array([ofstX, ofstY, rectWidth, rectHeight]), 0, 4 * 4);
    }
    const webgpuHardwareTexture = gpuOrHdwTexture;
    const outputTexture = webgpuHardwareTexture?._copyInvertYTempTexture ?? this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, 1 | 16 | 4, undefined, "TempTextureForCopyWithInvertY");
    const renderPassDescriptor = webgpuHardwareTexture?._copyInvertYRenderPassDescr ?? {
      label: `BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${format}_${invertY ? "InvertY" : "DontInvertY"}_${premultiplyAlpha ? "PremultiplyAlpha" : "DontPremultiplyAlpha"}`,
      colorAttachments: [
        {
          view: outputTexture.createView({
            format,
            dimension: "2d",
            baseMipLevel: 0,
            mipLevelCount: 1,
            arrayLayerCount: 1,
            baseArrayLayer: 0
          }),
          loadOp: "load",
          storeOp: "store"
        }
      ]
    };
    const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
    let bindGroup = useRect ? webgpuHardwareTexture?._copyInvertYBindGroupWithOfst : webgpuHardwareTexture?._copyInvertYBindGroup;
    if (!bindGroup) {
      const descriptor = {
        layout: bindGroupLayout,
        entries: [
          {
            binding: 0,
            resource: gpuTexture.createView({
              format,
              dimension: "2d",
              baseMipLevel: mipLevel,
              mipLevelCount: 1,
              arrayLayerCount: layers,
              baseArrayLayer: faceIndex
            })
          }
        ]
      };
      if (useRect) {
        descriptor.entries.push({
          binding: 1,
          resource: {
            buffer: this._ubCopyWithOfst
          }
        });
      }
      bindGroup = this._device.createBindGroup(descriptor);
    }
    passEncoder.setPipeline(pipeline);
    passEncoder.setBindGroup(0, bindGroup);
    passEncoder.draw(4, 1, 0, 0);
    passEncoder.end();
    commandEncoder.copyTextureToTexture({
      texture: outputTexture
    }, {
      texture: gpuTexture,
      mipLevel,
      origin: {
        x: 0,
        y: 0,
        z: faceIndex
      }
    }, {
      width: rectWidth || width,
      height: rectHeight || height,
      depthOrArrayLayers: 1
    });
    if (webgpuHardwareTexture) {
      webgpuHardwareTexture._copyInvertYTempTexture = outputTexture;
      webgpuHardwareTexture._copyInvertYRenderPassDescr = renderPassDescriptor;
      if (useRect) {
        webgpuHardwareTexture._copyInvertYBindGroupWithOfst = bindGroup;
      } else {
        webgpuHardwareTexture._copyInvertYBindGroup = bindGroup;
      }
    } else {
      this._deferredReleaseTextures.push([outputTexture, null]);
    }
    commandEncoder.popDebugGroup?.();
    if (useOwnCommandEncoder) {
      this._device.queue.submit([commandEncoder.finish()]);
      commandEncoder = null;
    }
  }
  createTexture(imageBitmap, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, is3D = false, format = "rgba8unorm", sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {
    sampleCount = WebGPUTextureHelper.GetSample(sampleCount);
    const layerCount = imageBitmap.layers || 1;
    const textureSize = {
      width: imageBitmap.width,
      height: imageBitmap.height,
      depthOrArrayLayers: layerCount
    };
    const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? 16 : 0;
    const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);
    const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(imageBitmap.width, imageBitmap.height) : 1;
    const usages = usage >= 0 ? usage : 1 | 2 | 4;
    additionalUsages |= hasMipmaps && !isCompressedFormat ? 1 | renderAttachmentFlag : 0;
    if (!isCompressedFormat && !is3D) {
      additionalUsages |= renderAttachmentFlag | 2;
    }
    const gpuTexture = this._device.createTexture({
      label: `BabylonWebGPUDevice${this._engine.uniqueId}_Texture${is3D ? "3D" : "2D"}_${label ? label + "_" : ""}${textureSize.width}x${textureSize.height}x${textureSize.depthOrArrayLayers}_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`,
      size: textureSize,
      dimension: is3D ? "3d" : "2d",
      format,
      usage: usages | additionalUsages,
      sampleCount,
      mipLevelCount
    });
    if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {
      this.updateTexture(imageBitmap, gpuTexture, imageBitmap.width, imageBitmap.height, layerCount, format, 0, 0, invertY, premultiplyAlpha, 0, 0);
      if (hasMipmaps && generateMipmaps) {
        this.generateMipmaps(gpuTexture, format, mipLevelCount, 0, is3D, commandEncoder);
      }
    }
    return gpuTexture;
  }
  createCubeTexture(imageBitmaps, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, format = "rgba8unorm", sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {
    sampleCount = WebGPUTextureHelper.GetSample(sampleCount);
    const width = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].width : imageBitmaps.width;
    const height = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].height : imageBitmaps.height;
    const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? 16 : 0;
    const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);
    const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;
    const usages = usage >= 0 ? usage : 1 | 2 | 4;
    additionalUsages |= hasMipmaps && !isCompressedFormat ? 1 | renderAttachmentFlag : 0;
    if (!isCompressedFormat) {
      additionalUsages |= renderAttachmentFlag | 2;
    }
    const gpuTexture = this._device.createTexture({
      label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${label ? label + "_" : ""}${width}x${height}x6_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`,
      size: {
        width,
        height,
        depthOrArrayLayers: 6
      },
      dimension: "2d",
      format,
      usage: usages | additionalUsages,
      sampleCount,
      mipLevelCount
    });
    if (WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps)) {
      this.updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY, premultiplyAlpha, 0, 0);
      if (hasMipmaps && generateMipmaps) {
        this.generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder);
      }
    }
    return gpuTexture;
  }
  generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder) {
    const useOwnCommandEncoder = commandEncoder === undefined;
    if (useOwnCommandEncoder) {
      commandEncoder = this._device.createCommandEncoder({});
    }
    commandEncoder.pushDebugGroup?.(`create cube mipmaps - ${mipLevelCount} levels`);
    for (let f = 0;f < 6; ++f) {
      this.generateMipmaps(gpuTexture, format, mipLevelCount, f, false, commandEncoder);
    }
    commandEncoder.popDebugGroup?.();
    if (useOwnCommandEncoder) {
      this._device.queue.submit([commandEncoder.finish()]);
      commandEncoder = null;
    }
  }
  generateMipmaps(gpuOrHdwTexture, format, mipLevelCount, faceIndex = 0, is3D = false, commandEncoder) {
    const useOwnCommandEncoder = commandEncoder === undefined;
    const [pipeline, bindGroupLayout] = this._getPipeline(format);
    faceIndex = Math.max(faceIndex, 0);
    if (useOwnCommandEncoder) {
      commandEncoder = this._device.createCommandEncoder({});
    }
    commandEncoder.pushDebugGroup?.(`create mipmaps for face #${faceIndex} - ${mipLevelCount} levels`);
    let gpuTexture;
    if (WebGPUTextureHelper.IsHardwareTexture(gpuOrHdwTexture)) {
      gpuTexture = gpuOrHdwTexture.underlyingResource;
      gpuOrHdwTexture._mipmapGenRenderPassDescr = gpuOrHdwTexture._mipmapGenRenderPassDescr || [];
      gpuOrHdwTexture._mipmapGenBindGroup = gpuOrHdwTexture._mipmapGenBindGroup || [];
    } else {
      gpuTexture = gpuOrHdwTexture;
      gpuOrHdwTexture = undefined;
    }
    if (!gpuTexture) {
      return;
    }
    const webgpuHardwareTexture = gpuOrHdwTexture;
    for (let i = 1;i < mipLevelCount; ++i) {
      const renderPassDescriptor = webgpuHardwareTexture?._mipmapGenRenderPassDescr[faceIndex]?.[i - 1] ?? {
        label: `BabylonWebGPUDevice${this._engine.uniqueId}_generateMipmaps_${format}_faceIndex${faceIndex}_level${i}`,
        colorAttachments: [
          {
            view: gpuTexture.createView({
              format,
              dimension: is3D ? "3d" : "2d",
              baseMipLevel: i,
              mipLevelCount: 1,
              arrayLayerCount: 1,
              baseArrayLayer: faceIndex
            }),
            loadOp: "load",
            storeOp: "store"
          }
        ]
      };
      if (webgpuHardwareTexture) {
        webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] = webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] || [];
        webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex][i - 1] = renderPassDescriptor;
      }
      const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
      const bindGroup = webgpuHardwareTexture?._mipmapGenBindGroup[faceIndex]?.[i - 1] ?? this._device.createBindGroup({
        layout: bindGroupLayout,
        entries: [
          {
            binding: 0,
            resource: gpuTexture.createView({
              format,
              dimension: is3D ? "3d" : "2d",
              baseMipLevel: i - 1,
              mipLevelCount: 1,
              arrayLayerCount: 1,
              baseArrayLayer: faceIndex
            })
          },
          {
            binding: 1,
            resource: this._mipmapSampler
          }
        ]
      });
      if (webgpuHardwareTexture) {
        webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] = webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] || [];
        webgpuHardwareTexture._mipmapGenBindGroup[faceIndex][i - 1] = bindGroup;
      }
      passEncoder.setPipeline(pipeline);
      passEncoder.setBindGroup(0, bindGroup);
      passEncoder.draw(4, 1, 0, 0);
      passEncoder.end();
    }
    commandEncoder.popDebugGroup?.();
    if (useOwnCommandEncoder) {
      this._device.queue.submit([commandEncoder.finish()]);
      commandEncoder = null;
    }
  }
  createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags, dontCreateMSAATexture) {
    if (!texture._hardwareTexture) {
      texture._hardwareTexture = new WebGPUHardwareTexture(this._engine);
    }
    if (width === undefined) {
      width = texture.width;
    }
    if (height === undefined) {
      height = texture.height;
    }
    if (depth === undefined) {
      depth = texture.depth;
    }
    const gpuTextureWrapper = texture._hardwareTexture;
    const isStorageTexture = ((creationFlags ?? 0) & 1) !== 0;
    gpuTextureWrapper.format = WebGPUTextureHelper.GetWebGPUTextureFormat(texture.type, texture.format, texture._useSRGBBuffer);
    gpuTextureWrapper.textureUsages = texture._source === 5 || texture.source === 6 ? 4 | 1 | 16 : texture._source === 12 ? 4 | 16 : -1;
    gpuTextureWrapper.textureAdditionalUsages = isStorageTexture ? 8 : 0;
    const hasMipMaps = texture.generateMipMaps;
    const layerCount = depth || 1;
    let mipmapCount;
    if (texture._maxLodLevel !== null) {
      mipmapCount = texture._maxLodLevel;
    } else {
      mipmapCount = hasMipMaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;
    }
    if (texture.isCube) {
      const gpuTexture = this.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);
      gpuTextureWrapper.set(gpuTexture);
      const arrayLayerCount = texture.is3D ? 1 : layerCount;
      const format = WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format);
      const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? "depth-only" : "all";
      const dimension = texture.is2DArray ? "cube-array" : "cube";
      gpuTextureWrapper.createView({
        label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureViewCube${texture.is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}_${hasMipMaps ? "wmips" : "womips"}_${format}_${dimension}_${aspect}_${texture.label ?? "noname"}`,
        format,
        dimension,
        mipLevelCount: mipmapCount,
        baseArrayLayer: 0,
        baseMipLevel: 0,
        arrayLayerCount: 6,
        aspect
      }, isStorageTexture);
    } else {
      const gpuTexture = this.createTexture({ width, height, layers: layerCount }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, texture.is3D, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);
      gpuTextureWrapper.set(gpuTexture);
      const arrayLayerCount = texture.is3D ? 1 : layerCount;
      const format = WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format);
      const aspect = WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? "depth-only" : "all";
      const dimension = texture.is2DArray ? "2d-array" : texture.is3D ? "3d" : "2d";
      gpuTextureWrapper.createView({
        label: `BabylonWebGPUDevice${this._engine.uniqueId}_TextureView${texture.is3D ? "3D" : "2D"}${texture.is2DArray ? "_Array" + arrayLayerCount : ""}_${width}x${height}${texture.is3D ? "x" + layerCount : ""}_${hasMipMaps ? "wmips" : "womips"}_${format}_${dimension}_${aspect}_${texture.label ?? "noname"}`,
        format,
        dimension,
        mipLevelCount: mipmapCount,
        baseArrayLayer: 0,
        baseMipLevel: 0,
        arrayLayerCount,
        aspect
      }, isStorageTexture);
    }
    texture.width = texture.baseWidth = width;
    texture.height = texture.baseHeight = height;
    texture.depth = texture.baseDepth = depth;
    if (!dontCreateMSAATexture) {
      this.createMSAATexture(texture, texture.samples);
    }
    return gpuTextureWrapper;
  }
  createMSAATexture(texture, samples, releaseExisting = true, index = 0) {
    const gpuTextureWrapper = texture._hardwareTexture;
    if (releaseExisting) {
      gpuTextureWrapper?.releaseMSAATexture();
    }
    if (!gpuTextureWrapper || (samples ?? 1) <= 1) {
      return;
    }
    const width = texture.width;
    const height = texture.height;
    const gpuMSAATexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, gpuTextureWrapper.format, samples, this._commandEncoderForCreation, 16, 0, texture.label ? "MSAA_" + texture.label : "MSAA");
    gpuTextureWrapper.setMSAATexture(gpuMSAATexture, index);
  }
  updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0) {
    const faces = [0, 3, 1, 4, 2, 5];
    for (let f = 0;f < faces.length; ++f) {
      const imageBitmap = imageBitmaps[faces[f]];
      this.updateTexture(imageBitmap, gpuTexture, width, height, 1, format, f, 0, invertY, premultiplyAlpha, offsetX, offsetY);
    }
  }
  updateTexture(imageBitmap, texture, width, height, layers, format, faceIndex = 0, mipLevel = 0, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0, allowGPUOptimization) {
    const gpuTexture = WebGPUTextureHelper.IsInternalTexture(texture) ? texture._hardwareTexture.underlyingResource : texture;
    const blockInformation = WebGPUTextureHelper.GetBlockInformationFromFormat(format);
    const gpuOrHdwTexture = WebGPUTextureHelper.IsInternalTexture(texture) ? texture._hardwareTexture : texture;
    const textureCopyView = {
      texture: gpuTexture,
      origin: {
        x: offsetX,
        y: offsetY,
        z: Math.max(faceIndex, 0)
      },
      mipLevel,
      premultipliedAlpha: premultiplyAlpha
    };
    const textureExtent = {
      width: Math.ceil(width / blockInformation.width) * blockInformation.width,
      height: Math.ceil(height / blockInformation.height) * blockInformation.height,
      depthOrArrayLayers: layers || 1
    };
    if (imageBitmap.byteLength !== undefined) {
      imageBitmap = imageBitmap;
      const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;
      const aligned = Math.ceil(bytesPerRow / 256) * 256 === bytesPerRow;
      if (aligned) {
        const commandEncoder = this._device.createCommandEncoder({});
        const buffer2 = this._bufferManager.createRawBuffer(imageBitmap.byteLength, BufferUsage.MapWrite | BufferUsage.CopySrc, true, "TempBufferForUpdateTexture" + (gpuTexture ? "_" + gpuTexture.label : ""));
        const arrayBuffer = buffer2.getMappedRange();
        new Uint8Array(arrayBuffer).set(imageBitmap);
        buffer2.unmap();
        commandEncoder.copyBufferToTexture({
          buffer: buffer2,
          offset: 0,
          bytesPerRow,
          rowsPerImage: height
        }, textureCopyView, textureExtent);
        this._device.queue.submit([commandEncoder.finish()]);
        this._bufferManager.releaseBuffer(buffer2);
      } else {
        this._device.queue.writeTexture(textureCopyView, imageBitmap, {
          offset: 0,
          bytesPerRow,
          rowsPerImage: height
        }, textureExtent);
      }
      if (invertY || premultiplyAlpha) {
        if (WebGPUTextureHelper.IsInternalTexture(texture)) {
          const dontUseRect = offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height;
          this.invertYPreMultiplyAlpha(gpuOrHdwTexture, texture.width, texture.height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, offsetX, offsetY, dontUseRect ? 0 : width, dontUseRect ? 0 : height, undefined, allowGPUOptimization);
        } else {
          throw "updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!";
        }
      }
    } else {
      imageBitmap = imageBitmap;
      this._device.queue.copyExternalImageToTexture({ source: imageBitmap, flipY: invertY }, textureCopyView, textureExtent);
    }
  }
  readPixels(texture, x, y, width, height, format, faceIndex = 0, mipLevel = 0, buffer2 = null, noDataConversion = false) {
    const blockInformation = WebGPUTextureHelper.GetBlockInformationFromFormat(format);
    const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;
    const bytesPerRowAligned = Math.ceil(bytesPerRow / 256) * 256;
    const size = bytesPerRowAligned * height;
    const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempBufferForReadPixels" + (texture.label ? "_" + texture.label : ""));
    const commandEncoder = this._device.createCommandEncoder({});
    commandEncoder.copyTextureToBuffer({
      texture,
      mipLevel,
      origin: {
        x,
        y,
        z: Math.max(faceIndex, 0)
      }
    }, {
      buffer: gpuBuffer,
      offset: 0,
      bytesPerRow: bytesPerRowAligned
    }, {
      width,
      height,
      depthOrArrayLayers: 1
    });
    this._device.queue.submit([commandEncoder.finish()]);
    return this._bufferManager.readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, WebGPUTextureHelper.GetTextureTypeFromFormat(format), 0, buffer2, true, noDataConversion);
  }
  releaseTexture(texture) {
    if (WebGPUTextureHelper.IsInternalTexture(texture)) {
      const hardwareTexture = texture._hardwareTexture;
      const irradianceTexture = texture._irradianceTexture;
      this._deferredReleaseTextures.push([hardwareTexture, irradianceTexture]);
    } else {
      this._deferredReleaseTextures.push([texture, null]);
    }
  }
  destroyDeferredTextures() {
    for (let i = 0;i < this._deferredReleaseTextures.length; ++i) {
      const [hardwareTexture, irradianceTexture] = this._deferredReleaseTextures[i];
      if (hardwareTexture) {
        if (WebGPUTextureHelper.IsHardwareTexture(hardwareTexture)) {
          hardwareTexture.release();
        } else {
          hardwareTexture.destroy();
        }
      }
      irradianceTexture?.dispose();
    }
    this._deferredReleaseTextures.length = 0;
  }
}

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_abstractEngine();

// node_modules/@babylonjs/core/Meshes/WebGPU/webgpuDataBuffer.js
init_dataBuffer();

class WebGPUDataBuffer extends DataBuffer {
  set buffer(buffer2) {
    this._buffer = buffer2;
  }
  constructor(resource, capacity = 0) {
    super();
    this.engineId = -1;
    this.capacity = capacity;
    if (resource) {
      this._buffer = resource;
    }
  }
  get underlyingResource() {
    return this._buffer;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuBufferManager.js
init_textureTools();
init_abstractEngine_functions();
class WebGPUBufferManager {
  static _IsGPUBuffer(buffer2) {
    return buffer2.underlyingResource === undefined;
  }
  static _FlagsToString(flags, suffix3 = "") {
    let result = suffix3;
    for (let i = 0;i <= 9; ++i) {
      if (flags & 1 << i) {
        if (result) {
          result += "_";
        }
        result += BufferUsage[1 << i];
      }
    }
    return result;
  }
  constructor(engine, device) {
    this._deferredReleaseBuffers = [];
    this._engine = engine;
    this._device = device;
  }
  createRawBuffer(viewOrSize, flags, mappedAtCreation = false, label) {
    const alignedLength = viewOrSize.byteLength !== undefined ? viewOrSize.byteLength + 3 & ~3 : viewOrSize + 3 & ~3;
    const verticesBufferDescriptor = {
      label: "BabylonWebGPUDevice" + this._engine.uniqueId + "_" + WebGPUBufferManager._FlagsToString(flags, label ?? "Buffer") + "_size" + alignedLength,
      mappedAtCreation,
      size: alignedLength,
      usage: flags
    };
    return this._device.createBuffer(verticesBufferDescriptor);
  }
  createBuffer(viewOrSize, flags, label) {
    const isView = viewOrSize.byteLength !== undefined;
    const dataBuffer2 = new WebGPUDataBuffer;
    const labelId = "DataBufferUniqueId=" + dataBuffer2.uniqueId;
    dataBuffer2.buffer = this.createRawBuffer(viewOrSize, flags, undefined, label ? labelId + "-" + label : labelId);
    dataBuffer2.references = 1;
    dataBuffer2.capacity = isView ? viewOrSize.byteLength : viewOrSize;
    dataBuffer2.engineId = this._engine.uniqueId;
    if (isView) {
      this.setSubData(dataBuffer2, 0, viewOrSize);
    }
    return dataBuffer2;
  }
  setRawData(buffer2, dstByteOffset, src, srcByteOffset, byteLength) {
    srcByteOffset += src.byteOffset;
    this._device.queue.writeBuffer(buffer2, dstByteOffset, src.buffer, srcByteOffset, byteLength);
  }
  setSubData(dataBuffer2, dstByteOffset, src, srcByteOffset = 0, byteLength = 0) {
    const buffer2 = dataBuffer2.underlyingResource;
    byteLength = byteLength || src.byteLength - srcByteOffset;
    const startPre = dstByteOffset & 3;
    srcByteOffset -= startPre;
    dstByteOffset -= startPre;
    const originalByteLength = byteLength;
    byteLength = byteLength + startPre + 3 & ~3;
    const backingBufferSize = src.buffer.byteLength - src.byteOffset;
    if (backingBufferSize < byteLength) {
      const tmpBuffer = new Uint8Array(byteLength);
      tmpBuffer.set(new Uint8Array(src.buffer, src.byteOffset + srcByteOffset, originalByteLength));
      src = tmpBuffer;
      srcByteOffset = 0;
    }
    this.setRawData(buffer2, dstByteOffset, src, srcByteOffset, byteLength);
  }
  _getHalfFloatAsFloatRGBAArrayBuffer(dataLength, arrayBuffer, destArray) {
    if (!destArray) {
      destArray = new Float32Array(dataLength);
    }
    const srcData = new Uint16Array(arrayBuffer);
    while (dataLength--) {
      destArray[dataLength] = FromHalfFloat(srcData[dataLength]);
    }
    return destArray;
  }
  readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, type = 0, offset = 0, buffer2 = null, destroyBuffer = true, noDataConversion = false) {
    const floatFormat = type === 1 ? 2 : type === 2 ? 1 : 0;
    const engineId = this._engine.uniqueId;
    return new Promise((resolve3, reject) => {
      gpuBuffer.mapAsync(1, offset, size).then(() => {
        const copyArrayBuffer = gpuBuffer.getMappedRange(offset, size);
        let data = buffer2;
        if (noDataConversion) {
          if (data === null) {
            data = allocateAndCopyTypedBuffer(type, size, true, copyArrayBuffer);
          } else {
            data = allocateAndCopyTypedBuffer(type, data.buffer, undefined, copyArrayBuffer);
          }
        } else {
          if (data === null) {
            switch (floatFormat) {
              case 0:
                data = new Uint8Array(size);
                data.set(new Uint8Array(copyArrayBuffer));
                break;
              case 1:
                data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer);
                break;
              case 2:
                data = new Float32Array(size / 4);
                data.set(new Float32Array(copyArrayBuffer));
                break;
            }
          } else {
            switch (floatFormat) {
              case 0:
                data = new Uint8Array(data.buffer);
                data.set(new Uint8Array(copyArrayBuffer));
                break;
              case 1:
                data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer, buffer2);
                break;
              case 2:
                data = new Float32Array(data.buffer);
                data.set(new Float32Array(copyArrayBuffer));
                break;
            }
          }
        }
        if (bytesPerRow !== bytesPerRowAligned) {
          if (floatFormat === 1 && !noDataConversion) {
            bytesPerRow *= 2;
            bytesPerRowAligned *= 2;
          }
          const data2 = new Uint8Array(data.buffer);
          let offset2 = bytesPerRow, offset22 = 0;
          for (let y = 1;y < height; ++y) {
            offset22 = y * bytesPerRowAligned;
            for (let x = 0;x < bytesPerRow; ++x) {
              data2[offset2++] = data2[offset22++];
            }
          }
          if (floatFormat !== 0 && !noDataConversion) {
            data = new Float32Array(data2.buffer, 0, offset2 / 4);
          } else {
            data = new Uint8Array(data2.buffer, 0, offset2);
          }
        }
        gpuBuffer.unmap();
        if (destroyBuffer) {
          this.releaseBuffer(gpuBuffer);
        }
        resolve3(data);
      }, (reason) => {
        if (this._engine.isDisposed || this._engine.uniqueId !== engineId) {
          resolve3(new Uint8Array);
        } else {
          reject(reason);
        }
      });
    });
  }
  releaseBuffer(buffer2) {
    if (WebGPUBufferManager._IsGPUBuffer(buffer2)) {
      this._deferredReleaseBuffers.push(buffer2);
      return true;
    }
    buffer2.references--;
    if (buffer2.references === 0) {
      this._deferredReleaseBuffers.push(buffer2.underlyingResource);
      return true;
    }
    return false;
  }
  destroyDeferredBuffers() {
    for (let i = 0;i < this._deferredReleaseBuffers.length; ++i) {
      this._deferredReleaseBuffers[i].destroy();
    }
    this._deferredReleaseBuffers.length = 0;
  }
}

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_uniformBuffer();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheSampler.js
var filterToBits = [
  0 | 0 << 1 | 0 << 2,
  0 | 0 << 1 | 0 << 2,
  1 | 1 << 1 | 0 << 2,
  1 | 1 << 1 | 1 << 2,
  0 | 0 << 1 | 0 << 2,
  0 | 1 << 1 | 0 << 2,
  0 | 1 << 1 | 1 << 2,
  0 | 1 << 1 | 0 << 2,
  0 | 0 << 1 | 1 << 2,
  1 | 0 << 1 | 0 << 2,
  1 | 0 << 1 | 1 << 2,
  1 | 1 << 1 | 0 << 2,
  1 | 0 << 1 | 0 << 2
];
var comparisonFunctionToBits = [
  0 << 3 | 0 << 4 | 0 << 5 | 0 << 6,
  0 << 3 | 0 << 4 | 0 << 5 | 1 << 6,
  0 << 3 | 0 << 4 | 1 << 5 | 0 << 6,
  0 << 3 | 0 << 4 | 1 << 5 | 1 << 6,
  0 << 3 | 1 << 4 | 0 << 5 | 0 << 6,
  0 << 3 | 1 << 4 | 0 << 5 | 1 << 6,
  0 << 3 | 1 << 4 | 1 << 5 | 0 << 6,
  0 << 3 | 1 << 4 | 1 << 5 | 1 << 6,
  1 << 3 | 0 << 4 | 0 << 5 | 0 << 6
];
var filterNoMipToBits = [
  0 << 7,
  1 << 7,
  1 << 7,
  0 << 7,
  0 << 7,
  0 << 7,
  0 << 7,
  1 << 7,
  0 << 7,
  0 << 7,
  0 << 7,
  0 << 7,
  1 << 7
];

class WebGPUCacheSampler {
  constructor(device) {
    this._samplers = {};
    this._device = device;
    this.disabled = false;
  }
  static GetSamplerHashCode(sampler) {
    const anisotropy = sampler._cachedAnisotropicFilteringLevel ? sampler._cachedAnisotropicFilteringLevel : 1;
    const code = filterToBits[sampler.samplingMode] + comparisonFunctionToBits[(sampler._comparisonFunction || 514) - 512 + 1] + filterNoMipToBits[sampler.samplingMode] + ((sampler._cachedWrapU ?? 1) << 8) + ((sampler._cachedWrapV ?? 1) << 10) + ((sampler._cachedWrapR ?? 1) << 12) + ((sampler.useMipMaps ? 1 : 0) << 14) + (anisotropy << 15);
    return code;
  }
  static _GetSamplerFilterDescriptor(sampler, anisotropy) {
    let magFilter, minFilter, mipmapFilter, lodMinClamp, lodMaxClamp;
    const useMipMaps = sampler.useMipMaps;
    switch (sampler.samplingMode) {
      case 11:
        magFilter = "linear";
        minFilter = "linear";
        mipmapFilter = "nearest";
        if (!useMipMaps) {
          lodMinClamp = lodMaxClamp = 0;
        }
        break;
      case 3:
      case 3:
        magFilter = "linear";
        minFilter = "linear";
        if (!useMipMaps) {
          mipmapFilter = "nearest";
          lodMinClamp = lodMaxClamp = 0;
        } else {
          mipmapFilter = "linear";
        }
        break;
      case 8:
        magFilter = "nearest";
        minFilter = "nearest";
        if (!useMipMaps) {
          mipmapFilter = "nearest";
          lodMinClamp = lodMaxClamp = 0;
        } else {
          mipmapFilter = "linear";
        }
        break;
      case 4:
        magFilter = "nearest";
        minFilter = "nearest";
        mipmapFilter = "nearest";
        if (!useMipMaps) {
          lodMinClamp = lodMaxClamp = 0;
        }
        break;
      case 5:
        magFilter = "nearest";
        minFilter = "linear";
        mipmapFilter = "nearest";
        if (!useMipMaps) {
          lodMinClamp = lodMaxClamp = 0;
        }
        break;
      case 6:
        magFilter = "nearest";
        minFilter = "linear";
        if (!useMipMaps) {
          mipmapFilter = "nearest";
          lodMinClamp = lodMaxClamp = 0;
        } else {
          mipmapFilter = "linear";
        }
        break;
      case 7:
        magFilter = "nearest";
        minFilter = "linear";
        mipmapFilter = "nearest";
        lodMinClamp = lodMaxClamp = 0;
        break;
      case 1:
      case 1:
        magFilter = "nearest";
        minFilter = "nearest";
        mipmapFilter = "nearest";
        lodMinClamp = lodMaxClamp = 0;
        break;
      case 9:
        magFilter = "linear";
        minFilter = "nearest";
        mipmapFilter = "nearest";
        if (!useMipMaps) {
          lodMinClamp = lodMaxClamp = 0;
        }
        break;
      case 10:
        magFilter = "linear";
        minFilter = "nearest";
        if (!useMipMaps) {
          mipmapFilter = "nearest";
          lodMinClamp = lodMaxClamp = 0;
        } else {
          mipmapFilter = "linear";
        }
        break;
      case 2:
      case 2:
        magFilter = "linear";
        minFilter = "linear";
        if (anisotropy > 1) {
          mipmapFilter = "linear";
        } else {
          mipmapFilter = "nearest";
          lodMinClamp = lodMaxClamp = 0;
        }
        break;
      case 12:
        magFilter = "linear";
        minFilter = "nearest";
        mipmapFilter = "nearest";
        lodMinClamp = lodMaxClamp = 0;
        break;
      default:
        magFilter = "nearest";
        minFilter = "nearest";
        mipmapFilter = "nearest";
        lodMinClamp = lodMaxClamp = 0;
        break;
    }
    if (anisotropy > 1 && (lodMinClamp !== 0 || lodMaxClamp !== 0)) {
      return {
        magFilter: "linear",
        minFilter: "linear",
        mipmapFilter: "linear",
        anisotropyEnabled: true
      };
    }
    return {
      magFilter,
      minFilter,
      mipmapFilter,
      lodMinClamp,
      lodMaxClamp
    };
  }
  static _GetWrappingMode(mode) {
    switch (mode) {
      case 1:
        return "repeat";
      case 0:
        return "clamp-to-edge";
      case 2:
        return "mirror-repeat";
    }
    return "repeat";
  }
  static _GetSamplerWrappingDescriptor(sampler) {
    return {
      addressModeU: this._GetWrappingMode(sampler._cachedWrapU),
      addressModeV: this._GetWrappingMode(sampler._cachedWrapV),
      addressModeW: this._GetWrappingMode(sampler._cachedWrapR)
    };
  }
  static _GetSamplerDescriptor(sampler, label) {
    let anisotropy = (sampler.useMipMaps || sampler.samplingMode === 2) && sampler._cachedAnisotropicFilteringLevel ? sampler._cachedAnisotropicFilteringLevel : 1;
    if (sampler.samplingMode !== 11 && sampler.samplingMode !== 3 && sampler.samplingMode !== 2) {
      anisotropy = 1;
    }
    const filterDescriptor = this._GetSamplerFilterDescriptor(sampler, anisotropy);
    return {
      label,
      ...filterDescriptor,
      ...this._GetSamplerWrappingDescriptor(sampler),
      compare: sampler._comparisonFunction ? WebGPUCacheSampler.GetCompareFunction(sampler._comparisonFunction) : undefined,
      maxAnisotropy: filterDescriptor.anisotropyEnabled ? anisotropy : 1
    };
  }
  static GetCompareFunction(compareFunction) {
    switch (compareFunction) {
      case 519:
        return "always";
      case 514:
        return "equal";
      case 516:
        return "greater";
      case 518:
        return "greater-equal";
      case 513:
        return "less";
      case 515:
        return "less-equal";
      case 512:
        return "never";
      case 517:
        return "not-equal";
      default:
        return "less";
    }
  }
  getSampler(sampler, bypassCache = false, hash2 = 0, label) {
    if (this.disabled) {
      return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler, label));
    }
    if (bypassCache) {
      hash2 = 0;
    } else if (hash2 === 0) {
      hash2 = WebGPUCacheSampler.GetSamplerHashCode(sampler);
    }
    let gpuSampler = bypassCache ? undefined : this._samplers[hash2];
    if (!gpuSampler) {
      gpuSampler = this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler, label));
      if (!bypassCache) {
        this._samplers[hash2] = gpuSampler;
      }
    }
    return gpuSampler;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipeline.js
init_buffer();
init_logger();
var StatePosition;
(function(StatePosition2) {
  StatePosition2[StatePosition2["StencilReadMask"] = 0] = "StencilReadMask";
  StatePosition2[StatePosition2["StencilWriteMask"] = 1] = "StencilWriteMask";
  StatePosition2[StatePosition2["DepthBias"] = 2] = "DepthBias";
  StatePosition2[StatePosition2["DepthBiasSlopeScale"] = 3] = "DepthBiasSlopeScale";
  StatePosition2[StatePosition2["DepthStencilState"] = 4] = "DepthStencilState";
  StatePosition2[StatePosition2["MRTAttachments1"] = 5] = "MRTAttachments1";
  StatePosition2[StatePosition2["MRTAttachments2"] = 6] = "MRTAttachments2";
  StatePosition2[StatePosition2["RasterizationState"] = 7] = "RasterizationState";
  StatePosition2[StatePosition2["ColorStates"] = 8] = "ColorStates";
  StatePosition2[StatePosition2["ShaderStage"] = 9] = "ShaderStage";
  StatePosition2[StatePosition2["TextureStage"] = 10] = "TextureStage";
  StatePosition2[StatePosition2["VertexState"] = 11] = "VertexState";
  StatePosition2[StatePosition2["NumStates"] = 12] = "NumStates";
})(StatePosition || (StatePosition = {}));
var alphaBlendFactorToIndex = {
  0: 1,
  1: 2,
  768: 3,
  769: 4,
  770: 5,
  771: 6,
  772: 7,
  773: 8,
  774: 9,
  775: 10,
  776: 11,
  32769: 12,
  32770: 13,
  32771: 12,
  32772: 13
};
var stencilOpToIndex = {
  0: 0,
  7680: 1,
  7681: 2,
  7682: 3,
  7683: 4,
  5386: 5,
  34055: 6,
  34056: 7
};

class WebGPUCacheRenderPipeline {
  constructor(device, emptyVertexBuffer) {
    this.mrtTextureCount = 0;
    this._device = device;
    this._useTextureStage = true;
    this._states = new Array(30);
    this._statesLength = 0;
    this._stateDirtyLowestIndex = 0;
    this._emptyVertexBuffer = emptyVertexBuffer;
    this._mrtFormats = [];
    this._parameter = { token: undefined, pipeline: null };
    this.disabled = false;
    this.vertexBuffers = [];
    this._kMaxVertexBufferStride = device.limits.maxVertexBufferArrayStride || 2048;
    this.reset();
  }
  reset() {
    this._isDirty = true;
    this.vertexBuffers.length = 0;
    this.setAlphaToCoverage(false);
    this.resetDepthCullingState();
    this.setClampDepth(false);
    this.setDepthBias(0);
    this._webgpuColorFormat = ["bgra8unorm"];
    this.setColorFormat("bgra8unorm");
    this.setMRT([]);
    this.setAlphaBlendEnabled(false);
    this.setAlphaBlendFactors([null, null, null, null], [null, null]);
    this.setWriteMask(15);
    this.setDepthStencilFormat("depth24plus-stencil8");
    this.setStencilEnabled(false);
    this.resetStencilState();
    this.setBuffers(null, null, null);
    this._setTextureState(0);
  }
  get colorFormats() {
    return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat;
  }
  getRenderPipeline(fillMode, effect, sampleCount, textureState = 0) {
    sampleCount = WebGPUTextureHelper.GetSample(sampleCount);
    if (this.disabled) {
      const topology2 = WebGPUCacheRenderPipeline._GetTopology(fillMode);
      this._setVertexState(effect);
      this._setTextureState(textureState);
      this._parameter.pipeline = this._createRenderPipeline(effect, topology2, sampleCount);
      WebGPUCacheRenderPipeline.NumCacheMiss++;
      WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;
      return this._parameter.pipeline;
    }
    this._setShaderStage(effect.uniqueId);
    this._setRasterizationState(fillMode, sampleCount);
    this._setColorStates();
    this._setDepthStencilState();
    this._setVertexState(effect);
    this._setTextureState(textureState);
    this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex;
    if (!this._isDirty && this._parameter.pipeline) {
      this._stateDirtyLowestIndex = this._statesLength;
      WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++;
      return this._parameter.pipeline;
    }
    this._getRenderPipeline(this._parameter);
    this._isDirty = false;
    this._stateDirtyLowestIndex = this._statesLength;
    if (this._parameter.pipeline) {
      WebGPUCacheRenderPipeline.NumCacheHitWithHash++;
      return this._parameter.pipeline;
    }
    const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode);
    this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount);
    this._setRenderPipeline(this._parameter);
    WebGPUCacheRenderPipeline.NumCacheMiss++;
    WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;
    return this._parameter.pipeline;
  }
  endFrame() {
    WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame;
    WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;
  }
  setAlphaToCoverage(enabled) {
    this._alphaToCoverageEnabled = enabled;
  }
  setFrontFace(frontFace) {
    this._frontFace = frontFace;
  }
  setCullEnabled(enabled) {
    this._cullEnabled = enabled;
  }
  setCullFace(cullFace) {
    this._cullFace = cullFace;
  }
  setClampDepth(clampDepth) {
    this._clampDepth = clampDepth;
  }
  resetDepthCullingState() {
    this.setDepthCullingState(false, 2, 1, 0, 0, true, true, 519);
  }
  setDepthCullingState(cullEnabled, frontFace, cullFace, zOffset, zOffsetUnits, depthTestEnabled, depthWriteEnabled, depthCompare) {
    this._depthWriteEnabled = depthWriteEnabled;
    this._depthTestEnabled = depthTestEnabled;
    this._depthCompare = (depthCompare ?? 519) - 512;
    this._cullFace = cullFace;
    this._cullEnabled = cullEnabled;
    this._frontFace = frontFace;
    this.setDepthBiasSlopeScale(zOffset);
    this.setDepthBias(zOffsetUnits);
  }
  setDepthBias(depthBias) {
    if (this._depthBias !== depthBias) {
      this._depthBias = depthBias;
      this._states[StatePosition.DepthBias] = depthBias;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias);
    }
  }
  setDepthBiasSlopeScale(depthBiasSlopeScale) {
    if (this._depthBiasSlopeScale !== depthBiasSlopeScale) {
      this._depthBiasSlopeScale = depthBiasSlopeScale;
      this._states[StatePosition.DepthBiasSlopeScale] = depthBiasSlopeScale;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale);
    }
  }
  setColorFormat(format) {
    this._webgpuColorFormat[0] = format;
    this._colorFormat = renderableTextureFormatToIndex[format ?? ""];
  }
  setMRTAttachments(attachments) {
    this.mrtAttachments = attachments;
    let mask = 0;
    for (let i = 0;i < attachments.length; ++i) {
      if (attachments[i] !== 0) {
        mask += 1 << i;
      }
    }
    if (this._mrtEnabledMask !== mask) {
      this._mrtEnabledMask = mask;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);
    }
  }
  setMRT(textureArray, textureCount) {
    textureCount = textureCount ?? textureArray.length;
    if (textureCount > 10) {
      throw "Can't handle more than 10 attachments for a MRT in cache render pipeline!";
    }
    this.mrtTextureArray = textureArray;
    this.mrtTextureCount = textureCount;
    this._mrtEnabledMask = 65535;
    const bits = [0, 0];
    let indexBits = 0, mask = 0, numRT = 0;
    for (let i = 0;i < textureCount; ++i) {
      const texture = textureArray[i];
      const gpuWrapper = texture?._hardwareTexture;
      this._mrtFormats[numRT] = gpuWrapper?.format ?? this._webgpuColorFormat[0];
      bits[indexBits] += renderableTextureFormatToIndex[this._mrtFormats[numRT] ?? ""] << mask;
      mask += 6;
      numRT++;
      if (mask >= 32) {
        mask = 0;
        indexBits++;
      }
    }
    this._mrtFormats.length = numRT;
    if (this._mrtAttachments1 !== bits[0] || this._mrtAttachments2 !== bits[1]) {
      this._mrtAttachments1 = bits[0];
      this._mrtAttachments2 = bits[1];
      this._states[StatePosition.MRTAttachments1] = bits[0];
      this._states[StatePosition.MRTAttachments2] = bits[1];
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);
    }
  }
  setAlphaBlendEnabled(enabled) {
    this._alphaBlendEnabled = enabled;
  }
  setAlphaBlendFactors(factors, operations) {
    this._alphaBlendFuncParams = factors;
    this._alphaBlendEqParams = operations;
  }
  setWriteMask(mask) {
    this._writeMask = mask;
  }
  setDepthStencilFormat(format) {
    this._webgpuDepthStencilFormat = format;
    this._depthStencilFormat = format === undefined ? 0 : renderableTextureFormatToIndex[format];
  }
  setDepthTestEnabled(enabled) {
    this._depthTestEnabled = enabled;
  }
  setDepthWriteEnabled(enabled) {
    this._depthWriteEnabled = enabled;
  }
  setDepthCompare(func) {
    this._depthCompare = (func ?? 519) - 512;
  }
  setStencilEnabled(enabled) {
    this._stencilEnabled = enabled;
  }
  setStencilCompare(func) {
    this._stencilFrontCompare = (func ?? 519) - 512;
  }
  setStencilDepthFailOp(op) {
    this._stencilFrontDepthFailOp = op === null ? 1 : stencilOpToIndex[op];
  }
  setStencilPassOp(op) {
    this._stencilFrontPassOp = op === null ? 2 : stencilOpToIndex[op];
  }
  setStencilFailOp(op) {
    this._stencilFrontFailOp = op === null ? 1 : stencilOpToIndex[op];
  }
  setStencilReadMask(mask) {
    if (this._stencilReadMask !== mask) {
      this._stencilReadMask = mask;
      this._states[StatePosition.StencilReadMask] = mask;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask);
    }
  }
  setStencilWriteMask(mask) {
    if (this._stencilWriteMask !== mask) {
      this._stencilWriteMask = mask;
      this._states[StatePosition.StencilWriteMask] = mask;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask);
    }
  }
  resetStencilState() {
    this.setStencilState(false, 519, 7680, 7681, 7680, 255, 255);
  }
  setStencilState(stencilEnabled, compare, depthFailOp, passOp, failOp, readMask, writeMask) {
    this._stencilEnabled = stencilEnabled;
    this._stencilFrontCompare = (compare ?? 519) - 512;
    this._stencilFrontDepthFailOp = depthFailOp === null ? 1 : stencilOpToIndex[depthFailOp];
    this._stencilFrontPassOp = passOp === null ? 2 : stencilOpToIndex[passOp];
    this._stencilFrontFailOp = failOp === null ? 1 : stencilOpToIndex[failOp];
    this.setStencilReadMask(readMask);
    this.setStencilWriteMask(writeMask);
  }
  setBuffers(vertexBuffers, indexBuffer, overrideVertexBuffers) {
    this._vertexBuffers = vertexBuffers;
    this._overrideVertexBuffers = overrideVertexBuffers;
    this._indexBuffer = indexBuffer;
  }
  static _GetTopology(fillMode) {
    switch (fillMode) {
      case 0:
        return "triangle-list";
      case 2:
        return "point-list";
      case 1:
        return "line-list";
      case 3:
        return "point-list";
      case 4:
        return "line-list";
      case 5:
        throw "LineLoop is an unsupported fillmode in WebGPU";
      case 6:
        return "line-strip";
      case 7:
        return "triangle-strip";
      case 8:
        throw "TriangleFan is an unsupported fillmode in WebGPU";
      default:
        return "triangle-list";
    }
  }
  static _GetAphaBlendOperation(operation) {
    switch (operation) {
      case 32774:
        return "add";
      case 32778:
        return "subtract";
      case 32779:
        return "reverse-subtract";
      case 32775:
        return "min";
      case 32776:
        return "max";
      default:
        return "add";
    }
  }
  static _GetAphaBlendFactor(factor) {
    switch (factor) {
      case 0:
        return "zero";
      case 1:
        return "one";
      case 768:
        return "src";
      case 769:
        return "one-minus-src";
      case 770:
        return "src-alpha";
      case 771:
        return "one-minus-src-alpha";
      case 772:
        return "dst-alpha";
      case 773:
        return "one-minus-dst-alpha";
      case 774:
        return "dst";
      case 775:
        return "one-minus-dst";
      case 776:
        return "src-alpha-saturated";
      case 32769:
        return "constant";
      case 32770:
        return "one-minus-constant";
      case 32771:
        return "constant";
      case 32772:
        return "one-minus-constant";
      case 35065:
        return "src1";
      case 35066:
        return "one-minus-src1";
      case 34185:
        return "src1-alpha";
      case 35067:
        return "one-minus-src1-alpha";
      default:
        return "one";
    }
  }
  static _GetCompareFunction(compareFunction) {
    switch (compareFunction) {
      case 0:
        return "never";
      case 1:
        return "less";
      case 2:
        return "equal";
      case 3:
        return "less-equal";
      case 4:
        return "greater";
      case 5:
        return "not-equal";
      case 6:
        return "greater-equal";
      case 7:
        return "always";
    }
    return "never";
  }
  static _GetStencilOpFunction(operation) {
    switch (operation) {
      case 0:
        return "zero";
      case 1:
        return "keep";
      case 2:
        return "replace";
      case 3:
        return "increment-clamp";
      case 4:
        return "decrement-clamp";
      case 5:
        return "invert";
      case 6:
        return "increment-wrap";
      case 7:
        return "decrement-wrap";
    }
    return "keep";
  }
  static _GetVertexInputDescriptorFormat(vertexBuffer) {
    const type = vertexBuffer.type;
    const normalized = vertexBuffer.normalized;
    const size = vertexBuffer.getSize();
    switch (type) {
      case VertexBuffer.BYTE:
        switch (size) {
          case 1:
          case 2:
            return normalized ? "snorm8x2" : "sint8x2";
          case 3:
          case 4:
            return normalized ? "snorm8x4" : "sint8x4";
        }
        break;
      case VertexBuffer.UNSIGNED_BYTE:
        switch (size) {
          case 1:
          case 2:
            return normalized ? "unorm8x2" : "uint8x2";
          case 3:
          case 4:
            return normalized ? "unorm8x4" : "uint8x4";
        }
        break;
      case VertexBuffer.SHORT:
        switch (size) {
          case 1:
          case 2:
            return normalized ? "snorm16x2" : "sint16x2";
          case 3:
          case 4:
            return normalized ? "snorm16x4" : "sint16x4";
        }
        break;
      case VertexBuffer.UNSIGNED_SHORT:
        switch (size) {
          case 1:
          case 2:
            return normalized ? "unorm16x2" : "uint16x2";
          case 3:
          case 4:
            return normalized ? "unorm16x4" : "uint16x4";
        }
        break;
      case VertexBuffer.INT:
        switch (size) {
          case 1:
            return "sint32";
          case 2:
            return "sint32x2";
          case 3:
            return "sint32x3";
          case 4:
            return "sint32x4";
        }
        break;
      case VertexBuffer.UNSIGNED_INT:
        switch (size) {
          case 1:
            return "uint32";
          case 2:
            return "uint32x2";
          case 3:
            return "uint32x3";
          case 4:
            return "uint32x4";
        }
        break;
      case VertexBuffer.FLOAT:
        switch (size) {
          case 1:
            return "float32";
          case 2:
            return "float32x2";
          case 3:
            return "float32x3";
          case 4:
            return "float32x4";
        }
        break;
    }
    throw new Error(`Invalid Format '${vertexBuffer.getKind()}' - type=${type}, normalized=${normalized}, size=${size}`);
  }
  _getAphaBlendState() {
    if (!this._alphaBlendEnabled) {
      return null;
    }
    return {
      srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),
      dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),
      operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1])
    };
  }
  _getColorBlendState() {
    if (!this._alphaBlendEnabled) {
      return null;
    }
    return {
      srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),
      dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),
      operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0])
    };
  }
  _setShaderStage(id) {
    if (this._shaderId !== id) {
      this._shaderId = id;
      this._states[StatePosition.ShaderStage] = id;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage);
    }
  }
  _setRasterizationState(topology, sampleCount) {
    const frontFace = this._frontFace;
    const cullMode = this._cullEnabled ? this._cullFace : 0;
    const clampDepth = this._clampDepth ? 1 : 0;
    const alphaToCoverage = this._alphaToCoverageEnabled ? 1 : 0;
    const rasterizationState = frontFace - 1 + (cullMode << 1) + (clampDepth << 3) + (alphaToCoverage << 4) + (topology << 5) + (sampleCount << 8);
    if (this._rasterizationState !== rasterizationState) {
      this._rasterizationState = rasterizationState;
      this._states[StatePosition.RasterizationState] = this._rasterizationState;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState);
    }
  }
  _setColorStates() {
    let colorStates = ((this._writeMask ? 1 : 0) << 22) + (this._colorFormat << 23) + ((this._depthWriteEnabled ? 1 : 0) << 29);
    if (this._alphaBlendEnabled) {
      colorStates += ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) + ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) + ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) + ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) + ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 32773) << 16) + ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 32773) << 19);
    }
    if (colorStates !== this._colorStates) {
      this._colorStates = colorStates;
      this._states[StatePosition.ColorStates] = this._colorStates;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates);
    }
  }
  _setDepthStencilState() {
    const stencilState = !this._stencilEnabled ? 7 + (1 << 3) + (1 << 6) + (1 << 9) : this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9);
    const depthStencilState = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) << 6) + (stencilState << 10);
    if (this._depthStencilState !== depthStencilState) {
      this._depthStencilState = depthStencilState;
      this._states[StatePosition.DepthStencilState] = this._depthStencilState;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState);
    }
  }
  _setVertexState(effect) {
    const currStateLen = this._statesLength;
    let newNumStates = StatePosition.VertexState;
    const webgpuPipelineContext = effect._pipelineContext;
    const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;
    const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;
    let currentGPUBuffer;
    let numVertexBuffers = 0;
    for (let index = 0;index < attributes.length; index++) {
      const location2 = locations[index];
      let vertexBuffer = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]]) ?? this._vertexBuffers[attributes[index]];
      if (!vertexBuffer) {
        vertexBuffer = this._emptyVertexBuffer;
        if (WebGPUCacheRenderPipeline.LogErrorIfNoVertexBuffer) {
          Logger.Error(`No vertex buffer is provided for the "${attributes[index]}" attribute. A default empty vertex buffer will be used, but this may generate errors in some browsers.`);
        }
      }
      const buffer2 = vertexBuffer.effectiveBuffer?.underlyingResource;
      if (vertexBuffer._validOffsetRange === undefined) {
        const offset = vertexBuffer.effectiveByteOffset;
        const formatSize = vertexBuffer.getSize(true);
        const byteStride = vertexBuffer.effectiveByteStride;
        vertexBuffer._validOffsetRange = offset + formatSize <= this._kMaxVertexBufferStride && byteStride === 0 || byteStride !== 0 && offset + formatSize <= byteStride;
      }
      if (!(currentGPUBuffer && currentGPUBuffer === buffer2 && vertexBuffer._validOffsetRange)) {
        this.vertexBuffers[numVertexBuffers++] = vertexBuffer;
        currentGPUBuffer = vertexBuffer._validOffsetRange ? buffer2 : null;
      }
      const vid = vertexBuffer.hashCode + (location2 << 7);
      this._isDirty = this._isDirty || this._states[newNumStates] !== vid;
      this._states[newNumStates++] = vid;
    }
    this.vertexBuffers.length = numVertexBuffers;
    this._statesLength = newNumStates;
    this._isDirty = this._isDirty || newNumStates !== currStateLen;
    if (this._isDirty) {
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState);
    }
  }
  _setTextureState(textureState) {
    if (this._textureState !== textureState) {
      this._textureState = textureState;
      this._states[StatePosition.TextureStage] = this._textureState;
      this._isDirty = true;
      this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage);
    }
  }
  _createPipelineLayout(webgpuPipelineContext) {
    if (this._useTextureStage) {
      return this._createPipelineLayoutWithTextureStage(webgpuPipelineContext);
    }
    const bindGroupLayouts = [];
    const bindGroupLayoutEntries = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries;
    for (let i = 0;i < bindGroupLayoutEntries.length; i++) {
      const setDefinition = bindGroupLayoutEntries[i];
      bindGroupLayouts[i] = this._device.createBindGroupLayout({
        entries: setDefinition
      });
    }
    webgpuPipelineContext.bindGroupLayouts[0] = bindGroupLayouts;
    return this._device.createPipelineLayout({ bindGroupLayouts });
  }
  _createPipelineLayoutWithTextureStage(webgpuPipelineContext) {
    const shaderProcessingContext = webgpuPipelineContext.shaderProcessingContext;
    const bindGroupLayoutEntries = shaderProcessingContext.bindGroupLayoutEntries;
    let bitVal = 1;
    for (let i = 0;i < bindGroupLayoutEntries.length; i++) {
      const setDefinition = bindGroupLayoutEntries[i];
      for (let j = 0;j < setDefinition.length; j++) {
        const entry = bindGroupLayoutEntries[i][j];
        if (entry.texture) {
          const name155 = shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;
          const textureInfo = shaderProcessingContext.availableTextures[name155];
          const samplerInfo = textureInfo.autoBindSampler ? shaderProcessingContext.availableSamplers[name155 + `Sampler`] : null;
          let sampleType = textureInfo.sampleType;
          let samplerType = samplerInfo?.type ?? "filtering";
          if (this._textureState & bitVal && sampleType !== "depth") {
            if (textureInfo.autoBindSampler) {
              samplerType = "non-filtering";
            }
            sampleType = "unfilterable-float";
          }
          entry.texture.sampleType = sampleType;
          if (samplerInfo) {
            const binding = shaderProcessingContext.bindGroupLayoutEntryInfo[samplerInfo.binding.groupIndex][samplerInfo.binding.bindingIndex].index;
            bindGroupLayoutEntries[samplerInfo.binding.groupIndex][binding].sampler.type = samplerType;
          }
          bitVal = bitVal << 1;
        }
      }
    }
    const bindGroupLayouts = [];
    for (let i = 0;i < bindGroupLayoutEntries.length; ++i) {
      bindGroupLayouts[i] = this._device.createBindGroupLayout({
        entries: bindGroupLayoutEntries[i]
      });
    }
    webgpuPipelineContext.bindGroupLayouts[this._textureState] = bindGroupLayouts;
    return this._device.createPipelineLayout({ bindGroupLayouts });
  }
  _getVertexInputDescriptor(effect) {
    const descriptors = [];
    const webgpuPipelineContext = effect._pipelineContext;
    const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;
    const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;
    let currentGPUBuffer;
    let currentGPUAttributes;
    for (let index = 0;index < attributes.length; index++) {
      const location2 = locations[index];
      let vertexBuffer = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]]) ?? this._vertexBuffers[attributes[index]];
      if (!vertexBuffer) {
        vertexBuffer = this._emptyVertexBuffer;
      }
      let buffer2 = vertexBuffer.effectiveBuffer?.underlyingResource;
      let offset = vertexBuffer.effectiveByteOffset;
      const invalidOffsetRange = !vertexBuffer._validOffsetRange;
      if (!(currentGPUBuffer && currentGPUAttributes && currentGPUBuffer === buffer2) || invalidOffsetRange) {
        const vertexBufferDescriptor = {
          arrayStride: vertexBuffer.effectiveByteStride,
          stepMode: vertexBuffer.getIsInstanced() ? "instance" : "vertex",
          attributes: []
        };
        descriptors.push(vertexBufferDescriptor);
        currentGPUAttributes = vertexBufferDescriptor.attributes;
        if (invalidOffsetRange) {
          offset = 0;
          buffer2 = null;
        }
      }
      currentGPUAttributes.push({
        shaderLocation: location2,
        offset,
        format: WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(vertexBuffer)
      });
      currentGPUBuffer = buffer2;
    }
    return descriptors;
  }
  _createRenderPipeline(effect, topology, sampleCount) {
    const webgpuPipelineContext = effect._pipelineContext;
    const inputStateDescriptor = this._getVertexInputDescriptor(effect);
    const pipelineLayout = this._createPipelineLayout(webgpuPipelineContext);
    const colorStates = [];
    const alphaBlend = this._getAphaBlendState();
    const colorBlend = this._getColorBlendState();
    if (this._vertexBuffers) {
      checkNonFloatVertexBuffers(this._vertexBuffers, effect);
    }
    if (this._mrtAttachments1 > 0) {
      for (let i = 0;i < this._mrtFormats.length; ++i) {
        const format = this._mrtFormats[i];
        if (format) {
          const descr = {
            format,
            writeMask: (this._mrtEnabledMask & 1 << i) !== 0 ? this._writeMask : 0
          };
          if (alphaBlend && colorBlend) {
            descr.blend = {
              alpha: alphaBlend,
              color: colorBlend
            };
          }
          colorStates.push(descr);
        } else {
          colorStates.push(null);
        }
      }
    } else {
      if (this._webgpuColorFormat[0]) {
        const descr = {
          format: this._webgpuColorFormat[0],
          writeMask: this._writeMask
        };
        if (alphaBlend && colorBlend) {
          descr.blend = {
            alpha: alphaBlend,
            color: colorBlend
          };
        }
        colorStates.push(descr);
      } else {
        colorStates.push(null);
      }
    }
    const stencilFrontBack = {
      compare: WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7),
      depthFailOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1),
      failOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1),
      passOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1)
    };
    const topologyIsTriangle = topology === "triangle-list" || topology === "triangle-strip";
    let stripIndexFormat = undefined;
    if (topology === "line-strip" || topology === "triangle-strip") {
      stripIndexFormat = !this._indexBuffer || this._indexBuffer.is32Bits ? "uint32" : "uint16";
    }
    const depthStencilFormatHasStencil = this._webgpuDepthStencilFormat ? WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat) : false;
    return this._device.createRenderPipeline({
      label: `RenderPipeline_${colorStates[0]?.format ?? "nooutput"}_${this._webgpuDepthStencilFormat ?? "nodepth"}_samples${sampleCount}_textureState${this._textureState}`,
      layout: pipelineLayout,
      vertex: {
        module: webgpuPipelineContext.stages.vertexStage.module,
        entryPoint: webgpuPipelineContext.stages.vertexStage.entryPoint,
        buffers: inputStateDescriptor
      },
      primitive: {
        topology,
        stripIndexFormat,
        frontFace: this._frontFace === 1 ? "ccw" : "cw",
        cullMode: !this._cullEnabled ? "none" : this._cullFace === 2 ? "front" : "back"
      },
      fragment: !webgpuPipelineContext.stages.fragmentStage ? undefined : {
        module: webgpuPipelineContext.stages.fragmentStage.module,
        entryPoint: webgpuPipelineContext.stages.fragmentStage.entryPoint,
        targets: colorStates
      },
      multisample: {
        count: sampleCount
      },
      depthStencil: this._webgpuDepthStencilFormat === undefined ? undefined : {
        depthWriteEnabled: this._depthWriteEnabled,
        depthCompare: this._depthTestEnabled ? WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare) : "always",
        format: this._webgpuDepthStencilFormat,
        stencilFront: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,
        stencilBack: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,
        stencilReadMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilReadMask : undefined,
        stencilWriteMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilWriteMask : undefined,
        depthBias: this._depthBias,
        depthBiasClamp: topologyIsTriangle ? this._depthBiasClamp : 0,
        depthBiasSlopeScale: topologyIsTriangle ? this._depthBiasSlopeScale : 0
      }
    });
  }
}
WebGPUCacheRenderPipeline.LogErrorIfNoVertexBuffer = false;
WebGPUCacheRenderPipeline.NumCacheHitWithoutHash = 0;
WebGPUCacheRenderPipeline.NumCacheHitWithHash = 0;
WebGPUCacheRenderPipeline.NumCacheMiss = 0;
WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = 0;
WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipelineTree.js
class NodeState {
  constructor() {
    this.values = {};
  }
  count() {
    let countNode = 0, countPipeline = this.pipeline ? 1 : 0;
    for (const value in this.values) {
      const node = this.values[value];
      const [childCountNodes, childCoundPipeline] = node.count();
      countNode += childCountNodes;
      countPipeline += childCoundPipeline;
      countNode++;
    }
    return [countNode, countPipeline];
  }
}

class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline {
  static GetNodeCounts() {
    const counts = WebGPUCacheRenderPipelineTree._Cache.count();
    return { nodeCount: counts[0], pipelineCount: counts[1] };
  }
  static _GetPipelines(node, pipelines, curPath, curPathLen) {
    if (node.pipeline) {
      const path = curPath.slice();
      path.length = curPathLen;
      pipelines.push(path);
    }
    for (const value in node.values) {
      const nnode = node.values[value];
      curPath[curPathLen] = parseInt(value);
      WebGPUCacheRenderPipelineTree._GetPipelines(nnode, pipelines, curPath, curPathLen + 1);
    }
  }
  static GetPipelines() {
    const pipelines = [];
    WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache, pipelines, [], 0);
    return pipelines;
  }
  static ResetCache() {
    WebGPUCacheRenderPipelineTree._Cache = new NodeState;
  }
  reset() {
    this._nodeStack = [];
    this._nodeStack[0] = WebGPUCacheRenderPipelineTree._Cache;
    super.reset();
  }
  _getRenderPipeline(param) {
    let node = this._nodeStack[this._stateDirtyLowestIndex];
    for (let i = this._stateDirtyLowestIndex;i < this._statesLength; ++i) {
      let nn = node.values[this._states[i]];
      if (!nn) {
        nn = new NodeState;
        node.values[this._states[i]] = nn;
      }
      node = nn;
      this._nodeStack[i + 1] = node;
    }
    param.token = node;
    param.pipeline = node.pipeline;
  }
  _setRenderPipeline(param) {
    param.token.pipeline = param.pipeline;
  }
}
WebGPUCacheRenderPipelineTree._Cache = new NodeState;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuStencilStateComposer.js
class WebGPUStencilStateComposer extends StencilStateComposer {
  constructor(cache) {
    super(false);
    this._cache = cache;
    this.reset();
  }
  get func() {
    return this._func;
  }
  set func(value) {
    if (this._func === value) {
      return;
    }
    this._func = value;
    this._cache.setStencilCompare(value);
  }
  get funcMask() {
    return this._funcMask;
  }
  set funcMask(value) {
    if (this._funcMask === value) {
      return;
    }
    this._funcMask = value;
    this._cache.setStencilReadMask(value);
  }
  get opStencilFail() {
    return this._opStencilFail;
  }
  set opStencilFail(value) {
    if (this._opStencilFail === value) {
      return;
    }
    this._opStencilFail = value;
    this._cache.setStencilFailOp(value);
  }
  get opDepthFail() {
    return this._opDepthFail;
  }
  set opDepthFail(value) {
    if (this._opDepthFail === value) {
      return;
    }
    this._opDepthFail = value;
    this._cache.setStencilDepthFailOp(value);
  }
  get opStencilDepthPass() {
    return this._opStencilDepthPass;
  }
  set opStencilDepthPass(value) {
    if (this._opStencilDepthPass === value) {
      return;
    }
    this._opStencilDepthPass = value;
    this._cache.setStencilPassOp(value);
  }
  get mask() {
    return this._mask;
  }
  set mask(value) {
    if (this._mask === value) {
      return;
    }
    this._mask = value;
    this._cache.setStencilWriteMask(value);
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(value) {
    if (this._enabled === value) {
      return;
    }
    this._enabled = value;
    this._cache.setStencilEnabled(value);
  }
  reset() {
    super.reset();
    this._cache.resetStencilState();
  }
  apply() {
    const stencilMaterialEnabled = this.stencilMaterial?.enabled;
    this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;
    if (!this.enabled) {
      return;
    }
    this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;
    this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;
    this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;
    this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;
    this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;
    this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;
    this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuDepthCullingState.js
class WebGPUDepthCullingState extends DepthCullingState {
  constructor(cache) {
    super(false);
    this._cache = cache;
    this.reset();
  }
  get zOffset() {
    return this._zOffset;
  }
  set zOffset(value) {
    if (this._zOffset === value) {
      return;
    }
    this._zOffset = value;
    this._isZOffsetDirty = true;
    this._cache.setDepthBiasSlopeScale(value);
  }
  get zOffsetUnits() {
    return this._zOffsetUnits;
  }
  set zOffsetUnits(value) {
    if (this._zOffsetUnits === value) {
      return;
    }
    this._zOffsetUnits = value;
    this._isZOffsetDirty = true;
    this._cache.setDepthBias(value);
  }
  get cullFace() {
    return this._cullFace;
  }
  set cullFace(value) {
    if (this._cullFace === value) {
      return;
    }
    this._cullFace = value;
    this._isCullFaceDirty = true;
    this._cache.setCullFace(value ?? 1);
  }
  get cull() {
    return this._cull;
  }
  set cull(value) {
    if (this._cull === value) {
      return;
    }
    this._cull = value;
    this._isCullDirty = true;
    this._cache.setCullEnabled(!!value);
  }
  get depthFunc() {
    return this._depthFunc;
  }
  set depthFunc(value) {
    if (this._depthFunc === value) {
      return;
    }
    this._depthFunc = value;
    this._isDepthFuncDirty = true;
    this._cache.setDepthCompare(value);
  }
  get depthMask() {
    return this._depthMask;
  }
  set depthMask(value) {
    if (this._depthMask === value) {
      return;
    }
    this._depthMask = value;
    this._isDepthMaskDirty = true;
    this._cache.setDepthWriteEnabled(value);
  }
  get depthTest() {
    return this._depthTest;
  }
  set depthTest(value) {
    if (this._depthTest === value) {
      return;
    }
    this._depthTest = value;
    this._isDepthTestDirty = true;
    this._cache.setDepthTestEnabled(value);
  }
  get frontFace() {
    return this._frontFace;
  }
  set frontFace(value) {
    if (this._frontFace === value) {
      return;
    }
    this._frontFace = value;
    this._isFrontFaceDirty = true;
    this._cache.setFrontFace(value ?? 2);
  }
  reset() {
    super.reset();
    this._cache.resetDepthCullingState();
  }
  apply() {}
}

// node_modules/@babylonjs/core/Materials/Textures/externalTexture.js
init_internalTexture();

class ExternalTexture {
  static IsExternalTexture(texture) {
    return texture.underlyingResource !== undefined;
  }
  getClassName() {
    return "ExternalTexture";
  }
  get underlyingResource() {
    return this._video;
  }
  constructor(video) {
    this.useMipMaps = false;
    this.type = 16;
    this.format = 4294967295;
    this._video = video;
    this.uniqueId = InternalTexture._Counter++;
  }
  isReady() {
    return this._video.readyState >= this._video.HAVE_CURRENT_DATA;
  }
  dispose() {}
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuMaterialContext.js
class WebGPUMaterialContext {
  get forceBindGroupCreation() {
    return this._numExternalTextures > 0;
  }
  get hasFloatOrDepthTextures() {
    return this._numFloatOrDepthTextures > 0;
  }
  constructor() {
    this.uniqueId = WebGPUMaterialContext._Counter++;
    this.updateId = 0;
    this.textureState = 0;
    this.reset();
  }
  reset() {
    this.samplers = {};
    this.textures = {};
    this.isDirty = true;
    this._numFloatOrDepthTextures = 0;
    this._numExternalTextures = 0;
  }
  setSampler(name155, sampler) {
    let samplerCache = this.samplers[name155];
    let currentHashCode = -1;
    if (!samplerCache) {
      this.samplers[name155] = samplerCache = { sampler, hashCode: 0 };
    } else {
      currentHashCode = samplerCache.hashCode;
    }
    samplerCache.sampler = sampler;
    samplerCache.hashCode = sampler ? WebGPUCacheSampler.GetSamplerHashCode(sampler) : 0;
    const isDirty = currentHashCode !== samplerCache.hashCode;
    if (isDirty) {
      this.updateId++;
    }
    this.isDirty || (this.isDirty = isDirty);
  }
  setTexture(name155, texture) {
    let textureCache = this.textures[name155];
    let currentTextureId = -1;
    if (!textureCache) {
      this.textures[name155] = textureCache = { texture, isFloatOrDepthTexture: false, isExternalTexture: false };
    } else {
      currentTextureId = textureCache.texture?.uniqueId ?? -1;
    }
    if (textureCache.isExternalTexture) {
      this._numExternalTextures--;
    }
    if (textureCache.isFloatOrDepthTexture) {
      this._numFloatOrDepthTextures--;
    }
    if (texture) {
      textureCache.isFloatOrDepthTexture = texture.type === 1 || texture.format >= 13 && texture.format <= 18;
      textureCache.isExternalTexture = ExternalTexture.IsExternalTexture(texture);
      if (textureCache.isFloatOrDepthTexture) {
        this._numFloatOrDepthTextures++;
      }
      if (textureCache.isExternalTexture) {
        this._numExternalTextures++;
      }
    } else {
      textureCache.isFloatOrDepthTexture = false;
      textureCache.isExternalTexture = false;
    }
    textureCache.texture = texture;
    const isDirty = currentTextureId !== (texture?.uniqueId ?? -1);
    if (isDirty) {
      this.updateId++;
    }
    this.isDirty || (this.isDirty = isDirty);
  }
}
WebGPUMaterialContext._Counter = 0;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuDrawContext.js
class WebGPUDrawContext {
  isDirty(materialContextUpdateId) {
    return this._isDirty || this._materialContextUpdateId !== materialContextUpdateId;
  }
  resetIsDirty(materialContextUpdateId) {
    this._isDirty = false;
    this._materialContextUpdateId = materialContextUpdateId;
  }
  get useInstancing() {
    return this._useInstancing;
  }
  set useInstancing(use) {
    if (this._useInstancing === use) {
      return;
    }
    if (!use) {
      if (this.indirectDrawBuffer) {
        this._bufferManager.releaseBuffer(this.indirectDrawBuffer);
      }
      this.indirectDrawBuffer = undefined;
      this._indirectDrawData = undefined;
    } else {
      this.indirectDrawBuffer = this._bufferManager.createRawBuffer(20, BufferUsage.CopyDst | BufferUsage.Indirect | BufferUsage.Storage, undefined, "IndirectDrawBuffer");
      this._indirectDrawData = new Uint32Array(5);
      this._indirectDrawData[3] = 0;
      this._indirectDrawData[4] = 0;
    }
    this._useInstancing = use;
    this._currentInstanceCount = -1;
  }
  constructor(bufferManager) {
    this._bufferManager = bufferManager;
    this.uniqueId = WebGPUDrawContext._Counter++;
    this._useInstancing = false;
    this._currentInstanceCount = 0;
    this.reset();
  }
  reset() {
    this.buffers = {};
    this._isDirty = true;
    this._materialContextUpdateId = 0;
    this.fastBundle = undefined;
    this.bindGroups = undefined;
  }
  setBuffer(name155, buffer2) {
    this._isDirty || (this._isDirty = buffer2?.uniqueId !== this.buffers[name155]?.uniqueId);
    this.buffers[name155] = buffer2;
  }
  setIndirectData(indexOrVertexCount, instanceCount, firstIndexOrVertex) {
    if (instanceCount === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData) {
      return;
    }
    this._currentInstanceCount = instanceCount;
    this._indirectDrawData[0] = indexOrVertexCount;
    this._indirectDrawData[1] = instanceCount;
    this._indirectDrawData[2] = firstIndexOrVertex;
    this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20);
  }
  dispose() {
    if (this.indirectDrawBuffer) {
      this._bufferManager.releaseBuffer(this.indirectDrawBuffer);
      this.indirectDrawBuffer = undefined;
      this._indirectDrawData = undefined;
    }
    this.fastBundle = undefined;
    this.bindGroups = undefined;
    this.buffers = undefined;
  }
}
WebGPUDrawContext._Counter = 0;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheBindGroups.js
init_logger();
var bufferIdStart = 1 << 20;
var textureIdStart = 2 ** 35;

class WebGPUBindGroupCacheNode {
  constructor() {
    this.values = {};
  }
}

class WebGPUCacheBindGroups {
  static get Statistics() {
    return {
      totalCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,
      lastFrameCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,
      lookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,
      noLookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame
    };
  }
  static ResetCache() {
    WebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode;
    WebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0;
    WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0;
    WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0;
    WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0;
    WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;
    WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;
    WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;
  }
  constructor(device, cacheSampler, engine) {
    this.disabled = false;
    this._device = device;
    this._cacheSampler = cacheSampler;
    this._engine = engine;
  }
  endFrame() {
    WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame;
    WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame;
    WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame;
    WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;
    WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;
    WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;
  }
  getBindGroups(webgpuPipelineContext, drawContext, materialContext) {
    let bindGroups = undefined;
    let node = WebGPUCacheBindGroups._Cache;
    const cacheIsDisabled = this.disabled || materialContext.forceBindGroupCreation;
    if (!cacheIsDisabled) {
      if (!drawContext.isDirty(materialContext.updateId) && !materialContext.isDirty) {
        WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++;
        return drawContext.bindGroups;
      }
      for (const bufferName of webgpuPipelineContext.shaderProcessingContext.bufferNames) {
        const uboId = (drawContext.buffers[bufferName]?.uniqueId ?? 0) + bufferIdStart;
        let nextNode = node.values[uboId];
        if (!nextNode) {
          nextNode = new WebGPUBindGroupCacheNode;
          node.values[uboId] = nextNode;
        }
        node = nextNode;
      }
      for (const samplerName of webgpuPipelineContext.shaderProcessingContext.samplerNames) {
        const samplerHashCode = materialContext.samplers[samplerName]?.hashCode ?? 0;
        let nextNode = node.values[samplerHashCode];
        if (!nextNode) {
          nextNode = new WebGPUBindGroupCacheNode;
          node.values[samplerHashCode] = nextNode;
        }
        node = nextNode;
      }
      for (const textureName of webgpuPipelineContext.shaderProcessingContext.textureNames) {
        const textureId = (materialContext.textures[textureName]?.texture?.uniqueId ?? 0) + textureIdStart;
        let nextNode = node.values[textureId];
        if (!nextNode) {
          nextNode = new WebGPUBindGroupCacheNode;
          node.values[textureId] = nextNode;
        }
        node = nextNode;
      }
      bindGroups = node.bindGroups;
    }
    drawContext.resetIsDirty(materialContext.updateId);
    materialContext.isDirty = false;
    if (bindGroups) {
      drawContext.bindGroups = bindGroups;
      WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++;
      return bindGroups;
    }
    bindGroups = [];
    drawContext.bindGroups = bindGroups;
    if (!cacheIsDisabled) {
      node.bindGroups = bindGroups;
    }
    WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++;
    WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;
    const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[materialContext.textureState];
    for (let i = 0;i < webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries.length; i++) {
      const setDefinition = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i];
      const entries = webgpuPipelineContext.shaderProcessingContext.bindGroupEntries[i];
      for (let j = 0;j < setDefinition.length; j++) {
        const entry = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i][j];
        const entryInfo = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding];
        const name155 = entryInfo.nameInArrayOfTexture ?? entryInfo.name;
        if (entry.sampler) {
          const bindingInfo = materialContext.samplers[name155];
          if (bindingInfo) {
            const sampler = bindingInfo.sampler;
            if (!sampler) {
              if (this._engine.dbgSanityChecks) {
                Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(entry)}, name=${name155}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);
              }
              continue;
            }
            entries[j].resource = this._cacheSampler.getSampler(sampler, false, bindingInfo.hashCode, sampler.label);
          } else {
            Logger.Error(`Sampler "${name155}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50);
          }
        } else if (entry.texture || entry.storageTexture) {
          const bindingInfo = materialContext.textures[name155];
          if (bindingInfo) {
            if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {
              Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(entry)}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);
              continue;
            }
            const hardwareTexture = bindingInfo.texture._hardwareTexture;
            if (this._engine.dbgSanityChecks && (!hardwareTexture || entry.texture && !hardwareTexture.view || entry.storageTexture && !hardwareTexture.viewForWriting)) {
              Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(entry)}, name=${name155}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, isReady=${bindingInfo.texture?.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);
              continue;
            }
            entries[j].resource = entry.storageTexture ? hardwareTexture.viewForWriting : hardwareTexture.view;
          } else {
            Logger.Error(`Texture "${name155}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50);
          }
        } else if (entry.externalTexture) {
          const bindingInfo = materialContext.textures[name155];
          if (bindingInfo) {
            if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {
              Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(entry)}, name=${name155}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);
              continue;
            }
            const externalTexture = bindingInfo.texture.underlyingResource;
            if (this._engine.dbgSanityChecks && !externalTexture) {
              Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(entry)}, name=${name155}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, isReady=${bindingInfo.texture?.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);
              continue;
            }
            entries[j].resource = this._device.importExternalTexture({ source: externalTexture });
          } else {
            Logger.Error(`Texture "${name155}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50);
          }
        } else if (entry.buffer) {
          const dataBuffer2 = drawContext.buffers[name155];
          if (dataBuffer2) {
            const webgpuBuffer = dataBuffer2.underlyingResource;
            entries[j].resource.buffer = webgpuBuffer;
            entries[j].resource.size = dataBuffer2.capacity;
          } else {
            Logger.Error(`Can't find buffer "${name155}". entry=${JSON.stringify(entry)}, buffers=${JSON.stringify(drawContext.buffers)}, drawContext.uniqueId=${drawContext.uniqueId}`, 50);
          }
        }
      }
      const groupLayout = bindGroupLayouts[i];
      bindGroups[i] = this._device.createBindGroup({
        layout: groupLayout,
        entries
      });
    }
    return bindGroups;
  }
}
WebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0;
WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0;
WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0;
WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0;
WebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode;
WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;
WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;
WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;

// node_modules/@babylonjs/core/ShadersWGSL/clearQuad.vertex.js
init_shaderStore();
var name155 = "clearQuadVertexShader";
var shader154 = `uniform depthValue: f32;const pos=array(
vec2f(-1.0,1.0),
vec2f(1.0,1.0),
vec2f(-1.0,-1.0),
vec2f(1.0,-1.0)
);
#define CUSTOM_VERTEX_DEFINITIONS
@vertex
fn main(input : VertexInputs)->FragmentInputs {
#define CUSTOM_VERTEX_MAIN_BEGIN
vertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);
#define CUSTOM_VERTEX_MAIN_END
}
`;
if (!ShaderStore.ShadersStoreWGSL[name155]) {
  ShaderStore.ShadersStoreWGSL[name155] = shader154;
}

// node_modules/@babylonjs/core/ShadersWGSL/clearQuad.fragment.js
init_shaderStore();
var name156 = "clearQuadPixelShader";
var shader155 = `uniform color: vec4f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}
`;
if (!ShaderStore.ShadersStoreWGSL[name156]) {
  ShaderStore.ShadersStoreWGSL[name156] = shader155;
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuClearQuad.js
class WebGPUClearQuad {
  setDepthStencilFormat(format) {
    this._depthTextureFormat = format;
    this._cacheRenderPipeline.setDepthStencilFormat(format);
  }
  setColorFormat(format) {
    this._cacheRenderPipeline.setColorFormat(format);
  }
  setMRTAttachments(attachments, textureArray, textureCount) {
    this._cacheRenderPipeline.setMRT(textureArray, textureCount);
    this._cacheRenderPipeline.setMRTAttachments(attachments);
  }
  constructor(device, engine, emptyVertexBuffer) {
    this._bindGroups = {};
    this._bundleCache = {};
    this._keyTemp = [];
    this._device = device;
    this._engine = engine;
    this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, emptyVertexBuffer);
    this._cacheRenderPipeline.setDepthTestEnabled(false);
    this._cacheRenderPipeline.setStencilReadMask(255);
    this._effect = engine.createEffect("clearQuad", [], ["color", "depthValue"], undefined, undefined, undefined, undefined, undefined, undefined, 1);
  }
  clear(renderPass, clearColor, clearDepth, clearStencil, sampleCount = 1) {
    let renderPass2;
    let bundle = null;
    let bundleKey;
    const isRTTPass = !!this._engine._currentRenderTarget;
    if (renderPass) {
      renderPass2 = renderPass;
    } else {
      let idx = 0;
      this._keyTemp.length = 0;
      for (let i = 0;i < this._cacheRenderPipeline.colorFormats.length; ++i) {
        this._keyTemp[idx++] = renderableTextureFormatToIndex[this._cacheRenderPipeline.colorFormats[i] ?? ""];
      }
      const depthStencilFormatIndex = renderableTextureFormatToIndex[this._depthTextureFormat ?? 0];
      this._keyTemp[idx] = (clearColor ? clearColor.r + clearColor.g * 256 + clearColor.b * 256 * 256 + clearColor.a * 256 * 256 * 256 : 0) + (clearDepth ? 2 ** 32 : 0) + (clearStencil ? 2 ** 33 : 0) + (this._engine.useReverseDepthBuffer ? 2 ** 34 : 0) + (isRTTPass ? 2 ** 35 : 0) + (sampleCount > 1 ? 2 ** 36 : 0) + depthStencilFormatIndex * 2 ** 37;
      bundleKey = this._keyTemp.join("_");
      bundle = this._bundleCache[bundleKey];
      if (bundle) {
        return bundle;
      }
      renderPass2 = this._device.createRenderBundleEncoder({
        label: "clearQuadRenderBundle",
        colorFormats: this._cacheRenderPipeline.colorFormats,
        depthStencilFormat: this._depthTextureFormat,
        sampleCount: WebGPUTextureHelper.GetSample(sampleCount)
      });
    }
    this._cacheRenderPipeline.setDepthWriteEnabled(!!clearDepth);
    this._cacheRenderPipeline.setStencilEnabled(!!clearStencil && !!this._depthTextureFormat && WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat));
    this._cacheRenderPipeline.setStencilWriteMask(clearStencil ? 255 : 0);
    this._cacheRenderPipeline.setStencilCompare(clearStencil ? 519 : 512);
    this._cacheRenderPipeline.setStencilPassOp(clearStencil ? 7681 : 7680);
    this._cacheRenderPipeline.setWriteMask(clearColor ? 15 : 0);
    const pipeline = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, sampleCount);
    const webgpuPipelineContext = this._effect._pipelineContext;
    if (clearColor) {
      this._effect.setDirectColor4("color", clearColor);
    }
    this._effect.setFloat("depthValue", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue);
    webgpuPipelineContext.uniformBuffer.update();
    const bufferInternals = isRTTPass ? this._engine._ubInvertY : this._engine._ubDontInvertY;
    const bufferLeftOver = webgpuPipelineContext.uniformBuffer.getBuffer();
    const key = bufferLeftOver.uniqueId + "-" + bufferInternals.uniqueId;
    let bindGroups = this._bindGroups[key];
    if (!bindGroups) {
      const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[0];
      bindGroups = this._bindGroups[key] = [];
      bindGroups.push(this._device.createBindGroup({
        label: `clearQuadBindGroup0-${key}`,
        layout: bindGroupLayouts[0],
        entries: []
      }));
      if (!WebGPUShaderProcessingContext._SimplifiedKnownBindings) {
        bindGroups.push(this._device.createBindGroup({
          label: `clearQuadBindGroup1-${key}`,
          layout: bindGroupLayouts[1],
          entries: []
        }));
      }
      bindGroups.push(this._device.createBindGroup({
        label: `clearQuadBindGroup${WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2}-${key}`,
        layout: bindGroupLayouts[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2],
        entries: [
          {
            binding: 0,
            resource: {
              buffer: bufferInternals.underlyingResource,
              size: bufferInternals.capacity
            }
          },
          {
            binding: 1,
            resource: {
              buffer: bufferLeftOver.underlyingResource,
              size: bufferLeftOver.capacity
            }
          }
        ]
      }));
    }
    renderPass2.setPipeline(pipeline);
    for (let i = 0;i < bindGroups.length; ++i) {
      renderPass2.setBindGroup(i, bindGroups[i]);
    }
    renderPass2.draw(4, 1, 0, 0);
    if (!renderPass) {
      bundle = renderPass2.finish();
      this._bundleCache[bundleKey] = bundle;
    }
    return bundle;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuBundleList.js
class WebGPURenderItemViewport {
  constructor(x, y, w, h) {
    this.x = Math.floor(x);
    this.y = Math.floor(y);
    this.w = Math.floor(w);
    this.h = Math.floor(h);
  }
  run(renderPass) {
    renderPass.setViewport(this.x, this.y, this.w, this.h, 0, 1);
  }
  clone() {
    return new WebGPURenderItemViewport(this.x, this.y, this.w, this.h);
  }
}

class WebGPURenderItemScissor {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }
  run(renderPass) {
    renderPass.setScissorRect(this.x, this.y, this.w, this.h);
  }
  clone() {
    return new WebGPURenderItemScissor(this.x, this.y, this.w, this.h);
  }
}

class WebGPURenderItemStencilRef {
  constructor(ref) {
    this.ref = ref;
  }
  run(renderPass) {
    renderPass.setStencilReference(this.ref);
  }
  clone() {
    return new WebGPURenderItemStencilRef(this.ref);
  }
}

class WebGPURenderItemBlendColor {
  constructor(color) {
    this.color = color;
  }
  run(renderPass) {
    renderPass.setBlendConstant(this.color);
  }
  clone() {
    return new WebGPURenderItemBlendColor(this.color);
  }
}

class WebGPURenderItemBeginOcclusionQuery {
  constructor(query) {
    this.query = query;
  }
  run(renderPass) {
    renderPass.beginOcclusionQuery(this.query);
  }
  clone() {
    return new WebGPURenderItemBeginOcclusionQuery(this.query);
  }
}

class WebGPURenderItemEndOcclusionQuery {
  constructor() {}
  run(renderPass) {
    renderPass.endOcclusionQuery();
  }
  clone() {
    return new WebGPURenderItemEndOcclusionQuery;
  }
}

class WebGPURenderItemBundles {
  constructor() {
    this.bundles = [];
  }
  run(renderPass) {
    renderPass.executeBundles(this.bundles);
  }
  clone() {
    const cloned = new WebGPURenderItemBundles;
    cloned.bundles = this.bundles;
    return cloned;
  }
}

class WebGPUBundleList {
  constructor(device) {
    this.numDrawCalls = 0;
    this._device = device;
    this._list = new Array(10);
    this._listLength = 0;
  }
  addBundle(bundle) {
    if (!this._currentItemIsBundle) {
      const item = new WebGPURenderItemBundles;
      this._list[this._listLength++] = item;
      this._currentBundleList = item.bundles;
      this._currentItemIsBundle = true;
    }
    if (bundle) {
      this._currentBundleList.push(bundle);
    }
  }
  _finishBundle() {
    if (this._currentItemIsBundle && this._bundleEncoder) {
      this._currentBundleList.push(this._bundleEncoder.finish());
      this._bundleEncoder = undefined;
      this._currentItemIsBundle = false;
    }
  }
  addItem(item) {
    this._finishBundle();
    this._list[this._listLength++] = item;
    this._currentItemIsBundle = false;
  }
  getBundleEncoder(colorFormats, depthStencilFormat, sampleCount) {
    if (!this._currentItemIsBundle) {
      this.addBundle();
      this._bundleEncoder = this._device.createRenderBundleEncoder({
        colorFormats,
        depthStencilFormat,
        sampleCount: WebGPUTextureHelper.GetSample(sampleCount)
      });
    }
    return this._bundleEncoder;
  }
  close() {
    this._finishBundle();
  }
  run(renderPass) {
    this.close();
    for (let i = 0;i < this._listLength; ++i) {
      this._list[i].run(renderPass);
    }
  }
  reset() {
    this._listLength = 0;
    this._currentItemIsBundle = false;
    this.numDrawCalls = 0;
  }
  clone() {
    this.close();
    const cloned = new WebGPUBundleList(this._device);
    cloned._list = new Array(this._listLength);
    cloned._listLength = this._listLength;
    cloned.numDrawCalls = this.numDrawCalls;
    for (let i = 0;i < this._listLength; ++i) {
      cloned._list[i] = this._list[i].clone();
    }
    return cloned;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuTimestampQuery.js
init_perfCounter();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuQuerySet.js
class WebGPUQuerySet {
  get querySet() {
    return this._querySet;
  }
  constructor(engine, count, type, device, bufferManager, canUseMultipleBuffers = true, label) {
    this._dstBuffers = [];
    this._engine = engine;
    this._device = device;
    this._bufferManager = bufferManager;
    this._count = count;
    this._canUseMultipleBuffers = canUseMultipleBuffers;
    this._querySet = device.createQuerySet({
      label: label ?? "QuerySet",
      type,
      count
    });
    this._queryBuffer = bufferManager.createRawBuffer(8 * count, BufferUsage.QueryResolve | BufferUsage.CopySrc, undefined, "QueryBuffer");
    if (!canUseMultipleBuffers) {
      this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "QueryBufferNoMultipleBuffers"));
    }
  }
  _getBuffer(firstQuery, queryCount) {
    if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0) {
      return null;
    }
    const encoderResult = this._device.createCommandEncoder();
    let buffer2;
    if (this._dstBuffers.length === 0) {
      buffer2 = this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "QueryBufferAdditionalBuffer");
    } else {
      buffer2 = this._dstBuffers[this._dstBuffers.length - 1];
      this._dstBuffers.length--;
    }
    encoderResult.resolveQuerySet(this._querySet, firstQuery, queryCount, this._queryBuffer, 0);
    encoderResult.copyBufferToBuffer(this._queryBuffer, 0, buffer2, 0, 8 * queryCount);
    this._device.queue.submit([encoderResult.finish()]);
    return buffer2;
  }
  async readValues(firstQuery = 0, queryCount = 1) {
    const buffer2 = this._getBuffer(firstQuery, queryCount);
    if (buffer2 === null) {
      return null;
    }
    const engineId = this._engine.uniqueId;
    return buffer2.mapAsync(1).then(() => {
      const arrayBuf = new BigUint64Array(buffer2.getMappedRange()).slice();
      buffer2.unmap();
      this._dstBuffers[this._dstBuffers.length] = buffer2;
      return arrayBuf;
    }, (err) => {
      if (this._engine.isDisposed || this._engine.uniqueId !== engineId) {
        return null;
      }
      throw err;
    });
  }
  async readValue(firstQuery = 0) {
    const buffer2 = this._getBuffer(firstQuery, 1);
    if (buffer2 === null) {
      return null;
    }
    const engineId = this._engine.uniqueId;
    return buffer2.mapAsync(1).then(() => {
      const arrayBuf = new BigUint64Array(buffer2.getMappedRange());
      const value = Number(arrayBuf[0]);
      buffer2.unmap();
      this._dstBuffers[this._dstBuffers.length] = buffer2;
      return value;
    }, (err) => {
      if (this._engine.isDisposed || this._engine.uniqueId !== engineId) {
        return 0;
      }
      throw err;
    });
  }
  async readTwoValuesAndSubtract(firstQuery = 0) {
    const buffer2 = this._getBuffer(firstQuery, 2);
    if (buffer2 === null) {
      return null;
    }
    const engineId = this._engine.uniqueId;
    return buffer2.mapAsync(1).then(() => {
      const arrayBuf = new BigUint64Array(buffer2.getMappedRange());
      const value = Number(arrayBuf[1] - arrayBuf[0]);
      buffer2.unmap();
      this._dstBuffers[this._dstBuffers.length] = buffer2;
      return value;
    }, (err) => {
      if (this._engine.isDisposed || this._engine.uniqueId !== engineId) {
        return 0;
      }
      throw err;
    });
  }
  dispose() {
    this._querySet.destroy();
    this._bufferManager.releaseBuffer(this._queryBuffer);
    for (let i = 0;i < this._dstBuffers.length; ++i) {
      this._bufferManager.releaseBuffer(this._dstBuffers[i]);
    }
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuTimestampQuery.js
init_logger();

class WebGPUTimestampQuery {
  get gpuFrameTimeCounter() {
    return this._gpuFrameTimeCounter;
  }
  constructor(engine, device, bufferManager) {
    this._enabled = false;
    this._gpuFrameTimeCounter = new PerfCounter;
    this._measureDurationState = 0;
    this._engine = engine;
    this._device = device;
    this._bufferManager = bufferManager;
  }
  get enable() {
    return this._enabled;
  }
  set enable(value) {
    if (this._enabled === value) {
      return;
    }
    this._enabled = value;
    this._measureDurationState = 0;
    if (value) {
      try {
        this._measureDuration = new WebGPUDurationMeasure(this._engine, this._device, this._bufferManager, 2000, "QuerySet_TimestampQuery");
      } catch (e) {
        this._enabled = false;
        Logger.Error(`Could not create a WebGPUDurationMeasure!
Error: ` + e.message + `
Make sure timestamp query is supported and enabled in your browser.`);
        return;
      }
    } else {
      this._measureDuration.dispose();
    }
  }
  startFrame(commandEncoder) {
    if (this._enabled && this._measureDurationState === 0) {
      this._measureDuration.start(commandEncoder);
      this._measureDurationState = 1;
    }
  }
  endFrame(commandEncoder) {
    if (this._measureDurationState === 1) {
      this._measureDurationState = 2;
      this._measureDuration.stop(commandEncoder).then((duration) => {
        if (duration !== null && duration >= 0) {
          this._gpuFrameTimeCounter.fetchNewFrame();
          this._gpuFrameTimeCounter.addCount(duration, true);
        }
        this._measureDurationState = 0;
      });
    }
  }
  startPass(descriptor, index) {
    if (this._enabled) {
      this._measureDuration.startPass(descriptor, index);
    } else {
      descriptor.timestampWrites = undefined;
    }
  }
  endPass(index, gpuPerfCounter) {
    if (!this._enabled || !gpuPerfCounter) {
      return;
    }
    const currentFrameId = this._engine.frameId;
    this._measureDuration.stopPass(index).then((duration_) => {
      gpuPerfCounter._addDuration(currentFrameId, duration_ !== null && duration_ > 0 ? duration_ : 0);
    });
  }
  dispose() {
    this._measureDuration?.dispose();
  }
}

class WebGPUDurationMeasure {
  constructor(engine, device, bufferManager, count = 2, querySetLabel) {
    this._count = count;
    this._querySet = new WebGPUQuerySet(engine, count, "timestamp", device, bufferManager, true, querySetLabel);
  }
  start(encoder) {
    encoder.writeTimestamp?.(this._querySet.querySet, 0);
  }
  async stop(encoder) {
    encoder.writeTimestamp?.(this._querySet.querySet, 1);
    return encoder.writeTimestamp ? this._querySet.readTwoValuesAndSubtract(0) : 0;
  }
  startPass(descriptor, index) {
    if (index + 3 > this._count) {
      throw new Error("WebGPUDurationMeasure: index out of range (" + index + ")");
    }
    descriptor.timestampWrites = {
      querySet: this._querySet.querySet,
      beginningOfPassWriteIndex: index + 2,
      endOfPassWriteIndex: index + 3
    };
  }
  async stopPass(index) {
    return this._querySet.readTwoValuesAndSubtract(index + 2);
  }
  dispose() {
    this._querySet.dispose();
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuOcclusionQuery.js
class WebGPUOcclusionQuery {
  get querySet() {
    return this._querySet.querySet;
  }
  get hasQueries() {
    return this._currentTotalIndices !== this._availableIndices.length;
  }
  canBeginQuery(index) {
    if (this._frameQuerySetIsDirty === this._engine.frameId || this._queryFrameId[index] === this._engine.frameId) {
      return false;
    }
    const canBegin = this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet !== undefined;
    if (canBegin) {
      this._queryFrameId[index] = this._engine.frameId;
    }
    return canBegin;
  }
  constructor(engine, device, bufferManager, startCount = 50, incrementCount = 100) {
    this._availableIndices = [];
    this._frameQuerySetIsDirty = -1;
    this._queryFrameId = [];
    this._engine = engine;
    this._device = device;
    this._bufferManager = bufferManager;
    this._frameLastBuffer = -1;
    this._currentTotalIndices = 0;
    this._countIncrement = incrementCount;
    this._allocateNewIndices(startCount);
  }
  createQuery() {
    if (this._availableIndices.length === 0) {
      this._allocateNewIndices();
    }
    const index = this._availableIndices[this._availableIndices.length - 1];
    this._availableIndices.length--;
    return index;
  }
  deleteQuery(index) {
    this._availableIndices[this._availableIndices.length] = index;
  }
  isQueryResultAvailable(index) {
    this._retrieveQueryBuffer();
    return !!this._lastBuffer && index < this._lastBuffer.length;
  }
  getQueryResult(index) {
    return Number(this._lastBuffer?.[index] ?? -1);
  }
  _retrieveQueryBuffer() {
    if (this._lastBuffer && this._frameLastBuffer === this._engine.frameId) {
      return;
    }
    if (this._frameLastBuffer !== this._engine.frameId) {
      this._frameLastBuffer = this._engine.frameId;
      this._querySet.readValues(0, this._currentTotalIndices).then((arrayBuffer) => {
        this._lastBuffer = arrayBuffer;
      });
    }
  }
  _allocateNewIndices(numIndices) {
    numIndices = numIndices ?? this._countIncrement;
    this._delayQuerySetDispose();
    for (let i = 0;i < numIndices; ++i) {
      this._availableIndices.push(this._currentTotalIndices + i);
    }
    this._currentTotalIndices += numIndices;
    this._querySet = new WebGPUQuerySet(this._engine, this._currentTotalIndices, "occlusion", this._device, this._bufferManager, false, "QuerySet_OcclusionQuery_count_" + this._currentTotalIndices);
    this._frameQuerySetIsDirty = this._engine.frameId;
  }
  _delayQuerySetDispose() {
    const querySet = this._querySet;
    if (querySet) {
      setTimeout(() => querySet.dispose, 1000);
    }
  }
  dispose() {
    this._querySet?.dispose();
    this._availableIndices.length = 0;
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuTintWASM.js
init_logger();
init_tools();

class WebGPUTintWASM {
  async initTwgsl(twgslOptions) {
    if (WebGPUTintWASM._Twgsl) {
      return;
    }
    twgslOptions = twgslOptions || {};
    twgslOptions = {
      ...WebGPUTintWASM._TWgslDefaultOptions,
      ...twgslOptions
    };
    if (twgslOptions.twgsl) {
      WebGPUTintWASM._Twgsl = twgslOptions.twgsl;
      return Promise.resolve();
    }
    if (twgslOptions.jsPath && twgslOptions.wasmPath) {
      await Tools.LoadBabylonScriptAsync(twgslOptions.jsPath);
    }
    if (self.twgsl) {
      WebGPUTintWASM._Twgsl = await self.twgsl(Tools.GetBabylonScriptURL(twgslOptions.wasmPath));
      return Promise.resolve();
    }
    return Promise.reject("twgsl is not available.");
  }
  convertSpirV2WGSL(code, disableUniformityAnalysis = false) {
    const ccode = WebGPUTintWASM._Twgsl.convertSpirV2WGSL(code, WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis);
    if (WebGPUTintWASM.ShowWGSLShaderCode) {
      Logger.Log(ccode);
      Logger.Log("***********************************************");
    }
    return WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis ? `diagnostic(off, derivative_uniformity);
` + ccode : ccode;
  }
}
WebGPUTintWASM._TWgslDefaultOptions = {
  jsPath: `${Tools._DefaultCdnUrl}/twgsl/twgsl.js`,
  wasmPath: `${Tools._DefaultCdnUrl}/twgsl/twgsl.wasm`
};
WebGPUTintWASM.ShowWGSLShaderCode = false;
WebGPUTintWASM.DisableUniformityAnalysis = false;
WebGPUTintWASM._Twgsl = null;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuSnapshotRendering.js
init_logger();

class WebGPUSnapshotRendering {
  constructor(engine, renderingMode, bundleList) {
    this._record = false;
    this._play = false;
    this._playBundleListIndex = 0;
    this._allBundleLists = [];
    this._enabled = false;
    this.showDebugLogs = false;
    this._engine = engine;
    this._mode = renderingMode;
    this._bundleList = bundleList;
  }
  get enabled() {
    return this._enabled;
  }
  get play() {
    return this._play;
  }
  get record() {
    return this._record;
  }
  set enabled(activate) {
    this._log("enabled", `activate=${activate}, mode=${this._mode}`);
    this._allBundleLists.length = 0;
    this._record = this._enabled = activate;
    this._play = false;
    if (activate) {
      this._modeSaved = this._mode;
      this._mode = 0;
    }
  }
  get mode() {
    return this._mode;
  }
  set mode(mode) {
    if (this._record) {
      this._modeSaved = mode;
    } else {
      this._mode = mode;
    }
  }
  endRenderPass(currentRenderPass) {
    if (!this._record && !this._play) {
      return false;
    }
    let bundleList = null;
    if (this._record) {
      bundleList = this._bundleList.clone();
      this._allBundleLists.push(bundleList);
      this._bundleList.reset();
      this._log("endRenderPass", `bundleList recorded at position #${this._allBundleLists.length - 1}`);
    } else {
      if (this._playBundleListIndex >= this._allBundleLists.length) {
        this._log("endRenderPass", `empty or out-of-sync bundleList (_allBundleLists.length=${this._allBundleLists.length}, playBundleListIndex=${this._playBundleListIndex})`);
      } else {
        this._log("endRenderPass", `run bundleList #${this._playBundleListIndex}`);
        bundleList = this._allBundleLists[this._playBundleListIndex++];
      }
    }
    if (bundleList) {
      bundleList.run(currentRenderPass);
      if (this._mode === 1) {
        this._engine._reportDrawCall(bundleList.numDrawCalls);
      }
    }
    return true;
  }
  endFrame() {
    if (this._record) {
      this._record = false;
      this._play = true;
      this._mode = this._modeSaved;
      this._log("endFrame", "bundles recorded, switching to play mode");
    }
    this._playBundleListIndex = 0;
  }
  reset() {
    this._log("reset", "called");
    if (this._record) {
      this._mode = this._modeSaved;
    }
    this.enabled = false;
    this.enabled = true;
  }
  _log(funcName, message) {
    if (this.showDebugLogs) {
      Logger.Log(`[Frame: ${this._engine.frameId}] WebGPUSnapshotRendering:${funcName} - ${message}`);
    }
  }
}

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
init_sphericalPolynomial();
init_performanceMonitor();
init_engine_common();
init_perfCounter();
init_abstractEngine_loadingScreen();
init_abstractEngine_dom();
init_abstractEngine_states();
init_abstractEngine_renderPass();
init_effect_functions();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuExternalTexture.js
class WebGPUExternalTexture extends ExternalTexture {
  constructor(video) {
    super(video);
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.rawTexture.js
init_internalTexture();
init_logger();
ThinWebGPUEngine.prototype.createRawTexture = function(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {
  const texture = new InternalTexture(this, 3);
  texture.baseWidth = width;
  texture.baseHeight = height;
  texture.width = width;
  texture.height = height;
  texture.format = format;
  texture.generateMipMaps = generateMipMaps;
  texture.samplingMode = samplingMode;
  texture.invertY = invertY;
  texture._compression = compression;
  texture.type = type;
  texture._creationFlags = creationFlags;
  texture._useSRGBBuffer = useSRGBBuffer;
  if (!this._doNotHandleContextLost) {
    texture._bufferView = data;
  }
  this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);
  this.updateRawTexture(texture, data, format, invertY, compression, type, useSRGBBuffer);
  this._internalTexturesCache.push(texture);
  return texture;
};
ThinWebGPUEngine.prototype.updateRawTexture = function(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
  if (!texture) {
    return;
  }
  if (!this._doNotHandleContextLost) {
    texture._bufferView = bufferView;
    texture.invertY = invertY;
    texture._compression = compression;
    texture._useSRGBBuffer = useSRGBBuffer;
  }
  if (bufferView) {
    const gpuTextureWrapper = texture._hardwareTexture;
    const needConversion = format === 4;
    if (needConversion) {
      bufferView = _convertRGBtoRGBATextureData2(bufferView, texture.width, texture.height, type);
    }
    const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
    this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);
    if (texture.generateMipMaps) {
      this._generateMipmaps(texture, this._uploadEncoder);
    }
  }
  texture.isReady = true;
};
ThinWebGPUEngine.prototype.createRawCubeTexture = function(data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {
  const texture = new InternalTexture(this, 8);
  if (type === 1 && !this._caps.textureFloatLinearFiltering) {
    generateMipMaps = false;
    samplingMode = 1;
    Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  } else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
    generateMipMaps = false;
    samplingMode = 1;
    Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  } else if (type === 1 && !this._caps.textureFloatRender) {
    generateMipMaps = false;
    Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  } else if (type === 2 && !this._caps.colorBufferFloat) {
    generateMipMaps = false;
    Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  }
  texture.isCube = true;
  texture._originalFormat = format;
  texture.format = format === 4 ? 5 : format;
  texture.type = type;
  texture.generateMipMaps = generateMipMaps;
  texture.width = size;
  texture.height = size;
  texture.samplingMode = samplingMode;
  if (!this._doNotHandleContextLost) {
    texture._bufferViewArray = data;
  }
  texture.invertY = invertY;
  texture._compression = compression;
  texture._cachedWrapU = 0;
  texture._cachedWrapV = 0;
  this._textureHelper.createGPUTextureForInternalTexture(texture);
  if (format === 4) {
    const gpuTextureWrapper = texture._hardwareTexture;
    gpuTextureWrapper._originalFormatIsRGB = true;
  }
  if (data) {
    this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  }
  texture.isReady = true;
  return texture;
};
ThinWebGPUEngine.prototype.updateRawCubeTexture = function(texture, bufferView, _format, type, invertY, compression = null) {
  texture._bufferViewArray = bufferView;
  texture.invertY = invertY;
  texture._compression = compression;
  const gpuTextureWrapper = texture._hardwareTexture;
  const needConversion = gpuTextureWrapper._originalFormatIsRGB;
  const faces = [0, 2, 4, 1, 3, 5];
  const data = [];
  for (let i = 0;i < bufferView.length; ++i) {
    let faceData = bufferView[faces[i]];
    if (needConversion) {
      faceData = _convertRGBtoRGBATextureData2(faceData, texture.width, texture.height, type);
    }
    data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength));
  }
  this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0);
  if (texture.generateMipMaps) {
    this._generateMipmaps(texture, this._uploadEncoder);
  }
  texture.isReady = true;
};
ThinWebGPUEngine.prototype.createRawCubeTextureFromUrl = function(url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {
  const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);
  scene?.addPendingData(texture);
  texture.url = url;
  texture.isReady = false;
  this._internalTexturesCache.push(texture);
  const onerror = (request, exception) => {
    scene?.removePendingData(texture);
    if (onError && request) {
      onError(request.status + " " + request.statusText, exception);
    }
  };
  const internalCallback = (data) => {
    const width = texture.width;
    const faceDataArrays = callback(data);
    if (!faceDataArrays) {
      return;
    }
    if (mipmapGenerator) {
      const needConversion = format === 4;
      const mipData = mipmapGenerator(faceDataArrays);
      const gpuTextureWrapper = texture._hardwareTexture;
      const faces = [0, 1, 2, 3, 4, 5];
      for (let level = 0;level < mipData.length; level++) {
        const mipSize = width >> level;
        const allFaces = [];
        for (let faceIndex = 0;faceIndex < 6; faceIndex++) {
          let mipFaceData = mipData[level][faces[faceIndex]];
          if (needConversion) {
            mipFaceData = _convertRGBtoRGBATextureData2(mipFaceData, mipSize, mipSize, type);
          }
          allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength));
        }
        this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0);
      }
    } else {
      this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
    }
    texture.isReady = true;
    scene?.removePendingData(texture);
    if (onLoad) {
      onLoad();
    }
  };
  this._loadFile(url, (data) => {
    internalCallback(data);
  }, undefined, scene?.offlineProvider, true, onerror);
  return texture;
};
ThinWebGPUEngine.prototype.createRawTexture3D = function(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {
  const source = 10;
  const texture = new InternalTexture(this, source);
  texture.baseWidth = width;
  texture.baseHeight = height;
  texture.baseDepth = depth;
  texture.width = width;
  texture.height = height;
  texture.depth = depth;
  texture.format = format;
  texture.type = textureType;
  texture.generateMipMaps = generateMipMaps;
  texture.samplingMode = samplingMode;
  texture.is3D = true;
  texture._creationFlags = creationFlags;
  if (!this._doNotHandleContextLost) {
    texture._bufferView = data;
  }
  this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);
  this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  this._internalTexturesCache.push(texture);
  return texture;
};
ThinWebGPUEngine.prototype.updateRawTexture3D = function(texture, bufferView, format, invertY, compression = null, textureType = 0) {
  if (!this._doNotHandleContextLost) {
    texture._bufferView = bufferView;
    texture.format = format;
    texture.invertY = invertY;
    texture._compression = compression;
  }
  if (bufferView) {
    const gpuTextureWrapper = texture._hardwareTexture;
    const needConversion = format === 4;
    if (needConversion) {
      bufferView = _convertRGBtoRGBATextureData2(bufferView, texture.width, texture.height, textureType);
    }
    const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
    this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);
    if (texture.generateMipMaps) {
      this._generateMipmaps(texture, this._uploadEncoder);
    }
  }
  texture.isReady = true;
};
ThinWebGPUEngine.prototype.createRawTexture2DArray = function(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {
  const source = 11;
  const texture = new InternalTexture(this, source);
  texture.baseWidth = width;
  texture.baseHeight = height;
  texture.baseDepth = depth;
  texture.width = width;
  texture.height = height;
  texture.depth = depth;
  texture.format = format;
  texture.type = textureType;
  texture.generateMipMaps = generateMipMaps;
  texture.samplingMode = samplingMode;
  texture.is2DArray = true;
  texture._creationFlags = creationFlags;
  if (!this._doNotHandleContextLost) {
    texture._bufferView = data;
  }
  this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags);
  this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);
  this._internalTexturesCache.push(texture);
  return texture;
};
ThinWebGPUEngine.prototype.updateRawTexture2DArray = function(texture, bufferView, format, invertY, compression = null, textureType = 0) {
  if (!this._doNotHandleContextLost) {
    texture._bufferView = bufferView;
    texture.format = format;
    texture.invertY = invertY;
    texture._compression = compression;
  }
  if (bufferView) {
    const gpuTextureWrapper = texture._hardwareTexture;
    const needConversion = format === 4;
    if (needConversion) {
      bufferView = _convertRGBtoRGBATextureData2(bufferView, texture.width, texture.height, textureType);
    }
    const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
    this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);
    if (texture.generateMipMaps) {
      this._generateMipmaps(texture, this._uploadEncoder);
    }
  }
  texture.isReady = true;
};
function _convertRGBtoRGBATextureData2(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;
}

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.readTexture.js
ThinWebGPUEngine.prototype._readTexturePixels = function(texture, width, height, faceIndex = -1, level = 0, buffer2 = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {
  const gpuTextureWrapper = texture._hardwareTexture;
  if (flushRenderer) {
    this.flushFramebuffer();
  }
  return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource, x, y, width, height, gpuTextureWrapper.format, faceIndex, level, buffer2, noDataConversion);
};
ThinWebGPUEngine.prototype._readTexturePixelsSync = function() {
  throw "_readTexturePixelsSync is unsupported in WebGPU!";
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.cubeTexture.js
init_internalTexture();
ThinWebGPUEngine.prototype._createDepthStencilCubeTexture = function(size, options) {
  const internalTexture = new InternalTexture(this, options.generateStencil ? 12 : 14);
  internalTexture.isCube = true;
  internalTexture.label = options.label;
  const internalOptions = {
    bilinearFiltering: false,
    comparisonFunction: 0,
    generateStencil: false,
    samples: 1,
    depthTextureFormat: options.generateStencil ? 13 : 14,
    ...options
  };
  internalTexture.format = internalOptions.depthTextureFormat;
  this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  this._textureHelper.createGPUTextureForInternalTexture(internalTexture);
  const gpuTextureWrapper = internalTexture._hardwareTexture;
  internalTexture.type = WebGPUTextureHelper.GetTextureTypeFromFormat(gpuTextureWrapper.format);
  this._internalTexturesCache.push(internalTexture);
  return internalTexture;
};
ThinWebGPUEngine.prototype.createCubeTexture = function(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer2 = null) {
  return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, null, (texture, imgs) => {
    const imageBitmaps = imgs;
    const width = imageBitmaps[0].width;
    const height = width;
    this._setCubeMapTextureParams(texture, !noMipmap);
    texture.format = format ?? -1;
    const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
    this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource, width, height, gpuTextureWrapper.format, false, false, 0, 0);
    if (!noMipmap) {
      this._generateMipmaps(texture, this._uploadEncoder);
    }
    texture.isReady = true;
    texture.onLoadedObservable.notifyObservers(texture);
    texture.onLoadedObservable.clear();
    if (onLoad) {
      onLoad();
    }
  }, !!useSRGBBuffer, buffer2);
};
ThinWebGPUEngine.prototype._setCubeMapTextureParams = function(texture, loadMipmap, maxLevel) {
  texture.samplingMode = loadMipmap ? 3 : 2;
  texture._cachedWrapU = 0;
  texture._cachedWrapV = 0;
  if (maxLevel) {
    texture._maxLodLevel = maxLevel;
  }
};
ThinWebGPUEngine.prototype.generateMipMapsForCubemap = function(texture) {
  if (texture.generateMipMaps) {
    const gpuTexture = texture._hardwareTexture?.underlyingResource;
    if (!gpuTexture) {
      this._textureHelper.createGPUTextureForInternalTexture(texture);
    }
    this._generateMipmaps(texture);
  }
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTarget.js
init_internalTexture();

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderTargetWrapper.js
init_renderTargetWrapper();
init_webgpuPerfCounter();

class WebGPURenderTargetWrapper extends RenderTargetWrapper {
  constructor(isMulti, isCube, size, engine, label) {
    super(isMulti, isCube, size, engine, label);
    if (engine.enableGPUTimingMeasurements) {
      this.gpuTimeInFrame = new WebGPUPerfCounter;
    }
  }
}

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTarget.js
init_abstractEngine_texture();
ThinWebGPUEngine.prototype._createHardwareRenderTargetWrapper = function(isMulti, isCube, size) {
  const rtWrapper = new WebGPURenderTargetWrapper(isMulti, isCube, size, this);
  this._renderTargetWrapperCache.push(rtWrapper);
  return rtWrapper;
};
ThinWebGPUEngine.prototype.createRenderTargetTexture = function(size, options) {
  const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);
  const fullOptions = {};
  if (options !== undefined && typeof options === "object") {
    fullOptions.generateMipMaps = options.generateMipMaps;
    fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
    fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
    fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;
    fullOptions.creationFlags = options.creationFlags ?? 0;
    fullOptions.noColorAttachment = !!options.noColorAttachment;
    fullOptions.colorAttachment = options.colorAttachment;
    fullOptions.samples = options.samples;
    fullOptions.label = options.label;
    fullOptions.format = options.format;
    fullOptions.type = options.type;
  } else {
    fullOptions.generateMipMaps = options;
    fullOptions.generateDepthBuffer = true;
    fullOptions.generateStencilBuffer = false;
    fullOptions.samplingMode = 3;
    fullOptions.creationFlags = 0;
    fullOptions.noColorAttachment = false;
  }
  const texture = fullOptions.colorAttachment || (fullOptions.noColorAttachment ? null : this._createInternalTexture(size, fullOptions, true, 5));
  rtWrapper.label = fullOptions.label ?? "RenderTargetWrapper";
  rtWrapper._samples = fullOptions.colorAttachment?.samples ?? fullOptions.samples ?? 1;
  rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;
  rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  rtWrapper.setTextures(texture);
  if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {
    rtWrapper.createDepthStencilTexture(0, false, rtWrapper._generateStencilBuffer, rtWrapper.samples, fullOptions.generateStencilBuffer ? 13 : 14, fullOptions.label ? fullOptions.label + "-DepthStencil" : undefined);
  }
  if (texture && !fullOptions.colorAttachment) {
    if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
      texture.generateMipMaps = true;
    }
    this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, fullOptions.creationFlags);
    if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
      texture.generateMipMaps = false;
    }
  }
  return rtWrapper;
};
ThinWebGPUEngine.prototype._createDepthStencilTexture = function(size, options, wrapper) {
  const internalOptions = {
    bilinearFiltering: false,
    comparisonFunction: 0,
    generateStencil: false,
    samples: 1,
    depthTextureFormat: options.generateStencil ? 13 : 14,
    ...options
  };
  const hasStencil = HasStencilAspect(internalOptions.depthTextureFormat);
  wrapper._depthStencilTextureWithStencil = hasStencil;
  const internalTexture = new InternalTexture(this, hasStencil ? 12 : 14);
  internalTexture.label = options.label;
  internalTexture.format = internalOptions.depthTextureFormat;
  internalTexture.type = GetTypeForDepthTexture(internalTexture.format);
  this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  this._textureHelper.createGPUTextureForInternalTexture(internalTexture);
  this._internalTexturesCache.push(internalTexture);
  return internalTexture;
};
ThinWebGPUEngine.prototype._setupDepthStencilTexture = function(internalTexture, size, bilinearFiltering, comparisonFunction, samples = 1) {
  const width = size.width ?? size;
  const height = size.height ?? size;
  const layers = size.layers || 0;
  const depth = size.depth || 0;
  internalTexture.baseWidth = width;
  internalTexture.baseHeight = height;
  internalTexture.width = width;
  internalTexture.height = height;
  internalTexture.is2DArray = layers > 0;
  internalTexture.is3D = depth > 0;
  internalTexture.depth = layers || depth;
  internalTexture.isReady = true;
  internalTexture.samples = samples;
  internalTexture.generateMipMaps = false;
  internalTexture.samplingMode = bilinearFiltering ? 2 : 1;
  internalTexture.type = 1;
  internalTexture._comparisonFunction = comparisonFunction;
  internalTexture._cachedWrapU = 0;
  internalTexture._cachedWrapV = 0;
};
ThinWebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function(rtWrapper, samples) {
  if (!rtWrapper || !rtWrapper.texture || rtWrapper.samples === samples) {
    return samples;
  }
  samples = Math.min(samples, this.getCaps().maxMSAASamples);
  this._textureHelper.createMSAATexture(rtWrapper.texture, samples);
  if (rtWrapper._depthStencilTexture) {
    this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);
    rtWrapper._depthStencilTexture.samples = samples;
  }
  rtWrapper._samples = samples;
  rtWrapper.texture.samples = samples;
  return samples;
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTargetTexture.js
ThinWebGPUEngine.prototype.setDepthStencilTexture = function(channel, uniform, texture, name157) {
  if (!texture || !texture.depthStencilTexture) {
    this._setTexture(channel, null, undefined, undefined, name157);
  } else {
    this._setTexture(channel, texture, false, true, name157);
  }
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTargetCube.js
init_internalTexture();
ThinWebGPUEngine.prototype.createRenderTargetCubeTexture = function(size, options) {
  const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);
  const fullOptions = {
    generateMipMaps: true,
    generateDepthBuffer: true,
    generateStencilBuffer: false,
    type: 0,
    samplingMode: 3,
    format: 5,
    samples: 1,
    ...options
  };
  fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  rtWrapper.label = fullOptions.label ?? "RenderTargetWrapper";
  rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;
  rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;
  const texture = new InternalTexture(this, 5);
  texture.width = size;
  texture.height = size;
  texture.depth = 0;
  texture.isReady = true;
  texture.isCube = true;
  texture.samples = fullOptions.samples;
  texture.generateMipMaps = fullOptions.generateMipMaps;
  texture.samplingMode = fullOptions.samplingMode;
  texture.type = fullOptions.type;
  texture.format = fullOptions.format;
  this._internalTexturesCache.push(texture);
  rtWrapper.setTextures(texture);
  if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {
    rtWrapper.createDepthStencilTexture(0, fullOptions.samplingMode === undefined || fullOptions.samplingMode === 2 || fullOptions.samplingMode === 2 || fullOptions.samplingMode === 3 || fullOptions.samplingMode === 3 || fullOptions.samplingMode === 5 || fullOptions.samplingMode === 6 || fullOptions.samplingMode === 7 || fullOptions.samplingMode === 11, rtWrapper._generateStencilBuffer, rtWrapper.samples);
  }
  if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
    texture.generateMipMaps = true;
  }
  this._textureHelper.createGPUTextureForInternalTexture(texture);
  if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
    texture.generateMipMaps = false;
  }
  return rtWrapper;
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.query.js
ThinWebGPUEngine.prototype.getGPUFrameTimeCounter = function() {
  return this._timestampQuery.gpuFrameTimeCounter;
};
ThinWebGPUEngine.prototype.captureGPUFrameTime = function(value) {
  this._timestampQuery.enable = value && !!this._caps.timerQuery;
};
ThinWebGPUEngine.prototype.createQuery = function() {
  return this._occlusionQuery.createQuery();
};
ThinWebGPUEngine.prototype.deleteQuery = function(query) {
  this._occlusionQuery.deleteQuery(query);
  return this;
};
ThinWebGPUEngine.prototype.isQueryResultAvailable = function(query) {
  return this._occlusionQuery.isQueryResultAvailable(query);
};
ThinWebGPUEngine.prototype.getQueryResult = function(query) {
  return this._occlusionQuery.getQueryResult(query);
};
ThinWebGPUEngine.prototype.beginOcclusionQuery = function(algorithmType, query) {
  if (this.compatibilityMode) {
    if (this._occlusionQuery.canBeginQuery(query)) {
      this._currentRenderPass?.beginOcclusionQuery(query);
      return true;
    }
  } else {
    this._bundleList.addItem(new WebGPURenderItemBeginOcclusionQuery(query));
    return true;
  }
  return false;
};
ThinWebGPUEngine.prototype.endOcclusionQuery = function() {
  if (this.compatibilityMode) {
    this._currentRenderPass?.endOcclusionQuery();
  } else {
    this._bundleList.addItem(new WebGPURenderItemEndOcclusionQuery);
  }
  return this;
};

// node_modules/@babylonjs/core/Engines/webgpuEngine.js
var viewDescriptorSwapChainAntialiasing = {
  label: `TextureView_SwapChain_ResolveTarget`,
  dimension: "2d",
  format: undefined,
  mipLevelCount: 1,
  arrayLayerCount: 1
};
var viewDescriptorSwapChain = {
  label: `TextureView_SwapChain`,
  dimension: "2d",
  format: undefined,
  mipLevelCount: 1,
  arrayLayerCount: 1
};
var tempColor4 = new Color4;

class WebGPUEngine extends ThinWebGPUEngine {
  get snapshotRenderingMode() {
    return this._snapshotRendering.mode;
  }
  set snapshotRenderingMode(mode) {
    this._snapshotRendering.mode = mode;
  }
  snapshotRenderingReset() {
    this._snapshotRendering.reset();
  }
  get snapshotRendering() {
    return this._snapshotRendering.enabled;
  }
  set snapshotRendering(activate) {
    this._snapshotRendering.enabled = activate;
  }
  get disableCacheSamplers() {
    return this._cacheSampler ? this._cacheSampler.disabled : false;
  }
  set disableCacheSamplers(disable) {
    if (this._cacheSampler) {
      this._cacheSampler.disabled = disable;
    }
  }
  get disableCacheRenderPipelines() {
    return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false;
  }
  set disableCacheRenderPipelines(disable) {
    if (this._cacheRenderPipeline) {
      this._cacheRenderPipeline.disabled = disable;
    }
  }
  get disableCacheBindGroups() {
    return this._cacheBindGroups ? this._cacheBindGroups.disabled : false;
  }
  set disableCacheBindGroups(disable) {
    if (this._cacheBindGroups) {
      this._cacheBindGroups.disabled = disable;
    }
  }
  areAllEffectsReady() {
    return true;
  }
  getFontOffset(font) {
    return GetFontOffset(font);
  }
  static get IsSupportedAsync() {
    return !navigator.gpu ? Promise.resolve(false) : navigator.gpu.requestAdapter().then((adapter) => !!adapter, () => false).catch(() => false);
  }
  static get IsSupported() {
    Logger.Warn("You must call IsSupportedAsync for WebGPU!");
    return false;
  }
  get supportsUniformBuffers() {
    return true;
  }
  get supportedExtensions() {
    return this._adapterSupportedExtensions;
  }
  get enabledExtensions() {
    return this._deviceEnabledExtensions;
  }
  get supportedLimits() {
    return this._adapterSupportedLimits;
  }
  get currentLimits() {
    return this._deviceLimits;
  }
  get description() {
    const description = this.name + this.version;
    return description;
  }
  get version() {
    return 1;
  }
  getInfo() {
    return {
      vendor: this._adapterInfo.vendor || "unknown vendor",
      renderer: this._adapterInfo.architecture || "unknown renderer",
      version: this._adapterInfo.description || "unknown version"
    };
  }
  get compatibilityMode() {
    return this._compatibilityMode;
  }
  set compatibilityMode(mode) {
    this._compatibilityMode = mode;
  }
  get currentSampleCount() {
    return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount;
  }
  static CreateAsync(canvas, options = {}) {
    const engine = new WebGPUEngine(canvas, options);
    return new Promise((resolve3) => {
      engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve3(engine));
    });
  }
  constructor(canvas, options = {}) {
    super(options.antialias ?? true, options);
    this.uniqueId = -1;
    this._uploadEncoderDescriptor = { label: "upload" };
    this._renderEncoderDescriptor = { label: "render" };
    this._clearDepthValue = 1;
    this._clearReverseDepthValue = 0;
    this._clearStencilValue = 0;
    this._defaultSampleCount = 4;
    this._glslang = null;
    this._tintWASM = null;
    this._glslangAndTintAreFullyLoaded = false;
    this._adapterInfo = {
      vendor: "",
      architecture: "",
      device: "",
      description: ""
    };
    this._compiledComputeEffects = {};
    this._counters = {
      numEnableEffects: 0,
      numEnableDrawWrapper: 0,
      numBundleCreationNonCompatMode: 0,
      numBundleReuseNonCompatMode: 0
    };
    this.countersLastFrame = {
      numEnableEffects: 0,
      numEnableDrawWrapper: 0,
      numBundleCreationNonCompatMode: 0,
      numBundleReuseNonCompatMode: 0
    };
    this.numMaxUncapturedErrors = 20;
    this.scenes = [];
    this._virtualScenes = new Array;
    this._commandBuffers = [null, null];
    this._mainRenderPassWrapper = {
      renderPassDescriptor: null,
      colorAttachmentViewDescriptor: null,
      depthAttachmentViewDescriptor: null,
      colorAttachmentGPUTextures: [],
      depthTextureFormat: undefined
    };
    this._rttRenderPassWrapper = {
      renderPassDescriptor: null,
      colorAttachmentViewDescriptor: null,
      depthAttachmentViewDescriptor: null,
      colorAttachmentGPUTextures: [],
      depthTextureFormat: undefined
    };
    this._pendingDebugCommands = [];
    this._currentOverrideVertexBuffers = null;
    this._currentIndexBuffer = null;
    this._colorWriteLocal = true;
    this._forceEnableEffect = false;
    this.isNDCHalfZRange = true;
    this.hasOriginBottomLeft = false;
    this._workingGlslangAndTintPromise = null;
    this._viewportsCurrent = { x: 0, y: 0, w: 0, h: 0 };
    this._scissorsCurrent = { x: 0, y: 0, w: 0, h: 0 };
    this._scissorCached = { x: 0, y: 0, z: 0, w: 0 };
    this._stencilRefsCurrent = -1;
    this._blendColorsCurrent = [null, null, null, null];
    this._performanceMonitor = new PerformanceMonitor;
    this._name = "WebGPU";
    this._drawCalls = new PerfCounter;
    options.deviceDescriptor = options.deviceDescriptor || {};
    options.enableGPUDebugMarkers = options.enableGPUDebugMarkers ?? false;
    Logger.Log(`Babylon.js v${AbstractEngine.Version} - ${this.description} engine`);
    if (!navigator.gpu) {
      Logger.Error("WebGPU is not supported by your browser.");
      return;
    }
    options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat();
    this._isWebGPU = true;
    this._shaderPlatformName = "WEBGPU";
    this._renderingCanvas = canvas;
    this._options = options;
    this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1;
    if (navigator && navigator.userAgent) {
      this._setupMobileChecks();
    }
    this._sharedInit(this._renderingCanvas);
    this._shaderProcessor = new WebGPUShaderProcessorGLSL;
    this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL;
  }
  prepareGlslangAndTintAsync() {
    if (!this._workingGlslangAndTintPromise) {
      this._workingGlslangAndTintPromise = new Promise((resolve3) => {
        this._initGlslang(this._glslangOptions ?? this._options?.glslangOptions).then((glslang) => {
          this._glslang = glslang;
          this._tintWASM = new WebGPUTintWASM;
          this._tintWASM.initTwgsl(this._twgslOptions ?? this._options?.twgslOptions).then(() => {
            this._glslangAndTintAreFullyLoaded = true;
            resolve3();
          });
        });
      });
    }
    return this._workingGlslangAndTintPromise;
  }
  initAsync(glslangOptions, twgslOptions) {
    this.uniqueId = WebGPUEngine._InstanceId++;
    this._glslangOptions = glslangOptions;
    this._twgslOptions = twgslOptions;
    return navigator.gpu.requestAdapter(this._options).then((adapter) => {
      if (!adapter) {
        throw "Could not retrieve a WebGPU adapter (adapter is null).";
      } else {
        this._adapter = adapter;
        this._adapterSupportedExtensions = [];
        this._adapter.features?.forEach((feature) => this._adapterSupportedExtensions.push(feature));
        this._adapterSupportedLimits = this._adapter.limits;
        this._adapterInfo = this._adapter.info;
        const deviceDescriptor = this._options.deviceDescriptor ?? {};
        const requiredFeatures = deviceDescriptor?.requiredFeatures ?? (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined);
        if (requiredFeatures) {
          const requestedExtensions = requiredFeatures;
          const validExtensions = [];
          for (const extension of requestedExtensions) {
            if (this._adapterSupportedExtensions.indexOf(extension) !== -1) {
              validExtensions.push(extension);
            }
          }
          deviceDescriptor.requiredFeatures = validExtensions;
        }
        if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) {
          deviceDescriptor.requiredLimits = {};
          for (const name157 in this._adapterSupportedLimits) {
            if (name157 === "minSubgroupSize" || name157 === "maxSubgroupSize") {
              continue;
            }
            deviceDescriptor.requiredLimits[name157] = this._adapterSupportedLimits[name157];
          }
        }
        deviceDescriptor.label = `BabylonWebGPUDevice${this.uniqueId}`;
        return this._adapter.requestDevice(deviceDescriptor);
      }
    }).then((device) => {
      this._device = device;
      this._deviceEnabledExtensions = [];
      this._device.features?.forEach((feature) => this._deviceEnabledExtensions.push(feature));
      this._deviceLimits = device.limits;
      let numUncapturedErrors = -1;
      this._device.addEventListener("uncapturederror", (event) => {
        if (++numUncapturedErrors < this.numMaxUncapturedErrors) {
          Logger.Warn(`WebGPU uncaptured error (${numUncapturedErrors + 1}): ${event.error} - ${event.error.message}`);
        } else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) {
          Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`);
        }
      });
      if (!this._doNotHandleContextLost) {
        this._device.lost?.then((info) => {
          if (this._isDisposed) {
            return;
          }
          this._contextWasLost = true;
          Logger.Warn("WebGPU context lost. " + info);
          this.onContextLostObservable.notifyObservers(this);
          this._restoreEngineAfterContextLost(async () => {
            const snapshotRenderingMode = this.snapshotRenderingMode;
            const snapshotRendering = this.snapshotRendering;
            const disableCacheSamplers = this.disableCacheSamplers;
            const disableCacheRenderPipelines = this.disableCacheRenderPipelines;
            const disableCacheBindGroups = this.disableCacheBindGroups;
            const enableGPUTimingMeasurements = this.enableGPUTimingMeasurements;
            await this.initAsync(this._glslangOptions ?? this._options?.glslangOptions, this._twgslOptions ?? this._options?.twgslOptions);
            this.snapshotRenderingMode = snapshotRenderingMode;
            this.snapshotRendering = snapshotRendering;
            this.disableCacheSamplers = disableCacheSamplers;
            this.disableCacheRenderPipelines = disableCacheRenderPipelines;
            this.disableCacheBindGroups = disableCacheBindGroups;
            this.enableGPUTimingMeasurements = enableGPUTimingMeasurements;
            this._currentRenderPass = null;
          });
        });
      }
    }).then(() => {
      this._initializeLimits();
      this._bufferManager = new WebGPUBufferManager(this, this._device);
      this._textureHelper = new WebGPUTextureManager(this, this._device, this._bufferManager, this._deviceEnabledExtensions);
      this._cacheSampler = new WebGPUCacheSampler(this._device);
      this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this);
      this._timestampQuery = new WebGPUTimestampQuery(this, this._device, this._bufferManager);
      this._occlusionQuery = this._device.createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : undefined;
      this._bundleList = new WebGPUBundleList(this._device);
      this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList);
      this._ubInvertY = this._bufferManager.createBuffer(new Float32Array([-1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst, "UBInvertY");
      this._ubDontInvertY = this._bufferManager.createBuffer(new Float32Array([1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst, "UBDontInvertY");
      if (this.dbgVerboseLogsForFirstFrames) {
        if (this._count === undefined) {
          this._count = 0;
          Logger.Log(["%c frame #" + this._count + " - begin", "background: #ffff00"]);
        }
      }
      this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
      this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
      this._emptyVertexBuffer = new VertexBuffer(this, [0], "", {
        stride: 1,
        offset: 0,
        size: 1,
        label: "EmptyVertexBuffer"
      });
      this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer);
      this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline);
      this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline);
      this._stencilStateComposer.stencilGlobal = this._stencilState;
      this._depthCullingState.depthTest = true;
      this._depthCullingState.depthFunc = 515;
      this._depthCullingState.depthMask = true;
      this._textureHelper.setCommandEncoder(this._uploadEncoder);
      this._clearQuad = new WebGPUClearQuad(this._device, this, this._emptyVertexBuffer);
      this._defaultDrawContext = this.createDrawContext();
      this._currentDrawContext = this._defaultDrawContext;
      this._defaultMaterialContext = this.createMaterialContext();
      this._currentMaterialContext = this._defaultMaterialContext;
      this._initializeContextAndSwapChain();
      this._initializeMainAttachments();
      this.resize();
    }).catch((e) => {
      Logger.Error("A fatal error occurred during WebGPU creation/initialization.");
      throw e;
    });
  }
  _initGlslang(glslangOptions) {
    glslangOptions = glslangOptions || {};
    glslangOptions = {
      ...WebGPUEngine._GlslangDefaultOptions,
      ...glslangOptions
    };
    if (glslangOptions.glslang) {
      return Promise.resolve(glslangOptions.glslang);
    }
    if (self.glslang) {
      return self.glslang(glslangOptions.wasmPath);
    }
    if (glslangOptions.jsPath && glslangOptions.wasmPath) {
      return Tools.LoadBabylonScriptAsync(glslangOptions.jsPath).then(() => {
        return self.glslang(Tools.GetBabylonScriptURL(glslangOptions.wasmPath));
      });
    }
    return Promise.reject("gslang is not available.");
  }
  _initializeLimits() {
    this._caps = {
      maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,
      maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,
      maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2,
      maxTextureSize: this._deviceLimits.maxTextureDimension2D,
      maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D,
      maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D,
      maxVertexAttribs: this._deviceLimits.maxVertexAttributes,
      maxDrawBuffers: 8,
      maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables,
      maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),
      maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),
      standardDerivatives: true,
      astc: this._deviceEnabledExtensions.indexOf("texture-compression-astc") >= 0 ? true : undefined,
      s3tc: this._deviceEnabledExtensions.indexOf("texture-compression-bc") >= 0 ? true : undefined,
      pvrtc: null,
      etc1: null,
      etc2: this._deviceEnabledExtensions.indexOf("texture-compression-etc2") >= 0 ? true : undefined,
      bptc: this._deviceEnabledExtensions.indexOf("texture-compression-bc") >= 0 ? true : undefined,
      maxAnisotropy: 16,
      uintIndices: true,
      fragmentDepthSupported: true,
      highPrecisionShaderSupported: true,
      colorBufferFloat: true,
      supportFloatTexturesResolve: false,
      rg11b10ufColorRenderable: this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable") >= 0,
      textureFloat: true,
      textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf("float32-filterable") >= 0,
      textureFloatRender: true,
      textureHalfFloat: true,
      textureHalfFloatLinearFiltering: true,
      textureHalfFloatRender: true,
      textureLOD: true,
      texelFetch: true,
      drawBuffersExtension: true,
      depthTextureExtension: true,
      vertexArrayObject: false,
      instancedArrays: true,
      timerQuery: typeof BigUint64Array !== "undefined" && this._deviceEnabledExtensions.indexOf("timestamp-query") !== -1 ? true : undefined,
      supportOcclusionQuery: typeof BigUint64Array !== "undefined",
      canUseTimestampForTimerQuery: true,
      multiview: false,
      oculusMultiview: false,
      parallelShaderCompile: undefined,
      blendMinMax: true,
      maxMSAASamples: 4,
      canUseGLInstanceID: true,
      canUseGLVertexID: true,
      supportComputeShaders: true,
      supportSRGBBuffers: true,
      supportTransformFeedbacks: false,
      textureMaxLevel: true,
      texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers,
      disableMorphTargetTexture: false,
      textureNorm16: false
    };
    this._features = {
      forceBitmapOverHTMLImageElement: true,
      supportRenderAndCopyToLodForFloatTextures: true,
      supportDepthStencilTexture: true,
      supportShadowSamplers: true,
      uniformBufferHardCheckMatrix: false,
      allowTexturePrefiltering: true,
      trackUbosInFrame: true,
      checkUbosContentBeforeUpload: true,
      supportCSM: true,
      basisNeedsPOT: false,
      support3DTextures: true,
      needTypeSuffixInShaderConstants: true,
      supportMSAA: true,
      supportSSAO2: true,
      supportIBLShadows: true,
      supportExtendedTextureFormats: true,
      supportSwitchCaseInShader: true,
      supportSyncTextureRead: false,
      needsInvertingBitmap: false,
      useUBOBindingCache: false,
      needShaderCodeInlining: true,
      needToAlwaysBindUniformBuffers: true,
      supportRenderPasses: true,
      supportSpriteInstancing: true,
      forceVertexBufferStrideAndOffsetMultiple4Bytes: true,
      _checkNonFloatVertexBuffersDontRecreatePipelineContext: true,
      _collectUbosUpdatedInFrame: false
    };
  }
  _initializeContextAndSwapChain() {
    if (!this._renderingCanvas) {
      throw "The rendering canvas has not been set!";
    }
    this._context = this._renderingCanvas.getContext("webgpu");
    this._configureContext();
    this._colorFormat = this._options.swapChainFormat;
    this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture(this)];
    this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat;
    this._setColorFormat(this._mainRenderPassWrapper);
  }
  _initializeMainAttachments() {
    if (!this._bufferManager) {
      return;
    }
    this.flushFramebuffer();
    this._mainTextureExtends = {
      width: this.getRenderWidth(true),
      height: this.getRenderHeight(true),
      depthOrArrayLayers: 1
    };
    const bufferDataUpdate = new Float32Array([this.getRenderHeight(true)]);
    this._bufferManager.setSubData(this._ubInvertY, 4, bufferDataUpdate);
    this._bufferManager.setSubData(this._ubDontInvertY, 4, bufferDataUpdate);
    let mainColorAttachments;
    if (this._options.antialias) {
      const mainTextureDescriptor = {
        label: `Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,
        size: this._mainTextureExtends,
        mipLevelCount: 1,
        sampleCount: this._mainPassSampleCount,
        dimension: "2d",
        format: this._options.swapChainFormat,
        usage: 16
      };
      if (this._mainTexture) {
        this._textureHelper.releaseTexture(this._mainTexture);
      }
      this._mainTexture = this._device.createTexture(mainTextureDescriptor);
      mainColorAttachments = [
        {
          view: this._mainTexture.createView({
            label: "TextureView_MainColor_antialiasing",
            dimension: "2d",
            format: this._options.swapChainFormat,
            mipLevelCount: 1,
            arrayLayerCount: 1
          }),
          clearValue: new Color4(0, 0, 0, 1),
          loadOp: "clear",
          storeOp: "store"
        }
      ];
    } else {
      mainColorAttachments = [
        {
          view: undefined,
          clearValue: new Color4(0, 0, 0, 1),
          loadOp: "clear",
          storeOp: "store"
        }
      ];
    }
    this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? "depth24plus-stencil8" : "depth32float";
    this._setDepthTextureFormat(this._mainRenderPassWrapper);
    this._setColorFormat(this._mainRenderPassWrapper);
    const depthTextureDescriptor = {
      label: `Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,
      size: this._mainTextureExtends,
      mipLevelCount: 1,
      sampleCount: this._mainPassSampleCount,
      dimension: "2d",
      format: this._mainRenderPassWrapper.depthTextureFormat,
      usage: 16
    };
    if (this._depthTexture) {
      this._textureHelper.releaseTexture(this._depthTexture);
    }
    this._depthTexture = this._device.createTexture(depthTextureDescriptor);
    const mainDepthAttachment = {
      view: this._depthTexture.createView({
        label: `TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,
        dimension: "2d",
        format: this._depthTexture.format,
        mipLevelCount: 1,
        arrayLayerCount: 1
      }),
      depthClearValue: this._clearDepthValue,
      depthLoadOp: "clear",
      depthStoreOp: "store",
      stencilClearValue: this._clearStencilValue,
      stencilLoadOp: !this.isStencilEnable ? undefined : "clear",
      stencilStoreOp: !this.isStencilEnable ? undefined : "store"
    };
    this._mainRenderPassWrapper.renderPassDescriptor = {
      label: "MainRenderPass",
      colorAttachments: mainColorAttachments,
      depthStencilAttachment: mainDepthAttachment
    };
  }
  _sharedInit(canvas) {
    super._sharedInit(canvas);
    _CommonInit(this, canvas, this._creationOptions);
  }
  _configureContext() {
    this._context.configure({
      device: this._device,
      format: this._options.swapChainFormat,
      usage: 16 | 1,
      alphaMode: this.premultipliedAlpha ? "premultiplied" : "opaque"
    });
  }
  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();
    }
  }
  enterPointerlock() {
    if (this._renderingCanvas) {
      RequestPointerlock(this._renderingCanvas);
    }
  }
  exitPointerlock() {
    ExitPointerlock();
  }
  _rebuildBuffers() {
    super._rebuildBuffers();
    for (const storageBuffer2 of this._storageBuffers) {
      if (storageBuffer2.getBuffer().engineId !== this.uniqueId) {
        storageBuffer2._rebuild();
      }
    }
  }
  _restoreEngineAfterContextLost(initEngine) {
    WebGPUCacheRenderPipelineTree.ResetCache();
    WebGPUCacheBindGroups.ResetCache();
    const cleanScenes = (scenes) => {
      for (const scene of scenes) {
        for (const mesh of scene.meshes) {
          const subMeshes = mesh.subMeshes;
          if (!subMeshes) {
            continue;
          }
          for (const subMesh of subMeshes) {
            subMesh._drawWrappers = [];
          }
        }
        for (const material of scene.materials) {
          material._materialContext?.reset();
        }
      }
    };
    cleanScenes(this.scenes);
    cleanScenes(this._virtualScenes);
    const uboList = [];
    for (const uniformBuffer of this._uniformBuffers) {
      if (uniformBuffer.name.indexOf("leftOver") < 0) {
        uboList.push(uniformBuffer);
      }
    }
    this._uniformBuffers = uboList;
    super._restoreEngineAfterContextLost(initEngine);
  }
  setSize(width, height, forceSetSize = false) {
    if (!super.setSize(width, height, forceSetSize)) {
      return false;
    }
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log(["frame #" + this._count + " - setSize -", width, height]);
      }
    }
    this._initializeMainAttachments();
    if (this.snapshotRendering) {
      this.snapshotRenderingReset();
    }
    return true;
  }
  _getShaderProcessor(shaderLanguage) {
    if (shaderLanguage === 1) {
      return this._shaderProcessorWGSL;
    }
    return this._shaderProcessor;
  }
  _getShaderProcessingContext(shaderLanguage, pureMode) {
    return new WebGPUShaderProcessingContext(shaderLanguage, pureMode);
  }
  _getCurrentRenderPass() {
    if (this._currentRenderTarget && !this._currentRenderPass) {
      this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false);
    } else if (!this._currentRenderPass) {
      this._startMainRenderPass(false);
    }
    return this._currentRenderPass;
  }
  _getCurrentRenderPassWrapper() {
    return this._currentRenderTarget ? this._rttRenderPassWrapper : this._mainRenderPassWrapper;
  }
  applyStates() {
    this._stencilStateComposer.apply();
    this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);
  }
  wipeCaches(bruteForce) {
    if (this.preventCacheWipeBetweenFrames && !bruteForce) {
      return;
    }
    this._forceEnableEffect = true;
    this._currentIndexBuffer = null;
    this._currentOverrideVertexBuffers = null;
    this._cacheRenderPipeline.setBuffers(null, null, null);
    if (bruteForce) {
      this._stencilStateComposer.reset();
      this._depthCullingState.reset();
      this._depthCullingState.depthFunc = 515;
      this._alphaState.reset();
      this._alphaMode = 1;
      this._alphaEquation = 0;
      this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);
      this._cacheRenderPipeline.setAlphaBlendEnabled(false);
      this.setColorWrite(true);
    }
    this._cachedVertexBuffers = null;
    this._cachedIndexBuffer = null;
    this._cachedEffectForVertexBuffers = null;
  }
  setColorWrite(enable) {
    this._colorWriteLocal = enable;
    this._cacheRenderPipeline.setWriteMask(enable ? 15 : 0);
  }
  getColorWrite() {
    return this._colorWriteLocal;
  }
  _mustUpdateViewport() {
    const x = this._viewportCached.x, y = this._viewportCached.y, w = this._viewportCached.z, h = this._viewportCached.w;
    const update = this._viewportsCurrent.x !== x || this._viewportsCurrent.y !== y || this._viewportsCurrent.w !== w || this._viewportsCurrent.h !== h;
    if (update) {
      this._viewportsCurrent.x = this._viewportCached.x;
      this._viewportsCurrent.y = this._viewportCached.y;
      this._viewportsCurrent.w = this._viewportCached.z;
      this._viewportsCurrent.h = this._viewportCached.w;
    }
    return update;
  }
  _applyViewport(bundleList) {
    const x = Math.floor(this._viewportCached.x);
    const w = Math.floor(this._viewportCached.z);
    const h = Math.floor(this._viewportCached.w);
    let y = Math.floor(this._viewportCached.y);
    if (!this._currentRenderTarget) {
      y = this.getRenderHeight(true) - y - h;
    }
    if (bundleList) {
      bundleList.addItem(new WebGPURenderItemViewport(x, y, w, h));
    } else {
      this._getCurrentRenderPass().setViewport(x, y, w, h, 0, 1);
    }
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log([
          "frame #" + this._count + " - viewport applied - (",
          this._viewportCached.x,
          this._viewportCached.y,
          this._viewportCached.z,
          this._viewportCached.w,
          ") current pass is main pass=" + this._currentPassIsMainPass()
        ]);
      }
    }
  }
  _viewport(x, y, width, height) {
    this._viewportCached.x = x;
    this._viewportCached.y = y;
    this._viewportCached.z = width;
    this._viewportCached.w = height;
  }
  _mustUpdateScissor() {
    const x = this._scissorCached.x, y = this._scissorCached.y, w = this._scissorCached.z, h = this._scissorCached.w;
    const update = this._scissorsCurrent.x !== x || this._scissorsCurrent.y !== y || this._scissorsCurrent.w !== w || this._scissorsCurrent.h !== h;
    if (update) {
      this._scissorsCurrent.x = this._scissorCached.x;
      this._scissorsCurrent.y = this._scissorCached.y;
      this._scissorsCurrent.w = this._scissorCached.z;
      this._scissorsCurrent.h = this._scissorCached.w;
    }
    return update;
  }
  _applyScissor(bundleList) {
    const y = this._currentRenderTarget ? this._scissorCached.y : this.getRenderHeight() - this._scissorCached.w - this._scissorCached.y;
    if (bundleList) {
      bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, y, this._scissorCached.z, this._scissorCached.w));
    } else {
      this._getCurrentRenderPass().setScissorRect(this._scissorCached.x, y, this._scissorCached.z, this._scissorCached.w);
    }
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log([
          "frame #" + this._count + " - scissor applied - (",
          this._scissorCached.x,
          this._scissorCached.y,
          this._scissorCached.z,
          this._scissorCached.w,
          ") current pass is main pass=" + this._currentPassIsMainPass()
        ]);
      }
    }
  }
  _scissorIsActive() {
    return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0;
  }
  enableScissor(x, y, width, height) {
    this._scissorCached.x = x;
    this._scissorCached.y = y;
    this._scissorCached.z = width;
    this._scissorCached.w = height;
  }
  disableScissor() {
    this._scissorCached.x = this._scissorCached.y = this._scissorCached.z = this._scissorCached.w = 0;
    this._scissorsCurrent.x = this._scissorsCurrent.y = this._scissorsCurrent.w = this._scissorsCurrent.h = 0;
  }
  _mustUpdateStencilRef() {
    const update = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent;
    if (update) {
      this._stencilRefsCurrent = this._stencilStateComposer.funcRef;
    }
    return update;
  }
  _applyStencilRef(bundleList) {
    if (bundleList) {
      bundleList.addItem(new WebGPURenderItemStencilRef(this._stencilStateComposer.funcRef ?? 0));
    } else {
      this._getCurrentRenderPass().setStencilReference(this._stencilStateComposer.funcRef ?? 0);
    }
  }
  _mustUpdateBlendColor() {
    const colorBlend = this._alphaState._blendConstants;
    const update = colorBlend[0] !== this._blendColorsCurrent[0] || colorBlend[1] !== this._blendColorsCurrent[1] || colorBlend[2] !== this._blendColorsCurrent[2] || colorBlend[3] !== this._blendColorsCurrent[3];
    if (update) {
      this._blendColorsCurrent[0] = colorBlend[0];
      this._blendColorsCurrent[1] = colorBlend[1];
      this._blendColorsCurrent[2] = colorBlend[2];
      this._blendColorsCurrent[3] = colorBlend[3];
    }
    return update;
  }
  _applyBlendColor(bundleList) {
    if (bundleList) {
      bundleList.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()));
    } else {
      this._getCurrentRenderPass().setBlendConstant(this._alphaState._blendConstants);
    }
  }
  _resetRenderPassStates() {
    this._viewportsCurrent.x = this._viewportsCurrent.y = this._viewportsCurrent.w = this._viewportsCurrent.h = 0;
    this._scissorsCurrent.x = this._scissorsCurrent.y = this._scissorsCurrent.w = this._scissorsCurrent.h = 0;
    this._stencilRefsCurrent = -1;
    this._blendColorsCurrent[0] = this._blendColorsCurrent[1] = this._blendColorsCurrent[2] = this._blendColorsCurrent[3] = null;
  }
  clear(color, backBuffer, depth, stencil = false) {
    if (color && color.a === undefined) {
      color.a = 1;
    }
    const hasScissor = this._scissorIsActive();
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log(["frame #" + this._count + " - clear - backBuffer=", backBuffer, " depth=", depth, " stencil=", stencil, " scissor is active=", hasScissor]);
      }
    }
    if (this._currentRenderTarget) {
      if (hasScissor) {
        if (!this._currentRenderPass) {
          this._startRenderTargetRenderPass(this._currentRenderTarget, false, backBuffer ? color : null, depth, stencil);
        }
        this._applyScissor(!this.compatibilityMode ? this._bundleList : null);
        this._clearFullQuad(backBuffer ? color : null, depth, stencil);
      } else {
        if (this._currentRenderPass) {
          this._endCurrentRenderPass();
        }
        this._startRenderTargetRenderPass(this._currentRenderTarget, true, backBuffer ? color : null, depth, stencil);
      }
    } else {
      if (!this._currentRenderPass || !hasScissor) {
        this._startMainRenderPass(!hasScissor, backBuffer ? color : null, depth, stencil);
      }
      if (hasScissor) {
        this._applyScissor(!this.compatibilityMode ? this._bundleList : null);
        this._clearFullQuad(backBuffer ? color : null, depth, stencil);
      }
    }
  }
  _clearFullQuad(clearColor, clearDepth, clearStencil) {
    const renderPass = !this.compatibilityMode ? null : this._getCurrentRenderPass();
    this._clearQuad.setColorFormat(this._colorFormat);
    this._clearQuad.setDepthStencilFormat(this._depthTextureFormat);
    this._clearQuad.setMRTAttachments(this._cacheRenderPipeline.mrtAttachments ?? [], this._cacheRenderPipeline.mrtTextureArray ?? [], this._cacheRenderPipeline.mrtTextureCount);
    if (!this.compatibilityMode) {
      this._bundleList.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));
    } else {
      renderPass.setStencilReference(this._clearStencilValue);
    }
    const bundle = this._clearQuad.clear(renderPass, clearColor, clearDepth, clearStencil, this.currentSampleCount);
    if (!this.compatibilityMode) {
      this._bundleList.addBundle(bundle);
      this._applyStencilRef(this._bundleList);
      this._reportDrawCall();
    } else {
      this._applyStencilRef(null);
    }
  }
  createVertexBuffer(data, _updatable, label) {
    let view;
    if (data instanceof Array) {
      view = new Float32Array(data);
    } else if (data instanceof ArrayBuffer) {
      view = new Uint8Array(data);
    } else {
      view = data;
    }
    const dataBuffer2 = this._bufferManager.createBuffer(view, BufferUsage.Vertex | BufferUsage.CopyDst, label);
    return dataBuffer2;
  }
  createDynamicVertexBuffer(data, label) {
    return this.createVertexBuffer(data, undefined, label);
  }
  createIndexBuffer(indices, _updatable, label) {
    let is32Bits = true;
    let view;
    if (indices instanceof Uint32Array || indices instanceof Int32Array) {
      view = indices;
    } else if (indices instanceof Uint16Array) {
      view = indices;
      is32Bits = false;
    } else {
      for (let index = 0;index < indices.length; index++) {
        if (indices[index] > 65535) {
          view = new Uint32Array(indices);
          break;
        }
      }
      if (!view) {
        view = new Uint16Array(indices);
        is32Bits = false;
      }
    }
    const dataBuffer2 = this._bufferManager.createBuffer(view, BufferUsage.Index | BufferUsage.CopyDst, label);
    dataBuffer2.is32Bits = is32Bits;
    return dataBuffer2;
  }
  updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) {
    const gpuBuffer = indexBuffer;
    let view;
    if (indexBuffer.is32Bits) {
      view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);
    } else {
      view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);
    }
    this._bufferManager.setSubData(gpuBuffer, offset, view);
  }
  updateDynamicVertexBuffer(vertexBuffer, data, byteOffset, byteLength) {
    const dataBuffer2 = vertexBuffer;
    if (byteOffset === undefined) {
      byteOffset = 0;
    }
    let view;
    if (byteLength === undefined) {
      if (data instanceof Array) {
        view = new Float32Array(data);
      } else if (data instanceof ArrayBuffer) {
        view = new Uint8Array(data);
      } else {
        view = data;
      }
      byteLength = view.byteLength;
    } else {
      if (data instanceof Array) {
        view = new Float32Array(data);
      } else if (data instanceof ArrayBuffer) {
        view = new Uint8Array(data);
      } else {
        view = data;
      }
    }
    this._bufferManager.setSubData(dataBuffer2, byteOffset, view, 0, byteLength);
  }
  _createBuffer(data, creationFlags, label) {
    let view;
    if (data instanceof Array) {
      view = new Float32Array(data);
    } else if (data instanceof ArrayBuffer) {
      view = new Uint8Array(data);
    } else {
      view = data;
    }
    let flags = 0;
    if (creationFlags & 1) {
      flags |= BufferUsage.CopySrc;
    }
    if (creationFlags & 2) {
      flags |= BufferUsage.CopyDst;
    }
    if (creationFlags & 4) {
      flags |= BufferUsage.Uniform;
    }
    if (creationFlags & 8) {
      flags |= BufferUsage.Vertex;
    }
    if (creationFlags & 16) {
      flags |= BufferUsage.Index;
    }
    if (creationFlags & 32) {
      flags |= BufferUsage.Storage;
    }
    if (creationFlags & 64) {
      flags |= BufferUsage.Indirect;
    }
    return this._bufferManager.createBuffer(view, flags, label);
  }
  bindBuffersDirectly() {
    throw "Not implemented on WebGPU";
  }
  updateAndBindInstancesBuffer() {
    throw "Not implemented on WebGPU";
  }
  unbindInstanceAttributes() {}
  bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
    this._currentIndexBuffer = indexBuffer;
    this._currentOverrideVertexBuffers = overrideVertexBuffers ?? null;
    this._cacheRenderPipeline.setBuffers(vertexBuffers, indexBuffer, this._currentOverrideVertexBuffers);
  }
  _releaseBuffer(buffer2) {
    return this._bufferManager.releaseBuffer(buffer2);
  }
  createUniformBuffer(elements, label) {
    let view;
    if (elements instanceof Array) {
      view = new Float32Array(elements);
    } else {
      view = elements;
    }
    const dataBuffer2 = this._bufferManager.createBuffer(view, BufferUsage.Uniform | BufferUsage.CopyDst, label);
    return dataBuffer2;
  }
  createDynamicUniformBuffer(elements, label) {
    return this.createUniformBuffer(elements, label);
  }
  updateUniformBuffer(uniformBuffer, elements, offset, count) {
    if (offset === undefined) {
      offset = 0;
    }
    const dataBuffer2 = uniformBuffer;
    let view;
    if (count === undefined) {
      if (elements instanceof Float32Array) {
        view = elements;
      } else {
        view = new Float32Array(elements);
      }
      count = view.byteLength;
    } else {
      if (elements instanceof Float32Array) {
        view = elements;
      } else {
        view = new Float32Array(elements);
      }
    }
    this._bufferManager.setSubData(dataBuffer2, offset, view, 0, count);
  }
  bindUniformBufferBase(buffer2, _location, name157) {
    this._currentDrawContext.setBuffer(name157, buffer2);
  }
  bindUniformBlock() {}
  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 name157 = vertex + "+" + fragment + "@" + fullDefines;
    if (this._compiledEffects[name157]) {
      const compiledEffect = this._compiledEffects[name157];
      if (onCompiled && compiledEffect.isReady()) {
        onCompiled(compiledEffect);
      }
      compiledEffect._refCount++;
      return compiledEffect;
    }
    const effect = new Effect(baseName, attributesNamesOrOptions, isOptions ? this : uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name157, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync);
    this._compiledEffects[name157] = effect;
    return effect;
  }
  _compileRawShaderToSpirV(source, type) {
    return this._glslang.compileGLSL(source, type);
  }
  _compileShaderToSpirV(source, type, defines, shaderVersion) {
    return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + `
` : "") + source, type);
  }
  _getWGSLShader(source, type, defines) {
    if (defines) {
      defines = "//" + defines.split(`
`).join(`
//`) + `
`;
    } else {
      defines = "";
    }
    return defines + source;
  }
  _createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment) {
    if (this._tintWASM && shaderLanguage === 0) {
      vertexShader = this._tintWASM.convertSpirV2WGSL(vertexShader, disableUniformityAnalysisInVertex);
      fragmentShader = this._tintWASM.convertSpirV2WGSL(fragmentShader, disableUniformityAnalysisInFragment);
    }
    return {
      vertexStage: {
        module: this._device.createShaderModule({
          label: "vertex",
          code: vertexShader
        }),
        entryPoint: "main"
      },
      fragmentStage: {
        module: this._device.createShaderModule({
          label: "fragment",
          code: fragmentShader
        }),
        entryPoint: "main"
      }
    };
  }
  _compileRawPipelineStageDescriptor(vertexCode, fragmentCode, shaderLanguage) {
    const disableUniformityAnalysisInVertex = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0;
    const disableUniformityAnalysisInFragment = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0;
    const vertexShader = shaderLanguage === 0 ? this._compileRawShaderToSpirV(vertexCode, "vertex") : vertexCode;
    const fragmentShader = shaderLanguage === 0 ? this._compileRawShaderToSpirV(fragmentCode, "fragment") : fragmentCode;
    return this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);
  }
  _compilePipelineStageDescriptor(vertexCode, fragmentCode, defines, shaderLanguage) {
    this.onBeforeShaderCompilationObservable.notifyObservers(this);
    const disableUniformityAnalysisInVertex = vertexCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0;
    const disableUniformityAnalysisInFragment = fragmentCode.indexOf(`#define DISABLE_UNIFORMITY_ANALYSIS`) >= 0;
    const shaderVersion = `#version 450
`;
    const vertexShader = shaderLanguage === 0 ? this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion) : this._getWGSLShader(vertexCode, "vertex", defines);
    const fragmentShader = shaderLanguage === 0 ? this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion) : this._getWGSLShader(fragmentCode, "fragment", defines);
    const program = this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);
    this.onAfterShaderCompilationObservable.notifyObservers(this);
    return program;
  }
  createRawShaderProgram() {
    throw "Not available on WebGPU";
  }
  createShaderProgram() {
    throw "Not available on WebGPU";
  }
  inlineShaderCode(code) {
    const sci = new ShaderCodeInliner(code);
    sci.debug = false;
    sci.processCode();
    return sci.code;
  }
  createPipelineContext(shaderProcessingContext) {
    return new WebGPUPipelineContext(shaderProcessingContext, this);
  }
  createMaterialContext() {
    return new WebGPUMaterialContext;
  }
  createDrawContext() {
    return new WebGPUDrawContext(this._bufferManager);
  }
  async _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, _rebuildRebind, defines, _transformFeedbackVaryings, _key, onReady) {
    const webGpuContext = pipelineContext;
    const shaderLanguage = webGpuContext.shaderProcessingContext.shaderLanguage;
    if (shaderLanguage === 0 && !this._glslangAndTintAreFullyLoaded) {
      await this.prepareGlslangAndTintAsync();
    }
    if (this.dbgShowShaderCode) {
      Logger.Log(["defines", defines]);
      Logger.Log(vertexSourceCode);
      Logger.Log(fragmentSourceCode);
      Logger.Log("***********************************************");
    }
    webGpuContext.sources = {
      fragment: fragmentSourceCode,
      vertex: vertexSourceCode,
      rawVertex: rawVertexSourceCode,
      rawFragment: rawFragmentSourceCode
    };
    if (createAsRaw) {
      webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, shaderLanguage);
    } else {
      webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines, shaderLanguage);
    }
    onReady();
  }
  getAttributes(pipelineContext, attributesNames) {
    const results = new Array(attributesNames.length);
    const gpuPipelineContext = pipelineContext;
    for (let i = 0;i < attributesNames.length; i++) {
      const attributeName = attributesNames[i];
      const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName];
      if (attributeLocation === undefined) {
        continue;
      }
      results[i] = attributeLocation;
    }
    return results;
  }
  enableEffect(effect) {
    if (!effect) {
      return;
    }
    if (!IsWrapper(effect)) {
      this._currentEffect = effect;
      this._currentMaterialContext = this._defaultMaterialContext;
      this._currentDrawContext = this._defaultDrawContext;
      this._counters.numEnableEffects++;
      if (this.dbgLogIfNotDrawWrapper) {
        Logger.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${effect.uniqueId}, effect.name=${effect.name}, effect.name.vertex=${typeof effect.name === "string" ? "" : effect.name.vertex}, effect.name.fragment=${typeof effect.name === "string" ? "" : effect.name.fragment}`, 10);
      }
    } else if (!effect.effect || effect.effect === this._currentEffect && effect.materialContext === this._currentMaterialContext && effect.drawContext === this._currentDrawContext && !this._forceEnableEffect) {
      if (!effect.effect && this.dbgShowEmptyEnableEffectCalls) {
        Logger.Log(["drawWrapper=", effect]);
        throw "Invalid call to enableEffect: the effect property is empty!";
      }
      return;
    } else {
      this._currentEffect = effect.effect;
      this._currentMaterialContext = effect.materialContext;
      this._currentDrawContext = effect.drawContext;
      this._counters.numEnableDrawWrapper++;
      if (!this._currentMaterialContext) {
        Logger.Log(["drawWrapper=", effect]);
        throw `Invalid call to enableEffect: the materialContext property is empty!`;
      }
    }
    this._stencilStateComposer.stencilMaterial = undefined;
    this._forceEnableEffect = false;
    if (this._currentEffect.onBind) {
      this._currentEffect.onBind(this._currentEffect);
    }
    if (this._currentEffect._onBindObservable) {
      this._currentEffect._onBindObservable.notifyObservers(this._currentEffect);
    }
  }
  _releaseEffect(effect) {
    if (this._compiledEffects[effect._key]) {
      delete this._compiledEffects[effect._key];
      this._deletePipelineContext(effect.getPipelineContext());
    }
  }
  releaseEffects() {
    for (const name157 in this._compiledEffects) {
      const webGPUPipelineContext = this._compiledEffects[name157].getPipelineContext();
      this._deletePipelineContext(webGPUPipelineContext);
    }
    this._compiledEffects = {};
    this.onReleaseEffectsObservable.notifyObservers(this);
  }
  _deletePipelineContext(pipelineContext) {
    const webgpuPipelineContext = pipelineContext;
    if (webgpuPipelineContext) {
      resetCachedPipeline(webgpuPipelineContext);
    }
  }
  get needPOTTextures() {
    return false;
  }
  _createHardwareTexture() {
    return new WebGPUHardwareTexture(this);
  }
  _releaseTexture(texture) {
    const index = this._internalTexturesCache.indexOf(texture);
    if (index !== -1) {
      this._internalTexturesCache.splice(index, 1);
    }
    this._textureHelper.releaseTexture(texture);
  }
  _getRGBABufferInternalSizedFormat() {
    return 5;
  }
  updateTextureComparisonFunction(texture, comparisonFunction) {
    texture._comparisonFunction = comparisonFunction;
  }
  _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0) {
    const fullOptions = {};
    if (options !== undefined && typeof options === "object") {
      fullOptions.generateMipMaps = options.generateMipMaps;
      fullOptions.createMipMaps = options.createMipMaps;
      fullOptions.type = options.type === undefined ? 0 : options.type;
      fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;
      fullOptions.format = options.format === undefined ? 5 : options.format;
      fullOptions.samples = options.samples ?? 1;
      fullOptions.creationFlags = options.creationFlags ?? 0;
      fullOptions.useSRGBBuffer = options.useSRGBBuffer ?? false;
      fullOptions.label = options.label;
    } else {
      fullOptions.generateMipMaps = options;
      fullOptions.type = 0;
      fullOptions.samplingMode = 3;
      fullOptions.format = 5;
      fullOptions.samples = 1;
      fullOptions.creationFlags = 0;
      fullOptions.useSRGBBuffer = false;
    }
    if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {
      fullOptions.samplingMode = 1;
    } else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
      fullOptions.samplingMode = 1;
    }
    if (fullOptions.type === 1 && !this._caps.textureFloat) {
      fullOptions.type = 0;
      Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE");
    }
    const texture = new InternalTexture(this, source);
    const width = size.width ?? size;
    const height = size.height ?? size;
    const depth = size.depth ?? 0;
    const layers = size.layers ?? 0;
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.width = width;
    texture.height = height;
    texture.depth = depth || layers;
    texture.isReady = true;
    texture.samples = fullOptions.samples;
    texture.generateMipMaps = !!fullOptions.generateMipMaps;
    texture.samplingMode = fullOptions.samplingMode;
    texture.type = fullOptions.type;
    texture.format = fullOptions.format;
    texture.is2DArray = layers > 0;
    texture.is3D = depth > 0;
    texture._cachedWrapU = 0;
    texture._cachedWrapV = 0;
    texture._useSRGBBuffer = fullOptions.useSRGBBuffer;
    texture.label = fullOptions.label;
    this._internalTexturesCache.push(texture);
    if (!delayGPUTextureCreation) {
      const createMipMapsOnly = !fullOptions.generateMipMaps && fullOptions.createMipMaps;
      if (createMipMapsOnly) {
        texture.generateMipMaps = true;
      }
      this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, layers || 1, fullOptions.creationFlags);
      if (createMipMapsOnly) {
        texture.generateMipMaps = false;
      }
    }
    return texture;
  }
  createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer2 = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) {
    return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (texture, extension, scene2, img, invertY2, noMipmap2, isCompressed, processFunction) => {
      const imageBitmap = img;
      texture.baseWidth = imageBitmap.width;
      texture.baseHeight = imageBitmap.height;
      texture.width = imageBitmap.width;
      texture.height = imageBitmap.height;
      texture.format = texture.format !== -1 ? texture.format : format ?? 5;
      texture.type = texture.type !== -1 ? texture.type : 0;
      texture._creationFlags = creationFlags ?? 0;
      processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => {});
      if (!texture._hardwareTexture?.underlyingResource) {
        const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height, undefined, creationFlags);
        if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {
          this._textureHelper.updateTexture(imageBitmap, texture, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY2, false, 0, 0);
          if (!noMipmap2 && !isCompressed) {
            this._generateMipmaps(texture, this._uploadEncoder);
          }
        }
      } else if (!noMipmap2 && !isCompressed) {
        this._generateMipmaps(texture, this._uploadEncoder);
      }
      if (scene2) {
        scene2.removePendingData(texture);
      }
      texture.isReady = true;
      texture.onLoadedObservable.notifyObservers(texture);
      texture.onLoadedObservable.clear();
    }, () => false, buffer2, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer);
  }
  wrapWebGPUTexture(texture) {
    const hardwareTexture = new WebGPUHardwareTexture(this, texture);
    const internalTexture = new InternalTexture(this, 0, true);
    internalTexture._hardwareTexture = hardwareTexture;
    internalTexture.isReady = true;
    return internalTexture;
  }
  wrapWebGLTexture() {
    throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.");
  }
  _getUseSRGBBuffer(useSRGBBuffer, _noMipmap) {
    return useSRGBBuffer && this._caps.supportSRGBBuffers;
  }
  _unpackFlipY(_value) {}
  updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) {
    if (generateMipMaps) {
      texture.generateMipMaps = true;
      this._generateMipmaps(texture);
    }
    texture.samplingMode = samplingMode;
  }
  updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) {
    if (wrapU !== null) {
      texture._cachedWrapU = wrapU;
    }
    if (wrapV !== null) {
      texture._cachedWrapV = wrapV;
    }
    if ((texture.is2DArray || texture.is3D) && wrapR !== null) {
      texture._cachedWrapR = wrapR;
    }
  }
  updateTextureDimensions(texture, width, height, depth = 1) {
    if (!texture._hardwareTexture) {
      return;
    }
    if (texture.width === width && texture.height === height && texture.depth === depth) {
      return;
    }
    const additionalUsages = texture._hardwareTexture.textureAdditionalUsages;
    texture._hardwareTexture.release();
    this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, additionalUsages);
  }
  _setInternalTexture(name157, texture, baseName) {
    baseName = baseName ?? name157;
    if (this._currentEffect) {
      const webgpuPipelineContext = this._currentEffect._pipelineContext;
      const availableTexture = webgpuPipelineContext.shaderProcessingContext.availableTextures[baseName];
      this._currentMaterialContext.setTexture(name157, texture);
      if (availableTexture && availableTexture.autoBindSampler) {
        const samplerName = baseName + `Sampler`;
        this._currentMaterialContext.setSampler(samplerName, texture);
      }
    }
  }
  createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) {
    const callback = (loadData) => {
      if (!loadData) {
        if (onLoad) {
          onLoad(null);
        }
        return;
      }
      const texture = loadData.texture;
      if (!createPolynomials) {
        texture._sphericalPolynomial = new SphericalPolynomial;
      } else if (loadData.info.sphericalPolynomial) {
        texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
      }
      texture._source = 9;
      if (onLoad) {
        onLoad(texture);
      }
    };
    return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  }
  setTexture(channel, unused, texture, name157) {
    this._setTexture(channel, texture, false, false, name157, name157);
  }
  setTextureArray(channel, unused, textures, name157) {
    for (let index = 0;index < textures.length; index++) {
      this._setTexture(-1, textures[index], true, false, name157 + index.toString(), name157);
    }
  }
  _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false, name157 = "", baseName) {
    baseName = baseName ?? name157;
    if (this._currentEffect) {
      if (!texture) {
        this._currentMaterialContext.setTexture(name157, null);
        return false;
      }
      if (texture.video) {
        texture.update();
      } else if (texture.delayLoadState === 4) {
        texture.delayLoad();
        return false;
      }
      let internalTexture = null;
      if (depthStencilTexture) {
        internalTexture = texture.depthStencilTexture;
      } else if (texture.isReady()) {
        internalTexture = texture.getInternalTexture();
      } else if (texture.isCube) {
        internalTexture = this.emptyCubeTexture;
      } else if (texture.is3D) {
        internalTexture = this.emptyTexture3D;
      } else if (texture.is2DArray) {
        internalTexture = this.emptyTexture2DArray;
      } else {
        internalTexture = this.emptyTexture;
      }
      if (internalTexture && !internalTexture.isMultiview) {
        if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
          internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
          const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 ? 1 : 0;
          texture.wrapU = textureWrapMode;
          texture.wrapV = textureWrapMode;
        }
        internalTexture._cachedWrapU = texture.wrapU;
        internalTexture._cachedWrapV = texture.wrapV;
        if (internalTexture.is3D) {
          internalTexture._cachedWrapR = texture.wrapR;
        }
        this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel);
      }
      this._setInternalTexture(name157, internalTexture, baseName);
    } else {
      if (this.dbgVerboseLogsForFirstFrames) {
        if (this._count === undefined) {
          this._count = 0;
        }
        if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
          Logger.Log(["frame #" + this._count + " - _setTexture called with a null _currentEffect! texture=", texture]);
        }
      }
    }
    return true;
  }
  _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) {
    if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
      internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy);
    }
  }
  _bindTexture(channel, texture, name157) {
    if (channel === undefined) {
      return;
    }
    this._setInternalTexture(name157, texture);
  }
  generateMipmaps(texture) {
    this._generateMipmaps(texture);
  }
  updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {
    let gpuTextureWrapper = texture._hardwareTexture;
    if (!texture._hardwareTexture?.underlyingResource) {
      gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
    }
    const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
    this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset);
    if (generateMipMaps) {
      this._generateMipmaps(texture);
    }
  }
  _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, imageData, faceIndex = 0, lod = 0) {
    let gpuTextureWrapper = texture._hardwareTexture;
    if (!texture._hardwareTexture?.underlyingResource) {
      texture.format = internalFormat;
      gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
    }
    const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
    this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0);
  }
  _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) {
    const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
    const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
    const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
    const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
    let gpuTextureWrapper = texture._hardwareTexture;
    if (!texture._hardwareTexture?.underlyingResource) {
      gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
    }
    const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
    this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);
  }
  _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {
    this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  }
  _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {
    let gpuTextureWrapper = texture._hardwareTexture;
    if (!texture._hardwareTexture?.underlyingResource) {
      gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
    }
    if (image instanceof HTMLImageElement) {
      throw "WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";
    }
    const bitmap = image;
    const width = Math.ceil(texture.width / (1 << lod));
    const height = Math.ceil(texture.height / (1 << lod));
    this._textureHelper.updateTexture(bitmap, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);
  }
  readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true, data = null) {
    const renderPassWrapper = this._getCurrentRenderPassWrapper();
    const hardwareTexture = renderPassWrapper.colorAttachmentGPUTextures[0];
    if (!hardwareTexture) {
      return Promise.resolve(new Uint8Array(0));
    }
    const gpuTexture = hardwareTexture.underlyingResource;
    const gpuTextureFormat = hardwareTexture.format;
    if (!gpuTexture) {
      return Promise.resolve(new Uint8Array(0));
    }
    if (flushRenderer) {
      this.flushFramebuffer();
    }
    return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat, undefined, undefined, data);
  }
  _measureFps() {
    this._performanceMonitor.sampleFrame();
    this._fps = this._performanceMonitor.averageFPS;
    this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  }
  get performanceMonitor() {
    return this._performanceMonitor;
  }
  beginFrame() {
    this._measureFps();
    super.beginFrame();
  }
  endFrame() {
    this._endCurrentRenderPass();
    this._snapshotRendering.endFrame();
    this._timestampQuery.endFrame(this._renderEncoder);
    this._timestampIndex = 0;
    this.flushFramebuffer();
    this._textureHelper.destroyDeferredTextures();
    this._bufferManager.destroyDeferredBuffers();
    if (this._features._collectUbosUpdatedInFrame) {
      if (this.dbgVerboseLogsForFirstFrames) {
        if (this._count === undefined) {
          this._count = 0;
        }
        if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
          const list = [];
          for (const name157 in UniformBuffer._UpdatedUbosInFrame) {
            list.push(name157 + ":" + UniformBuffer._UpdatedUbosInFrame[name157]);
          }
          Logger.Log(["frame #" + this._count + " - updated ubos -", list.join(", ")]);
        }
      }
      UniformBuffer._UpdatedUbosInFrame = {};
    }
    this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects;
    this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper;
    this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode;
    this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode;
    this._counters.numEnableEffects = 0;
    this._counters.numEnableDrawWrapper = 0;
    this._counters.numBundleCreationNonCompatMode = 0;
    this._counters.numBundleReuseNonCompatMode = 0;
    this._cacheRenderPipeline.endFrame();
    this._cacheBindGroups.endFrame();
    this._pendingDebugCommands.length = 0;
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log(["%c frame #" + this._count + " - end", "background: #ffff00"]);
      }
      if (this._count < this.dbgVerboseLogsNumFrames) {
        this._count++;
        if (this._count !== this.dbgVerboseLogsNumFrames) {
          Logger.Log(["%c frame #" + this._count + " - begin", "background: #ffff00"]);
        }
      }
    }
    super.endFrame();
  }
  extractDriverInfo() {
    return "";
  }
  flushFramebuffer() {
    this._endCurrentRenderPass();
    this._commandBuffers[0] = this._uploadEncoder.finish();
    this._commandBuffers[1] = this._renderEncoder.finish();
    this._device.queue.submit(this._commandBuffers);
    this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
    this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
    this._timestampQuery.startFrame(this._uploadEncoder);
    this._textureHelper.setCommandEncoder(this._uploadEncoder);
    this._bundleList.reset();
  }
  _currentFrameBufferIsDefaultFrameBuffer() {
    return this._currentPassIsMainPass();
  }
  _startRenderTargetRenderPass(renderTargetWrapper, setClearStates, clearColor, clearDepth, clearStencil) {
    this._endCurrentRenderPass();
    const rtWrapper = renderTargetWrapper;
    const depthStencilTexture = rtWrapper._depthStencilTexture;
    const gpuDepthStencilWrapper = depthStencilTexture?._hardwareTexture;
    const gpuDepthStencilTexture = gpuDepthStencilWrapper?.underlyingResource;
    const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper?.getMSAATexture(0);
    const depthTextureView = gpuDepthStencilTexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);
    const depthMSAATextureView = gpuDepthStencilMSAATexture?.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);
    const depthTextureHasStencil = gpuDepthStencilWrapper ? WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format) : false;
    const colorAttachments = [];
    if (this.useReverseDepthBuffer) {
      this.setDepthFunctionToGreaterOrEqual();
    }
    const clearColorForIntegerRT = tempColor4;
    if (clearColor) {
      clearColorForIntegerRT.r = clearColor.r * 255;
      clearColorForIntegerRT.g = clearColor.g * 255;
      clearColorForIntegerRT.b = clearColor.b * 255;
      clearColorForIntegerRT.a = clearColor.a * 255;
    }
    const mustClearColor = setClearStates && clearColor;
    const mustClearDepth = setClearStates && clearDepth;
    const mustClearStencil = setClearStates && clearStencil;
    if (rtWrapper._attachments && rtWrapper.isMulti) {
      if (!this._mrtAttachments || this._mrtAttachments.length === 0) {
        this._mrtAttachments = rtWrapper._defaultAttachments;
      }
      for (let i = 0;i < this._mrtAttachments.length; ++i) {
        const index = this._mrtAttachments[i];
        const mrtTexture = rtWrapper.textures[i];
        const gpuMRTWrapper = mrtTexture?._hardwareTexture;
        const gpuMRTTexture = gpuMRTWrapper?.underlyingResource;
        if (gpuMRTWrapper && gpuMRTTexture) {
          const baseArrayLayer = rtWrapper.getBaseArrayLayer(i);
          const gpuMSAATexture = gpuMRTWrapper.getMSAATexture(baseArrayLayer);
          const viewDescriptor = {
            ...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,
            dimension: mrtTexture.is3D ? "3d" : "2d",
            format: gpuMRTWrapper.format,
            baseArrayLayer
          };
          const msaaViewDescriptor = {
            ...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,
            dimension: mrtTexture.is3D ? "3d" : "2d",
            format: gpuMRTWrapper.format,
            baseArrayLayer: 0
          };
          const isRTInteger = mrtTexture.type === 7 || mrtTexture.type === 5;
          const colorTextureView = gpuMRTTexture.createView(viewDescriptor);
          const colorMSAATextureView = gpuMSAATexture?.createView(msaaViewDescriptor);
          colorAttachments.push({
            view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,
            resolveTarget: gpuMSAATexture ? colorTextureView : undefined,
            depthSlice: mrtTexture.is3D ? rtWrapper.layerIndices?.[i] ?? 0 : undefined,
            clearValue: index !== 0 && mustClearColor ? isRTInteger ? clearColorForIntegerRT : clearColor : undefined,
            loadOp: index !== 0 && mustClearColor ? "clear" : "load",
            storeOp: "store"
          });
        }
      }
      this._cacheRenderPipeline.setMRT(rtWrapper.textures, this._mrtAttachments.length);
      this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);
    } else {
      const internalTexture = rtWrapper.texture;
      if (internalTexture) {
        const gpuWrapper = internalTexture._hardwareTexture;
        const gpuTexture = gpuWrapper.underlyingResource;
        let depthSlice = undefined;
        if (rtWrapper.is3D) {
          depthSlice = this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer;
          this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer = 0;
        }
        const gpuMSAATexture = gpuWrapper.getMSAATexture(0);
        const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);
        const colorMSAATextureView = gpuMSAATexture?.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);
        const isRTInteger = internalTexture.type === 7 || internalTexture.type === 5;
        colorAttachments.push({
          view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,
          resolveTarget: gpuMSAATexture ? colorTextureView : undefined,
          depthSlice,
          clearValue: mustClearColor ? isRTInteger ? clearColorForIntegerRT : clearColor : undefined,
          loadOp: mustClearColor ? "clear" : "load",
          storeOp: "store"
        });
      } else {
        colorAttachments.push(null);
      }
    }
    this._debugPushGroup?.("render target pass" + (renderTargetWrapper.label ? " (" + renderTargetWrapper.label + ")" : ""), 0);
    this._rttRenderPassWrapper.renderPassDescriptor = {
      label: (renderTargetWrapper.label ?? "RTT") + " - RenderPass",
      colorAttachments,
      depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture ? {
        view: depthMSAATextureView ? depthMSAATextureView : depthTextureView,
        depthClearValue: mustClearDepth ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : undefined,
        depthLoadOp: mustClearDepth ? "clear" : "load",
        depthStoreOp: "store",
        stencilClearValue: rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? this._clearStencilValue : undefined,
        stencilLoadOp: !depthTextureHasStencil ? undefined : rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? "clear" : "load",
        stencilStoreOp: !depthTextureHasStencil ? undefined : "store"
      } : undefined,
      occlusionQuerySet: this._occlusionQuery?.hasQueries ? this._occlusionQuery.querySet : undefined
    };
    this._timestampQuery.startPass(this._rttRenderPassWrapper.renderPassDescriptor, this._timestampIndex);
    this._currentRenderPass = this._renderEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor);
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        const internalTexture = rtWrapper.texture;
        Logger.Log([
          "frame #" + this._count + " - render target begin pass - rtt name=" + renderTargetWrapper.label + ", internalTexture.uniqueId=" + internalTexture.uniqueId + ", width=" + internalTexture.width + ", height=" + internalTexture.height + ", setClearStates=" + setClearStates,
          "renderPassDescriptor=",
          this._rttRenderPassWrapper.renderPassDescriptor
        ]);
      }
    }
    this._debugFlushPendingCommands?.();
    this._resetRenderPassStates();
    if (!gpuDepthStencilWrapper || !WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format)) {
      this._stencilStateComposer.enabled = false;
    }
  }
  _startMainRenderPass(setClearStates, clearColor, clearDepth, clearStencil) {
    this._endCurrentRenderPass();
    if (this.useReverseDepthBuffer) {
      this.setDepthFunctionToGreaterOrEqual();
    }
    const mustClearColor = setClearStates && clearColor;
    const mustClearDepth = setClearStates && clearDepth;
    const mustClearStencil = setClearStates && clearStencil;
    this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue = mustClearColor ? clearColor : undefined;
    this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp = mustClearColor ? "clear" : "load";
    this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue = mustClearDepth ? this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue : undefined;
    this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp = mustClearDepth ? "clear" : "load";
    this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue = mustClearStencil ? this._clearStencilValue : undefined;
    this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp = !this.isStencilEnable ? undefined : mustClearStencil ? "clear" : "load";
    this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = this._occlusionQuery?.hasQueries ? this._occlusionQuery.querySet : undefined;
    const swapChainTexture = this._context.getCurrentTexture();
    this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(swapChainTexture);
    if (this._options.antialias) {
      viewDescriptorSwapChainAntialiasing.format = swapChainTexture.format;
      this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget = swapChainTexture.createView(viewDescriptorSwapChainAntialiasing);
    } else {
      viewDescriptorSwapChain.format = swapChainTexture.format;
      this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view = swapChainTexture.createView(viewDescriptorSwapChain);
    }
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log([
          "frame #" + this._count + " - main begin pass - texture width=" + this._mainTextureExtends.width,
          " height=" + this._mainTextureExtends.height + ", setClearStates=" + setClearStates,
          "renderPassDescriptor=",
          this._mainRenderPassWrapper.renderPassDescriptor
        ]);
      }
    }
    this._debugPushGroup?.("main pass", 0);
    this._timestampQuery.startPass(this._mainRenderPassWrapper.renderPassDescriptor, this._timestampIndex);
    this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor);
    this._setDepthTextureFormat(this._mainRenderPassWrapper);
    this._setColorFormat(this._mainRenderPassWrapper);
    this._debugFlushPendingCommands?.();
    this._resetRenderPassStates();
    if (!this._isStencilEnable) {
      this._stencilStateComposer.enabled = false;
    }
  }
  bindFramebuffer(texture, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) {
    const hardwareTexture = texture.texture?._hardwareTexture;
    if (this._currentRenderTarget) {
      this.unBindFramebuffer(this._currentRenderTarget);
    } else {
      this._endCurrentRenderPass();
    }
    this._currentRenderTarget = texture;
    const depthStencilTexture = this._currentRenderTarget._depthStencilTexture;
    this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture;
    this._rttRenderPassWrapper.depthTextureFormat = depthStencilTexture ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, depthStencilTexture.format) : undefined;
    this._setDepthTextureFormat(this._rttRenderPassWrapper);
    this._setColorFormat(this._rttRenderPassWrapper);
    this._rttRenderPassWrapper.colorAttachmentViewDescriptor = {
      format: this._colorFormat,
      dimension: texture.is3D ? "3d" : "2d",
      mipLevelCount: 1,
      baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,
      baseMipLevel: lodLevel,
      arrayLayerCount: 1,
      aspect: "all"
    };
    this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {
      format: this._depthTextureFormat,
      dimension: depthStencilTexture && depthStencilTexture.is3D ? "3d" : "2d",
      mipLevelCount: 1,
      baseArrayLayer: depthStencilTexture ? depthStencilTexture.isCube ? layer * 6 + faceIndex : layer : 0,
      baseMipLevel: 0,
      arrayLayerCount: 1,
      aspect: "all"
    };
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log([
          "frame #" + this._count + " - bindFramebuffer - rtt name=" + texture.label + ", internalTexture.uniqueId=" + texture.texture?.uniqueId + ", face=" + faceIndex + ", lodLevel=" + lodLevel + ", layer=" + layer,
          "colorAttachmentViewDescriptor=",
          this._rttRenderPassWrapper.colorAttachmentViewDescriptor,
          "depthAttachmentViewDescriptor=",
          this._rttRenderPassWrapper.depthAttachmentViewDescriptor
        ]);
      }
    }
    if (this._cachedViewport && !forceFullscreenViewport) {
      this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
    } else {
      if (!requiredWidth) {
        requiredWidth = texture.width;
        if (lodLevel) {
          requiredWidth = requiredWidth / Math.pow(2, lodLevel);
        }
      }
      if (!requiredHeight) {
        requiredHeight = texture.height;
        if (lodLevel) {
          requiredHeight = requiredHeight / Math.pow(2, lodLevel);
        }
      }
      this._viewport(0, 0, requiredWidth, requiredHeight);
    }
    this.wipeCaches();
  }
  unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {
    const saveCRT = this._currentRenderTarget;
    this._currentRenderTarget = null;
    if (onBeforeUnbind) {
      onBeforeUnbind();
    }
    this._currentRenderTarget = saveCRT;
    this._endCurrentRenderPass();
    if (!disableGenerateMipMaps) {
      if (texture.isMulti) {
        this.generateMipMapsMultiFramebuffer(texture);
      } else {
        this.generateMipMapsFramebuffer(texture);
      }
    }
    this._currentRenderTarget = null;
    if (this.dbgVerboseLogsForFirstFrames) {
      if (this._count === undefined) {
        this._count = 0;
      }
      if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {
        Logger.Log("frame #" + this._count + " - unBindFramebuffer - rtt name=" + texture.label + ", internalTexture.uniqueId=", texture.texture?.uniqueId);
      }
    }
    this._mrtAttachments = [];
    this._cacheRenderPipeline.setMRT([]);
    this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);
  }
  generateMipMapsFramebuffer(texture) {
    if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) {
      this._generateMipmaps(texture.texture);
    }
  }
  resolveFramebuffer(_texture) {
    throw new Error("resolveFramebuffer is not yet implemented in WebGPU!");
  }
  restoreDefaultFramebuffer() {
    if (this._currentRenderTarget) {
      this.unBindFramebuffer(this._currentRenderTarget);
    } else if (!this._currentRenderPass) {
      this._startMainRenderPass(false);
    }
    if (this._cachedViewport) {
      this.setViewport(this._cachedViewport);
    }
    this.wipeCaches();
  }
  _setColorFormat(wrapper) {
    const format = wrapper.colorAttachmentGPUTextures[0]?.format ?? null;
    this._cacheRenderPipeline.setColorFormat(format);
    if (this._colorFormat === format) {
      return;
    }
    this._colorFormat = format;
  }
  _setDepthTextureFormat(wrapper) {
    this._cacheRenderPipeline.setDepthStencilFormat(wrapper.depthTextureFormat);
    if (this._depthTextureFormat === wrapper.depthTextureFormat) {
      return;
    }
    this._depthTextureFormat = wrapper.depthTextureFormat;
  }
  setDitheringState() {}
  setRasterizerState() {}
  _executeWhenRenderingStateIsCompiled(pipelineContext, action2) {
    action2();
  }
  bindSamplers() {}
  _getUnpackAlignement() {
    return 1;
  }
  _bindTextureDirectly() {
    return false;
  }
  setStateCullFaceType(cullBackFaces, force = false) {
    const cullFace = this.cullBackFaces ?? cullBackFaces ?? true ? 1 : 2;
    if (this._depthCullingState.cullFace !== cullFace || force) {
      this._depthCullingState.cullFace = cullFace;
    }
  }
  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._currentRenderTarget ? 1 : 2 : this._currentRenderTarget ? 2 : 1;
    if (this._depthCullingState.frontFace !== frontFace || force) {
      this._depthCullingState.frontFace = frontFace;
    }
    this._stencilStateComposer.stencilMaterial = stencil;
  }
  _applyRenderPassChanges(bundleList) {
    const mustUpdateStencilRef = !this._stencilStateComposer.enabled ? false : this._mustUpdateStencilRef();
    const mustUpdateBlendColor = !this._alphaState.alphaBlend ? false : this._mustUpdateBlendColor();
    if (this._mustUpdateViewport()) {
      this._applyViewport(bundleList);
    }
    if (this._mustUpdateScissor()) {
      this._applyScissor(bundleList);
    }
    if (mustUpdateStencilRef) {
      this._applyStencilRef(bundleList);
    }
    if (mustUpdateBlendColor) {
      this._applyBlendColor(bundleList);
    }
  }
  _draw(drawType, fillMode, start, count, instancesCount) {
    const renderPass = this._getCurrentRenderPass();
    const bundleList = this._bundleList;
    this.applyStates();
    const webgpuPipelineContext = this._currentEffect._pipelineContext;
    this.bindUniformBufferBase(this._currentRenderTarget ? this._ubInvertY : this._ubDontInvertY, 0, WebGPUShaderProcessor.InternalsUBOName);
    if (webgpuPipelineContext.uniformBuffer) {
      webgpuPipelineContext.uniformBuffer.update();
      this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName);
    }
    if (this._snapshotRendering.play) {
      this._reportDrawCall();
      return;
    }
    if (!this.compatibilityMode && (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation)) {
      this._currentDrawContext.fastBundle = undefined;
    }
    const useFastPath = !this.compatibilityMode && this._currentDrawContext.fastBundle;
    let renderPass2 = renderPass;
    if (useFastPath || this._snapshotRendering.record) {
      this._applyRenderPassChanges(bundleList);
      if (!this._snapshotRendering.record) {
        this._counters.numBundleReuseNonCompatMode++;
        if (this._currentDrawContext.indirectDrawBuffer) {
          this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);
        }
        bundleList.addBundle(this._currentDrawContext.fastBundle);
        this._reportDrawCall();
        return;
      }
      renderPass2 = bundleList.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount);
      bundleList.numDrawCalls++;
    }
    let textureState = 0;
    if (this._currentMaterialContext.hasFloatOrDepthTextures) {
      let bitVal = 1;
      for (let i = 0;i < webgpuPipelineContext.shaderProcessingContext.textureNames.length; ++i) {
        const textureName = webgpuPipelineContext.shaderProcessingContext.textureNames[i];
        const texture = this._currentMaterialContext.textures[textureName]?.texture;
        const textureIsDepth = texture && texture.format >= 13 && texture.format <= 18;
        if (texture?.type === 1 && !this._caps.textureFloatLinearFiltering || textureIsDepth) {
          textureState |= bitVal;
        }
        bitVal = bitVal << 1;
      }
    }
    this._currentMaterialContext.textureState = textureState;
    const pipeline = this._cacheRenderPipeline.getRenderPipeline(fillMode, this._currentEffect, this.currentSampleCount, textureState);
    const bindGroups = this._cacheBindGroups.getBindGroups(webgpuPipelineContext, this._currentDrawContext, this._currentMaterialContext);
    if (!this._snapshotRendering.record) {
      this._applyRenderPassChanges(!this.compatibilityMode ? bundleList : null);
      if (!this.compatibilityMode) {
        this._counters.numBundleCreationNonCompatMode++;
        renderPass2 = this._device.createRenderBundleEncoder({
          colorFormats: this._cacheRenderPipeline.colorFormats,
          depthStencilFormat: this._depthTextureFormat,
          sampleCount: WebGPUTextureHelper.GetSample(this.currentSampleCount)
        });
      }
    }
    renderPass2.setPipeline(pipeline);
    if (this._currentIndexBuffer) {
      renderPass2.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? "uint32" : "uint16", 0);
    }
    const vertexBuffers = this._cacheRenderPipeline.vertexBuffers;
    for (let index = 0;index < vertexBuffers.length; index++) {
      const vertexBuffer = vertexBuffers[index];
      const buffer2 = vertexBuffer.effectiveBuffer;
      if (buffer2) {
        renderPass2.setVertexBuffer(index, buffer2.underlyingResource, vertexBuffer._validOffsetRange ? 0 : vertexBuffer.byteOffset);
      }
    }
    for (let i = 0;i < bindGroups.length; i++) {
      renderPass2.setBindGroup(i, bindGroups[i]);
    }
    const nonCompatMode = !this.compatibilityMode && !this._snapshotRendering.record;
    if (nonCompatMode && this._currentDrawContext.indirectDrawBuffer) {
      this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);
      if (drawType === 0) {
        renderPass2.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0);
      } else {
        renderPass2.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0);
      }
    } else if (drawType === 0) {
      renderPass2.drawIndexed(count, instancesCount || 1, start, 0, 0);
    } else {
      renderPass2.draw(count, instancesCount || 1, start, 0);
    }
    if (nonCompatMode) {
      this._currentDrawContext.fastBundle = renderPass2.finish();
      bundleList.addBundle(this._currentDrawContext.fastBundle);
    }
    this._reportDrawCall();
  }
  drawElementsType(fillMode, indexStart, indexCount, instancesCount = 1) {
    this._draw(0, fillMode, indexStart, indexCount, instancesCount);
  }
  drawArraysType(fillMode, verticesStart, verticesCount, instancesCount = 1) {
    this._currentIndexBuffer = null;
    this._draw(1, fillMode, verticesStart, verticesCount, instancesCount);
  }
  dispose() {
    this._isDisposed = true;
    this.hideLoadingUI();
    this._timestampQuery.dispose();
    this._mainTexture?.destroy();
    this._depthTexture?.destroy();
    this._textureHelper.destroyDeferredTextures();
    this._bufferManager.destroyDeferredBuffers();
    this._device.destroy();
    _CommonDispose(this, this._renderingCanvas);
    super.dispose();
  }
  getRenderWidth(useScreen = false) {
    if (!useScreen && this._currentRenderTarget) {
      return this._currentRenderTarget.width;
    }
    return this._renderingCanvas?.width ?? 0;
  }
  getRenderHeight(useScreen = false) {
    if (!useScreen && this._currentRenderTarget) {
      return this._currentRenderTarget.height;
    }
    return this._renderingCanvas?.height ?? 0;
  }
  getError() {
    return 0;
  }
  createExternalTexture(video) {
    const texture = new WebGPUExternalTexture(video);
    return texture;
  }
  setExternalTexture(name157, texture) {
    if (!texture) {
      this._currentMaterialContext.setTexture(name157, null);
      return;
    }
    this._setInternalTexture(name157, texture);
  }
  setTextureSampler(name157, sampler) {
    this._currentMaterialContext?.setSampler(name157, sampler);
  }
  createStorageBuffer(data, creationFlags, label) {
    return this._createBuffer(data, creationFlags | 32, label);
  }
  updateStorageBuffer(buffer2, data, byteOffset, byteLength) {
    const dataBuffer2 = buffer2;
    if (byteOffset === undefined) {
      byteOffset = 0;
    }
    let view;
    if (byteLength === undefined) {
      if (data instanceof Array) {
        view = new Float32Array(data);
      } else if (data instanceof ArrayBuffer) {
        view = new Uint8Array(data);
      } else {
        view = data;
      }
      byteLength = view.byteLength;
    } else {
      if (data instanceof Array) {
        view = new Float32Array(data);
      } else if (data instanceof ArrayBuffer) {
        view = new Uint8Array(data);
      } else {
        view = data;
      }
    }
    this._bufferManager.setSubData(dataBuffer2, byteOffset, view, 0, byteLength);
  }
  _readFromGPUBuffer(gpuBuffer, size, buffer2, noDelay) {
    return new Promise((resolve3, reject) => {
      const readFromBuffer = () => {
        gpuBuffer.mapAsync(1, 0, size).then(() => {
          const copyArrayBuffer = gpuBuffer.getMappedRange(0, size);
          let data = buffer2;
          if (data === undefined) {
            data = new Uint8Array(size);
            data.set(new Uint8Array(copyArrayBuffer));
          } else {
            const ctor = data.constructor;
            data = new ctor(data.buffer);
            data.set(new ctor(copyArrayBuffer));
          }
          gpuBuffer.unmap();
          this._bufferManager.releaseBuffer(gpuBuffer);
          resolve3(data);
        }, (reason) => {
          if (this.isDisposed) {
            resolve3(new Uint8Array);
          } else {
            reject(reason);
          }
        });
      };
      if (noDelay) {
        this.flushFramebuffer();
        readFromBuffer();
      } else {
        this.onEndFrameObservable.addOnce(() => {
          readFromBuffer();
        });
      }
    });
  }
  readFromStorageBuffer(storageBuffer2, offset, size, buffer2, noDelay) {
    size = size || storageBuffer2.capacity;
    const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempReadFromStorageBuffer");
    this._renderEncoder.copyBufferToBuffer(storageBuffer2.underlyingResource, offset ?? 0, gpuBuffer, 0, size);
    return this._readFromGPUBuffer(gpuBuffer, size, buffer2, noDelay);
  }
  readFromMultipleStorageBuffers(storageBuffers, offset, size, buffer2, noDelay) {
    size = size || storageBuffers[0].capacity;
    const gpuBuffer = this._bufferManager.createRawBuffer(size * storageBuffers.length, BufferUsage.MapRead | BufferUsage.CopyDst, undefined, "TempReadFromMultipleStorageBuffers");
    for (let i = 0;i < storageBuffers.length; i++) {
      this._renderEncoder.copyBufferToBuffer(storageBuffers[i].underlyingResource, offset ?? 0, gpuBuffer, i * size, size);
    }
    return this._readFromGPUBuffer(gpuBuffer, size * storageBuffers.length, buffer2, noDelay);
  }
  setStorageBuffer(name157, buffer2) {
    this._currentDrawContext?.setBuffer(name157, buffer2?.getBuffer() ?? null);
  }
}
WebGPUEngine._GlslangDefaultOptions = {
  jsPath: `${Tools._DefaultCdnUrl}/glslang/glslang.js`,
  wasmPath: `${Tools._DefaultCdnUrl}/glslang/glslang.wasm`
};
WebGPUEngine._InstanceId = 0;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputeContext.js
init_logger();

class WebGPUComputeContext {
  getBindGroups(bindings, computePipeline, bindingsMapping) {
    if (!bindingsMapping) {
      throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");
    }
    if (this._bindGroups.length === 0) {
      const bindGroupEntriesExist = this._bindGroupEntries.length > 0;
      for (const key in bindings) {
        const binding = bindings[key], location2 = bindingsMapping[key], group = location2.group, index = location2.binding, type = binding.type, object = binding.object;
        let indexInGroupEntries = binding.indexInGroupEntries;
        let entries = this._bindGroupEntries[group];
        if (!entries) {
          entries = this._bindGroupEntries[group] = [];
        }
        switch (type) {
          case 5: {
            const sampler = object;
            if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {
              entries[indexInGroupEntries].resource = this._cacheSampler.getSampler(sampler);
            } else {
              binding.indexInGroupEntries = entries.length;
              entries.push({
                binding: index,
                resource: this._cacheSampler.getSampler(sampler)
              });
            }
            break;
          }
          case 0:
          case 4: {
            const texture = object;
            const hardwareTexture = texture._texture._hardwareTexture;
            if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {
              if (type === 0) {
                entries[indexInGroupEntries++].resource = this._cacheSampler.getSampler(texture._texture);
              }
              entries[indexInGroupEntries].resource = hardwareTexture.view;
            } else {
              binding.indexInGroupEntries = entries.length;
              if (type === 0) {
                entries.push({
                  binding: index - 1,
                  resource: this._cacheSampler.getSampler(texture._texture)
                });
              }
              entries.push({
                binding: index,
                resource: hardwareTexture.view
              });
            }
            break;
          }
          case 1: {
            const texture = object;
            const hardwareTexture = texture._texture._hardwareTexture;
            if ((hardwareTexture.textureAdditionalUsages & 8) === 0) {
              Logger.Error(`computeDispatch: The texture (name=${texture.name}, uniqueId=${texture.uniqueId}) is not a storage texture!`, 50);
            }
            if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {
              entries[indexInGroupEntries].resource = hardwareTexture.viewForWriting;
            } else {
              binding.indexInGroupEntries = entries.length;
              entries.push({
                binding: index,
                resource: hardwareTexture.viewForWriting
              });
            }
            break;
          }
          case 6: {
            const texture = object;
            const externalTexture = texture.underlyingResource;
            if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {
              entries[indexInGroupEntries].resource = this._device.importExternalTexture({ source: externalTexture });
            } else {
              binding.indexInGroupEntries = entries.length;
              entries.push({
                binding: index,
                resource: this._device.importExternalTexture({ source: externalTexture })
              });
            }
            break;
          }
          case 2:
          case 3:
          case 7: {
            const dataBuffer2 = type === 7 ? object : type === 2 ? object.getBuffer() : object.getBuffer();
            const webgpuBuffer = dataBuffer2.underlyingResource;
            if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {
              entries[indexInGroupEntries].resource.buffer = webgpuBuffer;
              entries[indexInGroupEntries].resource.size = dataBuffer2.capacity;
            } else {
              binding.indexInGroupEntries = entries.length;
              entries.push({
                binding: index,
                resource: {
                  buffer: webgpuBuffer,
                  offset: 0,
                  size: dataBuffer2.capacity
                }
              });
            }
            break;
          }
        }
      }
      for (let i = 0;i < this._bindGroupEntries.length; ++i) {
        const entries = this._bindGroupEntries[i];
        if (!entries) {
          this._bindGroups[i] = undefined;
          continue;
        }
        this._bindGroups[i] = this._device.createBindGroup({
          layout: computePipeline.getBindGroupLayout(i),
          entries
        });
      }
      this._bindGroups.length = this._bindGroupEntries.length;
    }
    return this._bindGroups;
  }
  constructor(device, cacheSampler) {
    this._device = device;
    this._cacheSampler = cacheSampler;
    this.uniqueId = WebGPUComputeContext._Counter++;
    this._bindGroupEntries = [];
    this.clear();
  }
  clear() {
    this._bindGroups = [];
  }
}
WebGPUComputeContext._Counter = 0;

// node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputePipelineContext.js
class WebGPUComputePipelineContext {
  get isAsync() {
    return false;
  }
  get isReady() {
    if (this.isAsync) {
      return false;
    }
    return false;
  }
  constructor(engine) {
    this._name = "unnamed";
    this.engine = engine;
  }
  _getComputeShaderCode() {
    return this.sources?.compute;
  }
  dispose() {}
}

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.computeShader.js
var computePassDescriptor = {};
WebGPUEngine.prototype.createComputeContext = function() {
  return new WebGPUComputeContext(this._device, this._cacheSampler);
};
WebGPUEngine.prototype.createComputeEffect = function(baseName, options) {
  const compute = typeof baseName === "string" ? baseName : baseName.computeToken || baseName.computeSource || baseName.computeElement || baseName.compute;
  const name157 = compute + "@" + options.defines;
  if (this._compiledComputeEffects[name157]) {
    const compiledEffect = this._compiledComputeEffects[name157];
    if (options.onCompiled && compiledEffect.isReady()) {
      options.onCompiled(compiledEffect);
    }
    return compiledEffect;
  }
  const effect = new ComputeEffect(baseName, options, this, name157);
  this._compiledComputeEffects[name157] = effect;
  return effect;
};
WebGPUEngine.prototype.createComputePipelineContext = function() {
  return new WebGPUComputePipelineContext(this);
};
WebGPUEngine.prototype.areAllComputeEffectsReady = function() {
  for (const key in this._compiledComputeEffects) {
    const effect = this._compiledComputeEffects[key];
    if (!effect.isReady()) {
      return false;
    }
  }
  return true;
};
WebGPUEngine.prototype.computeDispatch = function(effect, context, bindings, x, y = 1, z = 1, bindingsMapping, gpuPerfCounter) {
  this._computeDispatch(effect, context, bindings, x, y, z, undefined, undefined, bindingsMapping, gpuPerfCounter);
};
WebGPUEngine.prototype.computeDispatchIndirect = function(effect, context, bindings, buffer2, offset = 0, bindingsMapping, gpuPerfCounter) {
  this._computeDispatch(effect, context, bindings, undefined, undefined, undefined, buffer2, offset, bindingsMapping, gpuPerfCounter);
};
WebGPUEngine.prototype._computeDispatch = function(effect, context, bindings, x, y, z, buffer2, offset, bindingsMapping, gpuPerfCounter) {
  this._endCurrentRenderPass();
  const contextPipeline = effect._pipelineContext;
  const computeContext = context;
  if (!contextPipeline.computePipeline) {
    contextPipeline.computePipeline = this._device.createComputePipeline({
      layout: "auto",
      compute: contextPipeline.stage
    });
  }
  if (gpuPerfCounter) {
    this._timestampQuery.startPass(computePassDescriptor, this._timestampIndex);
  }
  const computePass = this._renderEncoder.beginComputePass(computePassDescriptor);
  computePass.setPipeline(contextPipeline.computePipeline);
  const bindGroups = computeContext.getBindGroups(bindings, contextPipeline.computePipeline, bindingsMapping);
  for (let i = 0;i < bindGroups.length; ++i) {
    const bindGroup = bindGroups[i];
    if (!bindGroup) {
      continue;
    }
    computePass.setBindGroup(i, bindGroup);
  }
  if (buffer2 !== undefined) {
    computePass.dispatchWorkgroupsIndirect(buffer2.underlyingResource, offset);
  } else {
    if (x + y + z > 0) {
      computePass.dispatchWorkgroups(x, y, z);
    }
  }
  computePass.end();
  if (gpuPerfCounter) {
    this._timestampQuery.endPass(this._timestampIndex, gpuPerfCounter);
    this._timestampIndex += 2;
  }
};
WebGPUEngine.prototype.releaseComputeEffects = function() {
  for (const name157 in this._compiledComputeEffects) {
    const webGPUPipelineContextCompute = this._compiledComputeEffects[name157].getPipelineContext();
    this._deleteComputePipelineContext(webGPUPipelineContextCompute);
  }
  this._compiledComputeEffects = {};
};
WebGPUEngine.prototype._prepareComputePipelineContext = function(pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) {
  const webGpuContext = pipelineContext;
  if (this.dbgShowShaderCode) {
    Logger.Log(defines);
    Logger.Log(computeSourceCode);
  }
  webGpuContext.sources = {
    compute: computeSourceCode,
    rawCompute: rawComputeSourceCode
  };
  webGpuContext.stage = this._createComputePipelineStageDescriptor(computeSourceCode, defines, entryPoint);
};
WebGPUEngine.prototype._releaseComputeEffect = function(effect) {
  if (this._compiledComputeEffects[effect._key]) {
    delete this._compiledComputeEffects[effect._key];
    this._deleteComputePipelineContext(effect.getPipelineContext());
  }
};
WebGPUEngine.prototype._rebuildComputeEffects = function() {
  for (const key in this._compiledComputeEffects) {
    const effect = this._compiledComputeEffects[key];
    effect._pipelineContext = null;
    effect._wasPreviouslyReady = false;
    effect._prepareEffect();
  }
};
WebGPUEngine.prototype._executeWhenComputeStateIsCompiled = function(pipelineContext, action2) {
  pipelineContext.stage.module.getCompilationInfo().then((info) => {
    const compilationMessages = {
      numErrors: 0,
      messages: []
    };
    for (const message of info.messages) {
      if (message.type === "error") {
        compilationMessages.numErrors++;
      }
      compilationMessages.messages.push({
        type: message.type,
        text: message.message,
        line: message.lineNum,
        column: message.linePos,
        length: message.length,
        offset: message.offset
      });
    }
    action2(compilationMessages);
  });
};
WebGPUEngine.prototype._deleteComputePipelineContext = function(pipelineContext) {
  const webgpuPipelineContext = pipelineContext;
  if (webgpuPipelineContext) {
    pipelineContext.dispose();
  }
};
WebGPUEngine.prototype._createComputePipelineStageDescriptor = function(computeShader2, defines, entryPoint) {
  if (defines) {
    defines = "//" + defines.split(`
`).join(`
//`) + `
`;
  } else {
    defines = "";
  }
  return {
    module: this._device.createShaderModule({
      code: defines + computeShader2
    }),
    entryPoint
  };
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.debugging.js
WebGPUEngine.prototype._debugPushGroup = function(groupName, targetObject) {
  if (!this._options.enableGPUDebugMarkers) {
    return;
  }
  if (targetObject === 0 || targetObject === 1) {
    if (targetObject === 1) {
      if (this._currentRenderTarget) {
        this.unBindFramebuffer(this._currentRenderTarget);
      } else {
        this._endCurrentRenderPass();
      }
    }
    this._renderEncoder.pushDebugGroup(groupName);
  } else if (this._currentRenderPass) {
    this._currentRenderPass.pushDebugGroup(groupName);
    this._debugStackRenderPass.push(groupName);
  } else {
    this._pendingDebugCommands.push(["push", groupName, targetObject]);
  }
};
WebGPUEngine.prototype._debugPopGroup = function(targetObject) {
  if (!this._options.enableGPUDebugMarkers) {
    return;
  }
  if (targetObject === 0 || targetObject === 1) {
    if (targetObject === 1) {
      if (this._currentRenderTarget) {
        this.unBindFramebuffer(this._currentRenderTarget);
      } else {
        this._endCurrentRenderPass();
      }
    }
    this._renderEncoder.popDebugGroup();
  } else if (this._currentRenderPass) {
    this._currentRenderPass.popDebugGroup();
    this._debugStackRenderPass.pop();
  } else {
    this._pendingDebugCommands.push(["pop", null, targetObject]);
  }
};
WebGPUEngine.prototype._debugInsertMarker = function(text, targetObject) {
  if (!this._options.enableGPUDebugMarkers) {
    return;
  }
  if (targetObject === 0 || targetObject === 1) {
    if (targetObject === 1) {
      if (this._currentRenderTarget) {
        this.unBindFramebuffer(this._currentRenderTarget);
      } else {
        this._endCurrentRenderPass();
      }
    }
    this._renderEncoder.insertDebugMarker(text);
  } else if (this._currentRenderPass) {
    this._currentRenderPass.insertDebugMarker(text);
  } else {
    this._pendingDebugCommands.push(["insert", text, targetObject]);
  }
};
WebGPUEngine.prototype._debugFlushPendingCommands = function() {
  if (this._debugStackRenderPass.length !== 0) {
    const currentDebugStack = this._debugStackRenderPass.slice();
    this._debugStackRenderPass.length = 0;
    for (let i = 0;i < currentDebugStack.length; ++i) {
      this._debugPushGroup(currentDebugStack[i], 2);
    }
  }
  for (let i = 0;i < this._pendingDebugCommands.length; ++i) {
    const [name157, param, targetObject] = this._pendingDebugCommands[i];
    switch (name157) {
      case "push":
        this._debugPushGroup(param, targetObject);
        break;
      case "pop":
        this._debugPopGroup(targetObject);
        break;
      case "insert":
        this._debugInsertMarker(param, targetObject);
        break;
    }
  }
  this._pendingDebugCommands.length = 0;
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicTexture.js
init_internalTexture();
WebGPUEngine.prototype.createDynamicTexture = function(width, height, generateMipMaps, samplingMode) {
  const texture = new InternalTexture(this, 4);
  texture.baseWidth = width;
  texture.baseHeight = height;
  if (generateMipMaps) {
    width = this.needPOTTextures ? GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
    height = this.needPOTTextures ? GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  }
  texture.width = width;
  texture.height = height;
  texture.isReady = false;
  texture.generateMipMaps = generateMipMaps;
  texture.samplingMode = samplingMode;
  this.updateTextureSamplingMode(samplingMode, texture);
  this._internalTexturesCache.push(texture);
  if (width && height) {
    this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  }
  return texture;
};
WebGPUEngine.prototype.updateDynamicTexture = function(texture, source, invertY, premulAlpha = false, format, forceBindTexture, allowGPUOptimization) {
  if (!texture) {
    return;
  }
  const { width, height } = source;
  let gpuTextureWrapper = texture._hardwareTexture;
  if (!texture._hardwareTexture?.underlyingResource) {
    gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);
  }
  this._textureHelper.updateTexture(source, texture, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, allowGPUOptimization);
  if (texture.generateMipMaps) {
    this._generateMipmaps(texture);
  }
  texture._dynamicTextureSource = source;
  texture._premulAlpha = premulAlpha;
  texture.invertY = invertY || false;
  texture.isReady = true;
};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.multiRender.js
init_internalTexture();
init_logger();
WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {
  if (onBeforeUnbind) {
    onBeforeUnbind();
  }
  this._endCurrentRenderPass();
  if (!disableGenerateMipMaps) {
    this.generateMipMapsMultiFramebuffer(rtWrapper);
  }
  this._currentRenderTarget = null;
  this._mrtAttachments = [];
  this._cacheRenderPipeline.setMRT([]);
  this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);
};
WebGPUEngine.prototype.createMultipleRenderTarget = function(size, options, initializeBuffers) {
  let generateMipMaps = false;
  let generateDepthBuffer = true;
  let generateStencilBuffer = false;
  let generateDepthTexture = false;
  let depthTextureFormat = 15;
  let textureCount = 1;
  let samples = 1;
  const defaultType = 0;
  const defaultSamplingMode = 3;
  const defaultUseSRGBBuffer = false;
  const defaultFormat = 5;
  const defaultTarget = 3553;
  let types = [];
  let samplingModes = [];
  let useSRGBBuffers = [];
  let formats = [];
  let targets = [];
  let faceIndex = [];
  let layerIndex = [];
  let layers = [];
  let labels = [];
  let creationFlags = [];
  let dontCreateTextures = false;
  const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);
  if (options !== undefined) {
    generateMipMaps = options.generateMipMaps ?? false;
    generateDepthBuffer = options.generateDepthBuffer ?? true;
    generateStencilBuffer = options.generateStencilBuffer ?? false;
    generateDepthTexture = options.generateDepthTexture ?? false;
    textureCount = options.textureCount ?? 1;
    depthTextureFormat = options.depthTextureFormat ?? 15;
    types = options.types || types;
    samplingModes = options.samplingModes || samplingModes;
    useSRGBBuffers = options.useSRGBBuffers || useSRGBBuffers;
    formats = options.formats || formats;
    targets = options.targetTypes || targets;
    faceIndex = options.faceIndex || faceIndex;
    layerIndex = options.layerIndex || layerIndex;
    layers = options.layerCounts || layers;
    labels = options.labels || labels;
    creationFlags = options.creationFlags || creationFlags;
    samples = options.samples ?? samples;
    dontCreateTextures = options.dontCreateTextures ?? false;
  }
  const width = size.width ?? size;
  const height = size.height ?? size;
  const textures = [];
  const attachments = [];
  const defaultAttachments = [];
  rtWrapper.label = options?.label ?? "MultiRenderTargetWrapper";
  rtWrapper._generateDepthBuffer = generateDepthBuffer;
  rtWrapper._generateStencilBuffer = generateStencilBuffer;
  rtWrapper._attachments = attachments;
  rtWrapper._defaultAttachments = defaultAttachments;
  let depthStencilTexture = null;
  if ((generateDepthBuffer || generateStencilBuffer || generateDepthTexture) && !dontCreateTextures) {
    if (!generateDepthTexture) {
      if (generateDepthBuffer && generateStencilBuffer) {
        depthTextureFormat = 13;
      } else if (generateDepthBuffer) {
        depthTextureFormat = 14;
      } else {
        depthTextureFormat = 19;
      }
    }
    depthStencilTexture = rtWrapper.createDepthStencilTexture(0, false, generateStencilBuffer, 1, depthTextureFormat, rtWrapper.label + "-DepthStencil");
  }
  const mipmapsCreationOnly = options !== undefined && typeof options === "object" && options.createMipMaps && !generateMipMaps;
  for (let i = 0;i < textureCount; i++) {
    let samplingMode = samplingModes[i] || defaultSamplingMode;
    let type = types[i] || defaultType;
    const format = formats[i] || defaultFormat;
    const useSRGBBuffer = (useSRGBBuffers[i] || defaultUseSRGBBuffer) && this._caps.supportSRGBBuffers;
    const target = targets[i] || defaultTarget;
    const layerCount = layers[i] ?? 1;
    const creationFlag = creationFlags[i];
    if (type === 1 && !this._caps.textureFloatLinearFiltering) {
      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. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
    }
    attachments.push(i + 1);
    defaultAttachments.push(initializeBuffers ? i + 1 : i === 0 ? 1 : 0);
    if (target === -1 || dontCreateTextures) {
      continue;
    }
    const texture = new InternalTexture(this, 6);
    textures[i] = texture;
    switch (target) {
      case 34067:
        texture.isCube = true;
        break;
      case 32879:
        texture.is3D = true;
        texture.baseDepth = texture.depth = layerCount;
        break;
      case 35866:
        texture.is2DArray = true;
        texture.baseDepth = texture.depth = layerCount;
        break;
    }
    texture.baseWidth = width;
    texture.baseHeight = height;
    texture.width = width;
    texture.height = height;
    texture.isReady = true;
    texture.samples = 1;
    texture.generateMipMaps = generateMipMaps;
    texture.samplingMode = samplingMode;
    texture.type = type;
    texture._cachedWrapU = 0;
    texture._cachedWrapV = 0;
    texture._useSRGBBuffer = useSRGBBuffer;
    texture.format = format;
    texture.label = labels[i] ?? rtWrapper.label + "-Texture" + i;
    this._internalTexturesCache.push(texture);
    if (mipmapsCreationOnly) {
      texture.generateMipMaps = true;
    }
    this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, creationFlag, true);
    if (mipmapsCreationOnly) {
      texture.generateMipMaps = false;
    }
  }
  if (depthStencilTexture) {
    depthStencilTexture.incrementReferences();
    textures[textureCount] = depthStencilTexture;
    this._internalTexturesCache.push(depthStencilTexture);
  }
  rtWrapper.setTextures(textures);
  rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);
  if (!dontCreateTextures) {
    this.updateMultipleRenderTargetTextureSampleCount(rtWrapper, samples);
  } else {
    rtWrapper._samples = samples;
  }
  return rtWrapper;
};
WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(rtWrapper, samples) {
  if (!rtWrapper || !rtWrapper.textures || rtWrapper.textures.length === 0 || rtWrapper.textures[0].samples === samples) {
    return samples;
  }
  const count = rtWrapper.textures.length;
  if (count === 0) {
    return 1;
  }
  samples = Math.min(samples, this.getCaps().maxMSAASamples);
  for (let i = 0;i < count; ++i) {
    const texture = rtWrapper.textures[i];
    const gpuTextureWrapper = texture._hardwareTexture;
    gpuTextureWrapper?.releaseMSAATexture(rtWrapper.getBaseArrayLayer(i));
  }
  const lastTextureIsDepthTexture = rtWrapper._depthStencilTexture === rtWrapper.textures[count - 1];
  for (let i = 0;i < count; ++i) {
    const texture = rtWrapper.textures[i];
    this._textureHelper.createMSAATexture(texture, samples, false, rtWrapper.getBaseArrayLayer(i));
    texture.samples = samples;
  }
  if (rtWrapper._depthStencilTexture && !lastTextureIsDepthTexture) {
    this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);
    rtWrapper._depthStencilTexture.samples = samples;
  }
  rtWrapper._samples = samples;
  return samples;
};
WebGPUEngine.prototype.generateMipMapsMultiFramebuffer = function(texture) {
  const rtWrapper = texture;
  if (!rtWrapper.isMulti) {
    return;
  }
  const attachments = rtWrapper._attachments;
  const count = attachments.length;
  for (let i = 0;i < count; i++) {
    const texture2 = rtWrapper.textures[i];
    if (texture2.generateMipMaps && !texture2.isCube && !texture2.is3D) {
      this._generateMipmaps(texture2);
    }
  }
};
WebGPUEngine.prototype.resolveMultiFramebuffer = function(_texture) {
  throw new Error("resolveMultiFramebuffer is not yet implemented in WebGPU!");
};
WebGPUEngine.prototype.bindAttachments = function(attachments) {
  if (attachments.length === 0 || !this._currentRenderTarget) {
    return;
  }
  this._mrtAttachments = attachments;
  if (this._currentRenderPass) {
    this._cacheRenderPipeline.setMRTAttachments(attachments);
  } else {}
};
WebGPUEngine.prototype.buildTextureLayout = function(textureStatus) {
  const result = [];
  for (let i = 0;i < textureStatus.length; i++) {
    if (textureStatus[i]) {
      result.push(i + 1);
    } else {
      result.push(0);
    }
  }
  return result;
};
WebGPUEngine.prototype.restoreSingleAttachment = function() {};
WebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget = function() {};

// node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.videoTexture.js
function IsExternalTexture(texture) {
  return texture && texture.underlyingResource !== undefined ? true : false;
}
WebGPUEngine.prototype.updateVideoTexture = function(texture, video, invertY) {
  if (!texture || texture._isDisabled) {
    return;
  }
  if (this._videoTextureSupported === undefined) {
    this._videoTextureSupported = true;
  }
  let gpuTextureWrapper = texture._hardwareTexture;
  if (!texture._hardwareTexture?.underlyingResource) {
    gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);
  }
  if (IsExternalTexture(video)) {
    if (video.isReady()) {
      try {
        this._textureHelper.copyVideoToTexture(video, texture, gpuTextureWrapper.format, !invertY);
        if (texture.generateMipMaps) {
          this._generateMipmaps(texture);
        }
      } catch (e) {}
      texture.isReady = true;
    }
  } else if (video) {
    this.createImageBitmap(video).then((bitmap) => {
      this._textureHelper.updateTexture(bitmap, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0);
      if (texture.generateMipMaps) {
        this._generateMipmaps(texture);
      }
      texture.isReady = true;
    }).catch(() => {
      texture.isReady = true;
    });
  }
};

// node_modules/@babylonjs/core/Engines/index.js
init_webGL2ShaderProcessors();
init_performanceConfigurator();

// node_modules/@babylonjs/core/Engines/engineFactory.js
init_engine();

// node_modules/@babylonjs/core/Engines/index.js
init_shaderStore();
init_renderTargetWrapper();
init_engine_common();
// node_modules/@babylonjs/core/Events/index.js
init_keyboardEvents();
init_pointerEvents();

// node_modules/@babylonjs/core/Events/clipboardEvents.js
class ClipboardEventTypes {
}
ClipboardEventTypes.COPY = 1;
ClipboardEventTypes.CUT = 2;
ClipboardEventTypes.PASTE = 3;

// node_modules/@babylonjs/core/Events/index.js
init_deviceInputEvents();
// node_modules/@babylonjs/core/FlowGraph/index.js
init_flowGraph();
init_flowGraphBlock();
init_flowGraphSignalConnection();
init_flowGraphExecutionBlock();
init_flowGraphEventBlock();
init_flowGraphRichTypes();
init_flowGraphContext();
init_flowGraphCoordinator();
init_flowGraphConnection();
init_flowGraphDataConnection();
init_flowGraphAssetsContext();

// node_modules/@babylonjs/core/FlowGraph/flowGraphParser.js
init_flowGraphCoordinator();
init_flowGraphEventBlock();
init_flowGraphExecutionBlock();
init_serialization();
init_flowGraphRichTypes();

// node_modules/@babylonjs/core/FlowGraph/index.js
init_flowGraphPathConverterComponent();
init_flowGraphLogger();

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/index.js
init_flowGraphConsoleLogBlock();

// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/ControlFlow/index.js
init_flowGraphBranchBlock();
init_flowGraphDoNBlock();
init_flowGraphForLoopBlock();
init_flowGraphThrottleBlock();
init_flowGraphMultiGateBlock();
init_flowGraphSwitchBlock();
init_flowGraphWaitAllBlock();
init_flowGraphCounterBlock();
init_flowGraphWhileLoopBlock();
init_flowGraphDebounceBlock();
init_flowGraphFlipFlopBlock();
init_flowGraphSequenceBlock();
init_flowGraphSetDelayBlock();
init_flowGraphCancelDelayBlock();
// node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/Animation/index.js
init_flowGraphPlayAnimationBlock();
init_flowGraphStopAnimationBlock();
init_flowGraphPauseAnimationBlock();
init_flowGraphInterpolationBlock();
init_flowGraphEasingBlock();
init_flowGraphBezierCurveEasingBlock();
// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/index.js
init_flowGraphConditionalDataBlock();
init_flowGraphGetVariableBlock();
init_flowGraphSetVariableBlock();
init_flowGraphTransformCoordinatesSystemBlock();
init_flowGraphGetPropertyBlock();
init_flowGraphSetPropertyBlock();
init_flowGraphConstantBlock();
init_flowGraphGetAssetBlock();
init_flowGraphDataSwitchBlock();

// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Math/index.js
init_flowGraphMathBlocks();
init_flowGraphMathCombineExtractBlocks();
init_flowGraphMatrixMathBlocks();
init_flowGraphVectorMathBlocks();
// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Transformers/index.js
init_flowGraphJsonPointerParserBlock();
init_flowGraphTypeToTypeBlocks();
// node_modules/@babylonjs/core/FlowGraph/Blocks/Data/Utils/index.js
init_flowGraphContextBlock();
init_flowGraphArrayIndexBlock();
init_flowGraphCodeExecutionBlock();
init_flowGraphIndexOfBlock();
init_flowGraphFunctionReferenceBlock();
// node_modules/@babylonjs/core/FlowGraph/Blocks/Event/index.js
init_flowGraphMeshPickEventBlock();
init_flowGraphSceneReadyEventBlock();
init_flowGraphReceiveCustomEventBlock();
init_flowGraphSendCustomEventBlock();
init_flowGraphSceneTickEventBlock();
init_flowGraphPointerOutEventBlock();
init_flowGraphPointerOverEventBlock();
// node_modules/@babylonjs/core/FlowGraph/Blocks/flowGraphBlockNames.js
var FlowGraphBlockNames;
(function(FlowGraphBlockNames2) {
  FlowGraphBlockNames2["PlayAnimation"] = "FlowGraphPlayAnimationBlock";
  FlowGraphBlockNames2["StopAnimation"] = "FlowGraphStopAnimationBlock";
  FlowGraphBlockNames2["PauseAnimation"] = "FlowGraphPauseAnimationBlock";
  FlowGraphBlockNames2["ValueInterpolation"] = "FlowGraphInterpolationBlock";
  FlowGraphBlockNames2["SceneReadyEvent"] = "FlowGraphSceneReadyEventBlock";
  FlowGraphBlockNames2["SceneTickEvent"] = "FlowGraphSceneTickEventBlock";
  FlowGraphBlockNames2["SendCustomEvent"] = "FlowGraphSendCustomEventBlock";
  FlowGraphBlockNames2["ReceiveCustomEvent"] = "FlowGraphReceiveCustomEventBlock";
  FlowGraphBlockNames2["MeshPickEvent"] = "FlowGraphMeshPickEventBlock";
  FlowGraphBlockNames2["PointerEvent"] = "FlowGraphPointerEventBlock";
  FlowGraphBlockNames2["PointerDownEvent"] = "FlowGraphPointerDownEventBlock";
  FlowGraphBlockNames2["PointerUpEvent"] = "FlowGraphPointerUpEventBlock";
  FlowGraphBlockNames2["PointerMoveEvent"] = "FlowGraphPointerMoveEventBlock";
  FlowGraphBlockNames2["PointerOverEvent"] = "FlowGraphPointerOverEventBlock";
  FlowGraphBlockNames2["PointerOutEvent"] = "FlowGraphPointerOutEventBlock";
  FlowGraphBlockNames2["E"] = "FlowGraphEBlock";
  FlowGraphBlockNames2["PI"] = "FlowGraphPIBlock";
  FlowGraphBlockNames2["Inf"] = "FlowGraphInfBlock";
  FlowGraphBlockNames2["NaN"] = "FlowGraphNaNBlock";
  FlowGraphBlockNames2["Random"] = "FlowGraphRandomBlock";
  FlowGraphBlockNames2["Add"] = "FlowGraphAddBlock";
  FlowGraphBlockNames2["Subtract"] = "FlowGraphSubtractBlock";
  FlowGraphBlockNames2["Multiply"] = "FlowGraphMultiplyBlock";
  FlowGraphBlockNames2["Divide"] = "FlowGraphDivideBlock";
  FlowGraphBlockNames2["Abs"] = "FlowGraphAbsBlock";
  FlowGraphBlockNames2["Sign"] = "FlowGraphSignBlock";
  FlowGraphBlockNames2["Trunc"] = "FlowGraphTruncBlock";
  FlowGraphBlockNames2["Floor"] = "FlowGraphFloorBlock";
  FlowGraphBlockNames2["Ceil"] = "FlowGraphCeilBlock";
  FlowGraphBlockNames2["Round"] = "FlowGraphRoundBlock";
  FlowGraphBlockNames2["Fraction"] = "FlowGraphFractBlock";
  FlowGraphBlockNames2["Negation"] = "FlowGraphNegationBlock";
  FlowGraphBlockNames2["Modulo"] = "FlowGraphModuloBlock";
  FlowGraphBlockNames2["Min"] = "FlowGraphMinBlock";
  FlowGraphBlockNames2["Max"] = "FlowGraphMaxBlock";
  FlowGraphBlockNames2["Clamp"] = "FlowGraphClampBlock";
  FlowGraphBlockNames2["Saturate"] = "FlowGraphSaturateBlock";
  FlowGraphBlockNames2["MathInterpolation"] = "FlowGraphMathInterpolationBlock";
  FlowGraphBlockNames2["Equality"] = "FlowGraphEqualityBlock";
  FlowGraphBlockNames2["LessThan"] = "FlowGraphLessThanBlock";
  FlowGraphBlockNames2["LessThanOrEqual"] = "FlowGraphLessThanOrEqualBlock";
  FlowGraphBlockNames2["GreaterThan"] = "FlowGraphGreaterThanBlock";
  FlowGraphBlockNames2["GreaterThanOrEqual"] = "FlowGraphGreaterThanOrEqualBlock";
  FlowGraphBlockNames2["IsNaN"] = "FlowGraphIsNaNBlock";
  FlowGraphBlockNames2["IsInfinity"] = "FlowGraphIsInfBlock";
  FlowGraphBlockNames2["DegToRad"] = "FlowGraphDegToRadBlock";
  FlowGraphBlockNames2["RadToDeg"] = "FlowGraphRadToDegBlock";
  FlowGraphBlockNames2["Sin"] = "FlowGraphSinBlock";
  FlowGraphBlockNames2["Cos"] = "FlowGraphCosBlock";
  FlowGraphBlockNames2["Tan"] = "FlowGraphTanBlock";
  FlowGraphBlockNames2["Asin"] = "FlowGraphASinBlock";
  FlowGraphBlockNames2["Acos"] = "FlowGraphACosBlock";
  FlowGraphBlockNames2["Atan"] = "FlowGraphATanBlock";
  FlowGraphBlockNames2["Atan2"] = "FlowGraphATan2Block";
  FlowGraphBlockNames2["Sinh"] = "FlowGraphSinhBlock";
  FlowGraphBlockNames2["Cosh"] = "FlowGraphCoshBlock";
  FlowGraphBlockNames2["Tanh"] = "FlowGraphTanhBlock";
  FlowGraphBlockNames2["Asinh"] = "FlowGraphASinhBlock";
  FlowGraphBlockNames2["Acosh"] = "FlowGraphACoshBlock";
  FlowGraphBlockNames2["Atanh"] = "FlowGraphATanhBlock";
  FlowGraphBlockNames2["Exponential"] = "FlowGraphExponentialBlock";
  FlowGraphBlockNames2["Log"] = "FlowGraphLogBlock";
  FlowGraphBlockNames2["Log2"] = "FlowGraphLog2Block";
  FlowGraphBlockNames2["Log10"] = "FlowGraphLog10Block";
  FlowGraphBlockNames2["SquareRoot"] = "FlowGraphSquareRootBlock";
  FlowGraphBlockNames2["CubeRoot"] = "FlowGraphCubeRootBlock";
  FlowGraphBlockNames2["Power"] = "FlowGraphPowerBlock";
  FlowGraphBlockNames2["Length"] = "FlowGraphLengthBlock";
  FlowGraphBlockNames2["Normalize"] = "FlowGraphNormalizeBlock";
  FlowGraphBlockNames2["Dot"] = "FlowGraphDotBlock";
  FlowGraphBlockNames2["Cross"] = "FlowGraphCrossBlock";
  FlowGraphBlockNames2["Rotate2D"] = "FlowGraphRotate2DBlock";
  FlowGraphBlockNames2["Rotate3D"] = "FlowGraphRotate3DBlock";
  FlowGraphBlockNames2["Transpose"] = "FlowGraphTransposeBlock";
  FlowGraphBlockNames2["Determinant"] = "FlowGraphDeterminantBlock";
  FlowGraphBlockNames2["InvertMatrix"] = "FlowGraphInvertMatrixBlock";
  FlowGraphBlockNames2["MatrixMultiplication"] = "FlowGraphMatrixMultiplicationBlock";
  FlowGraphBlockNames2["BitwiseAnd"] = "FlowGraphBitwiseAndBlock";
  FlowGraphBlockNames2["BitwiseOr"] = "FlowGraphBitwiseOrBlock";
  FlowGraphBlockNames2["BitwiseXor"] = "FlowGraphBitwiseXorBlock";
  FlowGraphBlockNames2["BitwiseNot"] = "FlowGraphBitwiseNotBlock";
  FlowGraphBlockNames2["BitwiseLeftShift"] = "FlowGraphBitwiseLeftShiftBlock";
  FlowGraphBlockNames2["BitwiseRightShift"] = "FlowGraphBitwiseRightShiftBlock";
  FlowGraphBlockNames2["LeadingZeros"] = "FlowGraphLeadingZerosBlock";
  FlowGraphBlockNames2["TrailingZeros"] = "FlowGraphTrailingZerosBlock";
  FlowGraphBlockNames2["OneBitsCounter"] = "FlowGraphOneBitsCounterBlock";
  FlowGraphBlockNames2["Branch"] = "FlowGraphBranchBlock";
  FlowGraphBlockNames2["SetDelay"] = "FlowGraphSetDelayBlock";
  FlowGraphBlockNames2["CancelDelay"] = "FlowGraphCancelDelayBlock";
  FlowGraphBlockNames2["CallCounter"] = "FlowGraphCallCounterBlock";
  FlowGraphBlockNames2["Debounce"] = "FlowGraphDebounceBlock";
  FlowGraphBlockNames2["Throttle"] = "FlowGraphThrottleBlock";
  FlowGraphBlockNames2["DoN"] = "FlowGraphDoNBlock";
  FlowGraphBlockNames2["FlipFlop"] = "FlowGraphFlipFlopBlock";
  FlowGraphBlockNames2["ForLoop"] = "FlowGraphForLoopBlock";
  FlowGraphBlockNames2["MultiGate"] = "FlowGraphMultiGateBlock";
  FlowGraphBlockNames2["Sequence"] = "FlowGraphSequenceBlock";
  FlowGraphBlockNames2["Switch"] = "FlowGraphSwitchBlock";
  FlowGraphBlockNames2["WaitAll"] = "FlowGraphWaitAllBlock";
  FlowGraphBlockNames2["WhileLoop"] = "FlowGraphWhileLoopBlock";
  FlowGraphBlockNames2["ConsoleLog"] = "FlowGraphConsoleLogBlock";
  FlowGraphBlockNames2["Conditional"] = "FlowGraphConditionalBlock";
  FlowGraphBlockNames2["Constant"] = "FlowGraphConstantBlock";
  FlowGraphBlockNames2["TransformCoordinatesSystem"] = "FlowGraphTransformCoordinatesSystemBlock";
  FlowGraphBlockNames2["GetAsset"] = "FlowGraphGetAssetBlock";
  FlowGraphBlockNames2["GetProperty"] = "FlowGraphGetPropertyBlock";
  FlowGraphBlockNames2["SetProperty"] = "FlowGraphSetPropertyBlock";
  FlowGraphBlockNames2["GetVariable"] = "FlowGraphGetVariableBlock";
  FlowGraphBlockNames2["SetVariable"] = "FlowGraphSetVariableBlock";
  FlowGraphBlockNames2["JsonPointerParser"] = "FlowGraphJsonPointerParserBlock";
  FlowGraphBlockNames2["CombineVector2"] = "FlowGraphCombineVector2Block";
  FlowGraphBlockNames2["CombineVector3"] = "FlowGraphCombineVector3Block";
  FlowGraphBlockNames2["CombineVector4"] = "FlowGraphCombineVector4Block";
  FlowGraphBlockNames2["CombineMatrix"] = "FlowGraphCombineMatrixBlock";
  FlowGraphBlockNames2["CombineMatrix2D"] = "FlowGraphCombineMatrix2DBlock";
  FlowGraphBlockNames2["CombineMatrix3D"] = "FlowGraphCombineMatrix3DBlock";
  FlowGraphBlockNames2["ExtractVector2"] = "FlowGraphExtractVector2Block";
  FlowGraphBlockNames2["ExtractVector3"] = "FlowGraphExtractVector3Block";
  FlowGraphBlockNames2["ExtractVector4"] = "FlowGraphExtractVector4Block";
  FlowGraphBlockNames2["ExtractMatrix"] = "FlowGraphExtractMatrixBlock";
  FlowGraphBlockNames2["ExtractMatrix2D"] = "FlowGraphExtractMatrix2DBlock";
  FlowGraphBlockNames2["ExtractMatrix3D"] = "FlowGraphExtractMatrix3DBlock";
  FlowGraphBlockNames2["TransformVector"] = "FlowGraphTransformVectorBlock";
  FlowGraphBlockNames2["TransformCoordinates"] = "FlowGraphTransformCoordinatesBlock";
  FlowGraphBlockNames2["MatrixDecompose"] = "FlowGraphMatrixDecompose";
  FlowGraphBlockNames2["MatrixCompose"] = "FlowGraphMatrixCompose";
  FlowGraphBlockNames2["BooleanToFloat"] = "FlowGraphBooleanToFloat";
  FlowGraphBlockNames2["BooleanToInt"] = "FlowGraphBooleanToInt";
  FlowGraphBlockNames2["FloatToBoolean"] = "FlowGraphFloatToBoolean";
  FlowGraphBlockNames2["IntToBoolean"] = "FlowGraphIntToBoolean";
  FlowGraphBlockNames2["IntToFloat"] = "FlowGraphIntToFloat";
  FlowGraphBlockNames2["FloatToInt"] = "FlowGraphFloatToInt";
  FlowGraphBlockNames2["Easing"] = "FlowGraphEasingBlock";
  FlowGraphBlockNames2["Context"] = "FlowGraphContextBlock";
  FlowGraphBlockNames2["ArrayIndex"] = "FlowGraphArrayIndexBlock";
  FlowGraphBlockNames2["CodeExecution"] = "FlowGraphCodeExecutionBlock";
  FlowGraphBlockNames2["IndexOf"] = "FlowGraphIndexOfBlock";
  FlowGraphBlockNames2["FunctionReference"] = "FlowGraphFunctionReference";
  FlowGraphBlockNames2["BezierCurveEasing"] = "FlowGraphBezierCurveEasing";
  FlowGraphBlockNames2["DataSwitch"] = "FlowGraphDataSwitchBlock";
})(FlowGraphBlockNames || (FlowGraphBlockNames = {}));
// node_modules/@babylonjs/core/FlowGraph/CustomTypes/index.js
init_flowGraphInteger();
init_flowGraphMatrix();
// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraph.js
init_tslib_es6();
init_observable();

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphBlock.js
init_tslib_es6();
init_typeStore();
init_decorators();
init_uniqueIdGenerator();

// node_modules/@babylonjs/core/FrameGraph/Node/Types/nodeRenderGraphTypes.js
var NodeRenderGraphBlockConnectionPointTypes;
(function(NodeRenderGraphBlockConnectionPointTypes2) {
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["Texture"] = 1] = "Texture";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureBackBuffer"] = 2] = "TextureBackBuffer";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureBackBufferDepthStencilAttachment"] = 4] = "TextureBackBufferDepthStencilAttachment";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureDepthStencilAttachment"] = 8] = "TextureDepthStencilAttachment";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureViewDepth"] = 16] = "TextureViewDepth";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureViewNormal"] = 32] = "TextureViewNormal";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureAlbedo"] = 64] = "TextureAlbedo";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureReflectivity"] = 128] = "TextureReflectivity";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureWorldPosition"] = 256] = "TextureWorldPosition";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureVelocity"] = 512] = "TextureVelocity";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureIrradiance"] = 1024] = "TextureIrradiance";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureAlbedoSqrt"] = 2048] = "TextureAlbedoSqrt";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureScreenDepth"] = 4096] = "TextureScreenDepth";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureWorldNormal"] = 8192] = "TextureWorldNormal";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureLocalPosition"] = 16384] = "TextureLocalPosition";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureLinearVelocity"] = 32768] = "TextureLinearVelocity";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureAllButBackBufferDepthStencil"] = 1048571] = "TextureAllButBackBufferDepthStencil";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureAllButBackBuffer"] = 1048569] = "TextureAllButBackBuffer";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["TextureAll"] = 1048575] = "TextureAll";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["ResourceContainer"] = 1048576] = "ResourceContainer";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["ShadowGenerator"] = 2097152] = "ShadowGenerator";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["ShadowLight"] = 4194304] = "ShadowLight";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["Camera"] = 16777216] = "Camera";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["ObjectList"] = 33554432] = "ObjectList";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["AutoDetect"] = 268435456] = "AutoDetect";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["BasedOnInput"] = 536870912] = "BasedOnInput";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["Undefined"] = 1073741824] = "Undefined";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["Object"] = 2147483648] = "Object";
  NodeRenderGraphBlockConnectionPointTypes2[NodeRenderGraphBlockConnectionPointTypes2["All"] = 4294967295] = "All";
})(NodeRenderGraphBlockConnectionPointTypes || (NodeRenderGraphBlockConnectionPointTypes = {}));
var NodeRenderGraphConnectionPointCompatibilityStates;
(function(NodeRenderGraphConnectionPointCompatibilityStates2) {
  NodeRenderGraphConnectionPointCompatibilityStates2[NodeRenderGraphConnectionPointCompatibilityStates2["Compatible"] = 0] = "Compatible";
  NodeRenderGraphConnectionPointCompatibilityStates2[NodeRenderGraphConnectionPointCompatibilityStates2["TypeIncompatible"] = 1] = "TypeIncompatible";
  NodeRenderGraphConnectionPointCompatibilityStates2[NodeRenderGraphConnectionPointCompatibilityStates2["HierarchyIssue"] = 2] = "HierarchyIssue";
})(NodeRenderGraphConnectionPointCompatibilityStates || (NodeRenderGraphConnectionPointCompatibilityStates = {}));
var NodeRenderGraphConnectionPointDirection;
(function(NodeRenderGraphConnectionPointDirection2) {
  NodeRenderGraphConnectionPointDirection2[NodeRenderGraphConnectionPointDirection2["Input"] = 0] = "Input";
  NodeRenderGraphConnectionPointDirection2[NodeRenderGraphConnectionPointDirection2["Output"] = 1] = "Output";
})(NodeRenderGraphConnectionPointDirection || (NodeRenderGraphConnectionPointDirection = {}));

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphBlock.js
init_observable();
init_logger();

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphBlockConnectionPoint.js
init_observable();
class NodeRenderGraphConnectionPoint {
  get direction() {
    return this._direction;
  }
  static IsTextureHandle(value) {
    return value !== undefined && Number.isFinite(value);
  }
  static IsShadowGenerator(value) {
    return value !== undefined && value.mapSize !== undefined;
  }
  static IsShadowLight(value) {
    return value !== undefined && value.setShadowProjectionMatrix !== undefined;
  }
  get type() {
    if (this._type === NodeRenderGraphBlockConnectionPointTypes.AutoDetect) {
      if (this._ownerBlock.isInput) {
        return this._ownerBlock.type;
      }
      if (this._connectedPoint) {
        return this._connectedPoint.type;
      }
      if (this._linkedConnectionSource) {
        if (this._linkedConnectionSource.isConnected) {
          return this._linkedConnectionSource.type;
        }
        if (this._linkedConnectionSource._defaultConnectionPointType) {
          return this._linkedConnectionSource._defaultConnectionPointType;
        }
      }
      if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    if (this._type === NodeRenderGraphBlockConnectionPointTypes.BasedOnInput) {
      if (this._typeConnectionSource) {
        const typeConnectionSource = typeof this._typeConnectionSource === "function" ? this._typeConnectionSource() : this._typeConnectionSource;
        if (!typeConnectionSource.isConnected) {
          return this._defaultConnectionPointType ?? typeConnectionSource.type;
        }
        return typeConnectionSource._connectedPoint.type;
      } else if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    return this._type;
  }
  set type(value) {
    this._type = value;
  }
  get isConnected() {
    return this.connectedPoint !== null || this.hasEndpoints;
  }
  get connectedPoint() {
    return this._connectedPoint;
  }
  get ownerBlock() {
    return this._ownerBlock;
  }
  get sourceBlock() {
    if (!this._connectedPoint) {
      return null;
    }
    return this._connectedPoint.ownerBlock;
  }
  get connectedBlocks() {
    if (this._endpoints.length === 0) {
      return [];
    }
    return this._endpoints.map((e) => e.ownerBlock);
  }
  get endpoints() {
    return this._endpoints;
  }
  get hasEndpoints() {
    return this._endpoints && this._endpoints.length > 0;
  }
  get innerType() {
    if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) {
      return this.type;
    }
    return this._type;
  }
  createCustomInputBlock() {
    return null;
  }
  constructor(name157, ownerBlock, direction) {
    this._connectedPoint = null;
    this._acceptedConnectionPointType = null;
    this._endpoints = new Array;
    this._type = NodeRenderGraphBlockConnectionPointTypes.Undefined;
    this._linkedConnectionSource = null;
    this._isMainLinkSource = false;
    this._typeConnectionSource = null;
    this._defaultConnectionPointType = null;
    this.needDualDirectionValidation = false;
    this.acceptedConnectionPointTypes = [];
    this.excludedConnectionPointTypes = [];
    this.onConnectionObservable = new Observable;
    this.onDisconnectionObservable = new Observable;
    this.isExposedOnFrame = false;
    this.exposedPortPosition = -1;
    this._ownerBlock = ownerBlock;
    this.name = name157;
    this._direction = direction;
  }
  getClassName() {
    return "NodeRenderGraphConnectionPoint";
  }
  canConnectTo(connectionPoint) {
    return this.checkCompatibilityState(connectionPoint) === 0;
  }
  checkCompatibilityState(connectionPoint) {
    const ownerBlock = this._ownerBlock;
    const otherBlock = connectionPoint.ownerBlock;
    if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeRenderGraphBlockConnectionPointTypes.AutoDetect) {
      if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) {
        return 0;
      } else {
        return 1;
      }
    }
    if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) {
      return 1;
    }
    let targetBlock = otherBlock;
    let sourceBlock = ownerBlock;
    if (this.direction === 0) {
      targetBlock = ownerBlock;
      sourceBlock = otherBlock;
    }
    if (targetBlock.isAnAncestorOf(sourceBlock)) {
      return 2;
    }
    return 0;
  }
  connectTo(connectionPoint, ignoreConstraints = false) {
    if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {
      throw "Cannot connect these two connectors.";
    }
    this._endpoints.push(connectionPoint);
    connectionPoint._connectedPoint = this;
    this.onConnectionObservable.notifyObservers(connectionPoint);
    connectionPoint.onConnectionObservable.notifyObservers(this);
    return this;
  }
  disconnectFrom(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index === -1) {
      return this;
    }
    this._endpoints.splice(index, 1);
    endpoint._connectedPoint = null;
    this.onDisconnectionObservable.notifyObservers(endpoint);
    endpoint.onDisconnectionObservable.notifyObservers(this);
    return this;
  }
  addExcludedConnectionPointFromAllowedTypes(mask) {
    let bitmask = 0;
    let val = 2 ** bitmask;
    while (val < NodeRenderGraphBlockConnectionPointTypes.All) {
      if (!(mask & val)) {
        this.excludedConnectionPointTypes.push(val);
      }
      bitmask++;
      val = 2 ** bitmask;
    }
  }
  addAcceptedConnectionPointTypes(mask) {
    let bitmask = 0;
    let val = 2 ** bitmask;
    while (val < NodeRenderGraphBlockConnectionPointTypes.All) {
      if (mask & val && this.acceptedConnectionPointTypes.indexOf(val) === -1) {
        this.acceptedConnectionPointTypes.push(val);
      }
      bitmask++;
      val = 2 ** bitmask;
    }
  }
  serialize(isInput = true) {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.displayName = this.displayName;
    if (isInput && this.connectedPoint) {
      serializationObject.inputName = this.name;
      serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;
      serializationObject.targetConnectionName = this.connectedPoint.name;
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    if (this.isExposedOnFrame || this.exposedPortPosition >= 0) {
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    return serializationObject;
  }
  dispose() {
    this.onConnectionObservable.clear();
    this.onDisconnectionObservable.clear();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphBlock.js
class NodeRenderGraphBlock {
  get disabled() {
    return !!this._frameGraphTask?.disabled;
  }
  set disabled(value) {
    if (this._frameGraphTask) {
      this._frameGraphTask.disabled = value;
    }
  }
  get task() {
    return this._frameGraphTask;
  }
  get inputs() {
    return this._inputs;
  }
  get outputs() {
    return this._outputs;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
  get isInput() {
    return this._isInput;
  }
  get isTeleportOut() {
    return this._isTeleportOut;
  }
  get isTeleportIn() {
    return this._isTeleportIn;
  }
  get isDebug() {
    return this._isDebug;
  }
  get isUnique() {
    return this._isUnique;
  }
  getClassName() {
    return "NodeRenderGraphBlock";
  }
  _inputRename(name157) {
    return name157;
  }
  _outputRename(name157) {
    return name157;
  }
  isAnAncestorOf(block) {
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        if (endpoint.ownerBlock === block) {
          return true;
        }
        if (endpoint.ownerBlock.isAnAncestorOf(block)) {
          return true;
        }
      }
    }
    return false;
  }
  isAnAncestorOfType(type) {
    if (this.getClassName() === type) {
      return true;
    }
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        if (endpoint.ownerBlock.isAnAncestorOfType(type)) {
          return true;
        }
      }
    }
    return false;
  }
  getDescendantOfPredicate(predicate) {
    if (predicate(this)) {
      return this;
    }
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const descendant = endpoint.ownerBlock.getDescendantOfPredicate(predicate);
        if (descendant) {
          return descendant;
        }
      }
    }
    return null;
  }
  constructor(name157, frameGraph, scene, ..._additionalConstructionParameters) {
    this._name = "";
    this._isInput = false;
    this._isTeleportOut = false;
    this._isTeleportIn = false;
    this._isDebug = false;
    this._isUnique = false;
    this.onBuildObservable = new Observable;
    this._inputs = new Array;
    this._outputs = new Array;
    this._codeVariableName = "";
    this._additionalConstructionParameters = null;
    this.visibleOnFrame = false;
    this._name = name157;
    this._frameGraph = frameGraph;
    this._scene = scene;
    this._engine = scene.getEngine();
    this.uniqueId = UniqueIdGenerator.UniqueId;
  }
  registerInput(name157, type, isOptional = false, point) {
    point = point ?? new NodeRenderGraphConnectionPoint(name157, this, 0);
    point.type = type;
    point.isOptional = isOptional;
    this._inputs.push(point);
    return this;
  }
  registerOutput(name157, type, point) {
    point = point ?? new NodeRenderGraphConnectionPoint(name157, this, 1);
    point.type = type;
    this._outputs.push(point);
    return this;
  }
  _addDependenciesInput(additionalAllowedTypes = 0) {
    this.registerInput("dependencies", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    const dependencies = this.getInputByName("dependencies");
    dependencies.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ResourceContainer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator | additionalAllowedTypes);
    return dependencies;
  }
  _buildBlock(_state) {}
  _customBuildStep(_state) {}
  _propagateInputValueToOutput(inputConnectionPoint, outputConnectionPoint) {
    if (inputConnectionPoint.connectedPoint) {
      outputConnectionPoint.value = inputConnectionPoint.connectedPoint.value;
    }
  }
  build(state) {
    if (this._buildId === state.buildId) {
      return true;
    }
    this._buildId = state.buildId;
    for (const input of this._inputs) {
      if (!input.connectedPoint) {
        if (!input.isOptional) {
          state._notConnectedNonOptionalInputs.push(input);
        }
        continue;
      }
      const block = input.connectedPoint.ownerBlock;
      if (block && block !== this) {
        block.build(state);
      }
    }
    this._customBuildStep(state);
    if (state.verbose) {
      Logger.Log(`Building ${this.name} [${this.getClassName()}]`);
    }
    if (this._frameGraphTask) {
      this._frameGraphTask.name = this.name;
    }
    this._buildBlock(state);
    if (this._frameGraphTask) {
      this._frameGraphTask.dependencies = undefined;
      const dependenciesConnectedPoint = this.getInputByName("dependencies")?.connectedPoint;
      if (dependenciesConnectedPoint) {
        if (dependenciesConnectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.ResourceContainer) {
          const container = dependenciesConnectedPoint.ownerBlock;
          for (let i = 0;i < container.inputs.length; i++) {
            const input = container.inputs[i];
            if (input.connectedPoint && input.connectedPoint.value !== undefined && NodeRenderGraphConnectionPoint.IsTextureHandle(input.connectedPoint.value)) {
              this._frameGraphTask.dependencies = this._frameGraphTask.dependencies || new Set;
              this._frameGraphTask.dependencies.add(input.connectedPoint.value);
            }
          }
        } else if (NodeRenderGraphConnectionPoint.IsTextureHandle(dependenciesConnectedPoint.value)) {
          this._frameGraphTask.dependencies = this._frameGraphTask.dependencies || new Set;
          this._frameGraphTask.dependencies.add(dependenciesConnectedPoint.value);
        }
      }
      this._frameGraph.addTask(this._frameGraphTask);
    }
    this.onBuildObservable.notifyObservers(this);
    return false;
  }
  _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) {
    if (looseCoupling) {
      this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0];
    } else {
      this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
      this._inputs[inputIndex0]._isMainLinkSource = true;
    }
    this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
  }
  initialize() {}
  autoConfigure() {}
  getInputByName(name157) {
    const filter = this._inputs.filter((e) => e.name === name157);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  getOutputByName(name157) {
    const filter = this._outputs.filter((e) => e.name === name157);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.customType = "BABYLON." + this.getClassName();
    serializationObject.id = this.uniqueId;
    serializationObject.name = this.name;
    serializationObject.visibleOnFrame = this.visibleOnFrame;
    serializationObject.disabled = this.disabled;
    if (this._additionalConstructionParameters) {
      serializationObject.additionalConstructionParameters = this._additionalConstructionParameters;
    }
    serializationObject.inputs = [];
    serializationObject.outputs = [];
    for (const input of this.inputs) {
      serializationObject.inputs.push(input.serialize());
    }
    for (const output of this.outputs) {
      serializationObject.outputs.push(output.serialize(false));
    }
    return serializationObject;
  }
  _deserialize(serializationObject) {
    this._name = serializationObject.name;
    this.comments = serializationObject.comments;
    this.visibleOnFrame = serializationObject.visibleOnFrame;
    this.disabled = serializationObject.disabled;
    this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);
  }
  _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) {
    const serializedInputs = serializationObject.inputs;
    const serializedOutputs = serializationObject.outputs;
    if (serializedInputs) {
      serializedInputs.forEach((port) => {
        const input = this.inputs.find((i) => i.name === port.name);
        if (!input) {
          return;
        }
        if (port.displayName) {
          input.displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          input.isExposedOnFrame = port.isExposedOnFrame;
          input.exposedPortPosition = port.exposedPortPosition;
        }
      });
    }
    if (serializedOutputs) {
      serializedOutputs.forEach((port, i) => {
        if (port.displayName) {
          this.outputs[i].displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;
          this.outputs[i].exposedPortPosition = port.exposedPortPosition;
        }
      });
    }
  }
  _dumpPropertiesCode() {
    const variableName = this._codeVariableName;
    return `${variableName}.visibleOnFrame = ${this.visibleOnFrame};
${variableName}.disabled = ${this.disabled};
`;
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = "";
    if (alreadyDumped.indexOf(this) !== -1) {
      return codeString;
    }
    alreadyDumped.push(this);
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
      codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});
`;
    }
    return codeString;
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    alreadyDumped.push(this);
    const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
    this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;
    if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
      let index = 0;
      do {
        index++;
        this._codeVariableName = nameAsVariableName + index;
      } while (uniqueNames.indexOf(this._codeVariableName) !== -1);
    }
    uniqueNames.push(this._codeVariableName);
    let codeString = `
// ${this.getClassName()}
`;
    if (this.comments) {
      codeString += `// ${this.comments}
`;
    }
    const className = this.getClassName();
    if (className === "RenderGraphInputBlock") {
      const block = this;
      const blockType = block.type;
      codeString += `var ${this._codeVariableName} = new BABYLON.NodeRenderGraphInputBlock("${this.name}", nodeRenderGraph.frameGraph, scene, BABYLON.NodeRenderGraphBlockConnectionPointTypes.${NodeRenderGraphBlockConnectionPointTypes[blockType]});
`;
    } else {
      if (this._additionalConstructionParameters) {
        codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}", nodeRenderGraph.frameGraph, scene, ...${JSON.stringify(this._additionalConstructionParameters)});
`;
      } else {
        codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}", nodeRenderGraph.frameGraph, scene);
`;
      }
    }
    codeString += this._dumpPropertiesCode() + `
`;
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      if (alreadyDumped.indexOf(connectedBlock) === -1) {
        codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    for (const output of this.outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const connectedBlock = endpoint.ownerBlock;
        if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
          codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
        }
      }
    }
    return codeString;
  }
  clone() {
    const serializationObject = this.serialize();
    const blockType = GetClass(serializationObject.customType);
    if (blockType) {
      const additionalConstructionParameters = serializationObject.additionalConstructionParameters;
      const block = additionalConstructionParameters ? new blockType("", this._frameGraph, this._scene, ...additionalConstructionParameters) : new blockType("", this._frameGraph, this._scene);
      block._deserialize(serializationObject);
      return block;
    }
    return null;
  }
  dispose() {
    for (const input of this.inputs) {
      input.dispose();
    }
    for (const output of this.outputs) {
      output.dispose();
    }
    this._frameGraphTask?.dispose();
    this._frameGraphTask = undefined;
    this.onBuildObservable.clear();
  }
}
__decorate([
  serialize("comment")
], NodeRenderGraphBlock.prototype, "comments", undefined);

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/outputBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/frameGraphTypes.js
var backbufferColorTextureHandle = 0;
var backbufferDepthStencilTextureHandle = 1;

// node_modules/@babylonjs/core/FrameGraph/Passes/pass.js
class FrameGraphPass {
  constructor(name157, _parentTask, _context) {
    this.name = name157;
    this._parentTask = _parentTask;
    this._context = _context;
    this.disabled = false;
  }
  setExecuteFunc(func) {
    this._executeFunc = func;
  }
  _execute() {
    if (!this.disabled) {
      this._executeFunc(this._context);
    }
  }
  _isValid() {
    return this._executeFunc !== undefined ? null : "Execute function is not set (call setExecuteFunc to set it)";
  }
}

// node_modules/@babylonjs/core/FrameGraph/Passes/cullPass.js
class FrameGraphCullPass extends FrameGraphPass {
  static IsCullPass(pass) {
    return pass.setObjectList !== undefined;
  }
  get objectList() {
    return this._objectList;
  }
  setObjectList(objectList) {
    this._objectList = objectList;
  }
  constructor(name157, parentTask, context, engine2) {
    super(name157, parentTask, context);
    this._engine = engine2;
  }
  _isValid() {
    const errMsg = super._isValid();
    return errMsg ? errMsg : this._objectList !== undefined ? null : "Object list is not set (call setObjectList to set it)";
  }
}

// node_modules/@babylonjs/core/FrameGraph/Passes/renderPass.js
class FrameGraphRenderPass extends FrameGraphPass {
  static IsRenderPass(pass) {
    return pass.setRenderTarget !== undefined;
  }
  get renderTarget() {
    return this._renderTarget;
  }
  get renderTargetDepth() {
    return this._renderTargetDepth;
  }
  constructor(name157, parentTask, context, engine2) {
    super(name157, parentTask, context);
    this._dependencies = new Set;
    this._engine = engine2;
  }
  setRenderTarget(renderTargetHandle) {
    this._renderTarget = renderTargetHandle;
  }
  setRenderTargetDepth(renderTargetHandle) {
    this._renderTargetDepth = renderTargetHandle;
  }
  addDependencies(dependencies) {
    if (Array.isArray(dependencies)) {
      for (const dependency of dependencies) {
        this._dependencies.add(dependency);
      }
    } else {
      this._dependencies.add(dependencies);
    }
  }
  collectDependencies(dependencies) {
    const iterator = this._dependencies.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      dependencies.add(key.value);
    }
    if (this._renderTarget) {
      if (Array.isArray(this._renderTarget)) {
        for (const handle of this._renderTarget) {
          if (handle !== undefined) {
            dependencies.add(handle);
          }
        }
      } else {
        dependencies.add(this._renderTarget);
      }
    }
    if (this._renderTargetDepth) {
      dependencies.add(this._renderTargetDepth);
    }
  }
  _execute() {
    this._frameGraphRenderTarget = this._frameGraphRenderTarget || this._context.createRenderTarget(this.name, this._renderTarget, this._renderTargetDepth);
    this._context.bindRenderTarget(this._frameGraphRenderTarget, `frame graph render pass - ${this.name}`);
    super._execute();
    this._context._flushDebugMessages();
  }
  _isValid() {
    const errMsg = super._isValid();
    return errMsg ? errMsg : this._renderTarget !== undefined || this.renderTargetDepth !== undefined ? null : "Render target and render target depth cannot both be undefined.";
  }
}

// node_modules/@babylonjs/core/FrameGraph/frameGraphTask.js
init_observable();

class FrameGraphTask {
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
  get disabled() {
    return this._disabled;
  }
  set disabled(value) {
    this._disabled = value;
  }
  get passes() {
    return this._passes;
  }
  get passesDisabled() {
    return this._passesDisabled;
  }
  isReady() {
    return true;
  }
  dispose() {
    this._reset();
    this.onTexturesAllocatedObservable.clear();
  }
  constructor(name157, frameGraph) {
    this._passes = [];
    this._passesDisabled = [];
    this._disabled = false;
    this.onTexturesAllocatedObservable = new Observable;
    this.name = name157;
    this._frameGraph = frameGraph;
    this._reset();
  }
  _reset() {
    this._passes.length = 0;
    this._passesDisabled.length = 0;
  }
  _addPass(pass, disabled) {
    if (disabled) {
      this._passesDisabled.push(pass);
    } else {
      this._passes.push(pass);
    }
  }
  _checkTask() {
    let outputTexture = null;
    let outputDepthTexture = null;
    let outputObjectList;
    for (const pass of this._passes) {
      const errMsg = pass._isValid();
      if (errMsg) {
        throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`);
      }
      if (FrameGraphRenderPass.IsRenderPass(pass)) {
        const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget];
        outputTexture = [];
        for (const handle of handles) {
          if (handle !== undefined) {
            outputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle));
          }
        }
        outputDepthTexture = pass.renderTargetDepth !== undefined ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null;
      } else if (FrameGraphCullPass.IsCullPass(pass)) {
        outputObjectList = pass.objectList;
      }
    }
    let disabledOutputTexture = null;
    let disabledOutputTextureHandle = [];
    let disabledOutputDepthTexture = null;
    let disabledOutputObjectList;
    for (const pass of this._passesDisabled) {
      const errMsg = pass._isValid();
      if (errMsg) {
        throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`);
      }
      if (FrameGraphRenderPass.IsRenderPass(pass)) {
        const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget];
        disabledOutputTexture = [];
        for (const handle of handles) {
          if (handle !== undefined) {
            disabledOutputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle));
          }
        }
        disabledOutputTextureHandle = handles;
        disabledOutputDepthTexture = pass.renderTargetDepth !== undefined ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null;
      } else if (FrameGraphCullPass.IsCullPass(pass)) {
        disabledOutputObjectList = pass.objectList;
      }
    }
    if (this._passesDisabled.length > 0) {
      if (!this._checkSameRenderTarget(outputTexture, disabledOutputTexture)) {
        let ok = true;
        for (const handle of disabledOutputTextureHandle) {
          if (handle !== undefined && !this._frameGraph.textureManager.isHistoryTexture(handle)) {
            ok = false;
            break;
          }
        }
        if (!ok) {
          throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`);
        }
      }
      if (outputDepthTexture !== disabledOutputDepthTexture) {
        throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`);
      }
      if (outputObjectList !== disabledOutputObjectList) {
        throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`);
      }
    }
  }
  _getPasses() {
    return this.disabled && this._passesDisabled.length > 0 ? this._passesDisabled : this._passes;
  }
  _checkSameRenderTarget(src, dst) {
    if (src === null || dst === null) {
      return src === dst;
    }
    if (src.length !== dst.length) {
      return false;
    }
    for (let i = 0;i < src.length; i++) {
      if (src[i] !== dst[i]) {
        return false;
      }
    }
    return true;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/Texture/copyToBackbufferColorTask.js
class FrameGraphCopyToBackbufferColorTask extends FrameGraphTask {
  record() {
    if (this.sourceTexture === undefined) {
      throw new Error(`FrameGraphCopyToBackbufferColorTask "${this.name}": sourceTexture is required`);
    }
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.addDependencies(this.sourceTexture);
    pass.setRenderTarget(backbufferColorTextureHandle);
    pass.setExecuteFunc((context) => {
      if (!context.isBackbuffer(this.sourceTexture)) {
        context.copyTexture(this.sourceTexture);
      }
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(backbufferColorTextureHandle);
    passDisabled.setExecuteFunc((_context) => {});
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/outputBlock.js
class NodeRenderGraphOutputBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name157, frameGraph, scene) {
    super(name157, frameGraph, scene);
    this._isUnique = true;
    this.registerInput("texture", NodeRenderGraphBlockConnectionPointTypes.Texture);
    this.texture.addAcceptedConnectionPointTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll);
    this._frameGraphTask = new FrameGraphCopyToBackbufferColorTask(name157, frameGraph);
  }
  getClassName() {
    return "NodeRenderGraphOutputBlock";
  }
  get texture() {
    return this._inputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._frameGraphTask.name = this.name;
    const textureConnectedPoint = this.texture.connectedPoint;
    if (textureConnectedPoint) {
      this._frameGraphTask.sourceTexture = textureConnectedPoint.value;
    }
  }
}
RegisterClass("BABYLON.NodeRenderGraphOutputBlock", NodeRenderGraphOutputBlock);

// node_modules/@babylonjs/core/FrameGraph/frameGraphRenderContext.js
init_effectRenderer();

// node_modules/@babylonjs/core/Misc/copyTextureToTexture.js
init_effectRenderer();
var ConversionMode;
(function(ConversionMode2) {
  ConversionMode2[ConversionMode2["None"] = 0] = "None";
  ConversionMode2[ConversionMode2["ToLinearSpace"] = 1] = "ToLinearSpace";
  ConversionMode2[ConversionMode2["ToGammaSpace"] = 2] = "ToGammaSpace";
})(ConversionMode || (ConversionMode = {}));

class CopyTextureToTexture {
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  _textureIsInternal(texture) {
    return texture.getInternalTexture === undefined;
  }
  constructor(engine2, isDepthTexture = false) {
    this._shaderLanguage = 0;
    this._shadersLoaded = false;
    this._engine = engine2;
    this._isDepthTexture = isDepthTexture;
    this._renderer = new EffectRenderer(engine2);
    this._initShaderSourceAsync(isDepthTexture);
  }
  async _initShaderSourceAsync(isDepthTexture) {
    const engine2 = this._engine;
    if (engine2.isWebGPU) {
      this._shaderLanguage = 1;
      await Promise.resolve().then(() => (init_copyTextureToTexture_fragment(), exports_copyTextureToTexture_fragment));
    } else {
      await Promise.resolve().then(() => (init_copyTextureToTexture_fragment2(), exports_copyTextureToTexture_fragment2));
    }
    this._shadersLoaded = true;
    this._effectWrapper = new EffectWrapper({
      engine: engine2,
      name: "CopyTextureToTexture",
      fragmentShader: "copyTextureToTexture",
      useShaderStore: true,
      uniformNames: ["conversion"],
      samplerNames: ["textureSampler"],
      defines: isDepthTexture ? ["#define DEPTH_TEXTURE"] : [],
      shaderLanguage: this._shaderLanguage
    });
    this._effectWrapper.onApplyObservable.add(() => {
      if (isDepthTexture) {
        engine2.setState(false);
        engine2.setDepthBuffer(true);
        engine2.depthCullingState.depthMask = true;
        engine2.depthCullingState.depthFunc = 519;
      } else {
        engine2.depthCullingState.depthMask = false;
      }
      if (this._textureIsInternal(this._source)) {
        this._effectWrapper.effect._bindTexture("textureSampler", this._source);
      } else {
        this._effectWrapper.effect.setTexture("textureSampler", this._source);
      }
      this._effectWrapper.effect.setFloat("conversion", this._conversion);
    });
  }
  isReady() {
    return this._shadersLoaded && !!this._effectWrapper?.effect?.isReady();
  }
  copy(source, destination = null, conversion = 0) {
    if (!this.isReady()) {
      return false;
    }
    this._source = source;
    this._conversion = conversion;
    const engineDepthFunc = this._engine.getDepthFunction();
    const engineDepthMask = this._engine.getDepthWrite();
    this._renderer.render(this._effectWrapper, destination);
    this._engine.setDepthWrite(engineDepthMask);
    if (this._isDepthTexture && engineDepthFunc) {
      this._engine.setDepthFunction(engineDepthFunc);
    }
    return true;
  }
  dispose() {
    this._effectWrapper?.dispose();
    this._renderer.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/frameGraphContext.js
class FrameGraphContext {
}

// node_modules/@babylonjs/core/FrameGraph/frameGraphRenderContext.js
class FrameGraphRenderContext extends FrameGraphContext {
  static _IsObjectRenderer(value) {
    return value.initRender !== undefined;
  }
  constructor(_engine, _textureManager, _scene) {
    super();
    this._engine = _engine;
    this._textureManager = _textureManager;
    this._scene = _scene;
    this._debugMessageHasBeenPushed = false;
    this._renderTargetIsBound = true;
    this._effectRenderer = new EffectRenderer(this._engine);
    this._copyTexture = new CopyTextureToTexture(this._engine);
  }
  isBackbuffer(handle) {
    return this._textureManager.isBackbuffer(handle);
  }
  isBackbufferColor(handle) {
    return this._textureManager.isBackbufferColor(handle);
  }
  isBackbufferDepthStencil(handle) {
    return this._textureManager.isBackbufferDepthStencil(handle);
  }
  createRenderTarget(name159, renderTargets, renderTargetDepth) {
    return this._textureManager.createRenderTarget(name159, renderTargets, renderTargetDepth);
  }
  clear(color, backBuffer, depth, stencil) {
    this._applyRenderTarget();
    this._engine.clear(color, backBuffer, depth, stencil);
  }
  clearColorAttachments(color, attachments) {
    this._applyRenderTarget();
    this._engine.bindAttachments(attachments);
    this._engine.clear(color, true, false, false);
  }
  bindAttachments(attachments) {
    this._applyRenderTarget();
    this._engine.bindAttachments(attachments);
  }
  generateMipMaps() {
    if (this._currentRenderTarget?.renderTargetWrapper === undefined) {
      return;
    }
    if (this._renderTargetIsBound && this._engine._currentRenderTarget) {
      this._flushDebugMessages();
      this._engine.unBindFramebuffer(this._engine._currentRenderTarget);
      this._renderTargetIsBound = false;
    }
    const textures = this._currentRenderTarget.renderTargetWrapper.textures;
    if (textures) {
      for (const texture of textures) {
        this._engine.generateMipmaps(texture);
      }
    }
  }
  setTextureSamplingMode(handle, samplingMode) {
    const internalTexture = this._textureManager.getTextureFromHandle(handle);
    if (internalTexture && internalTexture.samplingMode !== samplingMode) {
      this._engine.updateTextureSamplingMode(samplingMode, internalTexture);
    }
  }
  bindTextureHandle(effect, name159, handle) {
    let texture;
    const historyEntry = this._textureManager._historyTextures.get(handle);
    if (historyEntry) {
      texture = historyEntry.textures[historyEntry.index];
      if (this._currentRenderTarget !== undefined && this._currentRenderTarget.renderTargetWrapper !== undefined && this._currentRenderTarget.renderTargetWrapper.textures.includes(texture)) {
        texture = historyEntry.textures[historyEntry.index ^ 1];
      }
    } else {
      texture = this._textureManager._textures.get(handle).texture;
    }
    effect._bindTexture(name159, texture);
  }
  saveDepthStates() {
    this._depthTest = this._engine.getDepthBuffer();
    this._depthWrite = this._engine.getDepthWrite();
  }
  restoreDepthStates() {
    this._engine.setDepthBuffer(this._depthTest);
    this._engine.setDepthWrite(this._depthWrite);
  }
  setDepthStates(depthTest, depthWrite) {
    this._engine.setDepthBuffer(depthTest);
    this._engine.setDepthWrite(depthWrite);
  }
  applyFullScreenEffect(drawWrapper, customBindings) {
    if (!drawWrapper.effect?.isReady()) {
      return false;
    }
    this._applyRenderTarget();
    const engineDepthMask = this._engine.getDepthWrite();
    this._effectRenderer.saveStates();
    this._effectRenderer.setViewport();
    this._engine.enableEffect(drawWrapper);
    this._engine.setState(false);
    this._engine.setDepthBuffer(false);
    this._engine.setDepthWrite(false);
    this._effectRenderer.bindBuffers(drawWrapper.effect);
    customBindings?.();
    this._effectRenderer.draw();
    this._effectRenderer.restoreStates();
    this._engine.setDepthWrite(engineDepthMask);
    this._engine.setAlphaMode(0);
    return true;
  }
  copyTexture(sourceTexture, forceCopyToBackbuffer = false) {
    if (forceCopyToBackbuffer) {
      this.bindRenderTarget();
    }
    this._applyRenderTarget();
    this._copyTexture.copy(this._textureManager.getTextureFromHandle(sourceTexture));
  }
  render(object, viewportWidth, viewportHeight) {
    if (FrameGraphRenderContext._IsObjectRenderer(object)) {
      if (object.shouldRender()) {
        this._scene.incrementRenderId();
        this._scene.resetCachedMaterial();
        this._applyRenderTarget();
        object.prepareRenderList();
        object.initRender(viewportWidth, viewportHeight);
        object.render();
        object.finishRender();
      }
    } else {
      this._applyRenderTarget();
      object.render();
    }
  }
  bindRenderTarget(renderTarget, debugMessage) {
    if (renderTarget?.renderTargetWrapper === undefined && this._currentRenderTarget === undefined || renderTarget && this._currentRenderTarget && renderTarget.equals(this._currentRenderTarget)) {
      this._flushDebugMessages();
      if (debugMessage !== undefined) {
        this._engine._debugPushGroup?.(debugMessage, 2);
        this._debugMessageWhenTargetBound = undefined;
        this._debugMessageHasBeenPushed = true;
      }
      return;
    }
    this._currentRenderTarget = renderTarget?.renderTargetWrapper === undefined ? undefined : renderTarget;
    this._debugMessageWhenTargetBound = debugMessage;
    this._renderTargetIsBound = false;
  }
  _flushDebugMessages() {
    if (this._debugMessageHasBeenPushed) {
      this._engine._debugPopGroup?.(2);
      this._debugMessageHasBeenPushed = false;
    }
  }
  _applyRenderTarget() {
    if (this._renderTargetIsBound) {
      return;
    }
    this._flushDebugMessages();
    const renderTargetWrapper2 = this._currentRenderTarget?.renderTargetWrapper;
    if (renderTargetWrapper2 === undefined) {
      this._engine.restoreDefaultFramebuffer();
    } else {
      if (this._engine._currentRenderTarget) {
        this._engine.unBindFramebuffer(this._engine._currentRenderTarget);
      }
      this._engine.bindFramebuffer(renderTargetWrapper2);
    }
    if (this._debugMessageWhenTargetBound !== undefined) {
      this._engine._debugPushGroup?.(this._debugMessageWhenTargetBound, 2);
      this._debugMessageWhenTargetBound = undefined;
      this._debugMessageHasBeenPushed = true;
    }
    this._renderTargetIsBound = true;
  }
  _isReady() {
    return this._copyTexture.isReady();
  }
  _dispose() {
    this._effectRenderer.dispose();
    this._copyTexture.dispose();
  }
}

// node_modules/@babylonjs/core/Materials/Textures/textureCreationOptions.js
function textureSizeIsObject(size) {
  return size.width !== undefined;
}
function getDimensionsFromTextureSize(size) {
  if (textureSizeIsObject(size)) {
    return { width: size.width, height: size.height };
  }
  return { width: size, height: size };
}

// node_modules/@babylonjs/core/FrameGraph/frameGraphTextureManager.js
init_texture();

// node_modules/@babylonjs/core/FrameGraph/frameGraphRenderTarget.js
class FrameGraphRenderTarget {
  constructor(name159, textureManager, renderTargets, renderTargetDepth) {
    this._isBackBuffer = false;
    this.name = name159;
    this._textureManager = textureManager;
    this._renderTargets = renderTargets === undefined ? undefined : Array.isArray(renderTargets) ? renderTargets : [renderTargets];
    this._renderTargetDepth = renderTargetDepth;
  }
  get renderTargetWrapper() {
    if (this._isBackBuffer) {
      return;
    }
    if (!this._renderTargetWrapper) {
      const engine2 = this._textureManager.engine;
      const textureHandle = this._renderTargets === undefined ? this._renderTargetDepth : this._renderTargets[0];
      if (this._textureManager.isBackbuffer(textureHandle)) {
        this._isBackBuffer = true;
        return;
      }
      const textureDescription = this._textureManager.getTextureDescription(textureHandle);
      const creationOptionsForTexture = {
        textureCount: this._renderTargets?.length ?? 0,
        generateDepthBuffer: false,
        label: this.name,
        samples: textureDescription.options.samples ?? 1,
        dontCreateTextures: true
      };
      this._renderTargetWrapper = engine2.createMultipleRenderTarget(textureDescription.size, creationOptionsForTexture, true);
      for (let i = 0;i < creationOptionsForTexture.textureCount; i++) {
        const handle = this._renderTargets[i];
        const texture = this._textureManager.getTextureFromHandle(handle);
        if (!texture) {
          throw new Error(`FrameGraphRenderTarget.renderTargetWrapper: Failed to get texture from handle. handle: ${handle}, name: ${this.name}, index: ${i}, renderTargets: ${this._renderTargets}`);
        }
        this._renderTargetWrapper.setTexture(texture, i, false);
      }
      if (this._renderTargetDepth !== undefined) {
        this._renderTargetWrapper.setDepthStencilTexture(this._textureManager.getTextureFromHandle(this._renderTargetDepth), false);
      }
    }
    return this._renderTargetWrapper;
  }
  equals(other) {
    const src = this._renderTargets;
    const dst = other._renderTargets;
    if (src !== undefined && dst !== undefined) {
      if (src.length !== dst.length) {
        return false;
      }
      for (let i = 0;i < src.length; i++) {
        if (src[i] !== dst[i]) {
          return false;
        }
      }
    } else if (src === undefined && dst !== undefined || src !== undefined && dst === undefined) {
      return false;
    }
    return this._renderTargetDepth === other._renderTargetDepth;
  }
}

// node_modules/@babylonjs/core/FrameGraph/frameGraphTextureManager.js
init_logger();
var FrameGraphTextureNamespace;
(function(FrameGraphTextureNamespace2) {
  FrameGraphTextureNamespace2[FrameGraphTextureNamespace2["Task"] = 0] = "Task";
  FrameGraphTextureNamespace2[FrameGraphTextureNamespace2["Graph"] = 1] = "Graph";
  FrameGraphTextureNamespace2[FrameGraphTextureNamespace2["External"] = 2] = "External";
})(FrameGraphTextureNamespace || (FrameGraphTextureNamespace = {}));

class FrameGraphTextureManager {
  constructor(engine2, _debugTextures = false, _scene) {
    this.engine = engine2;
    this._debugTextures = _debugTextures;
    this._scene = _scene;
    this._textures = new Map;
    this._historyTextures = new Map;
    this._isRecordingTask = false;
    this.showDebugLogsForTextureAllcationOptimization = false;
    this._addSystemTextures();
  }
  isBackbuffer(handle) {
    if (handle === backbufferColorTextureHandle || handle === backbufferDepthStencilTextureHandle) {
      return true;
    }
    const textureEntry = this._textures.get(handle);
    if (!textureEntry) {
      return false;
    }
    return textureEntry.refHandle === backbufferColorTextureHandle || textureEntry.refHandle === backbufferDepthStencilTextureHandle;
  }
  isBackbufferColor(handle) {
    if (handle === backbufferColorTextureHandle) {
      return true;
    }
    const textureEntry = this._textures.get(handle);
    if (!textureEntry) {
      return false;
    }
    return textureEntry.refHandle === backbufferColorTextureHandle;
  }
  isBackbufferDepthStencil(handle) {
    if (handle === backbufferDepthStencilTextureHandle) {
      return true;
    }
    const textureEntry = this._textures.get(handle);
    if (!textureEntry) {
      return false;
    }
    return textureEntry.refHandle === backbufferDepthStencilTextureHandle;
  }
  isHistoryTexture(handle) {
    const entry = this._textures.get(handle);
    if (!entry) {
      return false;
    }
    handle = entry.refHandle ?? handle;
    return this._historyTextures.has(handle);
  }
  getTextureCreationOptions(handle) {
    const entry = this._textures.get(handle);
    const creationOptions = entry.creationOptions;
    return {
      size: textureSizeIsObject(creationOptions.size) ? { ...creationOptions.size } : creationOptions.size,
      sizeIsPercentage: creationOptions.sizeIsPercentage,
      options: FrameGraphTextureManager.CloneTextureOptions(creationOptions.options, entry.textureIndex),
      isHistoryTexture: creationOptions.isHistoryTexture
    };
  }
  getTextureDescription(handle) {
    const creationOptions = this.getTextureCreationOptions(handle);
    const size = !creationOptions.sizeIsPercentage ? textureSizeIsObject(creationOptions.size) ? creationOptions.size : { width: creationOptions.size, height: creationOptions.size } : this.getAbsoluteDimensions(creationOptions.size);
    return {
      size,
      options: creationOptions.options
    };
  }
  getTextureHandleOrCreateTexture(handle, newTextureName, creationOptions) {
    if (handle === undefined) {
      if (newTextureName === undefined || creationOptions === undefined) {
        throw new Error("getTextureHandleOrCreateTexture: Either handle or newTextureName and creationOptions must be provided.");
      }
      return this.createRenderTargetTexture(newTextureName, creationOptions);
    }
    return handle;
  }
  getTextureFromHandle(handle) {
    const historyEntry = this._historyTextures.get(handle);
    if (historyEntry) {
      return historyEntry.textures[historyEntry.index ^ 1];
    }
    return this._textures.get(handle).texture;
  }
  importTexture(name159, texture, handle) {
    if (handle !== undefined) {
      this._freeEntry(handle);
    }
    const creationOptions = {
      size: { width: texture.width, height: texture.height },
      sizeIsPercentage: false,
      isHistoryTexture: false,
      options: {
        createMipMaps: texture.generateMipMaps,
        samples: texture.samples,
        types: [texture.type],
        formats: [texture.format],
        useSRGBBuffers: [texture._useSRGBBuffer],
        creationFlags: [texture._creationFlags],
        labels: texture.label ? [texture.label] : ["imported"]
      }
    };
    return this._createHandleForTexture(name159, texture, creationOptions, FrameGraphTextureNamespace.External, handle);
  }
  createRenderTargetTexture(name159, creationOptions, handle) {
    return this._createHandleForTexture(name159, null, {
      size: textureSizeIsObject(creationOptions.size) ? { ...creationOptions.size } : creationOptions.size,
      sizeIsPercentage: creationOptions.sizeIsPercentage,
      isHistoryTexture: creationOptions.isHistoryTexture,
      options: FrameGraphTextureManager.CloneTextureOptions(creationOptions.options, undefined, true)
    }, this._isRecordingTask ? FrameGraphTextureNamespace.Task : FrameGraphTextureNamespace.Graph, handle);
  }
  createRenderTarget(name159, renderTargets, renderTargetDepth) {
    const renderTarget = new FrameGraphRenderTarget(name159, this, renderTargets, renderTargetDepth);
    const rtw = renderTarget.renderTargetWrapper;
    if (rtw !== undefined && renderTargets) {
      const handles = Array.isArray(renderTargets) ? renderTargets : [renderTargets];
      for (let i = 0;i < handles.length; i++) {
        let handle = handles[i];
        handle = this._textures.get(handle)?.refHandle ?? handle;
        const historyEntry = this._historyTextures.get(handle);
        if (historyEntry) {
          historyEntry.references.push({ renderTargetWrapper: rtw, textureIndex: i });
          rtw.setTexture(historyEntry.textures[historyEntry.index], i, false);
        }
      }
    }
    return renderTarget;
  }
  createDanglingHandle() {
    return FrameGraphTextureManager._Counter++;
  }
  resolveDanglingHandle(danglingHandle, handle, newTextureName, creationOptions) {
    if (handle === undefined) {
      if (newTextureName === undefined || creationOptions === undefined) {
        throw new Error("resolveDanglingHandle: Either handle or newTextureName and creationOptions must be provided.");
      }
      this.createRenderTargetTexture(newTextureName, creationOptions, danglingHandle);
      return;
    }
    const textureEntry = this._textures.get(handle);
    if (textureEntry === undefined) {
      throw new Error(`resolveDanglingHandle: Handle ${handle} does not exist!`);
    }
    this._textures.set(danglingHandle, {
      texture: textureEntry.texture,
      refHandle: handle,
      name: textureEntry.name,
      creationOptions: {
        size: { ...textureEntry.creationOptions.size },
        options: FrameGraphTextureManager.CloneTextureOptions(textureEntry.creationOptions.options),
        sizeIsPercentage: textureEntry.creationOptions.sizeIsPercentage,
        isHistoryTexture: false
      },
      namespace: textureEntry.namespace,
      textureIndex: textureEntry.textureIndex
    });
  }
  getAbsoluteDimensions(size, screenWidth = this.engine.getRenderWidth(true), screenHeight = this.engine.getRenderHeight(true)) {
    const { width, height } = getDimensionsFromTextureSize(size);
    return {
      width: Math.floor(width * screenWidth / 100),
      height: Math.floor(height * screenHeight / 100)
    };
  }
  computeTotalTextureSize(optimizedSize, outputWidth, outputHeight) {
    let totalSize = 0;
    this._textures.forEach((entry, handle) => {
      if (handle === backbufferColorTextureHandle || handle === backbufferDepthStencilTextureHandle || entry.refHandle !== undefined) {
        return;
      }
      if (optimizedSize && entry.aliasHandle !== undefined) {
        return;
      }
      const options = entry.creationOptions;
      const textureIndex = entry.textureIndex || 0;
      const dimensions = options.sizeIsPercentage ? this.getAbsoluteDimensions(options.size, outputWidth, outputHeight) : getDimensionsFromTextureSize(options.size);
      const blockInfo = FrameGraphTextureManager._GetTextureBlockInformation(options.options.types?.[textureIndex] ?? 0, options.options.formats[textureIndex]);
      const textureByteSize = Math.ceil(dimensions.width / blockInfo.width) * Math.ceil(dimensions.height / blockInfo.height) * blockInfo.length;
      let byteSize = textureByteSize;
      if (options.options.createMipMaps) {
        byteSize = Math.floor(byteSize * 4 / 3);
      }
      if ((options.options.samples || 1) > 1) {
        byteSize += textureByteSize;
      }
      totalSize += byteSize;
    });
    return totalSize;
  }
  _dispose() {
    this._releaseTextures();
  }
  _allocateTextures(tasks) {
    if (tasks) {
      this._optimizeTextureAllocation(tasks);
    }
    this._textures.forEach((entry) => {
      if (!entry.texture) {
        if (entry.refHandle !== undefined) {
          const refEntry = this._textures.get(entry.refHandle);
          entry.texture = refEntry.texture;
          if (refEntry.refHandle === backbufferColorTextureHandle) {
            entry.refHandle = backbufferColorTextureHandle;
          }
          if (refEntry.refHandle === backbufferDepthStencilTextureHandle) {
            entry.refHandle = backbufferDepthStencilTextureHandle;
          }
        } else if (entry.namespace !== FrameGraphTextureNamespace.External) {
          if (entry.aliasHandle !== undefined) {
            const aliasEntry = this._textures.get(entry.aliasHandle);
            entry.texture = aliasEntry.texture;
            entry.texture.incrementReferences();
          } else {
            const creationOptions = entry.creationOptions;
            const size = creationOptions.sizeIsPercentage ? this.getAbsoluteDimensions(creationOptions.size) : creationOptions.size;
            const textureIndex = entry.textureIndex || 0;
            const internalTextureCreationOptions = {
              createMipMaps: creationOptions.options.createMipMaps,
              samples: creationOptions.options.samples,
              type: creationOptions.options.types?.[textureIndex],
              format: creationOptions.options.formats?.[textureIndex],
              useSRGBBuffer: creationOptions.options.useSRGBBuffers?.[textureIndex],
              creationFlags: creationOptions.options.creationFlags?.[textureIndex],
              label: creationOptions.options.labels?.[textureIndex] ?? `${entry.name}${textureIndex > 0 ? "#" + textureIndex : ""}`,
              samplingMode: 1,
              createMSAATexture: creationOptions.options.samples > 1
            };
            const isDepthTexture = IsDepthTexture(internalTextureCreationOptions.format);
            const hasStencil = HasStencilAspect(internalTextureCreationOptions.format);
            const source = isDepthTexture && hasStencil ? 12 : isDepthTexture || hasStencil ? 14 : 5;
            const internalTexture = this.engine._createInternalTexture(size, internalTextureCreationOptions, false, source);
            if (isDepthTexture) {
              internalTexture.type = GetTypeForDepthTexture(internalTexture.format);
            }
            entry.texture = internalTexture;
          }
        }
      }
      if (entry.texture && entry.refHandle === undefined) {
        entry.debug?.dispose();
        entry.debug = this._createDebugTexture(entry.name, entry.texture);
      }
    });
    this._historyTextures.forEach((entry) => {
      for (let i = 0;i < entry.handles.length; i++) {
        entry.textures[i] = this._textures.get(entry.handles[i]).texture;
      }
    });
  }
  _releaseTextures(releaseAll = true) {
    this._textures.forEach((entry, handle) => {
      if (entry.lifespan) {
        entry.lifespan.firstTask = Number.MAX_VALUE;
        entry.lifespan.lastTask = 0;
      }
      entry.aliasHandle = undefined;
      if (releaseAll || entry.namespace !== FrameGraphTextureNamespace.External) {
        entry.debug?.dispose();
        entry.debug = undefined;
      }
      if (entry.namespace === FrameGraphTextureNamespace.External) {
        return;
      }
      entry.texture?.dispose();
      entry.texture = null;
      if (releaseAll || entry.namespace === FrameGraphTextureNamespace.Task) {
        this._textures.delete(handle);
      }
    });
    this._historyTextures.forEach((entry) => {
      for (let i = 0;i < entry.handles.length; i++) {
        entry.textures[i] = null;
      }
    });
    if (releaseAll) {
      this._textures.clear();
      this._historyTextures.clear();
      this._addSystemTextures();
    }
  }
  _updateHistoryTextures() {
    this._historyTextures.forEach((entry) => {
      entry.index = entry.index ^ 1;
      const currentTexture = entry.textures[entry.index];
      if (currentTexture) {
        for (const { renderTargetWrapper: renderTargetWrapper2, textureIndex } of entry.references) {
          renderTargetWrapper2.setTexture(currentTexture, textureIndex, false);
        }
      }
    });
  }
  _addSystemTextures() {
    const size = { width: this.engine.getRenderWidth(true), height: this.engine.getRenderHeight(true) };
    this._textures.set(backbufferColorTextureHandle, {
      name: "backbuffer color",
      texture: null,
      creationOptions: {
        size,
        options: {
          createMipMaps: false,
          samples: this.engine.getCreationOptions().antialias ? 4 : 1,
          types: [0],
          formats: [5],
          useSRGBBuffers: [false],
          creationFlags: [0],
          labels: ["backbuffer color"]
        },
        sizeIsPercentage: false
      },
      namespace: FrameGraphTextureNamespace.External
    });
    this._textures.set(backbufferDepthStencilTextureHandle, {
      name: "backbuffer depth/stencil",
      texture: null,
      creationOptions: {
        size,
        options: {
          createMipMaps: false,
          samples: this.engine.getCreationOptions().antialias ? 4 : 1,
          types: [0],
          formats: [16],
          useSRGBBuffers: [false],
          creationFlags: [0],
          labels: ["backbuffer depth/stencil"]
        },
        sizeIsPercentage: false
      },
      namespace: FrameGraphTextureNamespace.External
    });
  }
  _createDebugTexture(name159, texture) {
    if (!this._debugTextures) {
      return;
    }
    const textureDebug = new Texture(null, this._scene);
    textureDebug.name = name159;
    textureDebug._texture = texture;
    textureDebug._texture.incrementReferences();
    return textureDebug;
  }
  _freeEntry(handle) {
    const entry = this._textures.get(handle);
    if (entry) {
      entry.debug?.dispose();
      this._textures.delete(handle);
    }
  }
  _createHandleForTexture(name159, texture, creationOptions, namespace, handle, textureIndex) {
    handle = handle ?? FrameGraphTextureManager._Counter++;
    textureIndex = textureIndex || 0;
    const textureName = creationOptions.isHistoryTexture ? `${name159} ping` : name159;
    let label = creationOptions.options.labels?.[textureIndex] ?? "";
    if (label === textureName) {
      label = "";
    }
    const textureEntry = {
      texture,
      name: `${textureName}${label ? " " + label : ""}`,
      creationOptions: {
        size: textureSizeIsObject(creationOptions.size) ? creationOptions.size : { width: creationOptions.size, height: creationOptions.size },
        options: creationOptions.options,
        sizeIsPercentage: creationOptions.sizeIsPercentage,
        isHistoryTexture: creationOptions.isHistoryTexture
      },
      namespace,
      textureIndex,
      textureDescriptionHash: this._createTextureDescriptionHash(creationOptions),
      lifespan: {
        firstTask: Number.MAX_VALUE,
        lastTask: 0
      }
    };
    this._textures.set(handle, textureEntry);
    if (namespace === FrameGraphTextureNamespace.External) {
      return handle;
    }
    if (creationOptions.isHistoryTexture) {
      const pongCreationOptions = {
        size: { ...textureEntry.creationOptions.size },
        options: { ...textureEntry.creationOptions.options },
        sizeIsPercentage: textureEntry.creationOptions.sizeIsPercentage,
        isHistoryTexture: false
      };
      const pongTexture = this._createHandleForTexture(`${name159} pong`, null, pongCreationOptions, namespace);
      this._historyTextures.set(handle, { textures: [null, null], handles: [handle, pongTexture], index: 0, references: [] });
      return handle;
    }
    if (creationOptions.options.types && creationOptions.options.types.length > 1 && textureIndex === 0) {
      const textureCount = creationOptions.options.types.length;
      const creationOptionsForTexture = {
        size: textureSizeIsObject(creationOptions.size) ? creationOptions.size : { width: creationOptions.size, height: creationOptions.size },
        options: creationOptions.options,
        sizeIsPercentage: creationOptions.sizeIsPercentage
      };
      for (let i = 1;i < textureCount; i++) {
        this._createHandleForTexture(textureName, null, creationOptionsForTexture, namespace, handle + i, i);
      }
      FrameGraphTextureManager._Counter += textureCount - 1;
    }
    return handle;
  }
  _createTextureDescriptionHash(options) {
    const hash2 = [];
    hash2.push(textureSizeIsObject(options.size) ? `${options.size.width}_${options.size.height}` : `${options.size}`);
    hash2.push(options.sizeIsPercentage ? "%" : "A");
    hash2.push(options.options.createMipMaps ? "M" : "N");
    hash2.push(options.options.samples ? `${options.options.samples}` : "S1");
    hash2.push(options.options.types ? options.options.types.join("_") : `${0}`);
    hash2.push(options.options.formats ? options.options.formats.join("_") : `${5}`);
    hash2.push(options.options.useSRGBBuffers ? options.options.useSRGBBuffers.join("_") : "false");
    hash2.push(options.options.creationFlags ? options.options.creationFlags.join("_") : "0");
    return hash2.join("_");
  }
  _optimizeTextureAllocation(tasks) {
    this._computeTextureLifespan(tasks);
    if (this.showDebugLogsForTextureAllcationOptimization) {
      Logger.Log(`================== Optimization of texture allocation ==================`);
    }
    const cache = new Map;
    const iterator = this._textures.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      const textureHandle = key.value;
      const textureEntry = this._textures.get(textureHandle);
      if (textureEntry.refHandle !== undefined || textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(textureHandle)) {
        continue;
      }
      const textureHash = textureEntry.textureDescriptionHash;
      const textureLifespan = textureEntry.lifespan;
      const cacheEntries = cache.get(textureHash);
      if (cacheEntries) {
        let cacheEntryFound = false;
        for (const cacheEntry of cacheEntries) {
          const [sourceHandle, lifespanArray] = cacheEntry;
          let overlapped = false;
          for (const lifespan of lifespanArray) {
            if (lifespan.firstTask <= textureLifespan.lastTask && lifespan.lastTask >= textureLifespan.firstTask) {
              overlapped = true;
              break;
            }
          }
          if (!overlapped) {
            if (this.showDebugLogsForTextureAllcationOptimization) {
              Logger.Log(`Texture ${textureHandle} (${textureEntry.name}) reuses cache entry ${sourceHandle}`);
            }
            lifespanArray.push(textureLifespan);
            textureEntry.aliasHandle = sourceHandle;
            cacheEntryFound = true;
            break;
          }
        }
        if (!cacheEntryFound) {
          cacheEntries.push([textureHandle, [textureLifespan]]);
        }
      } else {
        cache.set(textureHash, [[textureHandle, [textureLifespan]]]);
      }
    }
  }
  _computeTextureLifespan(tasks) {
    if (this.showDebugLogsForTextureAllcationOptimization) {
      Logger.Log(`================== Dump of texture dependencies for all tasks/passes ==================`);
    }
    for (let t = 0;t < tasks.length; ++t) {
      const task = tasks[t];
      if (task.passes.length > 0) {
        this._computeTextureLifespanForPasses(task, t, task.passes);
      }
      if (task.passesDisabled.length > 0) {
        this._computeTextureLifespanForPasses(task, t, task.passesDisabled);
      }
      if (task.dependencies) {
        if (this.showDebugLogsForTextureAllcationOptimization) {
          Logger.Log(`task#${t} (${task.name}), global dependencies`);
        }
        this._updateLifespan(t * 100 + 99, task.dependencies);
      }
    }
    if (this.showDebugLogsForTextureAllcationOptimization) {
      Logger.Log(`================== Texture lifespans ==================`);
      const iterator = this._textures.keys();
      for (let key = iterator.next();key.done !== true; key = iterator.next()) {
        const textureHandle = key.value;
        const textureEntry = this._textures.get(textureHandle);
        if (textureEntry.refHandle !== undefined || textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(textureHandle)) {
          continue;
        }
        Logger.Log(`${textureHandle} (${textureEntry.name}): ${textureEntry.lifespan.firstTask} - ${textureEntry.lifespan.lastTask}`);
      }
    }
  }
  _computeTextureLifespanForPasses(task, taskIndex, passes) {
    for (let p = 0;p < passes.length; ++p) {
      const dependencies = new Set;
      const pass = passes[p];
      if (!FrameGraphRenderPass.IsRenderPass(pass)) {
        continue;
      }
      pass.collectDependencies(dependencies);
      if (this.showDebugLogsForTextureAllcationOptimization) {
        Logger.Log(`task#${taskIndex} (${task.name}), pass#${p} (${pass.name})`);
      }
      this._updateLifespan(taskIndex * 100 + p, dependencies);
    }
  }
  _updateLifespan(passOrderNum, dependencies) {
    const iterator = dependencies.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      const textureHandle = key.value;
      let textureEntry = this._textures.get(textureHandle);
      if (!textureEntry) {
        throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${textureHandle}" not found in the texture manager.`);
      }
      let handle = textureHandle;
      while (textureEntry.refHandle !== undefined) {
        handle = textureEntry.refHandle;
        textureEntry = this._textures.get(handle);
        if (!textureEntry) {
          throw new Error(`FrameGraph._computeTextureLifespan: Texture handle "${handle}" not found in the texture manager (source handle="${textureHandle}").`);
        }
      }
      if (textureEntry.namespace === FrameGraphTextureNamespace.External || this._historyTextures.has(handle)) {
        continue;
      }
      if (this.showDebugLogsForTextureAllcationOptimization) {
        Logger.Log(`    ${handle} (${textureEntry.name})`);
      }
      textureEntry.lifespan.firstTask = Math.min(textureEntry.lifespan.firstTask, passOrderNum);
      textureEntry.lifespan.lastTask = Math.max(textureEntry.lifespan.lastTask, passOrderNum);
    }
  }
  static CloneTextureOptions(options, textureIndex, preserveLabels) {
    return textureIndex !== undefined ? {
      createMipMaps: options.createMipMaps,
      samples: options.samples,
      types: options.types ? [options.types[textureIndex]] : undefined,
      formats: options.formats ? [options.formats[textureIndex]] : undefined,
      useSRGBBuffers: options.useSRGBBuffers ? [options.useSRGBBuffers[textureIndex]] : undefined,
      creationFlags: options.creationFlags ? [options.creationFlags[textureIndex]] : undefined,
      labels: options.labels ? [options.labels[textureIndex]] : undefined
    } : {
      createMipMaps: options.createMipMaps,
      samples: options.samples,
      types: options.types ? [...options.types] : undefined,
      formats: options.formats ? [...options.formats] : undefined,
      useSRGBBuffers: options.useSRGBBuffers ? [...options.useSRGBBuffers] : undefined,
      creationFlags: options.creationFlags ? [...options.creationFlags] : undefined,
      labels: options.labels && preserveLabels ? [...options.labels] : undefined
    };
  }
  static _GetTextureBlockInformation(type, format) {
    switch (format) {
      case 15:
        return { width: 1, height: 1, length: 2 };
      case 16:
        return { width: 1, height: 1, length: 3 };
      case 13:
        return { width: 1, height: 1, length: 4 };
      case 14:
        return { width: 1, height: 1, length: 4 };
      case 18:
        return { width: 1, height: 1, length: 5 };
      case 19:
        return { width: 1, height: 1, length: 1 };
      case 36492:
        return { width: 4, height: 4, length: 16 };
      case 36495:
        return { width: 4, height: 4, length: 16 };
      case 36494:
        return { width: 4, height: 4, length: 16 };
      case 33779:
        return { width: 4, height: 4, length: 16 };
      case 33778:
        return { width: 4, height: 4, length: 16 };
      case 33777:
      case 33776:
        return { width: 4, height: 4, length: 8 };
      case 37808:
        return { width: 4, height: 4, length: 16 };
      case 36196:
      case 37492:
        return { width: 4, height: 4, length: 8 };
      case 37496:
        return { width: 4, height: 4, length: 16 };
    }
    switch (type) {
      case 3:
      case 0:
        switch (format) {
          case 6:
          case 8:
          case 0:
          case 1:
          case 2:
            return { width: 1, height: 1, length: 1 };
          case 7:
          case 9:
            return { width: 1, height: 1, length: 2 };
          case 4:
          case 10:
            return { width: 1, height: 1, length: 3 };
          case 11:
            return { width: 1, height: 1, length: 4 };
          default:
            return { width: 1, height: 1, length: 4 };
        }
      case 4:
      case 5:
        switch (format) {
          case 8:
            return { width: 1, height: 1, length: 2 };
          case 9:
            return { width: 1, height: 1, length: 4 };
          case 10:
            return { width: 1, height: 1, length: 6 };
          case 11:
            return { width: 1, height: 1, length: 8 };
          default:
            return { width: 1, height: 1, length: 8 };
        }
      case 6:
      case 7:
        switch (format) {
          case 8:
            return { width: 1, height: 1, length: 4 };
          case 9:
            return { width: 1, height: 1, length: 8 };
          case 10:
            return { width: 1, height: 1, length: 12 };
          case 11:
            return { width: 1, height: 1, length: 16 };
          default:
            return { width: 1, height: 1, length: 16 };
        }
      case 1:
        switch (format) {
          case 6:
            return { width: 1, height: 1, length: 4 };
          case 7:
            return { width: 1, height: 1, length: 8 };
          case 4:
            return { width: 1, height: 1, length: 12 };
          case 5:
            return { width: 1, height: 1, length: 16 };
          default:
            return { width: 1, height: 1, length: 16 };
        }
      case 2:
        switch (format) {
          case 6:
            return { width: 1, height: 1, length: 2 };
          case 7:
            return { width: 1, height: 1, length: 4 };
          case 4:
            return { width: 1, height: 1, length: 6 };
          case 5:
            return { width: 1, height: 1, length: 8 };
          default:
            return { width: 1, height: 1, length: 8 };
        }
      case 10:
        return { width: 1, height: 1, length: 2 };
      case 13:
        switch (format) {
          case 5:
          case 11:
            return { width: 1, height: 1, length: 4 };
          default:
            return { width: 1, height: 1, length: 4 };
        }
      case 14:
        switch (format) {
          case 5:
          case 11:
            return { width: 1, height: 1, length: 4 };
          default:
            return { width: 1, height: 1, length: 4 };
        }
      case 8:
        return { width: 1, height: 1, length: 2 };
      case 9:
        return { width: 1, height: 1, length: 2 };
      case 11:
        switch (format) {
          case 5:
            return { width: 1, height: 1, length: 4 };
          case 11:
            return { width: 1, height: 1, length: 4 };
          default:
            return { width: 1, height: 1, length: 4 };
        }
    }
    return { width: 1, height: 1, length: 4 };
  }
}
FrameGraphTextureManager._Counter = 2;

// node_modules/@babylonjs/core/FrameGraph/frameGraph.js
init_observable();
init_timingTools();
init_logger();
var FrameGraphPassType;
(function(FrameGraphPassType2) {
  FrameGraphPassType2[FrameGraphPassType2["Normal"] = 0] = "Normal";
  FrameGraphPassType2[FrameGraphPassType2["Render"] = 1] = "Render";
  FrameGraphPassType2[FrameGraphPassType2["Cull"] = 2] = "Cull";
})(FrameGraphPassType || (FrameGraphPassType = {}));

class FrameGraph {
  get engine() {
    return this._engine;
  }
  get scene() {
    return this._scene;
  }
  get tasks() {
    return this._tasks;
  }
  getLinkedNodeRenderGraph() {
    return this._linkedNodeRenderGraph;
  }
  constructor(scene, debugTextures = false, _linkedNodeRenderGraph = null) {
    this._linkedNodeRenderGraph = _linkedNodeRenderGraph;
    this._tasks = [];
    this._currentProcessedTask = null;
    this._whenReadyAsyncCancel = null;
    this.name = "Frame Graph";
    this.optimizeTextureAllocation = true;
    this.onBuildObservable = new Observable;
    this._scene = scene;
    this._engine = scene.getEngine();
    this.textureManager = new FrameGraphTextureManager(this._engine, debugTextures, scene);
    this._passContext = new FrameGraphContext;
    this._renderContext = new FrameGraphRenderContext(this._engine, this.textureManager, scene);
    this._scene.frameGraphs.push(this);
  }
  getClassName() {
    return "FrameGraph";
  }
  getTaskByName(name159) {
    return this._tasks.find((t) => t.name === name159);
  }
  addTask(task) {
    if (this._currentProcessedTask !== null) {
      throw new Error(`FrameGraph.addTask: Can't add the task "${task.name}" while another task is currently building (task: ${this._currentProcessedTask.name}).`);
    }
    this._tasks.push(task);
  }
  addPass(name159, whenTaskDisabled = false) {
    return this._addPass(name159, FrameGraphPassType.Normal, whenTaskDisabled);
  }
  addRenderPass(name159, whenTaskDisabled = false) {
    return this._addPass(name159, FrameGraphPassType.Render, whenTaskDisabled);
  }
  addCullPass(name159, whenTaskDisabled = false) {
    return this._addPass(name159, FrameGraphPassType.Cull, whenTaskDisabled);
  }
  _addPass(name159, passType, whenTaskDisabled = false) {
    if (!this._currentProcessedTask) {
      throw new Error("FrameGraph: A pass must be created during a Task.record execution only.");
    }
    let pass;
    switch (passType) {
      case FrameGraphPassType.Render:
        pass = new FrameGraphRenderPass(name159, this._currentProcessedTask, this._renderContext, this._engine);
        break;
      case FrameGraphPassType.Cull:
        pass = new FrameGraphCullPass(name159, this._currentProcessedTask, this._passContext, this._engine);
        break;
      default:
        pass = new FrameGraphPass(name159, this._currentProcessedTask, this._passContext);
        break;
    }
    this._currentProcessedTask._addPass(pass, whenTaskDisabled);
    return pass;
  }
  build() {
    this.textureManager._releaseTextures(false);
    try {
      for (const task of this._tasks) {
        task._reset();
        this._currentProcessedTask = task;
        this.textureManager._isRecordingTask = true;
        task.record();
        this.textureManager._isRecordingTask = false;
        this._currentProcessedTask = null;
      }
      this.textureManager._allocateTextures(this.optimizeTextureAllocation ? this._tasks : undefined);
      for (const task of this._tasks) {
        task._checkTask();
      }
      for (const task of this._tasks) {
        task.onTexturesAllocatedObservable.notifyObservers(this._renderContext);
      }
      this.onBuildObservable.notifyObservers(this);
    } catch (e) {
      this._tasks.length = 0;
      this._currentProcessedTask = null;
      this.textureManager._isRecordingTask = false;
      throw e;
    }
  }
  whenReadyAsync(timeStep = 16, maxTimeout = 30000) {
    let firstNotReadyTask = null;
    return new Promise((resolve3) => {
      this._whenReadyAsyncCancel = _retryWithInterval(() => {
        let ready = this._renderContext._isReady();
        for (const task of this._tasks) {
          const taskIsReady = task.isReady();
          if (!taskIsReady && !firstNotReadyTask) {
            firstNotReadyTask = task;
          }
          ready && (ready = taskIsReady);
        }
        return ready;
      }, () => {
        this._whenReadyAsyncCancel = null;
        resolve3();
      }, (err, isTimeout) => {
        this._whenReadyAsyncCancel = null;
        if (!isTimeout) {
          Logger.Error("FrameGraph: An unexpected error occurred while waiting for the frame graph to be ready.");
          if (err) {
            Logger.Error(err);
            if (err.stack) {
              Logger.Error(err.stack);
            }
          }
        } else {
          Logger.Error(`FrameGraph: Timeout while waiting for the frame graph to be ready.${firstNotReadyTask ? ` First task not ready: ${firstNotReadyTask.name}` : ""}`);
          if (err) {
            Logger.Error(err);
          }
        }
      }, timeStep, maxTimeout);
    });
  }
  execute() {
    this._renderContext.bindRenderTarget();
    this.textureManager._updateHistoryTextures();
    for (const task of this._tasks) {
      const passes = task._getPasses();
      for (const pass of passes) {
        pass._execute();
      }
    }
  }
  clear() {
    this._whenReadyAsyncCancel?.();
    this._whenReadyAsyncCancel = null;
    for (const task of this._tasks) {
      task._reset();
    }
    this._tasks.length = 0;
    this.textureManager._releaseTextures();
    this._currentProcessedTask = null;
  }
  dispose() {
    this._whenReadyAsyncCancel?.();
    this._whenReadyAsyncCancel = null;
    this.clear();
    this.textureManager._dispose();
    this._renderContext._dispose();
    const index = this._scene.frameGraphs.indexOf(this);
    if (index !== -1) {
      this._scene.frameGraphs.splice(index, 1);
    }
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraph.js
init_typeStore();
init_decorators();
init_decorators_serialization();
init_webRequest();

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/inputBlock.js
init_tslib_es6();
init_observable();
init_typeStore();

// node_modules/@babylonjs/core/Decorators/nodeDecorator.js
var PropertyTypeForEdition;
(function(PropertyTypeForEdition2) {
  PropertyTypeForEdition2[PropertyTypeForEdition2["Boolean"] = 0] = "Boolean";
  PropertyTypeForEdition2[PropertyTypeForEdition2["Float"] = 1] = "Float";
  PropertyTypeForEdition2[PropertyTypeForEdition2["Int"] = 2] = "Int";
  PropertyTypeForEdition2[PropertyTypeForEdition2["Vector2"] = 3] = "Vector2";
  PropertyTypeForEdition2[PropertyTypeForEdition2["List"] = 4] = "List";
  PropertyTypeForEdition2[PropertyTypeForEdition2["Color4"] = 5] = "Color4";
  PropertyTypeForEdition2[PropertyTypeForEdition2["SamplingMode"] = 6] = "SamplingMode";
  PropertyTypeForEdition2[PropertyTypeForEdition2["TextureFormat"] = 7] = "TextureFormat";
  PropertyTypeForEdition2[PropertyTypeForEdition2["TextureType"] = 8] = "TextureType";
})(PropertyTypeForEdition || (PropertyTypeForEdition = {}));
function editableInPropertyPage(displayName, propertyType = 0, groupName = "PROPERTIES", options) {
  return (target, propertyKey) => {
    let propStore = target._propStore;
    if (!propStore) {
      propStore = [];
      target._propStore = propStore;
    }
    propStore.push({
      propertyName: propertyKey,
      displayName,
      type: propertyType,
      groupName,
      options: options ?? {},
      className: target.getClassName()
    });
  };
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/inputBlock.js
class NodeRenderGraphInputBlock extends NodeRenderGraphBlock {
  get type() {
    return this._type;
  }
  constructor(name159, frameGraph, scene, type = NodeRenderGraphBlockConnectionPointTypes.Undefined) {
    super(name159, frameGraph, scene);
    this._storedValue = null;
    this._type = NodeRenderGraphBlockConnectionPointTypes.Undefined;
    this.onValueChangedObservable = new Observable;
    this.isExternal = false;
    this._type = type;
    this._isInput = true;
    this.registerOutput("output", type);
    this.setDefaultValue();
  }
  setDefaultValue() {
    switch (this.type) {
      case NodeRenderGraphBlockConnectionPointTypes.Texture:
      case NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth:
      case NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth:
      case NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal:
      case NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal:
      case NodeRenderGraphBlockConnectionPointTypes.TextureAlbedo:
      case NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity:
      case NodeRenderGraphBlockConnectionPointTypes.TextureLocalPosition:
      case NodeRenderGraphBlockConnectionPointTypes.TextureWorldPosition:
      case NodeRenderGraphBlockConnectionPointTypes.TextureVelocity:
      case NodeRenderGraphBlockConnectionPointTypes.TextureLinearVelocity:
      case NodeRenderGraphBlockConnectionPointTypes.TextureIrradiance:
      case NodeRenderGraphBlockConnectionPointTypes.TextureAlbedoSqrt: {
        const options = {
          size: { width: 100, height: 100 },
          options: {
            createMipMaps: false,
            types: [0],
            formats: [5],
            samples: 1,
            useSRGBBuffers: [false]
          },
          sizeIsPercentage: true
        };
        this.creationOptions = options;
        break;
      }
      case NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment: {
        const options = {
          size: { width: 100, height: 100 },
          options: {
            createMipMaps: false,
            types: [0],
            formats: [13],
            useSRGBBuffers: [false],
            labels: [this.name],
            samples: 1
          },
          sizeIsPercentage: true
        };
        this.creationOptions = options;
        break;
      }
      case NodeRenderGraphBlockConnectionPointTypes.ObjectList:
        this.value = { meshes: [], particleSystems: [] };
        this.isExternal = true;
        break;
      case NodeRenderGraphBlockConnectionPointTypes.Camera:
        this.value = this._scene.cameras[0];
        this.isExternal = true;
        break;
      default:
        this.isExternal = true;
    }
  }
  get value() {
    return this._storedValue;
  }
  set value(value) {
    this._storedValue = value;
    this.output.value = undefined;
    this.onValueChangedObservable.notifyObservers(this);
  }
  getTypedValue() {
    return this._storedValue;
  }
  getInternalTextureFromValue() {
    if (this._storedValue._swapAndDie) {
      return this._storedValue;
    }
    return null;
  }
  getClassName() {
    return "NodeRenderGraphInputBlock";
  }
  get output() {
    return this._outputs[0];
  }
  isAnyTexture() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureAll) !== 0;
  }
  isBackBuffer() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureBackBuffer) !== 0;
  }
  isBackBufferDepthStencilAttachment() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment) !== 0;
  }
  isCamera() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.Camera) !== 0;
  }
  isObjectList() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.ObjectList) !== 0;
  }
  isShadowLight() {
    return (this.type & NodeRenderGraphBlockConnectionPointTypes.ShadowLight) !== 0;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.isExternal) {
      if (this.isBackBuffer()) {
        this.output.value = backbufferColorTextureHandle;
      } else if (this.isBackBufferDepthStencilAttachment()) {
        this.output.value = backbufferDepthStencilTextureHandle;
      } else if (this.isCamera()) {
        this.output.value = this.getTypedValue();
      } else if (this.isObjectList()) {
        this.output.value = this.getTypedValue();
      } else if (this.isShadowLight()) {
        this.output.value = this.getTypedValue();
      } else {
        if (this._storedValue === undefined || this._storedValue === null) {
          throw new Error(`NodeRenderGraphInputBlock: External input "${this.name}" is not set`);
        }
        const texture = this.getInternalTextureFromValue();
        if (texture) {
          this.output.value = this._frameGraph.textureManager.importTexture(this.name, texture, this.output.value);
        }
      }
      return;
    }
    if ((this.type & NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer) !== 0) {
      const textureCreateOptions = this.creationOptions;
      if (!textureCreateOptions) {
        throw new Error(`NodeRenderGraphInputBlock: Creation options are missing for texture "${this.name}"`);
      }
      this.output.value = this._frameGraph.textureManager.createRenderTargetTexture(this.name, textureCreateOptions);
    }
  }
  dispose() {
    this._storedValue = null;
    this.onValueChangedObservable.clear();
    super.dispose();
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.isExternal = ${this.isExternal};`);
    if (this.isAnyTexture()) {
      if (!this.isExternal) {
        codes.push(`${this._codeVariableName}.creationOptions = ${JSON.stringify(this.creationOptions)};`);
      } else {
        codes.push(`${this._codeVariableName}.value = EXTERNAL_TEXTURE; // TODO: set the external texture`);
      }
    } else if (this.isCamera()) {
      codes.push(`${this._codeVariableName}.value = EXTERNAL_CAMERA; // TODO: set the external camera`);
    } else if (this.isObjectList()) {
      codes.push(`${this._codeVariableName}.value = EXTERNAL_OBJECT_LIST; // TODO: set the external object list`);
    } else if (this.isShadowLight()) {
      codes.push(`${this._codeVariableName}.value = EXTERNAL_SHADOW_LIGHT; // TODO: set the external shadow light`);
    }
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.type = this.type;
    serializationObject.isExternal = this.isExternal;
    if (this.creationOptions) {
      serializationObject.creationOptions = this.creationOptions;
    }
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this._type = serializationObject.type;
    this.output.type = this._type;
    this.isExternal = serializationObject.isExternal;
    if (serializationObject.creationOptions) {
      if (serializationObject.creationOptions.options.depthTextureFormat !== undefined) {
        serializationObject.creationOptions.options.formats = [serializationObject.creationOptions.options.depthTextureFormat];
      }
      this.creationOptions = serializationObject.creationOptions;
    }
  }
}
__decorate([
  editableInPropertyPage("Is external", 0, "PROPERTIES")
], NodeRenderGraphInputBlock.prototype, "isExternal", undefined);
RegisterClass("BABYLON.NodeRenderGraphInputBlock", NodeRenderGraphInputBlock);

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraph.js
init_tools();
init_engine();

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/clearBlock.js
init_tslib_es6();
init_typeStore();
init_math_color();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Texture/clearTextureTask.js
init_math_color();
class FrameGraphClearTextureTask extends FrameGraphTask {
  constructor(name159, frameGraph) {
    super(name159, frameGraph);
    this.color = new Color4(0.2, 0.2, 0.3, 1);
    this.clearColor = true;
    this.convertColorToLinearSpace = false;
    this.clearDepth = false;
    this.clearStencil = false;
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  record() {
    if (this.targetTexture === undefined && this.depthTexture === undefined) {
      throw new Error(`FrameGraphClearTextureTask ${this.name}: targetTexture and depthTexture can't both be undefined.`);
    }
    let textureSamples = 0;
    let depthSamples = 0;
    if (this.targetTexture !== undefined) {
      textureSamples = this._frameGraph.textureManager.getTextureDescription(this.targetTexture).options.samples || 1;
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    }
    if (this.depthTexture !== undefined) {
      depthSamples = this._frameGraph.textureManager.getTextureDescription(this.depthTexture).options.samples || 1;
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture);
    }
    if (textureSamples !== depthSamples && textureSamples !== 0 && depthSamples !== 0) {
      throw new Error(`FrameGraphClearTextureTask ${this.name}: the depth texture and the target texture must have the same number of samples.`);
    }
    const color = TmpColors.Color4[0];
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(this.targetTexture);
    pass.setRenderTargetDepth(this.depthTexture);
    pass.setExecuteFunc((context) => {
      color.copyFrom(this.color);
      if (this.convertColorToLinearSpace) {
        color.toLinearSpaceToRef(color);
      }
      context.clear(color, !!this.clearColor, !!this.clearDepth, !!this.clearStencil);
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.targetTexture);
    passDisabled.setRenderTargetDepth(this.depthTexture);
    passDisabled.setExecuteFunc((_context) => {});
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/clearBlock.js
class NodeRenderGraphClearBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name159, frameGraph, scene) {
    super(name159, frameGraph, scene);
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll);
    this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment);
    this.output._typeConnectionSource = this.target;
    this.outputDepth._typeConnectionSource = this.depth;
    this._frameGraphTask = new FrameGraphClearTextureTask(name159, frameGraph);
  }
  get color() {
    return this._frameGraphTask.color;
  }
  set color(value) {
    this._frameGraphTask.color = value;
  }
  get clearColor() {
    return !!this._frameGraphTask.clearColor;
  }
  set clearColor(value) {
    this._frameGraphTask.clearColor = value;
  }
  get convertColorToLinearSpace() {
    return !!this._frameGraphTask.convertColorToLinearSpace;
  }
  set convertColorToLinearSpace(value) {
    this._frameGraphTask.convertColorToLinearSpace = value;
  }
  get clearDepth() {
    return !!this._frameGraphTask.clearDepth;
  }
  set clearDepth(value) {
    this._frameGraphTask.clearDepth = value;
  }
  get clearStencil() {
    return !!this._frameGraphTask.clearStencil;
  }
  set clearStencil(value) {
    this._frameGraphTask.clearStencil = value;
  }
  getClassName() {
    return "NodeRenderGraphClearBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get depth() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  get outputDepth() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._propagateInputValueToOutput(this.target, this.output);
    this._propagateInputValueToOutput(this.depth, this.outputDepth);
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
    this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.color = new BABYLON.Color4(${this.color.r}, ${this.color.g}, ${this.color.b}, ${this.color.a});`);
    codes.push(`${this._codeVariableName}.clearColor = ${this.clearColor};`);
    codes.push(`${this._codeVariableName}.convertColorToLinearSpace = ${this.convertColorToLinearSpace};`);
    codes.push(`${this._codeVariableName}.clearDepth = ${this.clearDepth};`);
    codes.push(`${this._codeVariableName}.clearStencil = ${this.clearStencil};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.color = this.color.asArray();
    serializationObject.clearColor = this.clearColor;
    serializationObject.convertColorToLinearSpace = this.convertColorToLinearSpace;
    serializationObject.clearDepth = this.clearDepth;
    serializationObject.clearStencil = this.clearStencil;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.color = Color4.FromArray(serializationObject.color);
    this.clearColor = serializationObject.clearColor;
    this.convertColorToLinearSpace = !!serializationObject.convertColorToLinearSpace;
    this.clearDepth = serializationObject.clearDepth;
    this.clearStencil = serializationObject.clearStencil;
  }
}
__decorate([
  editableInPropertyPage("Color", 5)
], NodeRenderGraphClearBlock.prototype, "color", null);
__decorate([
  editableInPropertyPage("Clear color", 0, undefined, { embedded: true })
], NodeRenderGraphClearBlock.prototype, "clearColor", null);
__decorate([
  editableInPropertyPage("Convert color to linear space", 0)
], NodeRenderGraphClearBlock.prototype, "convertColorToLinearSpace", null);
__decorate([
  editableInPropertyPage("Clear depth", 0, undefined, { embedded: true })
], NodeRenderGraphClearBlock.prototype, "clearDepth", null);
__decorate([
  editableInPropertyPage("Clear stencil", 0, undefined, { embedded: true })
], NodeRenderGraphClearBlock.prototype, "clearStencil", null);
RegisterClass("BABYLON.NodeRenderGraphClearBlock", NodeRenderGraphClearBlock);

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/objectRendererBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js
init_objectRenderer();

// node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js
init_math_vector();
init_renderTargetTexture();
init_devTools();

// node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js
init_math_vector();
init_math_color();
init_buffer();
init_texture();
init_renderTargetTexture();
init_postProcess();

// node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js
init_tslib_es6();
init_postProcess();
init_texture();
init_typeStore();
init_decorators();
init_decorators_serialization();

// node_modules/@babylonjs/core/PostProcesses/thinBlurPostProcess.js
init_effectRenderer();
init_engine();

class ThinBlurPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment(), exports_kernelBlur_fragment)), Promise.resolve().then(() => (init_kernelBlur_vertex(), exports_kernelBlur_vertex))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment2(), exports_kernelBlur_fragment2)), Promise.resolve().then(() => (init_kernelBlur_vertex2(), exports_kernelBlur_vertex2))]));
    }
  }
  constructor(name173, engine2 = null, direction, kernel, options) {
    const blockCompilationFinal = !!options?.blockCompilation;
    super({
      ...options,
      name: name173,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinBlurPostProcess.FragmentUrl,
      uniforms: ThinBlurPostProcess.Uniforms,
      samplers: ThinBlurPostProcess.Samplers,
      vertexUrl: ThinBlurPostProcess.VertexUrl,
      blockCompilation: true
    });
    this._packedFloat = false;
    this._staticDefines = "";
    this.textureWidth = 0;
    this.textureHeight = 0;
    this.options.blockCompilation = blockCompilationFinal;
    if (direction !== undefined) {
      this.direction = direction;
    }
    if (kernel !== undefined) {
      this.kernel = kernel;
    }
  }
  set kernel(v) {
    if (this._idealKernel === v) {
      return;
    }
    v = Math.max(v, 1);
    this._idealKernel = v;
    this._kernel = this._nearestBestKernel(v);
    if (!this.options.blockCompilation) {
      this._updateParameters();
    }
  }
  get kernel() {
    return this._idealKernel;
  }
  set packedFloat(v) {
    if (this._packedFloat === v) {
      return;
    }
    this._packedFloat = v;
    if (!this.options.blockCompilation) {
      this._updateParameters();
    }
  }
  get packedFloat() {
    return this._packedFloat;
  }
  bind() {
    super.bind();
    this._drawWrapper.effect.setFloat2("delta", 1 / this.textureWidth * this.direction.x, 1 / this.textureHeight * this.direction.y);
  }
  _updateParameters(onCompiled, onError) {
    const N = this._kernel;
    const centerIndex = (N - 1) / 2;
    let offsets = [];
    let weights = [];
    let totalWeight = 0;
    for (let i = 0;i < N; i++) {
      const u = i / (N - 1);
      const w = this._gaussianWeight(u * 2 - 1);
      offsets[i] = i - centerIndex;
      weights[i] = w;
      totalWeight += w;
    }
    for (let i = 0;i < weights.length; i++) {
      weights[i] /= totalWeight;
    }
    const linearSamplingWeights = [];
    const linearSamplingOffsets = [];
    const linearSamplingMap = [];
    for (let i = 0;i <= centerIndex; i += 2) {
      const j = Math.min(i + 1, Math.floor(centerIndex));
      const singleCenterSample = i === j;
      if (singleCenterSample) {
        linearSamplingMap.push({ o: offsets[i], w: weights[i] });
      } else {
        const sharedCell = j === centerIndex;
        const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1);
        const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
        if (offsetLinear === 0) {
          linearSamplingMap.push({ o: offsets[i], w: weights[i] });
          linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
        } else {
          linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
          linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
        }
      }
    }
    for (let i = 0;i < linearSamplingMap.length; i++) {
      linearSamplingOffsets[i] = linearSamplingMap[i].o;
      linearSamplingWeights[i] = linearSamplingMap[i].w;
    }
    offsets = linearSamplingOffsets;
    weights = linearSamplingWeights;
    const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 ? 1 : 0);
    const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1;
    let varyingCount = Math.min(offsets.length, freeVaryingVec2);
    let defines = "";
    defines += this._staticDefines;
    if (this._staticDefines.indexOf("DOF") != -1) {
      defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}
`;
      varyingCount--;
    }
    for (let i = 0;i < varyingCount; i++) {
      defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}
`;
      defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}
`;
    }
    let depCount = 0;
    for (let i = freeVaryingVec2;i < offsets.length; i++) {
      defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}
`;
      defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}
`;
      depCount++;
    }
    if (this.packedFloat) {
      defines += `#define PACKEDFLOAT 1`;
    }
    this.options.blockCompilation = false;
    this.updateEffect(defines, null, null, {
      varyingCount,
      depCount
    }, onCompiled, onError);
  }
  _nearestBestKernel(idealKernel) {
    const v = Math.round(idealKernel);
    for (const k of [v, v - 1, v + 1, v - 2, v + 2]) {
      if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) {
        return Math.max(k, 3);
      }
    }
    return Math.max(v, 3);
  }
  _gaussianWeight(x) {
    const sigma = 1 / 3;
    const denominator = Math.sqrt(2 * Math.PI) * sigma;
    const exponent = -(x * x / (2 * sigma * sigma));
    const weight = 1 / denominator * Math.exp(exponent);
    return weight;
  }
  _glslFloat(x, decimalFigures = 8) {
    return x.toFixed(decimalFigures).replace(/0+$/, "");
  }
}
ThinBlurPostProcess.VertexUrl = "kernelBlur";
ThinBlurPostProcess.FragmentUrl = "kernelBlur";
ThinBlurPostProcess.Uniforms = ["delta", "direction"];
ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"];

// node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js
class BlurPostProcess extends PostProcess {
  get direction() {
    return this._effectWrapper.direction;
  }
  set direction(value) {
    this._effectWrapper.direction = value;
  }
  set kernel(v) {
    this._effectWrapper.kernel = v;
  }
  get kernel() {
    return this._effectWrapper.kernel;
  }
  set packedFloat(v) {
    this._effectWrapper.packedFloat = v;
  }
  get packedFloat() {
    return this._effectWrapper.packedFloat;
  }
  getClassName() {
    return "BlurPostProcess";
  }
  constructor(name173, direction, kernel, options, camera2 = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine2, reusable, textureType = 0, defines = "", blockCompilation = false, textureFormat = 5) {
    const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation;
    const localOptions = {
      uniforms: ThinBlurPostProcess.Uniforms,
      samplers: ThinBlurPostProcess.Samplers,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      vertexUrl: ThinBlurPostProcess.VertexUrl,
      indexParameters: { varyingCount: 0, depCount: 0 },
      textureFormat,
      defines,
      ...options,
      blockCompilation: true
    };
    super(name173, ThinBlurPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name173, engine2, undefined, undefined, localOptions) : undefined,
      ...localOptions
    });
    this._effectWrapper.options.blockCompilation = blockCompilationFinal;
    this.direction = direction;
    this.onApplyObservable.add(() => {
      this._effectWrapper.textureWidth = this._outputTexture ? this._outputTexture.width : this.width;
      this._effectWrapper.textureHeight = this._outputTexture ? this._outputTexture.height : this.height;
    });
    this.kernel = kernel;
  }
  updateEffect(_defines = null, _uniforms = null, _samplers = null, _indexParameters, onCompiled, onError) {
    this._effectWrapper._updateParameters(onCompiled, onError);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, undefined, false);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serializeAsVector2()
], BlurPostProcess.prototype, "direction", null);
__decorate([
  serialize()
], BlurPostProcess.prototype, "kernel", null);
__decorate([
  serialize()
], BlurPostProcess.prototype, "packedFloat", null);
RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess);

// node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js
init_observable();
init_devTools();
init_renderingManager();
init_drawWrapper();
init_materialHelper_functions();

class ShadowGenerator {
  get bias() {
    return this._bias;
  }
  set bias(bias) {
    this._bias = bias;
  }
  get normalBias() {
    return this._normalBias;
  }
  set normalBias(normalBias) {
    this._normalBias = normalBias;
  }
  get blurBoxOffset() {
    return this._blurBoxOffset;
  }
  set blurBoxOffset(value) {
    if (this._blurBoxOffset === value) {
      return;
    }
    this._blurBoxOffset = value;
    this._disposeBlurPostProcesses();
  }
  get blurScale() {
    return this._blurScale;
  }
  set blurScale(value) {
    if (this._blurScale === value) {
      return;
    }
    this._blurScale = value;
    this._disposeBlurPostProcesses();
  }
  get blurKernel() {
    return this._blurKernel;
  }
  set blurKernel(value) {
    if (this._blurKernel === value) {
      return;
    }
    this._blurKernel = value;
    this._disposeBlurPostProcesses();
  }
  get useKernelBlur() {
    return this._useKernelBlur;
  }
  set useKernelBlur(value) {
    if (this._useKernelBlur === value) {
      return;
    }
    this._useKernelBlur = value;
    this._disposeBlurPostProcesses();
  }
  get depthScale() {
    return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  }
  set depthScale(value) {
    this._depthScale = value;
  }
  _validateFilter(filter) {
    return filter;
  }
  get filter() {
    return this._filter;
  }
  set filter(value) {
    value = this._validateFilter(value);
    if (this._light.needCube()) {
      if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
        this.useExponentialShadowMap = true;
        return;
      } else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
        this.useCloseExponentialShadowMap = true;
        return;
      } else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
        this.usePoissonSampling = true;
        return;
      }
    }
    if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
      if (!this._scene.getEngine()._features.supportShadowSamplers) {
        this.usePoissonSampling = true;
        return;
      }
    }
    if (this._filter === value) {
      return;
    }
    this._filter = value;
    this._disposeBlurPostProcesses();
    this._applyFilterValues();
    this._light._markMeshesAsLightDirty();
  }
  get usePoissonSampling() {
    return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  }
  set usePoissonSampling(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);
    if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get useExponentialShadowMap() {
    return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  }
  set useExponentialShadowMap(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);
    if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get useBlurExponentialShadowMap() {
    return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  }
  set useBlurExponentialShadowMap(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);
    if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get useCloseExponentialShadowMap() {
    return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  }
  set useCloseExponentialShadowMap(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);
    if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get useBlurCloseExponentialShadowMap() {
    return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  }
  set useBlurCloseExponentialShadowMap(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
    if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get usePercentageCloserFiltering() {
    return this.filter === ShadowGenerator.FILTER_PCF;
  }
  set usePercentageCloserFiltering(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_PCF);
    if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get filteringQuality() {
    return this._filteringQuality;
  }
  set filteringQuality(filteringQuality) {
    if (this._filteringQuality === filteringQuality) {
      return;
    }
    this._filteringQuality = filteringQuality;
    this._disposeBlurPostProcesses();
    this._applyFilterValues();
    this._light._markMeshesAsLightDirty();
  }
  get useContactHardeningShadow() {
    return this.filter === ShadowGenerator.FILTER_PCSS;
  }
  set useContactHardeningShadow(value) {
    const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);
    if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
      return;
    }
    this.filter = value ? filter : ShadowGenerator.FILTER_NONE;
  }
  get contactHardeningLightSizeUVRatio() {
    return this._contactHardeningLightSizeUVRatio;
  }
  set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) {
    this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  }
  get darkness() {
    return this._darkness;
  }
  set darkness(value) {
    this.setDarkness(value);
  }
  getDarkness() {
    return this._darkness;
  }
  setDarkness(darkness) {
    if (darkness >= 1) {
      this._darkness = 1;
    } else if (darkness <= 0) {
      this._darkness = 0;
    } else {
      this._darkness = darkness;
    }
    return this;
  }
  get transparencyShadow() {
    return this._transparencyShadow;
  }
  set transparencyShadow(value) {
    this.setTransparencyShadow(value);
  }
  setTransparencyShadow(transparent) {
    this._transparencyShadow = transparent;
    return this;
  }
  getShadowMap() {
    return this._shadowMap;
  }
  getShadowMapForRendering() {
    if (this._shadowMap2) {
      return this._shadowMap2;
    }
    return this._shadowMap;
  }
  getClassName() {
    return ShadowGenerator.CLASSNAME;
  }
  addShadowCaster(mesh, includeDescendants = true) {
    if (!this._shadowMap) {
      return this;
    }
    if (!this._shadowMap.renderList) {
      this._shadowMap.renderList = [];
    }
    if (this._shadowMap.renderList.indexOf(mesh) === -1) {
      this._shadowMap.renderList.push(mesh);
    }
    if (includeDescendants) {
      for (const childMesh of mesh.getChildMeshes()) {
        if (this._shadowMap.renderList.indexOf(childMesh) === -1) {
          this._shadowMap.renderList.push(childMesh);
        }
      }
    }
    return this;
  }
  removeShadowCaster(mesh, includeDescendants = true) {
    if (!this._shadowMap || !this._shadowMap.renderList) {
      return this;
    }
    const index = this._shadowMap.renderList.indexOf(mesh);
    if (index !== -1) {
      this._shadowMap.renderList.splice(index, 1);
    }
    if (includeDescendants) {
      for (const child of mesh.getChildren()) {
        this.removeShadowCaster(child);
      }
    }
    return this;
  }
  getLight() {
    return this._light;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  _getCamera() {
    return this._camera ?? this._scene.activeCamera;
  }
  get mapSize() {
    return this._mapSize;
  }
  set mapSize(size) {
    this._mapSize = size;
    this._light._markMeshesAsLightDirty();
    this.recreateShadowMap();
  }
  constructor(mapSize, light, usefullFloatFirst, camera2, useRedTextureType, forceGLSL = false) {
    this.onBeforeShadowMapRenderObservable = new Observable;
    this.onAfterShadowMapRenderObservable = new Observable;
    this.onBeforeShadowMapRenderMeshObservable = new Observable;
    this.onAfterShadowMapRenderMeshObservable = new Observable;
    this.doNotSerialize = false;
    this._bias = 0.00005;
    this._normalBias = 0;
    this._blurBoxOffset = 1;
    this._blurScale = 2;
    this._blurKernel = 1;
    this._useKernelBlur = false;
    this._filter = ShadowGenerator.FILTER_NONE;
    this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
    this._contactHardeningLightSizeUVRatio = 0.1;
    this._darkness = 0;
    this._transparencyShadow = false;
    this.enableSoftTransparentShadow = false;
    this.useOpacityTextureForTransparentShadow = false;
    this.frustumEdgeFalloff = 0;
    this._shaderLanguage = 0;
    this.forceBackFacesOnly = false;
    this._lightDirection = Vector3.Zero();
    this._viewMatrix = Matrix.Zero();
    this._projectionMatrix = Matrix.Zero();
    this._transformMatrix = Matrix.Zero();
    this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._currentFaceIndex = 0;
    this._currentFaceIndexCache = 0;
    this._defaultTextureMatrix = Matrix.Identity();
    this._shadersLoaded = false;
    this._mapSize = mapSize;
    this._light = light;
    this._scene = light.getScene();
    this._camera = camera2 ?? null;
    this._useRedTextureType = !!useRedTextureType;
    this._initShaderSourceAsync(forceGLSL);
    let shadowGenerators = light._shadowGenerators;
    if (!shadowGenerators) {
      shadowGenerators = light._shadowGenerators = new Map;
    }
    shadowGenerators.set(this._camera, this);
    this.id = light.id;
    this._useUBO = this._scene.getEngine().supportsUniformBuffers;
    if (this._useUBO) {
      this._sceneUBOs = [];
      this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`));
    }
    ShadowGenerator._SceneComponentInitialization(this._scene);
    const caps = this._scene.getEngine().getCaps();
    if (!usefullFloatFirst) {
      if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
        this._textureType = 2;
      } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
        this._textureType = 1;
      } else {
        this._textureType = 0;
      }
    } else {
      if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
        this._textureType = 1;
      } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
        this._textureType = 2;
      } else {
        this._textureType = 0;
      }
    }
    this._initializeGenerator();
    this._applyFilterValues();
  }
  _initializeGenerator() {
    this._light._markMeshesAsLightDirty();
    this._initializeShadowMap();
  }
  _createTargetRenderTexture() {
    const engine2 = this._scene.getEngine();
    if (engine2._features.supportDepthStencilTexture) {
      this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false, undefined, this._useRedTextureType ? 6 : 5);
      this._shadowMap.createDepthStencilTexture(engine2.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForShadowGenerator-${this._light.name}`);
    } else {
      this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
    }
    this._shadowMap.noPrePassRenderer = true;
  }
  _initializeShadowMap() {
    this._createTargetRenderTexture();
    if (this._shadowMap === null) {
      return;
    }
    this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._shadowMap.anisotropicFilteringLevel = 1;
    this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    this._shadowMap.renderParticles = false;
    this._shadowMap.ignoreCameraViewport = true;
    if (this._storedUniqueId) {
      this._shadowMap.uniqueId = this._storedUniqueId;
    }
    this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes);
    this._shadowMap.customIsReadyFunction = (mesh, _refreshRate, preWarm) => {
      if (!preWarm || !mesh.subMeshes) {
        return true;
      }
      let isReady = true;
      for (const subMesh of mesh.subMeshes) {
        const renderingMesh = subMesh.getRenderingMesh();
        const scene = this._scene;
        const engine3 = scene.getEngine();
        const material = subMesh.getMaterial();
        if (!material || subMesh.verticesCount === 0 || this.customAllowRendering && !this.customAllowRendering(subMesh)) {
          continue;
        }
        const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
        if (batch.mustReturn) {
          continue;
        }
        const hardwareInstancedRendering = engine3.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined || renderingMesh.hasThinInstances);
        const isTransparent = material.needAlphaBlendingForMesh(renderingMesh);
        isReady = this.isReady(subMesh, hardwareInstancedRendering, isTransparent) && isReady;
      }
      return isReady;
    };
    const engine2 = this._scene.getEngine();
    this._shadowMap.onBeforeBindObservable.add(() => {
      this._currentSceneUBO = this._scene.getSceneUniformBuffer();
      engine2._debugPushGroup?.(`shadow map generation for pass id ${engine2.currentRenderPassId}`, 1);
    });
    this._shadowMap.onBeforeRenderObservable.add((faceIndex) => {
      if (this._sceneUBOs) {
        this._scene.setSceneUniformBuffer(this._sceneUBOs[0]);
      }
      this._currentFaceIndex = faceIndex;
      if (this._filter === ShadowGenerator.FILTER_PCF) {
        engine2.setColorWrite(false);
      }
      this.getTransformMatrix();
      this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);
      if (this._useUBO) {
        this._scene.getSceneUniformBuffer().unbindEffect();
        this._scene.finalizeSceneUbo();
      }
    });
    this._shadowMap.onAfterUnbindObservable.add(() => {
      if (this._sceneUBOs) {
        this._scene.setSceneUniformBuffer(this._currentSceneUBO);
      }
      this._scene.updateTransformMatrix();
      if (this._filter === ShadowGenerator.FILTER_PCF) {
        engine2.setColorWrite(true);
      }
      if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {
        engine2._debugPopGroup?.(1);
        return;
      }
      const shadowMap = this.getShadowMapForRendering();
      if (shadowMap) {
        this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true);
        engine2.unBindFramebuffer(shadowMap.renderTarget, true);
      }
      engine2._debugPopGroup?.(1);
    });
    const clearZero = new Color4(0, 0, 0, 0);
    const clearOne = new Color4(1, 1, 1, 1);
    this._shadowMap.onClearObservable.add((engine3) => {
      if (this._filter === ShadowGenerator.FILTER_PCF) {
        engine3.clear(clearOne, false, true, false);
      } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
        engine3.clear(clearZero, true, true, false);
      } else {
        engine3.clear(clearOne, true, true, false);
      }
    });
    this._shadowMap.onResizeObservable.add((rtt) => {
      this._storedUniqueId = this._shadowMap.uniqueId;
      this._mapSize = rtt.getRenderSize();
      this._light._markMeshesAsLightDirty();
      this.recreateShadowMap();
    });
    for (let i = RenderingManager.MIN_RENDERINGGROUPS;i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
      this._shadowMap.setRenderingAutoClearDepthStencil(i, false);
    }
  }
  async _initShaderSourceAsync(forceGLSL = false) {
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !forceGLSL && !ShadowGenerator.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([
        Promise.resolve().then(() => (init_shadowMap_fragment(), exports_shadowMap_fragment)),
        Promise.resolve().then(() => (init_shadowMap_vertex(), exports_shadowMap_vertex)),
        Promise.resolve().then(() => (init_depthBoxBlur_fragment(), exports_depthBoxBlur_fragment)),
        Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow(), exports_shadowMapFragmentSoftTransparentShadow))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_shadowMap_fragment2(), exports_shadowMap_fragment2)),
        Promise.resolve().then(() => (init_shadowMap_vertex2(), exports_shadowMap_vertex2)),
        Promise.resolve().then(() => (init_depthBoxBlur_fragment2(), exports_depthBoxBlur_fragment2)),
        Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow2(), exports_shadowMapFragmentSoftTransparentShadow2))
      ]);
    }
    this._shadersLoaded = true;
  }
  _initializeBlurRTTAndPostProcesses() {
    const engine2 = this._scene.getEngine();
    const targetSize = this._mapSize / this.blurScale;
    if (!this.useKernelBlur || this.blurScale !== 1) {
      this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false);
      this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
      this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
      this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    }
    if (this.useKernelBlur) {
      this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._textureType);
      this._kernelBlurXPostprocess.width = targetSize;
      this._kernelBlurXPostprocess.height = targetSize;
      this._kernelBlurXPostprocess.externalTextureSamplerBinding = true;
      this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {
        effect.setTexture("textureSampler", this._shadowMap);
      });
      this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._textureType);
      this._kernelBlurXPostprocess.autoClear = false;
      this._kernelBlurYPostprocess.autoClear = false;
      if (this._textureType === 0) {
        this._kernelBlurXPostprocess.packedFloat = true;
        this._kernelBlurYPostprocess.packedFloat = true;
      }
      this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
    } else {
      this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, undefined, undefined, undefined, undefined, this._shaderLanguage);
      this._boxBlurPostprocess.externalTextureSamplerBinding = true;
      this._boxBlurPostprocess.onApplyObservable.add((effect) => {
        effect.setFloat2("screenSize", targetSize, targetSize);
        effect.setTexture("textureSampler", this._shadowMap);
      });
      this._boxBlurPostprocess.autoClear = false;
      this._blurPostProcesses = [this._boxBlurPostprocess];
    }
  }
  _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
    let index;
    if (depthOnlySubMeshes.length) {
      for (index = 0;index < depthOnlySubMeshes.length; index++) {
        this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
      }
    }
    for (index = 0;index < opaqueSubMeshes.length; index++) {
      this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
    }
    for (index = 0;index < alphaTestSubMeshes.length; index++) {
      this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
    }
    if (this._transparencyShadow) {
      for (index = 0;index < transparentSubMeshes.length; index++) {
        this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true);
      }
    } else {
      for (index = 0;index < transparentSubMeshes.length; index++) {
        transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;
      }
    }
  }
  _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) {
    effect.setMatrix("viewProjection", this.getTransformMatrix());
  }
  _renderSubMeshForShadowMap(subMesh, isTransparent = false) {
    const renderingMesh = subMesh.getRenderingMesh();
    const effectiveMesh = subMesh.getEffectiveMesh();
    const scene = this._scene;
    const engine2 = scene.getEngine();
    const material = subMesh.getMaterial();
    effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
    if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {
      return;
    }
    const useRHS = scene.useRightHandedSystem;
    const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;
    let sideOrientation = material._getEffectiveOrientation(renderingMesh);
    if (detNeg && !useRHS || !detNeg && useRHS) {
      sideOrientation = sideOrientation === 0 ? 1 : 0;
    }
    const reverseSideOrientation = sideOrientation === 0;
    engine2.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces);
    const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
    if (batch.mustReturn) {
      return;
    }
    const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined || renderingMesh.hasThinInstances);
    if (this.customAllowRendering && !this.customAllowRendering(subMesh)) {
      return;
    }
    if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) {
      subMesh._renderId = scene.getRenderId();
      const shadowDepthWrapper = material.shadowDepthWrapper;
      const drawWrapper = shadowDepthWrapper?.getEffect(subMesh, this, engine2.currentRenderPassId) ?? subMesh._getDrawWrapper();
      const effect = DrawWrapper.GetEffect(drawWrapper);
      engine2.enableEffect(drawWrapper);
      if (!hardwareInstancedRendering) {
        renderingMesh._bind(subMesh, effect, material.fillMode);
      }
      this.getTransformMatrix();
      effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale);
      if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
        effect.setVector3("lightDataSM", this._cachedDirection);
      } else {
        effect.setVector3("lightDataSM", this._cachedPosition);
      }
      const camera2 = this._getCamera();
      effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(camera2), this.getLight().getDepthMinZ(camera2) + this.getLight().getDepthMaxZ(camera2));
      if (isTransparent && this.enableSoftTransparentShadow) {
        effect.setFloat2("softTransparentShadowSM", effectiveMesh.visibility * material.alpha, this._opacityTexture?.getAlphaFromRGB ? 1 : 0);
      }
      if (shadowDepthWrapper) {
        subMesh._setMainDrawWrapperOverride(drawWrapper);
        if (shadowDepthWrapper.standalone) {
          shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
        } else {
          material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
        }
        subMesh._setMainDrawWrapperOverride(null);
      } else {
        if (this._opacityTexture) {
          effect.setTexture("diffuseSampler", this._opacityTexture);
          effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix);
        }
        if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
          const skeleton2 = renderingMesh.skeleton;
          if (skeleton2.isUsingTextureForMatrices) {
            const boneTexture = skeleton2.getTransformMatrixTexture(renderingMesh);
            if (!boneTexture) {
              return;
            }
            effect.setTexture("boneSampler", boneTexture);
            effect.setFloat("boneTextureWidth", 4 * (skeleton2.bones.length + 1));
          } else {
            effect.setMatrices("mBones", skeleton2.getTransformMatrices(renderingMesh));
          }
        }
        BindMorphTargetParameters(renderingMesh, effect);
        if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
          renderingMesh.morphTargetManager._bind(effect);
        }
        const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
        if (bvaManager && bvaManager.isEnabled) {
          bvaManager.bind(effect, hardwareInstancedRendering);
        }
        bindClipPlane(effect, material, scene);
      }
      if (!this._useUBO && !shadowDepthWrapper) {
        this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh);
      }
      BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());
      this._scene.getSceneUniformBuffer().bindUniformBuffer();
      const world = effectiveMesh.getWorldMatrix();
      if (hardwareInstancedRendering) {
        effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
        effectiveMesh.transferToEffect(world);
      }
      if (this.forceBackFacesOnly) {
        engine2.setState(true, 0, false, true, material.cullBackFaces);
      }
      this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
      this.onBeforeShadowMapRenderObservable.notifyObservers(effect);
      renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => {
        if (effectiveMesh !== renderingMesh && !isInstance) {
          renderingMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
          renderingMesh.transferToEffect(worldOverride);
        } else {
          effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
          effectiveMesh.transferToEffect(isInstance ? worldOverride : world);
        }
      });
      if (this.forceBackFacesOnly) {
        engine2.setState(true, 0, false, false, material.cullBackFaces);
      }
      this.onAfterShadowMapRenderObservable.notifyObservers(effect);
      this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
    } else {
      if (this._shadowMap) {
        this._shadowMap.resetRefreshCounter();
      }
    }
  }
  _applyFilterValues() {
    if (!this._shadowMap) {
      return;
    }
    if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
      this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
    } else {
      this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    }
  }
  forceCompilation(onCompiled, options) {
    const localOptions = {
      useInstances: false,
      ...options
    };
    const shadowMap = this.getShadowMap();
    if (!shadowMap) {
      if (onCompiled) {
        onCompiled(this);
      }
      return;
    }
    const renderList = shadowMap.renderList;
    if (!renderList) {
      if (onCompiled) {
        onCompiled(this);
      }
      return;
    }
    const subMeshes = [];
    for (const mesh of renderList) {
      subMeshes.push(...mesh.subMeshes);
    }
    if (subMeshes.length === 0) {
      if (onCompiled) {
        onCompiled(this);
      }
      return;
    }
    let currentIndex = 0;
    const checkReady = () => {
      if (!this._scene || !this._scene.getEngine()) {
        return;
      }
      while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, subMeshes[currentIndex].getMaterial()?.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh()) ?? false)) {
        currentIndex++;
        if (currentIndex >= subMeshes.length) {
          if (onCompiled) {
            onCompiled(this);
          }
          return;
        }
      }
      setTimeout(checkReady, 16);
    };
    checkReady();
  }
  forceCompilationAsync(options) {
    return new Promise((resolve3) => {
      this.forceCompilation(() => {
        resolve3();
      }, options);
    });
  }
  _isReadyCustomDefines(defines, subMesh, useInstances) {}
  _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) {
    defines.push("#define SM_LIGHTTYPE_" + this._light.getClassName().toUpperCase());
    defines.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0"));
    defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0"));
    defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
    const mesh = subMesh.getMesh();
    defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0"));
    defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0"));
    defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0"));
    defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0"));
    this._isReadyCustomDefines(defines, subMesh, useInstances);
    return defines;
  }
  isReady(subMesh, useInstances, isTransparent) {
    if (!this._shadersLoaded) {
      return false;
    }
    const material = subMesh.getMaterial(), shadowDepthWrapper = material?.shadowDepthWrapper;
    this._opacityTexture = null;
    if (!material) {
      return false;
    }
    const defines = [];
    this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent);
    if (shadowDepthWrapper) {
      if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) {
        return false;
      }
    } else {
      const subMeshEffect = subMesh._getDrawWrapper(undefined, true);
      let effect = subMeshEffect.effect;
      let cachedDefines = subMeshEffect.defines;
      const attribs = [VertexBuffer.PositionKind];
      const mesh = subMesh.getMesh();
      let useNormal = false;
      let uv1 = false;
      let uv2 = false;
      const color = false;
      if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
        attribs.push(VertexBuffer.NormalKind);
        defines.push("#define NORMAL");
        useNormal = true;
        if (mesh.nonUniformScaling) {
          defines.push("#define NONUNIFORMSCALING");
        }
      }
      const needAlphaTesting = material.needAlphaTestingForMesh(mesh);
      if (needAlphaTesting || material.needAlphaBlendingForMesh(mesh)) {
        if (this.useOpacityTextureForTransparentShadow) {
          this._opacityTexture = material.opacityTexture;
        } else {
          this._opacityTexture = material.getAlphaTestTexture();
        }
        if (this._opacityTexture) {
          if (!this._opacityTexture.isReady()) {
            return false;
          }
          const alphaCutOff = material.alphaCutOff ?? ShadowGenerator.DEFAULT_ALPHA_CUTOFF;
          defines.push("#define ALPHATEXTURE");
          if (needAlphaTesting) {
            defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? "." : ""}`);
          }
          if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
            attribs.push(VertexBuffer.UVKind);
            defines.push("#define UV1");
            uv1 = true;
          }
          if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
            if (this._opacityTexture.coordinatesIndex === 1) {
              attribs.push(VertexBuffer.UV2Kind);
              defines.push("#define UV2");
              uv2 = true;
            }
          }
        }
      }
      const fallbacks = new EffectFallbacks;
      if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
        attribs.push(VertexBuffer.MatricesIndicesKind);
        attribs.push(VertexBuffer.MatricesWeightsKind);
        if (mesh.numBoneInfluencers > 4) {
          attribs.push(VertexBuffer.MatricesIndicesExtraKind);
          attribs.push(VertexBuffer.MatricesWeightsExtraKind);
        }
        const skeleton2 = mesh.skeleton;
        defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
        if (mesh.numBoneInfluencers > 0) {
          fallbacks.addCPUSkinningFallback(0, mesh);
        }
        if (skeleton2.isUsingTextureForMatrices) {
          defines.push("#define BONETEXTURE");
        } else {
          defines.push("#define BonesPerMesh " + (skeleton2.bones.length + 1));
        }
      } else {
        defines.push("#define NUM_BONE_INFLUENCERS 0");
      }
      const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, useNormal, false, uv1, uv2, color) : 0;
      prepareStringDefinesForClipPlanes(material, this._scene, defines);
      if (useInstances) {
        defines.push("#define INSTANCES");
        PushAttributesForInstances(attribs);
        if (subMesh.getRenderingMesh().hasThinInstances) {
          defines.push("#define THIN_INSTANCES");
        }
      }
      if (this.customShaderOptions) {
        if (this.customShaderOptions.defines) {
          for (const define of this.customShaderOptions.defines) {
            if (defines.indexOf(define) === -1) {
              defines.push(define);
            }
          }
        }
      }
      const bvaManager = mesh.bakedVertexAnimationManager;
      if (bvaManager && bvaManager.isEnabled) {
        defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
        if (useInstances) {
          attribs.push("bakedVertexAnimationSettingsInstanced");
        }
      }
      const join6 = defines.join(`
`);
      if (cachedDefines !== join6) {
        cachedDefines = join6;
        let shaderName = "shadowMap";
        const uniforms = [
          "world",
          "mBones",
          "viewProjection",
          "diffuseMatrix",
          "lightDataSM",
          "depthValuesSM",
          "biasAndScaleSM",
          "morphTargetInfluences",
          "morphTargetCount",
          "boneTextureWidth",
          "softTransparentShadowSM",
          "morphTargetTextureInfo",
          "morphTargetTextureIndices",
          "bakedVertexAnimationSettings",
          "bakedVertexAnimationTextureSizeInverted",
          "bakedVertexAnimationTime",
          "bakedVertexAnimationTexture"
        ];
        const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"];
        const uniformBuffers = ["Scene", "Mesh"];
        addClipPlaneUniforms(uniforms);
        if (this.customShaderOptions) {
          shaderName = this.customShaderOptions.shaderName;
          if (this.customShaderOptions.attributes) {
            for (const attrib of this.customShaderOptions.attributes) {
              if (attribs.indexOf(attrib) === -1) {
                attribs.push(attrib);
              }
            }
          }
          if (this.customShaderOptions.uniforms) {
            for (const uniform of this.customShaderOptions.uniforms) {
              if (uniforms.indexOf(uniform) === -1) {
                uniforms.push(uniform);
              }
            }
          }
          if (this.customShaderOptions.samplers) {
            for (const sampler of this.customShaderOptions.samplers) {
              if (samplers.indexOf(sampler) === -1) {
                samplers.push(sampler);
              }
            }
          }
        }
        const engine2 = this._scene.getEngine();
        effect = engine2.createEffect(shaderName, {
          attributes: attribs,
          uniformsNames: uniforms,
          uniformBuffersNames: uniformBuffers,
          samplers,
          defines: join6,
          fallbacks,
          onCompiled: null,
          onError: null,
          indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
          shaderLanguage: this._shaderLanguage
        }, engine2);
        subMeshEffect.setEffect(effect, cachedDefines);
      }
      if (!effect.isReady()) {
        return false;
      }
    }
    if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
      if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
        this._initializeBlurRTTAndPostProcesses();
      }
    }
    if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
      return false;
    }
    if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
      return false;
    }
    if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
      return false;
    }
    return true;
  }
  prepareDefines(defines, lightIndex) {
    const scene = this._scene;
    const light = this._light;
    if (!scene.shadowsEnabled || !light.shadowEnabled) {
      return;
    }
    defines["SHADOW" + lightIndex] = true;
    if (this.useContactHardeningShadow) {
      defines["SHADOWPCSS" + lightIndex] = true;
      if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
        defines["SHADOWLOWQUALITY" + lightIndex] = true;
      } else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
        defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
      }
    } else if (this.usePercentageCloserFiltering) {
      defines["SHADOWPCF" + lightIndex] = true;
      if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
        defines["SHADOWLOWQUALITY" + lightIndex] = true;
      } else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
        defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
      }
    } else if (this.usePoissonSampling) {
      defines["SHADOWPOISSON" + lightIndex] = true;
    } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
      defines["SHADOWESM" + lightIndex] = true;
    } else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
      defines["SHADOWCLOSEESM" + lightIndex] = true;
    }
    if (light.needCube()) {
      defines["SHADOWCUBE" + lightIndex] = true;
    }
  }
  bindShadowLight(lightIndex, effect) {
    const light = this._light;
    const scene = this._scene;
    if (!scene.shadowsEnabled || !light.shadowEnabled) {
      return;
    }
    const camera2 = this._getCamera();
    const shadowMap = this.getShadowMap();
    if (!shadowMap) {
      return;
    }
    if (!light.needCube()) {
      effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
    }
    const shadowMapForRendering = this.getShadowMapForRendering();
    if (this._filter === ShadowGenerator.FILTER_PCF) {
      effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
    } else if (this._filter === ShadowGenerator.FILTER_PCSS) {
      effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering);
      effect.setTexture("depthTexture" + lightIndex, shadowMapForRendering);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
    } else {
      effect.setTexture("shadowTexture" + lightIndex, shadowMapForRendering);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
    }
    light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera2), this.getLight().getDepthMinZ(camera2) + this.getLight().getDepthMaxZ(camera2), lightIndex);
  }
  get viewMatrix() {
    return this._viewMatrix;
  }
  get projectionMatrix() {
    return this._projectionMatrix;
  }
  getTransformMatrix() {
    const scene = this._scene;
    if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
      return this._transformMatrix;
    }
    this._currentRenderId = scene.getRenderId();
    this._currentFaceIndexCache = this._currentFaceIndex;
    let lightPosition = this._light.position;
    if (this._light.computeTransformedInformation()) {
      lightPosition = this._light.transformedPosition;
    }
    Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
    if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1) {
      this._lightDirection.z = 0.0000000000001;
    }
    if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
      this._cachedPosition.copyFrom(lightPosition);
      this._cachedDirection.copyFrom(this._lightDirection);
      Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
      const shadowMap = this.getShadowMap();
      if (shadowMap) {
        const renderList = shadowMap.renderList;
        if (renderList) {
          this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
        }
      }
      this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
    }
    return this._transformMatrix;
  }
  recreateShadowMap() {
    const shadowMap = this._shadowMap;
    if (!shadowMap) {
      return;
    }
    const renderList = shadowMap.renderList;
    this._disposeRTTandPostProcesses();
    this._initializeGenerator();
    this.filter = this._filter;
    this._applyFilterValues();
    if (renderList) {
      if (!this._shadowMap.renderList) {
        this._shadowMap.renderList = [];
      }
      for (const mesh of renderList) {
        this._shadowMap.renderList.push(mesh);
      }
    } else {
      this._shadowMap.renderList = null;
    }
  }
  _disposeBlurPostProcesses() {
    if (this._shadowMap2) {
      this._shadowMap2.dispose();
      this._shadowMap2 = null;
    }
    if (this._boxBlurPostprocess) {
      this._boxBlurPostprocess.dispose();
      this._boxBlurPostprocess = null;
    }
    if (this._kernelBlurXPostprocess) {
      this._kernelBlurXPostprocess.dispose();
      this._kernelBlurXPostprocess = null;
    }
    if (this._kernelBlurYPostprocess) {
      this._kernelBlurYPostprocess.dispose();
      this._kernelBlurYPostprocess = null;
    }
    this._blurPostProcesses = [];
  }
  _disposeRTTandPostProcesses() {
    if (this._shadowMap) {
      this._shadowMap.dispose();
      this._shadowMap = null;
    }
    this._disposeBlurPostProcesses();
  }
  _disposeSceneUBOs() {
    if (this._sceneUBOs) {
      for (const ubo of this._sceneUBOs) {
        ubo.dispose();
      }
      this._sceneUBOs = [];
    }
  }
  dispose() {
    this._disposeRTTandPostProcesses();
    this._disposeSceneUBOs();
    if (this._light) {
      if (this._light._shadowGenerators) {
        const iterator = this._light._shadowGenerators.entries();
        for (let entry = iterator.next();entry.done !== true; entry = iterator.next()) {
          const [camera2, shadowGenerator] = entry.value;
          if (shadowGenerator === this) {
            this._light._shadowGenerators.delete(camera2);
          }
        }
        if (this._light._shadowGenerators.size === 0) {
          this._light._shadowGenerators = null;
        }
      }
      this._light._markMeshesAsLightDirty();
    }
    this.onBeforeShadowMapRenderMeshObservable.clear();
    this.onBeforeShadowMapRenderObservable.clear();
    this.onAfterShadowMapRenderMeshObservable.clear();
    this.onAfterShadowMapRenderObservable.clear();
  }
  serialize() {
    const serializationObject = {};
    const shadowMap = this.getShadowMap();
    if (!shadowMap) {
      return serializationObject;
    }
    serializationObject.className = this.getClassName();
    serializationObject.lightId = this._light.id;
    serializationObject.cameraId = this._camera?.id;
    serializationObject.id = this.id;
    serializationObject.mapSize = shadowMap.getRenderSize();
    serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
    serializationObject.darkness = this.getDarkness();
    serializationObject.transparencyShadow = this._transparencyShadow;
    serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
    serializationObject.bias = this.bias;
    serializationObject.normalBias = this.normalBias;
    serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
    serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
    serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
    serializationObject.filteringQuality = this.filteringQuality;
    serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
    serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
    serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
    serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
    serializationObject.usePoissonSampling = this.usePoissonSampling;
    serializationObject.depthScale = this.depthScale;
    serializationObject.blurBoxOffset = this.blurBoxOffset;
    serializationObject.blurKernel = this.blurKernel;
    serializationObject.blurScale = this.blurScale;
    serializationObject.useKernelBlur = this.useKernelBlur;
    serializationObject.renderList = [];
    if (shadowMap.renderList) {
      for (let meshIndex = 0;meshIndex < shadowMap.renderList.length; meshIndex++) {
        const mesh = shadowMap.renderList[meshIndex];
        serializationObject.renderList.push(mesh.id);
      }
    }
    return serializationObject;
  }
  static Parse(parsedShadowGenerator, scene, constr) {
    const light = scene.getLightById(parsedShadowGenerator.lightId);
    const camera2 = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null;
    const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera2) : new ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera2);
    const shadowMap = shadowGenerator.getShadowMap();
    for (let meshIndex = 0;meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
      const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]);
      meshes.forEach(function(mesh) {
        if (!shadowMap) {
          return;
        }
        if (!shadowMap.renderList) {
          shadowMap.renderList = [];
        }
        shadowMap.renderList.push(mesh);
      });
    }
    if (parsedShadowGenerator.id !== undefined) {
      shadowGenerator.id = parsedShadowGenerator.id;
    }
    shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;
    if (parsedShadowGenerator.darkness !== undefined) {
      shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
    }
    if (parsedShadowGenerator.transparencyShadow) {
      shadowGenerator.setTransparencyShadow(true);
    }
    if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
      shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
    }
    if (parsedShadowGenerator.bias !== undefined) {
      shadowGenerator.bias = parsedShadowGenerator.bias;
    }
    if (parsedShadowGenerator.normalBias !== undefined) {
      shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
    }
    if (parsedShadowGenerator.usePercentageCloserFiltering) {
      shadowGenerator.usePercentageCloserFiltering = true;
    } else if (parsedShadowGenerator.useContactHardeningShadow) {
      shadowGenerator.useContactHardeningShadow = true;
    } else if (parsedShadowGenerator.usePoissonSampling) {
      shadowGenerator.usePoissonSampling = true;
    } else if (parsedShadowGenerator.useExponentialShadowMap) {
      shadowGenerator.useExponentialShadowMap = true;
    } else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
      shadowGenerator.useBlurExponentialShadowMap = true;
    } else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
      shadowGenerator.useCloseExponentialShadowMap = true;
    } else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
      shadowGenerator.useBlurCloseExponentialShadowMap = true;
    } else if (parsedShadowGenerator.useVarianceShadowMap) {
      shadowGenerator.useExponentialShadowMap = true;
    } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
      shadowGenerator.useBlurExponentialShadowMap = true;
    }
    if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {
      shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
    }
    if (parsedShadowGenerator.filteringQuality !== undefined) {
      shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
    }
    if (parsedShadowGenerator.depthScale) {
      shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
    }
    if (parsedShadowGenerator.blurScale) {
      shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
    }
    if (parsedShadowGenerator.blurBoxOffset) {
      shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
    }
    if (parsedShadowGenerator.useKernelBlur) {
      shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
    }
    if (parsedShadowGenerator.blurKernel) {
      shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
    }
    return shadowGenerator;
  }
}
ShadowGenerator.CLASSNAME = "ShadowGenerator";
ShadowGenerator.ForceGLSL = false;
ShadowGenerator.FILTER_NONE = 0;
ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
ShadowGenerator.FILTER_POISSONSAMPLING = 2;
ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
ShadowGenerator.FILTER_PCF = 6;
ShadowGenerator.FILTER_PCSS = 7;
ShadowGenerator.QUALITY_HIGH = 0;
ShadowGenerator.QUALITY_MEDIUM = 1;
ShadowGenerator.QUALITY_LOW = 2;
ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5;
ShadowGenerator._SceneComponentInitialization = (_) => {
  throw _WarnImport("ShadowGeneratorSceneComponent");
};

// node_modules/@babylonjs/core/Rendering/depthRenderer.js
init_math_color();
init_buffer();
init_texture();
init_renderTargetTexture();
init_depth_fragment();
init_depth_vertex();
init_devTools();
init_materialHelper_functions();
class DepthRenderer {
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  setMaterialForRendering(mesh, material) {
    this._depthMap.setMaterialForRendering(mesh, material);
  }
  constructor(scene, type = 1, camera2 = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name202) {
    this._shaderLanguage = 0;
    this.enabled = true;
    this.forceDepthWriteTransparentMeshes = false;
    this.useOnlyInActiveCamera = false;
    this.reverseCulling = false;
    this._shadersLoaded = false;
    this._scene = scene;
    this._storeNonLinearDepth = storeNonLinearDepth;
    this._storeCameraSpaceZ = storeCameraSpaceZ;
    this.isPacked = type === 0;
    if (this.isPacked) {
      this.clearColor = new Color4(1, 1, 1, 1);
    } else {
      this.clearColor = new Color4(storeCameraSpaceZ ? 1e8 : 1, 0, 0, 1);
    }
    this._initShaderSourceAsync();
    DepthRenderer._SceneComponentInitialization(this._scene);
    const engine2 = scene.getEngine();
    this._camera = camera2;
    if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) {
      if (type === 1 && !engine2._caps.textureFloatLinearFiltering) {
        samplingMode = Texture.NEAREST_SAMPLINGMODE;
      }
      if (type === 2 && !engine2._caps.textureHalfFloatLinearFiltering) {
        samplingMode = Texture.NEAREST_SAMPLINGMODE;
      }
    }
    const format = this.isPacked || !engine2._features.supportExtendedTextureFormats ? 5 : 6;
    this._depthMap = new RenderTargetTexture(name202 ?? "DepthRenderer", { width: engine2.getRenderWidth(), height: engine2.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, undefined, undefined, undefined, format);
    this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._depthMap.refreshRate = 1;
    this._depthMap.renderParticles = false;
    this._depthMap.renderList = null;
    this._depthMap.noPrePassRenderer = true;
    this._depthMap.activeCamera = this._camera;
    this._depthMap.ignoreCameraViewport = true;
    this._depthMap.useCameraPostProcesses = false;
    this._depthMap.onClearObservable.add((engine3) => {
      engine3.clear(this.clearColor, true, true, true);
    });
    this._depthMap.onBeforeBindObservable.add(() => {
      engine2._debugPushGroup?.("depth renderer", 1);
    });
    this._depthMap.onAfterUnbindObservable.add(() => {
      engine2._debugPopGroup?.(1);
    });
    this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => {
      if ((preWarm || refreshRate === 0) && mesh.subMeshes) {
        for (let i = 0;i < mesh.subMeshes.length; ++i) {
          const subMesh = mesh.subMeshes[i];
          const renderingMesh = subMesh.getRenderingMesh();
          const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
          const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined || renderingMesh.hasThinInstances);
          if (!this.isReady(subMesh, hardwareInstancedRendering)) {
            return false;
          }
        }
      }
      return true;
    };
    const renderSubMesh = (subMesh) => {
      const renderingMesh = subMesh.getRenderingMesh();
      const effectiveMesh = subMesh.getEffectiveMesh();
      const scene2 = this._scene;
      const engine3 = scene2.getEngine();
      const material = subMesh.getMaterial();
      effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
      if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene2.getRenderId()) {
        return;
      }
      const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;
      let sideOrientation = material._getEffectiveOrientation(renderingMesh);
      if (detNeg) {
        sideOrientation = sideOrientation === 0 ? 1 : 0;
      }
      const reverseSideOrientation = sideOrientation === 0;
      engine3.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces);
      const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
      if (batch.mustReturn) {
        return;
      }
      const hardwareInstancedRendering = engine3.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined || renderingMesh.hasThinInstances);
      const camera3 = this._camera || scene2.activeCamera;
      if (this.isReady(subMesh, hardwareInstancedRendering) && camera3) {
        subMesh._renderId = scene2.getRenderId();
        const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine3.currentRenderPassId];
        let drawWrapper = subMesh._getDrawWrapper();
        if (!drawWrapper && renderingMaterial) {
          drawWrapper = renderingMaterial._getDrawWrapper();
        }
        const cameraIsOrtho = camera3.mode === Camera.ORTHOGRAPHIC_CAMERA;
        if (!drawWrapper) {
          return;
        }
        const effect = drawWrapper.effect;
        engine3.enableEffect(drawWrapper);
        if (!hardwareInstancedRendering) {
          renderingMesh._bind(subMesh, effect, material.fillMode);
        }
        if (!renderingMaterial) {
          effect.setMatrix("viewProjection", scene2.getTransformMatrix());
          effect.setMatrix("world", effectiveMesh.getWorldMatrix());
          if (this._storeCameraSpaceZ) {
            effect.setMatrix("view", scene2.getViewMatrix());
          }
        } else {
          renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);
        }
        let minZ, maxZ;
        if (cameraIsOrtho) {
          minZ = !engine3.useReverseDepthBuffer && engine3.isNDCHalfZRange ? 0 : 1;
          maxZ = engine3.useReverseDepthBuffer && engine3.isNDCHalfZRange ? 0 : 1;
        } else {
          minZ = engine3.useReverseDepthBuffer && engine3.isNDCHalfZRange ? camera3.minZ : engine3.isNDCHalfZRange ? 0 : camera3.minZ;
          maxZ = engine3.useReverseDepthBuffer && engine3.isNDCHalfZRange ? 0 : camera3.maxZ;
        }
        effect.setFloat2("depthValues", minZ, minZ + maxZ);
        if (!renderingMaterial) {
          if (material.needAlphaTestingForMesh(effectiveMesh)) {
            const alphaTexture = material.getAlphaTestTexture();
            if (alphaTexture) {
              effect.setTexture("diffuseSampler", alphaTexture);
              effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
            }
          }
          BindBonesParameters(renderingMesh, effect);
          bindClipPlane(effect, material, scene2);
          BindMorphTargetParameters(renderingMesh, effect);
          if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
            renderingMesh.morphTargetManager._bind(effect);
          }
          const bvaManager = subMesh.getMesh().bakedVertexAnimationManager;
          if (bvaManager && bvaManager.isEnabled) {
            bvaManager.bind(effect, hardwareInstancedRendering);
          }
          if (material.pointsCloud) {
            effect.setFloat("pointSize", material.pointSize);
          }
        }
        renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world));
      }
    };
    this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {
      let index;
      if (depthOnlySubMeshes.length) {
        for (index = 0;index < depthOnlySubMeshes.length; index++) {
          renderSubMesh(depthOnlySubMeshes.data[index]);
        }
      }
      for (index = 0;index < opaqueSubMeshes.length; index++) {
        renderSubMesh(opaqueSubMeshes.data[index]);
      }
      for (index = 0;index < alphaTestSubMeshes.length; index++) {
        renderSubMesh(alphaTestSubMeshes.data[index]);
      }
      if (this.forceDepthWriteTransparentMeshes) {
        for (index = 0;index < transparentSubMeshes.length; index++) {
          renderSubMesh(transparentSubMeshes.data[index]);
        }
      } else {
        for (index = 0;index < transparentSubMeshes.length; index++) {
          transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;
        }
      }
    };
  }
  async _initShaderSourceAsync(forceGLSL = false) {
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !forceGLSL && !DepthRenderer.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([Promise.resolve().then(() => (init_depth_vertex2(), exports_depth_vertex2)), Promise.resolve().then(() => (init_depth_fragment2(), exports_depth_fragment2))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_depth_vertex(), exports_depth_vertex)), Promise.resolve().then(() => (init_depth_fragment(), exports_depth_fragment))]);
    }
    this._shadersLoaded = true;
  }
  isReady(subMesh, useInstances) {
    if (!this._shadersLoaded) {
      return false;
    }
    const engine2 = this._scene.getEngine();
    const mesh = subMesh.getMesh();
    const scene = mesh.getScene();
    const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId];
    if (renderingMaterial) {
      return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);
    }
    const material = subMesh.getMaterial();
    if (!material || material.disableDepthWrite) {
      return false;
    }
    const defines = [];
    const attribs = [VertexBuffer.PositionKind];
    let uv1 = false;
    let uv2 = false;
    const color = false;
    if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) {
      defines.push("#define ALPHATEST");
      if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
        attribs.push(VertexBuffer.UVKind);
        defines.push("#define UV1");
        uv1 = true;
      }
      if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
        attribs.push(VertexBuffer.UV2Kind);
        defines.push("#define UV2");
        uv2 = true;
      }
    }
    const fallbacks = new EffectFallbacks;
    if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
      if (mesh.numBoneInfluencers > 0) {
        fallbacks.addCPUSkinningFallback(0, mesh);
      }
      const skeleton2 = mesh.skeleton;
      if (skeleton2.isUsingTextureForMatrices) {
        defines.push("#define BONETEXTURE");
      } else {
        defines.push("#define BonesPerMesh " + (skeleton2.bones.length + 1));
      }
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
    }
    const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, false, false, uv1, uv2, color) : 0;
    if (material.pointsCloud) {
      defines.push("#define POINTSIZE");
    }
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs);
      if (subMesh.getRenderingMesh().hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
      }
    }
    const bvaManager = mesh.bakedVertexAnimationManager;
    if (bvaManager && bvaManager.isEnabled) {
      defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
      if (useInstances) {
        attribs.push("bakedVertexAnimationSettingsInstanced");
      }
    }
    if (this._storeNonLinearDepth) {
      defines.push("#define NONLINEARDEPTH");
    }
    if (this._storeCameraSpaceZ) {
      defines.push("#define STORE_CAMERASPACE_Z");
    }
    if (this.isPacked) {
      defines.push("#define PACKED");
    }
    prepareStringDefinesForClipPlanes(material, scene, defines);
    const drawWrapper = subMesh._getDrawWrapper(undefined, true);
    const cachedDefines = drawWrapper.defines;
    const join6 = defines.join(`
`);
    if (cachedDefines !== join6) {
      const uniforms = [
        "world",
        "mBones",
        "boneTextureWidth",
        "pointSize",
        "viewProjection",
        "view",
        "diffuseMatrix",
        "depthValues",
        "morphTargetInfluences",
        "morphTargetCount",
        "morphTargetTextureInfo",
        "morphTargetTextureIndices",
        "bakedVertexAnimationSettings",
        "bakedVertexAnimationTextureSizeInverted",
        "bakedVertexAnimationTime",
        "bakedVertexAnimationTexture"
      ];
      const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"];
      addClipPlaneUniforms(uniforms);
      drawWrapper.setEffect(engine2.createEffect("depth", {
        attributes: attribs,
        uniformsNames: uniforms,
        uniformBuffersNames: [],
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: null,
        onError: null,
        indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
        shaderLanguage: this._shaderLanguage
      }, engine2), join6);
    }
    return drawWrapper.effect.isReady();
  }
  getDepthMap() {
    return this._depthMap;
  }
  dispose() {
    const keysToDelete = [];
    for (const key in this._scene._depthRenderer) {
      const depthRenderer = this._scene._depthRenderer[key];
      if (depthRenderer === this) {
        keysToDelete.push(key);
      }
    }
    if (keysToDelete.length > 0) {
      this._depthMap.dispose();
      for (const key of keysToDelete) {
        delete this._scene._depthRenderer[key];
      }
    }
  }
}
DepthRenderer.ForceGLSL = false;
DepthRenderer._SceneComponentInitialization = (_) => {
  throw _WarnImport("DepthRendererSceneComponent");
};

// node_modules/@babylonjs/core/Misc/minMaxReducer.js
init_observable();
init_postProcess();
init_postProcessManager();

// node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js
init_shaderStore();
var name202 = "minmaxReduxPixelShader";
var shader201 = `varying vec2 vUV;uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);
#ifdef DEPTH_REDUX
float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#else
float maxz=max(max(max(f1,f2),f3),f4);
#endif
glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform ivec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
void main(void)
{glFragColor=vec4(0.);if (true) { 
discard;}}
#endif
`;
if (!ShaderStore.ShadersStore[name202]) {
  ShaderStore.ShadersStore[name202] = shader201;
}

// node_modules/@babylonjs/core/Misc/minMaxReducer.js
class MinMaxReducer {
  constructor(camera2) {
    this.onAfterReductionPerformed = new Observable;
    this._forceFullscreenViewport = true;
    this._activated = false;
    this._camera = camera2;
    this._postProcessManager = new PostProcessManager(camera2.getScene());
    this._onContextRestoredObserver = camera2.getEngine().onContextRestoredObservable.add(() => {
      this._postProcessManager._rebuild();
    });
  }
  get sourceTexture() {
    return this._sourceTexture;
  }
  setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {
    if (sourceTexture === this._sourceTexture) {
      return;
    }
    this.dispose(false);
    this._sourceTexture = sourceTexture;
    this._reductionSteps = [];
    this._forceFullscreenViewport = forceFullscreenViewport;
    const scene = this._camera.getScene();
    const reductionInitial = new PostProcess("Initial reduction phase", "minmaxRedux", ["texSize"], ["sourceTexture"], 1, null, 1, scene.getEngine(), false, "#define INITIAL" + (depthRedux ? `
#define DEPTH_REDUX` : ""), type, undefined, undefined, undefined, 7);
    reductionInitial.autoClear = false;
    reductionInitial.forceFullscreenViewport = forceFullscreenViewport;
    let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight();
    reductionInitial.onApply = ((w2, h2) => {
      return (effect) => {
        effect.setTexture("sourceTexture", this._sourceTexture);
        effect.setFloat2("texSize", w2, h2);
      };
    })(w, h);
    this._reductionSteps.push(reductionInitial);
    let index = 1;
    while (w > 1 || h > 1) {
      w = Math.max(Math.round(w / 2), 1);
      h = Math.max(Math.round(h / 2), 1);
      const reduction = new PostProcess("Reduction phase " + index, "minmaxRedux", ["texSize"], null, { width: w, height: h }, null, 1, scene.getEngine(), false, "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN"), type, undefined, undefined, undefined, 7);
      reduction.autoClear = false;
      reduction.forceFullscreenViewport = forceFullscreenViewport;
      reduction.onApply = ((w2, h2) => {
        return (effect) => {
          if (w2 == 1 || h2 == 1) {
            effect.setInt2("texSize", w2, h2);
          } else {
            effect.setFloat2("texSize", w2, h2);
          }
        };
      })(w, h);
      this._reductionSteps.push(reduction);
      index++;
      if (w == 1 && h == 1) {
        const func = (w2, h2, reduction2) => {
          const buffer2 = new Float32Array(4 * w2 * h2), minmax = { min: 0, max: 0 };
          return () => {
            scene.getEngine()._readTexturePixels(reduction2.inputTexture.texture, w2, h2, -1, 0, buffer2, false);
            minmax.min = buffer2[0];
            minmax.max = buffer2[1];
            this.onAfterReductionPerformed.notifyObservers(minmax);
          };
        };
        reduction.onAfterRenderObservable.add(func(w, h, reduction));
      }
    }
  }
  get refreshRate() {
    return this._sourceTexture ? this._sourceTexture.refreshRate : -1;
  }
  set refreshRate(value) {
    if (this._sourceTexture) {
      this._sourceTexture.refreshRate = value;
    }
  }
  get activated() {
    return this._activated;
  }
  activate() {
    if (this._onAfterUnbindObserver || !this._sourceTexture) {
      return;
    }
    this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => {
      const engine2 = this._camera.getScene().getEngine();
      engine2._debugPushGroup?.(`min max reduction`, 1);
      this._reductionSteps[0].activate(this._camera);
      this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport);
      engine2.unBindFramebuffer(this._reductionSteps[0].inputTexture, false);
      engine2._debugPopGroup?.(1);
    });
    this._activated = true;
  }
  deactivate() {
    if (!this._onAfterUnbindObserver || !this._sourceTexture) {
      return;
    }
    this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
    this._onAfterUnbindObserver = null;
    this._activated = false;
  }
  dispose(disposeAll = true) {
    if (disposeAll) {
      this.onAfterReductionPerformed.clear();
      if (this._onContextRestoredObserver) {
        this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);
        this._onContextRestoredObserver = null;
      }
    }
    this.deactivate();
    if (this._reductionSteps) {
      for (let i = 0;i < this._reductionSteps.length; ++i) {
        this._reductionSteps[i].dispose();
      }
      this._reductionSteps = null;
    }
    if (this._postProcessManager && disposeAll) {
      this._postProcessManager.dispose();
    }
    this._sourceTexture = null;
  }
}

// node_modules/@babylonjs/core/Misc/depthReducer.js
class DepthReducer extends MinMaxReducer {
  get depthRenderer() {
    return this._depthRenderer;
  }
  constructor(camera2) {
    super(camera2);
  }
  setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) {
    const scene = this._camera.getScene();
    if (this._depthRenderer) {
      delete scene._depthRenderer[this._depthRendererId];
      this._depthRenderer.dispose();
      this._depthRenderer = null;
    }
    if (depthRenderer === null) {
      if (!scene._depthRenderer) {
        scene._depthRenderer = {};
      }
      depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1);
      depthRenderer.enabled = false;
      this._depthRendererId = "minmax" + this._camera.id;
      scene._depthRenderer[this._depthRendererId] = depthRenderer;
    }
    super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport);
  }
  setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {
    super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport);
  }
  activate() {
    if (this._depthRenderer) {
      this._depthRenderer.enabled = true;
    }
    super.activate();
  }
  deactivate() {
    super.deactivate();
    if (this._depthRenderer) {
      this._depthRenderer.enabled = false;
    }
  }
  dispose(disposeAll = true) {
    super.dispose(disposeAll);
    if (this._depthRenderer && disposeAll) {
      const scene = this._depthRenderer.getDepthMap().getScene();
      if (scene) {
        delete scene._depthRenderer[this._depthRendererId];
      }
      this._depthRenderer.dispose();
      this._depthRenderer = null;
    }
  }
}

// node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js
init_logger();
init_engineStore();
var UpDir = Vector3.Up();
var ZeroVec = Vector3.Zero();
var tmpv1 = new Vector3;
var tmpv2 = new Vector3;
var tmpMatrix = new Matrix;

class CascadedShadowGenerator extends ShadowGenerator {
  _validateFilter(filter) {
    if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) {
      return filter;
    }
    Logger.Error('Unsupported filter "' + filter + '"!');
    return ShadowGenerator.FILTER_NONE;
  }
  get numCascades() {
    return this._numCascades;
  }
  set numCascades(value) {
    value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);
    if (value === this._numCascades) {
      return;
    }
    this._numCascades = value;
    this.recreateShadowMap();
    this._recreateSceneUBOs();
  }
  get freezeShadowCastersBoundingInfo() {
    return this._freezeShadowCastersBoundingInfo;
  }
  set freezeShadowCastersBoundingInfo(freeze) {
    if (this._freezeShadowCastersBoundingInfoObservable && freeze) {
      this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
      this._freezeShadowCastersBoundingInfoObservable = null;
    }
    if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {
      this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(() => this._computeShadowCastersBoundingInfo());
    }
    this._freezeShadowCastersBoundingInfo = freeze;
    if (freeze) {
      this._computeShadowCastersBoundingInfo();
    }
  }
  _computeShadowCastersBoundingInfo() {
    this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._scbiMax.copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    if (this._shadowMap && this._shadowMap.renderList) {
      const renderList = this._shadowMap.renderList;
      for (let meshIndex = 0;meshIndex < renderList.length; meshIndex++) {
        const mesh = renderList[meshIndex];
        if (!mesh) {
          continue;
        }
        const boundingInfo2 = mesh.getBoundingInfo(), boundingBox2 = boundingInfo2.boundingBox;
        this._scbiMin.minimizeInPlace(boundingBox2.minimumWorld);
        this._scbiMax.maximizeInPlace(boundingBox2.maximumWorld);
      }
    }
    this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);
  }
  get shadowCastersBoundingInfo() {
    return this._shadowCastersBoundingInfo;
  }
  set shadowCastersBoundingInfo(boundingInfo2) {
    this._shadowCastersBoundingInfo = boundingInfo2;
  }
  setMinMaxDistance(min, max) {
    if (this._minDistance === min && this._maxDistance === max) {
      return;
    }
    if (min > max) {
      min = 0;
      max = 1;
    }
    if (min < 0) {
      min = 0;
    }
    if (max > 1) {
      max = 1;
    }
    this._minDistance = min;
    this._maxDistance = max;
    this._breaksAreDirty = true;
  }
  get minDistance() {
    return this._minDistance;
  }
  get maxDistance() {
    return this._maxDistance;
  }
  getClassName() {
    return CascadedShadowGenerator.CLASSNAME;
  }
  getCascadeMinExtents(cascadeIndex) {
    return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;
  }
  getCascadeMaxExtents(cascadeIndex) {
    return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;
  }
  get shadowMaxZ() {
    if (!this._getCamera()) {
      return 0;
    }
    return this._shadowMaxZ;
  }
  set shadowMaxZ(value) {
    const camera2 = this._getCamera();
    if (!camera2) {
      this._shadowMaxZ = value;
      return;
    }
    if (this._shadowMaxZ === value || value < camera2.minZ || value > camera2.maxZ && camera2.maxZ !== 0) {
      return;
    }
    this._shadowMaxZ = value;
    this._light._markMeshesAsLightDirty();
    this._breaksAreDirty = true;
  }
  get debug() {
    return this._debug;
  }
  set debug(dbg) {
    this._debug = dbg;
    this._light._markMeshesAsLightDirty();
  }
  get depthClamp() {
    return this._depthClamp;
  }
  set depthClamp(value) {
    this._depthClamp = value;
  }
  get cascadeBlendPercentage() {
    return this._cascadeBlendPercentage;
  }
  set cascadeBlendPercentage(value) {
    this._cascadeBlendPercentage = value;
    this._light._markMeshesAsLightDirty();
  }
  get lambda() {
    return this._lambda;
  }
  set lambda(value) {
    const lambda = Math.min(Math.max(value, 0), 1);
    if (this._lambda == lambda) {
      return;
    }
    this._lambda = lambda;
    this._breaksAreDirty = true;
  }
  getCascadeViewMatrix(cascadeNum) {
    return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;
  }
  getCascadeProjectionMatrix(cascadeNum) {
    return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;
  }
  getCascadeTransformMatrix(cascadeNum) {
    return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;
  }
  setDepthRenderer(depthRenderer) {
    this._depthRenderer = depthRenderer;
    if (this._depthReducer) {
      this._depthReducer.setDepthRenderer(this._depthRenderer);
    }
  }
  get autoCalcDepthBounds() {
    return this._autoCalcDepthBounds;
  }
  set autoCalcDepthBounds(value) {
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    this._autoCalcDepthBounds = value;
    if (!value) {
      if (this._depthReducer) {
        this._depthReducer.deactivate();
      }
      this.setMinMaxDistance(0, 1);
      return;
    }
    if (!this._depthReducer) {
      this._depthReducer = new DepthReducer(camera2);
      this._depthReducer.onAfterReductionPerformed.add((minmax) => {
        let { min, max } = minmax;
        if (min >= max) {
          min = 0;
          max = 1;
        }
        if (min != this._minDistance || max != this._maxDistance) {
          this.setMinMaxDistance(min, max);
        }
      });
      this._depthReducer.setDepthRenderer(this._depthRenderer);
    }
    this._depthReducer.activate();
  }
  get autoCalcDepthBoundsRefreshRate() {
    return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate ?? -1;
  }
  set autoCalcDepthBoundsRefreshRate(value) {
    if (this._depthReducer?.depthRenderer) {
      this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;
    }
  }
  splitFrustum() {
    this._breaksAreDirty = true;
  }
  _splitFrustum() {
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    const near = camera2.minZ, far = camera2.maxZ || this._shadowMaxZ, cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;
    const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange;
    const range = maxZ - minZ, ratio = maxZ / minZ;
    for (let cascadeIndex = 0;cascadeIndex < this._cascades.length; ++cascadeIndex) {
      const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p;
      const d = this._lambda * (log - uniform) + uniform;
      this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;
      this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;
      this._viewSpaceFrustumsZ[cascadeIndex] = d;
      this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;
    }
    this._breaksAreDirty = false;
  }
  _computeMatrices() {
    const scene = this._scene;
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);
    if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1) {
      this._lightDirection.z = 0.0000000000001;
    }
    this._cachedDirection.copyFrom(this._lightDirection);
    const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;
    for (let cascadeIndex = 0;cascadeIndex < this._numCascades; ++cascadeIndex) {
      this._computeFrustumInWorldSpace(cascadeIndex);
      this._computeCascadeFrustum(cascadeIndex);
      this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1);
      this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);
      Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);
      let viewMinZ = 0, viewMaxZ = tmpv1.z;
      const boundingInfo2 = this._shadowCastersBoundingInfo;
      boundingInfo2.update(this._viewMatrices[cascadeIndex]);
      const castersViewMinZ = boundingInfo2.boundingBox.minimumWorld.z;
      const castersViewMaxZ = boundingInfo2.boundingBox.maximumWorld.z;
      if (castersViewMinZ > viewMaxZ) {} else {
        if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {
          viewMinZ = Math.min(viewMinZ, castersViewMinZ);
          if (this.filter !== ShadowGenerator.FILTER_PCSS) {
            viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
          }
        } else {
          viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ);
          viewMinZ = Math.max(viewMinZ, castersViewMinZ);
          viewMaxZ = Math.max(viewMinZ + 1, viewMaxZ);
        }
      }
      Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? viewMaxZ : viewMinZ, useReverseDepthBuffer ? viewMinZ : viewMaxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange);
      this._cascadeMinExtents[cascadeIndex].z = viewMinZ;
      this._cascadeMaxExtents[cascadeIndex].z = viewMaxZ;
      this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
      Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1);
      tmpv1.scaleInPlace(this._mapSize / 2);
      tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z));
      tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize);
      Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0, tmpMatrix);
      this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]);
      this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
      this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);
    }
  }
  _computeFrustumInWorldSpace(cascadeIndex) {
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance;
    const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange;
    camera2.getViewMatrix();
    const cameraInfiniteFarPlane = camera2.maxZ === 0;
    const saveCameraMaxZ = camera2.maxZ;
    if (cameraInfiniteFarPlane) {
      camera2.maxZ = this._shadowMaxZ;
      camera2.getProjectionMatrix(true);
    }
    const invViewProj = Matrix.Invert(camera2.getTransformationMatrix());
    if (cameraInfiniteFarPlane) {
      camera2.maxZ = saveCameraMaxZ;
      camera2.getProjectionMatrix(true);
    }
    const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0;
    for (let cornerIndex = 0;cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) {
      tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]);
      if (isNDCHalfZRange && tmpv1.z === -1) {
        tmpv1.z = 0;
      }
      Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
    }
    for (let cornerIndex = 0;cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) {
      tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
      tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist);
      tmpv1.scaleInPlace(splitDist);
      tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
      this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);
      this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);
    }
  }
  _computeCascadeFrustum(cascadeIndex) {
    this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    this._cascadeMaxExtents[cascadeIndex].copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    for (let cornerIndex = 0;cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
      this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
    }
    this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);
    if (this.stabilizeCascades) {
      let sphereRadius = 0;
      for (let cornerIndex = 0;cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
        const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();
        sphereRadius = Math.max(sphereRadius, dist);
      }
      sphereRadius = Math.ceil(sphereRadius * 16) / 16;
      this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);
      this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);
    } else {
      const lightCameraPos = this._frustumCenter[cascadeIndex];
      this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1);
      Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix);
      for (let cornerIndex = 0;cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
        Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1);
        this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);
        this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);
      }
    }
  }
  _recreateSceneUBOs() {
    this._disposeSceneUBOs();
    if (this._sceneUBOs) {
      for (let i = 0;i < this._numCascades; ++i) {
        this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${i})`));
      }
    }
  }
  static get IsSupported() {
    const engine2 = EngineStore.LastCreatedEngine;
    if (!engine2) {
      return false;
    }
    return engine2._features.supportCSM;
  }
  constructor(mapSize, light, usefulFloatFirst, camera2, useRedTextureType = true) {
    if (!CascadedShadowGenerator.IsSupported) {
      Logger.Error("CascadedShadowMap is not supported by the current engine.");
      return;
    }
    super(mapSize, light, usefulFloatFirst, camera2, useRedTextureType);
    this.usePercentageCloserFiltering = true;
  }
  _initializeGenerator() {
    this.penumbraDarkness = this.penumbraDarkness ?? 1;
    this._numCascades = this._numCascades ?? CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
    this.stabilizeCascades = this.stabilizeCascades ?? false;
    this._freezeShadowCastersBoundingInfoObservable = this._freezeShadowCastersBoundingInfoObservable ?? null;
    this.freezeShadowCastersBoundingInfo = this.freezeShadowCastersBoundingInfo ?? false;
    this._scbiMin = this._scbiMin ?? new Vector3(0, 0, 0);
    this._scbiMax = this._scbiMax ?? new Vector3(0, 0, 0);
    this._shadowCastersBoundingInfo = this._shadowCastersBoundingInfo ?? new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
    this._breaksAreDirty = this._breaksAreDirty ?? true;
    this._minDistance = this._minDistance ?? 0;
    this._maxDistance = this._maxDistance ?? 1;
    this._currentLayer = this._currentLayer ?? 0;
    this._shadowMaxZ = this._shadowMaxZ ?? this._getCamera()?.maxZ ?? 1e4;
    this._debug = this._debug ?? false;
    this._depthClamp = this._depthClamp ?? true;
    this._cascadeBlendPercentage = this._cascadeBlendPercentage ?? 0.1;
    this._lambda = this._lambda ?? 0.5;
    this._autoCalcDepthBounds = this._autoCalcDepthBounds ?? false;
    this._recreateSceneUBOs();
    super._initializeGenerator();
  }
  _createTargetRenderTexture() {
    const engine2 = this._scene.getEngine();
    const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };
    this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined, this._useRedTextureType ? 6 : 5);
    this._shadowMap.createDepthStencilTexture(engine2.useReverseDepthBuffer ? 516 : 513, true, undefined, undefined, undefined, `DepthStencilForCSMShadowGenerator-${this._light.name}`);
    this._shadowMap.noPrePassRenderer = true;
  }
  _initializeShadowMap() {
    super._initializeShadowMap();
    if (this._shadowMap === null) {
      return;
    }
    this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);
    this._viewSpaceFrustumsZ = new Array(this._numCascades);
    this._frustumLengths = new Array(this._numCascades);
    this._lightSizeUVCorrection = new Array(this._numCascades * 2);
    this._depthCorrection = new Array(this._numCascades);
    this._cascades = [];
    this._viewMatrices = [];
    this._projectionMatrices = [];
    this._transformMatrices = [];
    this._cascadeMinExtents = [];
    this._cascadeMaxExtents = [];
    this._frustumCenter = [];
    this._shadowCameraPos = [];
    this._frustumCornersWorldSpace = [];
    for (let cascadeIndex = 0;cascadeIndex < this._numCascades; ++cascadeIndex) {
      this._cascades[cascadeIndex] = {
        prevBreakDistance: 0,
        breakDistance: 0
      };
      this._viewMatrices[cascadeIndex] = Matrix.Zero();
      this._projectionMatrices[cascadeIndex] = Matrix.Zero();
      this._transformMatrices[cascadeIndex] = Matrix.Zero();
      this._cascadeMinExtents[cascadeIndex] = new Vector3;
      this._cascadeMaxExtents[cascadeIndex] = new Vector3;
      this._frustumCenter[cascadeIndex] = new Vector3;
      this._shadowCameraPos[cascadeIndex] = new Vector3;
      this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);
      for (let i = 0;i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) {
        this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3;
      }
    }
    const engine2 = this._scene.getEngine();
    this._shadowMap.onBeforeBindObservable.clear();
    this._shadowMap.onBeforeRenderObservable.clear();
    this._shadowMap.onBeforeRenderObservable.add((layer) => {
      if (this._sceneUBOs) {
        this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]);
      }
      this._currentLayer = layer;
      if (this._filter === ShadowGenerator.FILTER_PCF) {
        engine2.setColorWrite(false);
      }
      this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer));
      if (this._useUBO) {
        this._scene.getSceneUniformBuffer().unbindEffect();
        this._scene.finalizeSceneUbo();
      }
    });
    this._shadowMap.onBeforeBindObservable.add(() => {
      this._currentSceneUBO = this._scene.getSceneUniformBuffer();
      engine2._debugPushGroup?.(`cascaded shadow map generation for pass id ${engine2.currentRenderPassId}`, 1);
      if (this._breaksAreDirty) {
        this._splitFrustum();
      }
      this._computeMatrices();
    });
    this._splitFrustum();
  }
  _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) {
    effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer));
  }
  _isReadyCustomDefines(defines) {
    defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"));
  }
  prepareDefines(defines, lightIndex) {
    super.prepareDefines(defines, lightIndex);
    const scene = this._scene;
    const light = this._light;
    if (!scene.shadowsEnabled || !light.shadowEnabled) {
      return;
    }
    defines["SHADOWCSM" + lightIndex] = true;
    defines["SHADOWCSMDEBUG" + lightIndex] = this.debug;
    defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades;
    defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem;
    const camera2 = this._getCamera();
    if (camera2 && this._shadowMaxZ <= (camera2.maxZ || this._shadowMaxZ)) {
      defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true;
    }
    if (this.cascadeBlendPercentage === 0) {
      defines["SHADOWCSMNOBLEND" + lightIndex] = true;
    }
  }
  bindShadowLight(lightIndex, effect) {
    const light = this._light;
    const scene = this._scene;
    if (!scene.shadowsEnabled || !light.shadowEnabled) {
      return;
    }
    const camera2 = this._getCamera();
    if (!camera2) {
      return;
    }
    const shadowMap = this.getShadowMap();
    if (!shadowMap) {
      return;
    }
    const width = shadowMap.getSize().width;
    effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray);
    effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ);
    effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 1e4 : 1 / this.cascadeBlendPercentage);
    effect.setArray("frustumLengths" + lightIndex, this._frustumLengths);
    if (this._filter === ShadowGenerator.FILTER_PCF) {
      effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
    } else if (this._filter === ShadowGenerator.FILTER_PCSS) {
      for (let cascadeIndex = 0;cascadeIndex < this._numCascades; ++cascadeIndex) {
        this._lightSizeUVCorrection[cascadeIndex * 2 + 0] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x);
        this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y);
        this._depthCorrection[cascadeIndex] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
      }
      effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap);
      effect.setTexture("depthTexture" + lightIndex, shadowMap);
      effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection);
      effect.setArray("depthCorrection" + lightIndex, this._depthCorrection);
      effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);
    } else {
      effect.setTexture("shadowTexture" + lightIndex, shadowMap);
      light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
    }
    light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera2), this.getLight().getDepthMinZ(camera2) + this.getLight().getDepthMaxZ(camera2), lightIndex);
  }
  getTransformMatrix() {
    return this.getCascadeTransformMatrix(0);
  }
  dispose() {
    super.dispose();
    if (this._freezeShadowCastersBoundingInfoObservable) {
      this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
      this._freezeShadowCastersBoundingInfoObservable = null;
    }
    if (this._depthReducer) {
      this._depthReducer.dispose();
      this._depthReducer = null;
    }
  }
  serialize() {
    const serializationObject = super.serialize();
    const shadowMap = this.getShadowMap();
    if (!shadowMap) {
      return serializationObject;
    }
    serializationObject.numCascades = this._numCascades;
    serializationObject.debug = this._debug;
    serializationObject.stabilizeCascades = this.stabilizeCascades;
    serializationObject.lambda = this._lambda;
    serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;
    serializationObject.depthClamp = this._depthClamp;
    serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;
    serializationObject.shadowMaxZ = this._shadowMaxZ;
    serializationObject.penumbraDarkness = this.penumbraDarkness;
    serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;
    serializationObject.minDistance = this.minDistance;
    serializationObject.maxDistance = this.maxDistance;
    serializationObject.renderList = [];
    if (shadowMap.renderList) {
      for (let meshIndex = 0;meshIndex < shadowMap.renderList.length; meshIndex++) {
        const mesh = shadowMap.renderList[meshIndex];
        serializationObject.renderList.push(mesh.id);
      }
    }
    return serializationObject;
  }
  static Parse(parsedShadowGenerator, scene) {
    const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera2) => new CascadedShadowGenerator(mapSize, light, undefined, camera2));
    if (parsedShadowGenerator.numCascades !== undefined) {
      shadowGenerator.numCascades = parsedShadowGenerator.numCascades;
    }
    if (parsedShadowGenerator.debug !== undefined) {
      shadowGenerator.debug = parsedShadowGenerator.debug;
    }
    if (parsedShadowGenerator.stabilizeCascades !== undefined) {
      shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;
    }
    if (parsedShadowGenerator.lambda !== undefined) {
      shadowGenerator.lambda = parsedShadowGenerator.lambda;
    }
    if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {
      shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;
    }
    if (parsedShadowGenerator.depthClamp !== undefined) {
      shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;
    }
    if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {
      shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;
    }
    if (parsedShadowGenerator.shadowMaxZ !== undefined) {
      shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;
    }
    if (parsedShadowGenerator.penumbraDarkness !== undefined) {
      shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;
    }
    if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {
      shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;
    }
    if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {
      shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);
    }
    return shadowGenerator;
  }
}
CascadedShadowGenerator._FrustumCornersNDCSpace = [
  new Vector3(-1, 1, -1),
  new Vector3(1, 1, -1),
  new Vector3(1, -1, -1),
  new Vector3(-1, -1, -1),
  new Vector3(-1, 1, 1),
  new Vector3(1, 1, 1),
  new Vector3(1, -1, 1),
  new Vector3(-1, -1, 1)
];
CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator";
CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;
CascadedShadowGenerator.MIN_CASCADES_COUNT = 2;
CascadedShadowGenerator.MAX_CASCADES_COUNT = 4;
CascadedShadowGenerator._SceneComponentInitialization = (_) => {
  throw _WarnImport("ShadowGeneratorSceneComponent");
};

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/shadowGeneratorTask.js
class FrameGraphShadowGeneratorTask extends FrameGraphTask {
  get light() {
    return this._light;
  }
  set light(value) {
    if (value === this._light) {
      return;
    }
    this._light = value;
    this._setupShadowGenerator();
  }
  get camera() {
    return this._camera;
  }
  set camera(camera2) {
    this._camera = camera2;
    this._setupShadowGenerator();
  }
  get mapSize() {
    return this._mapSize;
  }
  set mapSize(value) {
    if (value === this._mapSize) {
      return;
    }
    this._mapSize = value;
    this._setupShadowGenerator();
  }
  get useFloat32TextureType() {
    return this._useFloat32TextureType;
  }
  set useFloat32TextureType(value) {
    if (value === this._useFloat32TextureType) {
      return;
    }
    this._useFloat32TextureType = value;
    this._setupShadowGenerator();
  }
  get useRedTextureFormat() {
    return this._useRedTextureFormat;
  }
  set useRedTextureFormat(value) {
    if (value === this._useRedTextureFormat) {
      return;
    }
    this._useRedTextureFormat = value;
    this._setupShadowGenerator();
  }
  get bias() {
    return this._bias;
  }
  set bias(value) {
    if (value === this._bias) {
      return;
    }
    this._bias = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.bias = value;
    }
  }
  get normalBias() {
    return this._normalBias;
  }
  set normalBias(value) {
    if (value === this._normalBias) {
      return;
    }
    this._normalBias = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.normalBias = value;
    }
  }
  get darkness() {
    return this._darkness;
  }
  set darkness(value) {
    if (value === this._darkness) {
      return;
    }
    this._darkness = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.darkness = value;
    }
  }
  get transparencyShadow() {
    return this._transparencyShadow;
  }
  set transparencyShadow(value) {
    if (value === this._transparencyShadow) {
      return;
    }
    this._transparencyShadow = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.transparencyShadow = value;
    }
  }
  get enableSoftTransparentShadow() {
    return this._enableSoftTransparentShadow;
  }
  set enableSoftTransparentShadow(value) {
    if (value === this._enableSoftTransparentShadow) {
      return;
    }
    this._enableSoftTransparentShadow = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.enableSoftTransparentShadow = value;
    }
  }
  get useOpacityTextureForTransparentShadow() {
    return this._useOpacityTextureForTransparentShadow;
  }
  set useOpacityTextureForTransparentShadow(value) {
    if (value === this._useOpacityTextureForTransparentShadow) {
      return;
    }
    this._useOpacityTextureForTransparentShadow = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.useOpacityTextureForTransparentShadow = value;
    }
  }
  get filter() {
    return this._filter;
  }
  set filter(value) {
    if (value === this._filter) {
      return;
    }
    this._filter = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.filter = value;
    }
  }
  get filteringQuality() {
    return this._filteringQuality;
  }
  set filteringQuality(value) {
    if (value === this._filteringQuality) {
      return;
    }
    this._filteringQuality = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.filteringQuality = value;
    }
  }
  _createShadowGenerator() {
    this._shadowGenerator = new ShadowGenerator(this._mapSize, this._light, this._useFloat32TextureType, undefined, this._useRedTextureFormat);
  }
  _setupShadowGenerator() {
    this._shadowGenerator?.dispose();
    this._shadowGenerator = undefined;
    if (this._light !== undefined) {
      this._createShadowGenerator();
      const shadowGenerator = this._shadowGenerator;
      if (shadowGenerator === undefined) {
        return;
      }
      shadowGenerator.bias = this._bias;
      shadowGenerator.normalBias = this._normalBias;
      shadowGenerator.darkness = this._darkness;
      shadowGenerator.transparencyShadow = this._transparencyShadow;
      shadowGenerator.enableSoftTransparentShadow = this._enableSoftTransparentShadow;
      shadowGenerator.useOpacityTextureForTransparentShadow = this._useOpacityTextureForTransparentShadow;
      shadowGenerator.filter = this._filter;
      shadowGenerator.filteringQuality = this._filteringQuality;
      const shadowMap = shadowGenerator.getShadowMap();
      shadowMap._disableEngineStages = true;
      shadowMap.cameraForLOD = this._camera;
      this.shadowGenerator = shadowGenerator;
    }
  }
  isReady() {
    return !!this._shadowGenerator && !!this._shadowGenerator.getShadowMap()?.isReadyForRendering();
  }
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph);
    this._mapSize = 1024;
    this._useFloat32TextureType = false;
    this._useRedTextureFormat = true;
    this._bias = 0.01;
    this._normalBias = 0;
    this._darkness = 0;
    this._transparencyShadow = false;
    this._enableSoftTransparentShadow = false;
    this._useOpacityTextureForTransparentShadow = false;
    this._filter = ShadowGenerator.FILTER_PCF;
    this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
    this._engine = scene.getEngine();
    this._scene = scene;
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  record() {
    if (this.light === undefined || this.objectList === undefined || this.camera === undefined) {
      throw new Error(`FrameGraphShadowGeneratorTask ${this.name}: light, objectList and camera are required`);
    }
    const shadowMap = this._shadowGenerator.getShadowMap();
    shadowMap.renderList = this.objectList.meshes;
    shadowMap.particleSystemList = this.objectList.particleSystems;
    const shadowTextureHandle = this._frameGraph.textureManager.importTexture(`${this.name} shadowmap`, this._shadowGenerator.getShadowMap().getInternalTexture());
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, shadowTextureHandle);
    const pass = this._frameGraph.addPass(this.name);
    pass.setExecuteFunc((_context) => {
      if (!this.light.isEnabled() || !this.light.shadowEnabled) {
        return;
      }
      const shadowMap2 = this._shadowGenerator.getShadowMap();
      shadowMap2.renderList = this.objectList.meshes;
      shadowMap2.particleSystemList = this.objectList.particleSystems;
      const currentRenderTarget = this._engine._currentRenderTarget;
      this._scene.incrementRenderId();
      this._scene.resetCachedMaterial();
      shadowMap2.render();
      if (this._engine._currentRenderTarget !== currentRenderTarget) {
        if (!currentRenderTarget) {
          this._engine.restoreDefaultFramebuffer();
        } else {
          this._engine.bindFramebuffer(currentRenderTarget);
        }
      }
    });
    const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true);
    passDisabled.setExecuteFunc((_context) => {});
  }
  dispose() {
    this._shadowGenerator?.dispose();
    this._shadowGenerator = undefined;
  }
}

// node_modules/@babylonjs/core/Lights/directionalLight.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_node();

// node_modules/@babylonjs/core/Lights/shadowLight.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_math_axis();

class ShadowLight extends Light {
  constructor() {
    super(...arguments);
    this._needProjectionMatrixCompute = true;
    this._viewMatrix = Matrix.Identity();
    this._projectionMatrix = Matrix.Identity();
  }
  _setPosition(value) {
    this._position = value;
  }
  get position() {
    return this._position;
  }
  set position(value) {
    this._setPosition(value);
  }
  _setDirection(value) {
    this._direction = value;
  }
  get direction() {
    return this._direction;
  }
  set direction(value) {
    this._setDirection(value);
  }
  get shadowMinZ() {
    return this._shadowMinZ;
  }
  set shadowMinZ(value) {
    this._shadowMinZ = value;
    this.forceProjectionMatrixCompute();
  }
  get shadowMaxZ() {
    return this._shadowMaxZ;
  }
  set shadowMaxZ(value) {
    this._shadowMaxZ = value;
    this.forceProjectionMatrixCompute();
  }
  computeTransformedInformation() {
    if (this.parent && this.parent.getWorldMatrix) {
      if (!this.transformedPosition) {
        this.transformedPosition = Vector3.Zero();
      }
      Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
      if (this.direction) {
        if (!this.transformedDirection) {
          this.transformedDirection = Vector3.Zero();
        }
        Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
      }
      return true;
    }
    return false;
  }
  getDepthScale() {
    return 50;
  }
  getShadowDirection(faceIndex) {
    return this.transformedDirection ? this.transformedDirection : this.direction;
  }
  getAbsolutePosition() {
    return this.transformedPosition ? this.transformedPosition : this.position;
  }
  setDirectionToTarget(target) {
    this.direction = Vector3.Normalize(target.subtract(this.position));
    return this.direction;
  }
  getRotation() {
    this.direction.normalize();
    const xaxis = Vector3.Cross(this.direction, Axis.Y);
    const yaxis = Vector3.Cross(xaxis, this.direction);
    return Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  }
  needCube() {
    return false;
  }
  needProjectionMatrixCompute() {
    return this._needProjectionMatrixCompute;
  }
  forceProjectionMatrixCompute() {
    this._needProjectionMatrixCompute = true;
  }
  _initCache() {
    super._initCache();
    this._cache.position = Vector3.Zero();
  }
  _isSynchronized() {
    if (!this._cache.position.equals(this.position)) {
      return false;
    }
    return true;
  }
  computeWorldMatrix(force) {
    if (!force && this.isSynchronized()) {
      this._currentRenderId = this.getScene().getRenderId();
      return this._worldMatrix;
    }
    this._updateCache();
    this._cache.position.copyFrom(this.position);
    if (!this._worldMatrix) {
      this._worldMatrix = Matrix.Identity();
    }
    Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
    if (this.parent && this.parent.getWorldMatrix) {
      this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
      this._markSyncedWithParent();
    }
    this._worldMatrixDeterminantIsDirty = true;
    return this._worldMatrix;
  }
  getDepthMinZ(activeCamera) {
    return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0;
  }
  getDepthMaxZ(activeCamera) {
    return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 1e4;
  }
  setShadowProjectionMatrix(matrix, viewMatrix, renderList) {
    if (this.customProjectionMatrixBuilder) {
      this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
    } else {
      this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
    }
    return this;
  }
  _syncParentEnabledState() {
    super._syncParentEnabledState();
    if (!this.parent || !this.parent.getWorldMatrix) {
      this.transformedPosition = null;
      this.transformedDirection = null;
    }
  }
  getViewMatrix(faceIndex) {
    const lightDirection = TmpVectors.Vector3[0];
    let lightPosition = this.position;
    if (this.computeTransformedInformation()) {
      lightPosition = this.transformedPosition;
    }
    Vector3.NormalizeToRef(this.getShadowDirection(faceIndex), lightDirection);
    if (Math.abs(Vector3.Dot(lightDirection, Vector3.Up())) === 1) {
      lightDirection.z = 0.0000000000001;
    }
    const lightTarget = TmpVectors.Vector3[1];
    lightPosition.addToRef(lightDirection, lightTarget);
    Matrix.LookAtLHToRef(lightPosition, lightTarget, Vector3.Up(), this._viewMatrix);
    return this._viewMatrix;
  }
  getProjectionMatrix(viewMatrix, renderList) {
    this.setShadowProjectionMatrix(this._projectionMatrix, viewMatrix ?? this._viewMatrix, renderList ?? []);
    return this._projectionMatrix;
  }
}
__decorate([
  serializeAsVector3()
], ShadowLight.prototype, "position", null);
__decorate([
  serializeAsVector3()
], ShadowLight.prototype, "direction", null);
__decorate([
  serialize()
], ShadowLight.prototype, "shadowMinZ", null);
__decorate([
  serialize()
], ShadowLight.prototype, "shadowMaxZ", null);

// node_modules/@babylonjs/core/Lights/directionalLight.js
init_typeStore();
Node2.AddNodeConstructor("Light_Type_1", (name203, scene) => {
  return () => new DirectionalLight(name203, Vector3.Zero(), scene);
});

class DirectionalLight extends ShadowLight {
  get shadowFrustumSize() {
    return this._shadowFrustumSize;
  }
  set shadowFrustumSize(value) {
    this._shadowFrustumSize = value;
    this.forceProjectionMatrixCompute();
  }
  get shadowOrthoScale() {
    return this._shadowOrthoScale;
  }
  set shadowOrthoScale(value) {
    this._shadowOrthoScale = value;
    this.forceProjectionMatrixCompute();
  }
  get orthoLeft() {
    return this._orthoLeft;
  }
  set orthoLeft(left) {
    this._orthoLeft = left;
  }
  get orthoRight() {
    return this._orthoRight;
  }
  set orthoRight(right) {
    this._orthoRight = right;
  }
  get orthoTop() {
    return this._orthoTop;
  }
  set orthoTop(top) {
    this._orthoTop = top;
  }
  get orthoBottom() {
    return this._orthoBottom;
  }
  set orthoBottom(bottom) {
    this._orthoBottom = bottom;
  }
  constructor(name203, direction, scene) {
    super(name203, scene);
    this._shadowFrustumSize = 0;
    this._shadowOrthoScale = 0.1;
    this.autoUpdateExtends = true;
    this.autoCalcShadowZBounds = false;
    this._orthoLeft = Number.MAX_VALUE;
    this._orthoRight = Number.MIN_VALUE;
    this._orthoTop = Number.MIN_VALUE;
    this._orthoBottom = Number.MAX_VALUE;
    this.position = direction.scale(-1);
    this.direction = direction;
  }
  getClassName() {
    return "DirectionalLight";
  }
  getTypeID() {
    return Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  }
  _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
    if (this.shadowFrustumSize > 0) {
      this._setDefaultFixedFrustumShadowProjectionMatrix(matrix);
    } else {
      this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
    }
  }
  _setDefaultFixedFrustumShadowProjectionMatrix(matrix) {
    const activeCamera = this.getScene().activeCamera;
    if (!activeCamera) {
      return;
    }
    Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange);
  }
  _setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList) {
    const activeCamera = this.getScene().activeCamera;
    if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
      const tempVector3 = Vector3.Zero();
      this._orthoLeft = Number.MAX_VALUE;
      this._orthoRight = -Number.MAX_VALUE;
      this._orthoTop = -Number.MAX_VALUE;
      this._orthoBottom = Number.MAX_VALUE;
      let shadowMinZ = Number.MAX_VALUE;
      let shadowMaxZ = -Number.MAX_VALUE;
      for (let meshIndex = 0;meshIndex < renderList.length; meshIndex++) {
        const mesh = renderList[meshIndex];
        if (!mesh) {
          continue;
        }
        const boundingInfo2 = mesh.getBoundingInfo();
        const boundingBox2 = boundingInfo2.boundingBox;
        for (let index = 0;index < boundingBox2.vectorsWorld.length; index++) {
          Vector3.TransformCoordinatesToRef(boundingBox2.vectorsWorld[index], viewMatrix, tempVector3);
          if (tempVector3.x < this._orthoLeft) {
            this._orthoLeft = tempVector3.x;
          }
          if (tempVector3.y < this._orthoBottom) {
            this._orthoBottom = tempVector3.y;
          }
          if (tempVector3.x > this._orthoRight) {
            this._orthoRight = tempVector3.x;
          }
          if (tempVector3.y > this._orthoTop) {
            this._orthoTop = tempVector3.y;
          }
          if (this.autoCalcShadowZBounds) {
            if (tempVector3.z < shadowMinZ) {
              shadowMinZ = tempVector3.z;
            }
            if (tempVector3.z > shadowMaxZ) {
              shadowMaxZ = tempVector3.z;
            }
          }
        }
      }
      if (this.autoCalcShadowZBounds) {
        this._shadowMinZ = shadowMinZ;
        this._shadowMaxZ = shadowMaxZ;
      }
    }
    const xOffset = this._orthoRight - this._orthoLeft;
    const yOffset = this._orthoTop - this._orthoBottom;
    const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ || 0;
    const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ || 1e4;
    const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
    Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange);
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("vLightData", 4);
    this._uniformBuffer.addUniform("vLightDiffuse", 4);
    this._uniformBuffer.addUniform("vLightSpecular", 4);
    this._uniformBuffer.addUniform("shadowsInfo", 3);
    this._uniformBuffer.addUniform("depthValues", 2);
    this._uniformBuffer.create();
  }
  transferToEffect(effect, lightIndex) {
    if (this.computeTransformedInformation()) {
      this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
      return this;
    }
    this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
    return this;
  }
  transferToNodeMaterialEffect(effect, lightDataUniformName) {
    if (this.computeTransformedInformation()) {
      effect.setFloat3(lightDataUniformName, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z);
      return this;
    }
    effect.setFloat3(lightDataUniformName, this.direction.x, this.direction.y, this.direction.z);
    return this;
  }
  getDepthMinZ(_activeCamera) {
    const engine2 = this._scene.getEngine();
    return !engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1;
  }
  getDepthMaxZ(_activeCamera) {
    const engine2 = this._scene.getEngine();
    return engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1;
  }
  prepareLightSpecificDefines(defines, lightIndex) {
    defines["DIRLIGHT" + lightIndex] = true;
  }
}
__decorate([
  serialize()
], DirectionalLight.prototype, "shadowFrustumSize", null);
__decorate([
  serialize()
], DirectionalLight.prototype, "shadowOrthoScale", null);
__decorate([
  serialize()
], DirectionalLight.prototype, "autoUpdateExtends", undefined);
__decorate([
  serialize()
], DirectionalLight.prototype, "autoCalcShadowZBounds", undefined);
__decorate([
  serialize("orthoLeft")
], DirectionalLight.prototype, "_orthoLeft", undefined);
__decorate([
  serialize("orthoRight")
], DirectionalLight.prototype, "_orthoRight", undefined);
__decorate([
  serialize("orthoTop")
], DirectionalLight.prototype, "_orthoTop", undefined);
__decorate([
  serialize("orthoBottom")
], DirectionalLight.prototype, "_orthoBottom", undefined);
RegisterClass("BABYLON.DirectionalLight", DirectionalLight);

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/csmShadowGeneratorTask.js
class FrameGraphCascadedShadowGeneratorTask extends FrameGraphShadowGeneratorTask {
  constructor() {
    super(...arguments);
    this._numCascades = CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
    this._debug = false;
    this._stabilizeCascades = false;
    this._lambda = 0.5;
    this._cascadeBlendPercentage = 0.1;
    this._depthClamp = true;
    this._autoCalcDepthBounds = false;
    this._shadowMaxZ = 1e4;
  }
  static IsCascadedShadowGenerator(task) {
    return task.numCascades !== undefined;
  }
  get numCascades() {
    return this._numCascades;
  }
  set numCascades(value) {
    if (value === this._numCascades) {
      return;
    }
    this._numCascades = value;
    this._setupShadowGenerator();
  }
  get debug() {
    return this._debug;
  }
  set debug(value) {
    if (value === this._debug) {
      return;
    }
    this._debug = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.debug = value;
    }
  }
  get stabilizeCascades() {
    return this._stabilizeCascades;
  }
  set stabilizeCascades(value) {
    if (value === this._stabilizeCascades) {
      return;
    }
    this._stabilizeCascades = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.stabilizeCascades = value;
    }
  }
  get lambda() {
    return this._lambda;
  }
  set lambda(value) {
    if (value === this._lambda) {
      return;
    }
    this._lambda = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.lambda = value;
    }
  }
  get cascadeBlendPercentage() {
    return this._cascadeBlendPercentage;
  }
  set cascadeBlendPercentage(value) {
    if (value === this._cascadeBlendPercentage) {
      return;
    }
    this._cascadeBlendPercentage = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.cascadeBlendPercentage = value;
    }
  }
  get depthClamp() {
    return this._depthClamp;
  }
  set depthClamp(value) {
    if (value === this._depthClamp) {
      return;
    }
    this._depthClamp = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.depthClamp = value;
    }
  }
  get autoCalcDepthBounds() {
    return this._autoCalcDepthBounds;
  }
  set autoCalcDepthBounds(value) {
    if (value === this._autoCalcDepthBounds) {
      return;
    }
    this._autoCalcDepthBounds = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.autoCalcDepthBounds = value;
    }
  }
  get shadowMaxZ() {
    return this._shadowMaxZ;
  }
  set shadowMaxZ(value) {
    if (value === this._shadowMaxZ) {
      return;
    }
    this._shadowMaxZ = value;
    if (this._shadowGenerator) {
      this._shadowGenerator.shadowMaxZ = value;
    }
  }
  _createShadowGenerator() {
    if (!(this.light instanceof DirectionalLight)) {
      throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: the CSM shadow generator only supports directional lights.`);
    }
    this._shadowGenerator = new CascadedShadowGenerator(this.mapSize, this.light, this.useFloat32TextureType, this.camera, this.useRedTextureFormat);
    this._shadowGenerator.numCascades = this._numCascades;
  }
  _setupShadowGenerator() {
    super._setupShadowGenerator();
    const shadowGenerator = this._shadowGenerator;
    if (shadowGenerator === undefined) {
      return;
    }
    shadowGenerator.debug = this._debug;
    shadowGenerator.stabilizeCascades = this._stabilizeCascades;
    shadowGenerator.lambda = this._lambda;
    shadowGenerator.cascadeBlendPercentage = this._cascadeBlendPercentage;
    shadowGenerator.depthClamp = this._depthClamp;
    shadowGenerator.autoCalcDepthBounds = this._autoCalcDepthBounds;
    shadowGenerator.shadowMaxZ = this._shadowMaxZ;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js
class FrameGraphObjectRendererTask extends FrameGraphTask {
  get camera() {
    return this._camera;
  }
  set camera(camera2) {
    this._camera = camera2;
    this._renderer.activeCamera = this.camera;
  }
  get objectRenderer() {
    return this._renderer;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
    if (this._renderer) {
      this._renderer.name = value;
    }
  }
  constructor(name203, frameGraph, scene, options, existingObjectRenderer) {
    super(name203, frameGraph);
    this.shadowGenerators = [];
    this.depthTest = true;
    this.depthWrite = true;
    this.disableShadows = false;
    this.renderInLinearSpace = false;
    this._onBeforeRenderObservable = null;
    this._onAfterRenderObservable = null;
    this._externalObjectRenderer = false;
    this._scene = scene;
    this._externalObjectRenderer = !!existingObjectRenderer;
    this._renderer = existingObjectRenderer ?? new ObjectRenderer(name203, scene, options);
    this.name = name203;
    if (!this._externalObjectRenderer) {
      this._renderer.onBeforeRenderingManagerRenderObservable.add(() => {
        if (!this._renderer.options.doNotChangeAspectRatio) {
          scene.updateTransformMatrix(true);
        }
      });
    }
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  isReady() {
    return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight);
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute) {
    if (this.targetTexture === undefined || this.objectList === undefined) {
      throw new Error(`FrameGraphObjectRendererTask ${this.name}: targetTexture and objectList are required`);
    }
    this._renderer.renderList = this.objectList.meshes;
    this._renderer.particleSystemList = this.objectList.particleSystems;
    this._renderer.renderInLinearSpace = this.renderInLinearSpace;
    const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture);
    let depthEnabled = false;
    if (this.depthTexture !== undefined) {
      if (this.depthTexture === backbufferDepthStencilTextureHandle && this.targetTexture !== backbufferColorTextureHandle) {
        throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`);
      }
      if (this.depthTexture !== backbufferDepthStencilTextureHandle && this.targetTexture === backbufferColorTextureHandle) {
        throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the target is the back buffer color`);
      }
      const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture);
      if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) {
        throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);
      }
      depthEnabled = true;
    }
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    if (this.depthTexture !== undefined) {
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture);
    }
    this._textureWidth = outputTextureDescription.size.width;
    this._textureHeight = outputTextureDescription.size.height;
    this._setLightsForShadow();
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(this.targetTexture);
    pass.setRenderTargetDepth(this.depthTexture);
    pass.setExecuteFunc((context) => {
      this._renderer.renderList = this.objectList.meshes;
      this._renderer.particleSystemList = this.objectList.particleSystems;
      this._renderer.renderInLinearSpace = this.renderInLinearSpace;
      context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled);
      context.render(this._renderer, this._textureWidth, this._textureHeight);
      additionalExecute?.(context);
    });
    if (!skipCreationOfDisabledPasses) {
      const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
      passDisabled.setRenderTarget(this.targetTexture);
      passDisabled.setRenderTargetDepth(this.depthTexture);
      passDisabled.setExecuteFunc((_context) => {});
    }
    return pass;
  }
  dispose() {
    this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable);
    this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable);
    if (!this._externalObjectRenderer) {
      this._renderer.dispose();
    }
    super.dispose();
  }
  _setLightsForShadow() {
    const lightsForShadow = new Set;
    const shadowEnabled = new Map;
    if (this.shadowGenerators) {
      for (const shadowGeneratorTask of this.shadowGenerators) {
        const shadowGenerator = shadowGeneratorTask.shadowGenerator;
        const light = shadowGenerator.getLight();
        if (light.isEnabled() && light.shadowEnabled) {
          lightsForShadow.add(light);
          if (FrameGraphCascadedShadowGeneratorTask.IsCascadedShadowGenerator(shadowGeneratorTask)) {
            light._shadowGenerators.set(shadowGeneratorTask.camera, shadowGenerator);
          } else {
            light._shadowGenerators.set(null, shadowGenerator);
          }
        }
      }
    }
    this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable);
    this._onBeforeRenderObservable = this._renderer.onBeforeRenderObservable.add(() => {
      for (let i = 0;i < this._scene.lights.length; i++) {
        const light = this._scene.lights[i];
        shadowEnabled.set(light, light.shadowEnabled);
        light.shadowEnabled = !this.disableShadows && lightsForShadow.has(light);
      }
    });
    this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable);
    this._onAfterRenderObservable = this._renderer.onAfterRenderObservable.add(() => {
      for (let i = 0;i < this._scene.lights.length; i++) {
        const light = this._scene.lights[i];
        light.shadowEnabled = shadowEnabled.get(light);
      }
    });
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/baseObjectRendererBlock.js
init_tslib_es6();

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphConnectionPointCustomObject.js
class NodeRenderGraphConnectionPointCustomObject extends NodeRenderGraphConnectionPoint {
  constructor(name203, ownerBlock, direction, _blockType, _blockName) {
    super(name203, ownerBlock, direction);
    this._blockType = _blockType;
    this._blockName = _blockName;
    this.needDualDirectionValidation = true;
  }
  checkCompatibilityState(connectionPoint) {
    return connectionPoint instanceof NodeRenderGraphConnectionPointCustomObject && connectionPoint._blockName === this._blockName ? 0 : 1;
  }
  createCustomInputBlock() {
    return [new this._blockType(this._blockName), this.name];
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/baseObjectRendererBlock.js
class NodeRenderGraphBaseObjectRendererBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph, scene);
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this._addDependenciesInput();
    this.registerInput("shadowGenerators", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 1, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock"));
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil);
    this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment);
    this.shadowGenerators.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator | NodeRenderGraphBlockConnectionPointTypes.ResourceContainer);
    this.output._typeConnectionSource = this.target;
    this.outputDepth._typeConnectionSource = this.depth;
  }
  get depthTest() {
    return this._frameGraphTask.depthTest;
  }
  set depthTest(value) {
    this._frameGraphTask.depthTest = value;
  }
  get depthWrite() {
    return this._frameGraphTask.depthWrite;
  }
  set depthWrite(value) {
    this._frameGraphTask.depthWrite = value;
  }
  get disableShadows() {
    return this._frameGraphTask.disableShadows;
  }
  set disableShadows(value) {
    this._frameGraphTask.disableShadows = value;
  }
  get renderInLinearSpace() {
    return this._frameGraphTask.renderInLinearSpace;
  }
  set renderInLinearSpace(value) {
    this._frameGraphTask.renderInLinearSpace = value;
  }
  getClassName() {
    return "NodeRenderGraphBaseObjectRendererBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get depth() {
    return this._inputs[1];
  }
  get camera() {
    return this._inputs[2];
  }
  get objects() {
    return this._inputs[3];
  }
  get dependencies() {
    return this._inputs[4];
  }
  get shadowGenerators() {
    return this._inputs[5];
  }
  get output() {
    return this._outputs[0];
  }
  get outputDepth() {
    return this._outputs[1];
  }
  get objectRenderer() {
    return this._outputs[2];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this.outputDepth.value = this._frameGraphTask.outputDepthTexture;
    this.objectRenderer.value = this._frameGraphTask;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
    this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
    this._frameGraphTask.objectList = this.objects.connectedPoint?.value;
    this._frameGraphTask.shadowGenerators = [];
    const shadowGeneratorsConnectedPoint = this.shadowGenerators.connectedPoint;
    if (shadowGeneratorsConnectedPoint) {
      if (shadowGeneratorsConnectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.ResourceContainer) {
        const container = shadowGeneratorsConnectedPoint.ownerBlock;
        container.inputs.forEach((input) => {
          if (input.connectedPoint && input.connectedPoint.value !== undefined && NodeRenderGraphConnectionPoint.IsShadowGenerator(input.connectedPoint.value)) {
            this._frameGraphTask.shadowGenerators.push(input.connectedPoint.value);
          }
        });
      } else if (NodeRenderGraphConnectionPoint.IsShadowGenerator(shadowGeneratorsConnectedPoint.value)) {
        this._frameGraphTask.shadowGenerators[0] = shadowGeneratorsConnectedPoint.value;
      }
    }
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`);
    codes.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`);
    codes.push(`${this._codeVariableName}.disableShadows = ${this.disableShadows};`);
    codes.push(`${this._codeVariableName}.renderInLinearSpace = ${this.renderInLinearSpace};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.depthTest = this.depthTest;
    serializationObject.depthWrite = this.depthWrite;
    serializationObject.disableShadows = this.disableShadows;
    serializationObject.renderInLinearSpace = this.renderInLinearSpace;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.depthTest = serializationObject.depthTest;
    this.depthWrite = serializationObject.depthWrite;
    this.disableShadows = serializationObject.disableShadows;
    this.renderInLinearSpace = !!serializationObject.renderInLinearSpace;
  }
}
__decorate([
  editableInPropertyPage("Depth test", 0, "PROPERTIES")
], NodeRenderGraphBaseObjectRendererBlock.prototype, "depthTest", null);
__decorate([
  editableInPropertyPage("Depth write", 0, "PROPERTIES")
], NodeRenderGraphBaseObjectRendererBlock.prototype, "depthWrite", null);
__decorate([
  editableInPropertyPage("Disable shadows", 0, "PROPERTIES")
], NodeRenderGraphBaseObjectRendererBlock.prototype, "disableShadows", null);
__decorate([
  editableInPropertyPage("Render in linear space", 0, "PROPERTIES")
], NodeRenderGraphBaseObjectRendererBlock.prototype, "renderInLinearSpace", null);

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/objectRendererBlock.js
class NodeRenderGraphObjectRendererBlock extends NodeRenderGraphBaseObjectRendererBlock {
  constructor(name203, frameGraph, scene, doNotChangeAspectRatio = true) {
    super(name203, frameGraph, scene);
    this._additionalConstructionParameters = [doNotChangeAspectRatio];
    this._frameGraphTask = new FrameGraphObjectRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio });
  }
  get doNotChangeAspectRatio() {
    return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio;
  }
  set doNotChangeAspectRatio(value) {
    const disabled = this._frameGraphTask.disabled;
    const depthTest = this.depthTest;
    const depthWrite = this.depthWrite;
    const disableShadows = this.disableShadows;
    const renderInLinearSpace = this.renderInLinearSpace;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphObjectRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value });
    this._additionalConstructionParameters = [value];
    this.depthTest = depthTest;
    this.depthWrite = depthWrite;
    this.disableShadows = disableShadows;
    this.renderInLinearSpace = renderInLinearSpace;
    this._frameGraphTask.disabled = disabled;
  }
  getClassName() {
    return "NodeRenderGraphObjectRendererBlock";
  }
}
__decorate([
  editableInPropertyPage("Do not change aspect ratio", 0, "PROPERTIES")
], NodeRenderGraphObjectRendererBlock.prototype, "doNotChangeAspectRatio", null);
RegisterClass("BABYLON.NodeRenderGraphObjectRendererBlock", NodeRenderGraphObjectRendererBlock);

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraphBuildState.js
init_logger();

class NodeRenderGraphBuildState {
  constructor() {
    this.verbose = false;
    this._notConnectedNonOptionalInputs = [];
  }
  emitErrors(errorObservable = null) {
    let errorMessage = "";
    for (const notConnectedInput of this._notConnectedNonOptionalInputs) {
      errorMessage += `input "${notConnectedInput.name}" from block "${notConnectedInput.ownerBlock.name}"[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.
`;
    }
    if (errorMessage) {
      if (errorObservable) {
        errorObservable.notifyObservers(errorMessage);
      }
      Logger.Error(`Build of node render graph failed:
` + errorMessage);
      return false;
    }
    return true;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/nodeRenderGraph.js
class NodeRenderGraph {
  _getGlobalNodeRenderGraphEditor() {
    if (typeof NODERENDERGRAPHEDITOR !== "undefined") {
      return NODERENDERGRAPHEDITOR;
    }
    if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeRenderGraphEditor !== "undefined") {
      return BABYLON;
    }
    return;
  }
  get frameGraph() {
    return this._frameGraph;
  }
  getScene() {
    return this._scene;
  }
  constructor(name203, scene, options) {
    this._buildId = NodeRenderGraph._BuildIdGenerator++;
    this.BJSNODERENDERGRAPHEDITOR = this._getGlobalNodeRenderGraphEditor();
    this.editorData = null;
    this.attachedBlocks = [];
    this.onBuildObservable = new Observable;
    this.onBuildErrorObservable = new Observable;
    this.outputBlock = null;
    this._resizeObserver = null;
    this.name = name203;
    this._scene = scene;
    this._engine = scene.getEngine();
    options = {
      debugTextures: false,
      autoConfigure: false,
      verbose: false,
      rebuildGraphOnEngineResize: true,
      autoFillExternalInputs: true,
      ...options
    };
    this._options = options;
    this._frameGraph = new FrameGraph(this._scene, options.debugTextures, this);
    this._frameGraph.name = name203;
    if (options.rebuildGraphOnEngineResize) {
      this._resizeObserver = this._engine.onResizeObservable.add(() => {
        this.build();
      });
    }
  }
  getClassName() {
    return "NodeRenderGraph";
  }
  getBlockByName(name203) {
    let result = null;
    for (const block of this.attachedBlocks) {
      if (block.name === name203) {
        if (!result) {
          result = block;
        } else {
          Tools.Warn("More than one block was found with the name `" + name203 + "`");
          return result;
        }
      }
    }
    return result;
  }
  getBlockByPredicate(predicate) {
    for (const block of this.attachedBlocks) {
      if (predicate(block)) {
        return block;
      }
    }
    return null;
  }
  getBlocksByPredicate(predicate) {
    const blocks = [];
    for (const block of this.attachedBlocks) {
      if (predicate(block)) {
        blocks.push(block);
      }
    }
    return blocks;
  }
  getInputBlocks() {
    const blocks = [];
    for (const block of this.attachedBlocks) {
      if (block.isInput) {
        blocks.push(block);
      }
    }
    return blocks;
  }
  edit(config) {
    return new Promise((resolve3) => {
      this.BJSNODERENDERGRAPHEDITOR = this.BJSNODERENDERGRAPHEDITOR || this._getGlobalNodeRenderGraphEditor();
      if (typeof this.BJSNODERENDERGRAPHEDITOR == "undefined") {
        const editorUrl = config && config.editorURL ? config.editorURL : NodeRenderGraph.EditorURL;
        Tools.LoadBabylonScript(editorUrl, () => {
          this.BJSNODERENDERGRAPHEDITOR = this.BJSNODERENDERGRAPHEDITOR || this._getGlobalNodeRenderGraphEditor();
          this._createNodeEditor(config?.nodeRenderGraphEditorConfig);
          resolve3();
        });
      } else {
        this._createNodeEditor(config?.nodeRenderGraphEditorConfig);
        resolve3();
      }
    });
  }
  _createNodeEditor(additionalConfig) {
    const nodeEditorConfig = {
      nodeRenderGraph: this,
      ...additionalConfig
    };
    this.BJSNODERENDERGRAPHEDITOR.NodeRenderGraphEditor.Show(nodeEditorConfig);
  }
  build() {
    if (!this.outputBlock) {
      throw new Error("You must define the outputBlock property before building the node render graph");
    }
    this._initializeBlock(this.outputBlock);
    this._frameGraph.clear();
    const state = new NodeRenderGraphBuildState;
    state.buildId = this._buildId;
    state.verbose = this._options.verbose;
    if (this._options.autoFillExternalInputs) {
      this._autoFillExternalInputs();
    }
    try {
      this.outputBlock.build(state);
      this._frameGraph.build();
    } finally {
      this._buildId = NodeRenderGraph._BuildIdGenerator++;
      if (state.emitErrors(this.onBuildErrorObservable)) {
        this.onBuildObservable.notifyObservers(this);
      }
    }
  }
  _autoFillExternalInputs() {
    const allInputs = this.getInputBlocks();
    const shadowLights = [];
    for (const light of this._scene.lights) {
      if (light.setShadowProjectionMatrix !== undefined) {
        shadowLights.push(light);
      }
    }
    let cameraIndex = 0;
    let lightIndex = 0;
    for (const input of allInputs) {
      if (!input.isExternal) {
        continue;
      }
      if (!input.isAnAncestorOfType("NodeRenderGraphOutputBlock")) {
        continue;
      }
      if ((input.type & NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer) !== 0) {} else if (input.isCamera()) {
        const camera2 = this._scene.cameras[cameraIndex++] || this._scene.cameras[0];
        if (!this._scene.cameraToUseForPointers) {
          this._scene.cameraToUseForPointers = camera2;
        }
        input.value = camera2;
      } else if (input.isObjectList()) {
        input.value = { meshes: this._scene.meshes, particleSystems: this._scene.particleSystems };
      } else if (input.isShadowLight()) {
        if (lightIndex < shadowLights.length) {
          input.value = shadowLights[lightIndex++];
          lightIndex = lightIndex % shadowLights.length;
        }
      }
    }
  }
  whenReadyAsync(timeStep = 16, maxTimeout = 30000) {
    return this._frameGraph.whenReadyAsync(timeStep, maxTimeout);
  }
  execute() {
    this._frameGraph.execute();
  }
  _initializeBlock(node) {
    node.initialize();
    if (this._options.autoConfigure) {
      node.autoConfigure();
    }
    if (this.attachedBlocks.indexOf(node) === -1) {
      this.attachedBlocks.push(node);
    }
    for (const input of node.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint) {
        const block = connectedPoint.ownerBlock;
        if (block !== node) {
          this._initializeBlock(block);
        }
      }
    }
  }
  clear() {
    this.outputBlock = null;
    this.attachedBlocks.length = 0;
  }
  removeBlock(block) {
    const attachedBlockIndex = this.attachedBlocks.indexOf(block);
    if (attachedBlockIndex > -1) {
      this.attachedBlocks.splice(attachedBlockIndex, 1);
    }
    if (block === this.outputBlock) {
      this.outputBlock = null;
    }
  }
  parseSerializedObject(source, merge = false) {
    if (!merge) {
      this.clear();
    }
    const map = {};
    for (const parsedBlock of source.blocks) {
      const blockType = GetClass(parsedBlock.customType);
      if (blockType) {
        const additionalConstructionParameters = parsedBlock.additionalConstructionParameters;
        const block = additionalConstructionParameters ? new blockType("", this._frameGraph, this._scene, ...additionalConstructionParameters) : new blockType("", this._frameGraph, this._scene);
        block._deserialize(parsedBlock);
        map[parsedBlock.id] = block;
        this.attachedBlocks.push(block);
      }
    }
    for (const block of this.attachedBlocks) {
      if (block.isTeleportOut) {
        const teleportOut = block;
        const id = teleportOut._tempEntryPointUniqueId;
        if (id) {
          const source2 = map[id];
          if (source2) {
            source2.attachToEndpoint(teleportOut);
          }
        }
      }
    }
    for (let blockIndex = 0;blockIndex < source.blocks.length; blockIndex++) {
      const parsedBlock = source.blocks[blockIndex];
      const block = map[parsedBlock.id];
      if (!block) {
        continue;
      }
      if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) {
        continue;
      }
      this._restoreConnections(block, source, map);
    }
    if (source.outputNodeId) {
      this.outputBlock = map[source.outputNodeId];
    }
    if (source.locations || source.editorData && source.editorData.locations) {
      const locations = source.locations || source.editorData.locations;
      for (const location2 of locations) {
        if (map[location2.blockId]) {
          location2.blockId = map[location2.blockId].uniqueId;
        }
      }
      if (merge && this.editorData && this.editorData.locations) {
        locations.concat(this.editorData.locations);
      }
      if (source.locations) {
        this.editorData = {
          locations
        };
      } else {
        this.editorData = source.editorData;
        this.editorData.locations = locations;
      }
      const blockMap = [];
      for (const key in map) {
        blockMap[key] = map[key].uniqueId;
      }
      this.editorData.map = blockMap;
    }
    this.comment = source.comment;
  }
  _restoreConnections(block, source, map) {
    for (const outputPoint of block.outputs) {
      for (const candidate of source.blocks) {
        const target = map[candidate.id];
        if (!target) {
          continue;
        }
        for (const input of candidate.inputs) {
          if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
            const inputPoint = target.getInputByName(input.inputName);
            if (!inputPoint || inputPoint.isConnected) {
              continue;
            }
            outputPoint.connectTo(inputPoint, true);
            this._restoreConnections(target, source, map);
            continue;
          }
        }
      }
    }
  }
  generateCode() {
    let alreadyDumped = [];
    const blocks = [];
    const uniqueNames = ["const", "var", "let"];
    if (this.outputBlock) {
      this._gatherBlocks(this.outputBlock, blocks);
    }
    const options = JSON.stringify(this._options);
    let codeString = `let nodeRenderGraph = new BABYLON.NodeRenderGraph("${this.name || "render graph"}", scene, ${options});
`;
    for (const node of blocks) {
      if (node.isInput && alreadyDumped.indexOf(node) === -1) {
        codeString += node._dumpCode(uniqueNames, alreadyDumped) + `
`;
      }
    }
    if (this.outputBlock) {
      alreadyDumped = [];
      codeString += `// Connections
`;
      codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped);
      codeString += `// Output nodes
`;
      codeString += `nodeRenderGraph.outputBlock = ${this.outputBlock._codeVariableName};
`;
      codeString += `nodeRenderGraph.build();
`;
    }
    return codeString;
  }
  _gatherBlocks(rootNode, list) {
    if (list.indexOf(rootNode) !== -1) {
      return;
    }
    list.push(rootNode);
    for (const input of rootNode.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint) {
        const block = connectedPoint.ownerBlock;
        if (block !== rootNode) {
          this._gatherBlocks(block, list);
        }
      }
    }
    if (rootNode.isTeleportOut) {
      const block = rootNode;
      if (block.entryPoint) {
        this._gatherBlocks(block.entryPoint, list);
      }
    }
  }
  setToDefault() {
    this.clear();
    this.editorData = null;
    const colorTexture = new NodeRenderGraphInputBlock("Color Texture", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.Texture);
    colorTexture.creationOptions.options.samples = 4;
    const depthTexture = new NodeRenderGraphInputBlock("Depth Texture", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment);
    depthTexture.creationOptions.options.samples = 4;
    const clear = new NodeRenderGraphClearBlock("Clear", this._frameGraph, this._scene);
    clear.clearDepth = true;
    clear.clearStencil = true;
    colorTexture.output.connectTo(clear.target);
    depthTexture.output.connectTo(clear.depth);
    const camera2 = new NodeRenderGraphInputBlock("Camera", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.Camera);
    const objectList = new NodeRenderGraphInputBlock("Object List", this._frameGraph, this._scene, NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    const mainRendering = new NodeRenderGraphObjectRendererBlock("Main Rendering", this._frameGraph, this._scene);
    camera2.output.connectTo(mainRendering.camera);
    objectList.output.connectTo(mainRendering.objects);
    clear.output.connectTo(mainRendering.target);
    clear.outputDepth.connectTo(mainRendering.depth);
    const output = new NodeRenderGraphOutputBlock("Output", this._frameGraph, this._scene);
    mainRendering.output.connectTo(output.texture);
    this.outputBlock = output;
  }
  clone(name203) {
    const serializationObject = this.serialize();
    const clone = SerializationHelper.Clone(() => new NodeRenderGraph(name203, this._scene), this);
    clone.name = name203;
    clone.parseSerializedObject(serializationObject);
    clone._buildId = this._buildId;
    clone.build();
    return clone;
  }
  serialize(selectedBlocks) {
    const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
    serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData));
    let blocks = [];
    if (selectedBlocks) {
      blocks = selectedBlocks;
    } else {
      serializationObject.customType = "BABYLON.NodeRenderGraph";
      if (this.outputBlock) {
        serializationObject.outputNodeId = this.outputBlock.uniqueId;
      }
    }
    serializationObject.blocks = [];
    for (const block of blocks) {
      serializationObject.blocks.push(block.serialize());
    }
    if (!selectedBlocks) {
      for (const block of this.attachedBlocks) {
        if (blocks.indexOf(block) !== -1) {
          continue;
        }
        serializationObject.blocks.push(block.serialize());
      }
    }
    return serializationObject;
  }
  dispose() {
    for (const block of this.attachedBlocks) {
      block.dispose();
    }
    this._frameGraph.dispose();
    this._frameGraph = undefined;
    this._engine.onResizeObservable.remove(this._resizeObserver);
    this._resizeObserver = null;
    this.attachedBlocks.length = 0;
    this.onBuildObservable.clear();
    this.onBuildErrorObservable.clear();
  }
  static CreateDefault(name203, scene, nodeRenderGraphOptions) {
    const renderGraph = new NodeRenderGraph(name203, scene, nodeRenderGraphOptions);
    renderGraph.setToDefault();
    renderGraph.build();
    return renderGraph;
  }
  static Parse(source, scene, nodeRenderGraphOptions, skipBuild = true) {
    const renderGraph = SerializationHelper.Parse(() => new NodeRenderGraph(source.name, scene, nodeRenderGraphOptions), source, null);
    renderGraph.parseSerializedObject(source);
    if (!skipBuild) {
      renderGraph.build();
    }
    return renderGraph;
  }
  static ParseFromSnippetAsync(snippetId, scene, nodeRenderGraphOptions, nodeRenderGraph, skipBuild = true) {
    if (snippetId === "_BLANK") {
      return Promise.resolve(NodeRenderGraph.CreateDefault("blank", scene, nodeRenderGraphOptions));
    }
    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);
            const serializationObject = JSON.parse(snippet.nodeRenderGraph);
            if (!nodeRenderGraph) {
              nodeRenderGraph = SerializationHelper.Parse(() => new NodeRenderGraph(snippetId, scene, nodeRenderGraphOptions), serializationObject, null);
            }
            nodeRenderGraph.parseSerializedObject(serializationObject);
            nodeRenderGraph.snippetId = snippetId;
            try {
              if (!skipBuild) {
                nodeRenderGraph.build();
              }
              resolve3(nodeRenderGraph);
            } catch (err) {
              reject(err);
            }
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
}
NodeRenderGraph._BuildIdGenerator = 0;
NodeRenderGraph.EditorURL = `${Tools._DefaultCdnUrl}/v${Engine.Version}/NodeRenderGraph/babylon.nodeRenderGraph.js`;
NodeRenderGraph.SnippetUrl = `https://snippet.babylonjs.com`;
__decorate([
  serialize()
], NodeRenderGraph.prototype, "name", undefined);
__decorate([
  serialize("comment")
], NodeRenderGraph.prototype, "comment", undefined);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/cullObjectsBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Misc/cullObjectsTask.js
class FrameGraphCullObjectsTask extends FrameGraphTask {
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph);
    this._scene = scene;
    this.outputObjectList = {
      meshes: [],
      particleSystems: []
    };
  }
  record() {
    if (this.objectList === undefined || this.camera === undefined) {
      throw new Error(`FrameGraphCullObjectsTask ${this.name}: objectList and camera are required`);
    }
    const pass = this._frameGraph.addCullPass(this.name);
    pass.setObjectList(this.outputObjectList);
    pass.setExecuteFunc((_context) => {
      this.outputObjectList.meshes = [];
      this.camera._updateFrustumPlanes();
      const frustumPlanes = this.camera._frustumPlanes;
      const meshes = this.objectList.meshes || this._scene.meshes;
      for (let i = 0;i < meshes.length; i++) {
        const mesh = meshes[i];
        if (mesh.isBlocked || !mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) {
          continue;
        }
        if (mesh.isVisible && mesh.visibility > 0 && (mesh.layerMask & this.camera.layerMask) !== 0 && (this._scene.skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(frustumPlanes))) {
          this.outputObjectList.meshes.push(mesh);
        }
      }
    });
    const passDisabled = this._frameGraph.addCullPass(this.name + "_disabled", true);
    passDisabled.setObjectList(this.outputObjectList);
    passDisabled.setExecuteFunc((_context) => {
      this.outputObjectList.meshes = this.objectList.meshes;
      this.outputObjectList.particleSystems = this.objectList.particleSystems;
    });
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/cullObjectsBlock.js
class NodeRenderGraphCullObjectsBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph, scene);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this._frameGraphTask = new FrameGraphCullObjectsTask(this.name, frameGraph, scene);
  }
  getClassName() {
    return "NodeRenderGraphCullObjectsBlock";
  }
  get camera() {
    return this._inputs[0];
  }
  get objects() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputObjectList;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
    this._frameGraphTask.objectList = this.objects.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
  }
}
RegisterClass("BABYLON.NodeRenderGraphCullObjectsBlock", NodeRenderGraphCullObjectsBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/elbowBlock.js
init_typeStore();
class NodeRenderGraphElbowBlock extends NodeRenderGraphBlock {
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph, scene);
    this.registerInput("input", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "NodeRenderGraphElbowBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input = this._inputs[0];
    this._propagateInputValueToOutput(input, output);
  }
}
RegisterClass("BABYLON.NodeRenderGraphElbowBlock", NodeRenderGraphElbowBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/executeBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Misc/executeTask.js
class FrameGraphExecuteTask extends FrameGraphTask {
  constructor(name203, frameGraph) {
    super(name203, frameGraph);
  }
  record() {
    if (!this.func) {
      throw new Error("FrameGraphExecuteTask: Execute task must have a function.");
    }
    const pass = this._frameGraph.addPass(this.name);
    pass.setExecuteFunc((context) => {
      this.func(context);
    });
    const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true);
    passDisabled.setExecuteFunc((context) => {
      this.funcDisabled?.(context);
    });
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/executeBlock.js
class NodeRenderGraphExecuteBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph, scene);
    this._addDependenciesInput(NodeRenderGraphBlockConnectionPointTypes.Camera | NodeRenderGraphBlockConnectionPointTypes.ShadowLight | NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ResourceContainer);
    this._frameGraphTask = new FrameGraphExecuteTask(name203, frameGraph);
  }
  getClassName() {
    return "NodeRenderGraphExecuteBlock";
  }
  get output() {
    return this._outputs[0];
  }
}
RegisterClass("BABYLON.NodeRenderGraphExecuteBlock", NodeRenderGraphExecuteBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/resourceContainerBlock.js
init_typeStore();
class NodeRenderGraphResourceContainerBlock extends NodeRenderGraphBlock {
  constructor(name203, frameGraph, scene) {
    super(name203, frameGraph, scene);
    this.registerInput("resource0", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource1", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource2", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource3", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource4", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource5", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource6", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("resource7", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.ResourceContainer);
    this.resource0.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource1.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource2.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource3.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource4.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource5.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource6.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.resource7.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer | NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
  }
  getClassName() {
    return "NodeRenderGraphResourceContainerBlock";
  }
  get resource0() {
    return this._inputs[0];
  }
  get resource1() {
    return this._inputs[1];
  }
  get resource2() {
    return this._inputs[2];
  }
  get resource3() {
    return this._inputs[3];
  }
  get resource4() {
    return this._inputs[4];
  }
  get resource5() {
    return this._inputs[5];
  }
  get resource6() {
    return this._inputs[6];
  }
  get resource7() {
    return this._inputs[7];
  }
  get output() {
    return this._outputs[0];
  }
}
RegisterClass("BABYLON.NodeRenderGraphResourceContainerBlock", NodeRenderGraphResourceContainerBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Layers/glowLayerBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/Layers/thinGlowLayer.js
init_math_vector();
init_buffer();

// node_modules/@babylonjs/core/Layers/thinEffectLayer.js
init_observable();
init_math_color();
init_engineStore();
init_buffer();
init_effectRenderer();
init_drawWrapper();
init_materialHelper_functions();
init_objectRenderer();
init_engine();

class ThinGlowBlurPostProcess extends EffectWrapper {
  constructor(name209, engine2 = null, direction, kernel, options) {
    super({
      ...options,
      name: name209,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinGlowBlurPostProcess.FragmentUrl,
      uniforms: ThinGlowBlurPostProcess.Uniforms
    });
    this.direction = direction;
    this.kernel = kernel;
    this.textureWidth = 0;
    this.textureHeight = 0;
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), exports_glowBlurPostProcess_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), exports_glowBlurPostProcess_fragment2)));
    }
    super._gatherImports(useWebGPU, list);
  }
  bind() {
    super.bind();
    this._drawWrapper.effect.setFloat2("screenSize", this.textureWidth, this.textureHeight);
    this._drawWrapper.effect.setVector2("direction", this.direction);
    this._drawWrapper.effect.setFloat("blurWidth", this.kernel);
  }
}
ThinGlowBlurPostProcess.FragmentUrl = "glowBlurPostProcess";
ThinGlowBlurPostProcess.Uniforms = ["screenSize", "direction", "blurWidth"];

class ThinEffectLayer {
  get camera() {
    return this._options.camera;
  }
  set camera(camera2) {
    this._options.camera = camera2;
  }
  get renderingGroupId() {
    return this._options.renderingGroupId;
  }
  set renderingGroupId(renderingGroupId) {
    this._options.renderingGroupId = renderingGroupId;
  }
  get objectRenderer() {
    return this._objectRenderer;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  setMaterialForRendering(mesh, material) {
    this._objectRenderer.setMaterialForRendering(mesh, material);
    if (Array.isArray(mesh)) {
      for (let i = 0;i < mesh.length; ++i) {
        const currentMesh = mesh[i];
        if (!material) {
          delete this._materialForRendering[currentMesh.uniqueId];
        } else {
          this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material];
        }
      }
    } else {
      if (!material) {
        delete this._materialForRendering[mesh.uniqueId];
      } else {
        this._materialForRendering[mesh.uniqueId] = [mesh, material];
      }
    }
  }
  getEffectIntensity(mesh) {
    return this._effectIntensity[mesh.uniqueId] ?? 1;
  }
  setEffectIntensity(mesh, intensity) {
    this._effectIntensity[mesh.uniqueId] = intensity;
  }
  constructor(name209, scene, forceGLSL = false, dontCheckIfReady = false, _additionalImportShadersAsync) {
    this._additionalImportShadersAsync = _additionalImportShadersAsync;
    this._vertexBuffers = {};
    this._dontCheckIfReady = false;
    this._shouldRender = true;
    this._emissiveTextureAndColor = { texture: null, color: new Color4 };
    this._effectIntensity = {};
    this._postProcesses = [];
    this.neutralColor = new Color4;
    this.isEnabled = true;
    this.disableBoundingBoxesFromEffectLayer = false;
    this.onDisposeObservable = new Observable;
    this.onBeforeRenderLayerObservable = new Observable;
    this.onBeforeComposeObservable = new Observable;
    this.onBeforeRenderMeshToEffect = new Observable;
    this.onAfterRenderMeshToEffect = new Observable;
    this.onAfterComposeObservable = new Observable;
    this.onBeforeBlurObservable = new Observable;
    this.onAfterBlurObservable = new Observable;
    this._shaderLanguage = 0;
    this._materialForRendering = {};
    this._shadersLoaded = false;
    this.name = name209;
    this._scene = scene || EngineStore.LastCreatedScene;
    this._dontCheckIfReady = dontCheckIfReady;
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !forceGLSL && !ThinEffectLayer.ForceGLSL) {
      this._shaderLanguage = 1;
    }
    this._engine = this._scene.getEngine();
    this._mergeDrawWrapper = [];
    this._generateIndexBuffer();
    this._generateVertexBuffer();
  }
  getEffectName() {
    return "";
  }
  isReady(_subMesh, _useInstances) {
    return true;
  }
  needStencil() {
    return false;
  }
  _createMergeEffect() {
    throw new Error("Effect Layer: no merge effect defined");
  }
  _createTextureAndPostProcesses() {}
  _internalCompose(_effect, _renderIndex) {}
  _setEmissiveTextureAndColor(_mesh, _subMesh, _material) {}
  _numInternalDraws() {
    return 1;
  }
  _init(options) {
    this._options = {
      mainTextureRatio: 0.5,
      mainTextureFixedSize: 0,
      mainTextureType: 0,
      alphaBlendingMode: 2,
      camera: null,
      renderingGroupId: -1,
      ...options
    };
    this._createObjectRenderer();
  }
  _generateIndexBuffer() {
    const indices = [];
    indices.push(0);
    indices.push(1);
    indices.push(2);
    indices.push(0);
    indices.push(2);
    indices.push(3);
    this._indexBuffer = this._engine.createIndexBuffer(indices);
  }
  _generateVertexBuffer() {
    const vertices = [];
    vertices.push(1, 1);
    vertices.push(-1, 1);
    vertices.push(-1, -1);
    vertices.push(1, -1);
    const vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);
    this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  }
  _createObjectRenderer() {
    this._objectRenderer = new ObjectRenderer(`ObjectRenderer for thin effect layer ${this.name}`, this._scene, {
      doNotChangeAspectRatio: true
    });
    this._objectRenderer.activeCamera = this._options.camera;
    this._objectRenderer.renderParticles = false;
    this._objectRenderer.renderList = null;
    const hasBoundingBoxRenderer = !!this._scene.getBoundingBoxRenderer;
    let boundingBoxRendererEnabled = false;
    if (hasBoundingBoxRenderer) {
      this._objectRenderer.onBeforeRenderObservable.add(() => {
        boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled;
        this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled;
      });
      this._objectRenderer.onAfterRenderObservable.add(() => {
        this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled;
      });
    }
    this._objectRenderer.customIsReadyFunction = (mesh, refreshRate, preWarm) => {
      if ((preWarm || refreshRate === 0) && mesh.subMeshes) {
        for (let i = 0;i < mesh.subMeshes.length; ++i) {
          const subMesh = mesh.subMeshes[i];
          const material = subMesh.getMaterial();
          const renderingMesh = subMesh.getRenderingMesh();
          if (!material) {
            continue;
          }
          const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
          const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;
          this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
          if (!this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
            return false;
          }
        }
      }
      return true;
    };
    this._objectRenderer.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {
      this.onBeforeRenderLayerObservable.notifyObservers(this);
      let index;
      const engine2 = this._scene.getEngine();
      if (depthOnlySubMeshes.length) {
        engine2.setColorWrite(false);
        for (index = 0;index < depthOnlySubMeshes.length; index++) {
          this._renderSubMesh(depthOnlySubMeshes.data[index]);
        }
        engine2.setColorWrite(true);
      }
      for (index = 0;index < opaqueSubMeshes.length; index++) {
        this._renderSubMesh(opaqueSubMeshes.data[index]);
      }
      for (index = 0;index < alphaTestSubMeshes.length; index++) {
        this._renderSubMesh(alphaTestSubMeshes.data[index]);
      }
      const previousAlphaMode = engine2.getAlphaMode();
      for (index = 0;index < transparentSubMeshes.length; index++) {
        const subMesh = transparentSubMeshes.data[index];
        const material = subMesh.getMaterial();
        if (material && material.needDepthPrePass) {
          const engine3 = material.getScene().getEngine();
          engine3.setColorWrite(false);
          this._renderSubMesh(subMesh);
          engine3.setColorWrite(true);
        }
        this._renderSubMesh(subMesh, true);
      }
      engine2.setAlphaMode(previousAlphaMode);
    };
  }
  _addCustomEffectDefines(_defines) {}
  _internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) {
    const engine2 = this._scene.getEngine();
    const mesh = subMesh.getMesh();
    const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId];
    if (renderingMaterial) {
      return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);
    }
    const material = subMesh.getMaterial();
    if (!material) {
      return false;
    }
    if (this._useMeshMaterial(subMesh.getRenderingMesh())) {
      return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances);
    }
    const defines = [];
    const attribs = [VertexBuffer.PositionKind];
    let uv1 = false;
    let uv2 = false;
    const color = false;
    if (material) {
      const needAlphaTest = material.needAlphaTestingForMesh(mesh);
      const diffuseTexture = material.getAlphaTestTexture();
      const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);
      if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
        defines.push("#define DIFFUSE");
        if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) {
          defines.push("#define DIFFUSEUV2");
          uv2 = true;
        } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
          defines.push("#define DIFFUSEUV1");
          uv1 = true;
        }
        if (needAlphaTest) {
          defines.push("#define ALPHATEST");
          defines.push("#define ALPHATESTVALUE 0.4");
        }
        if (!diffuseTexture.gammaSpace) {
          defines.push("#define DIFFUSE_ISLINEAR");
        }
      }
      const opacityTexture = material.opacityTexture;
      if (opacityTexture) {
        defines.push("#define OPACITY");
        if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) {
          defines.push("#define OPACITYUV2");
          uv2 = true;
        } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
          defines.push("#define OPACITYUV1");
          uv1 = true;
        }
      }
    }
    if (emissiveTexture) {
      defines.push("#define EMISSIVE");
      if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) {
        defines.push("#define EMISSIVEUV2");
        uv2 = true;
      } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
        defines.push("#define EMISSIVEUV1");
        uv1 = true;
      }
      if (!emissiveTexture.gammaSpace) {
        defines.push("#define EMISSIVE_ISLINEAR");
      }
    }
    if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== Material.MATERIAL_OPAQUE) {
      attribs.push(VertexBuffer.ColorKind);
      defines.push("#define VERTEXALPHA");
    }
    if (uv1) {
      attribs.push(VertexBuffer.UVKind);
      defines.push("#define UV1");
    }
    if (uv2) {
      attribs.push(VertexBuffer.UV2Kind);
      defines.push("#define UV2");
    }
    const fallbacks = new EffectFallbacks;
    if (mesh.useBones && mesh.computeBonesUsingShaders) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
      const skeleton2 = mesh.skeleton;
      if (skeleton2 && skeleton2.isUsingTextureForMatrices) {
        defines.push("#define BONETEXTURE");
      } else {
        defines.push("#define BonesPerMesh " + (skeleton2 ? skeleton2.bones.length + 1 : 0));
      }
      if (mesh.numBoneInfluencers > 0) {
        fallbacks.addCPUSkinningFallback(0, mesh);
      }
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
    }
    const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh.morphTargetManager, defines, attribs, mesh, true, false, false, uv1, uv2, color) : 0;
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs);
      if (subMesh.getRenderingMesh().hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
      }
    }
    prepareStringDefinesForClipPlanes(material, this._scene, defines);
    this._addCustomEffectDefines(defines);
    const drawWrapper = subMesh._getDrawWrapper(undefined, true);
    const cachedDefines = drawWrapper.defines;
    const join6 = defines.join(`
`);
    if (cachedDefines !== join6) {
      const uniforms = [
        "world",
        "mBones",
        "viewProjection",
        "glowColor",
        "morphTargetInfluences",
        "morphTargetCount",
        "boneTextureWidth",
        "diffuseMatrix",
        "emissiveMatrix",
        "opacityMatrix",
        "opacityIntensity",
        "morphTargetTextureInfo",
        "morphTargetTextureIndices",
        "glowIntensity"
      ];
      addClipPlaneUniforms(uniforms);
      drawWrapper.setEffect(this._engine.createEffect("glowMapGeneration", attribs, uniforms, ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], join6, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: numMorphInfluencers }, this._shaderLanguage, this._shadersLoaded ? undefined : async () => {
        await this._importShadersAsync();
        this._shadersLoaded = true;
      }), join6);
    }
    const effectIsReady = drawWrapper.effect.isReady();
    return effectIsReady && (this._dontCheckIfReady || !this._dontCheckIfReady && this.isLayerReady());
  }
  _isSubMeshReady(subMesh, useInstances, emissiveTexture) {
    return this._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture);
  }
  async _importShadersAsync() {
    if (this._shaderLanguage === 1) {
      await Promise.all([Promise.resolve().then(() => (init_glowMapGeneration_vertex(), exports_glowMapGeneration_vertex)), Promise.resolve().then(() => (init_glowMapGeneration_fragment(), exports_glowMapGeneration_fragment))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_glowMapGeneration_vertex2(), exports_glowMapGeneration_vertex2)), Promise.resolve().then(() => (init_glowMapGeneration_fragment2(), exports_glowMapGeneration_fragment2))]);
    }
    this._additionalImportShadersAsync?.();
  }
  _internalIsLayerReady() {
    let isReady = true;
    for (let i = 0;i < this._postProcesses.length; i++) {
      isReady = this._postProcesses[i].isReady() && isReady;
    }
    const numDraws = this._numInternalDraws();
    for (let i = 0;i < numDraws; ++i) {
      let currentEffect = this._mergeDrawWrapper[i];
      if (!currentEffect) {
        currentEffect = this._mergeDrawWrapper[i] = new DrawWrapper(this._engine);
        currentEffect.setEffect(this._createMergeEffect());
      }
      isReady = currentEffect.effect.isReady() && isReady;
    }
    return isReady;
  }
  isLayerReady() {
    return this._internalIsLayerReady();
  }
  compose() {
    if (!this._dontCheckIfReady && !this.isLayerReady()) {
      return false;
    }
    const engine2 = this._scene.getEngine();
    const numDraws = this._numInternalDraws();
    this.onBeforeComposeObservable.notifyObservers(this);
    const previousAlphaMode = engine2.getAlphaMode();
    for (let i = 0;i < numDraws; ++i) {
      const currentEffect = this._mergeDrawWrapper[i];
      engine2.enableEffect(currentEffect);
      engine2.setState(false);
      engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect);
      engine2.setAlphaMode(this._options.alphaBlendingMode);
      this._internalCompose(currentEffect.effect, i);
    }
    engine2.setAlphaMode(previousAlphaMode);
    this.onAfterComposeObservable.notifyObservers(this);
    return true;
  }
  _internalHasMesh(mesh) {
    if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
      return true;
    }
    return false;
  }
  hasMesh(mesh) {
    return this._internalHasMesh(mesh);
  }
  _internalShouldRender() {
    return this.isEnabled && this._shouldRender;
  }
  shouldRender() {
    return this._internalShouldRender();
  }
  _shouldRenderMesh(_mesh) {
    return true;
  }
  _internalCanRenderMesh(mesh, material) {
    return !material.needAlphaBlendingForMesh(mesh);
  }
  _canRenderMesh(mesh, material) {
    return this._internalCanRenderMesh(mesh, material);
  }
  _renderSubMesh(subMesh, enableAlphaMode = false) {
    if (!this._internalShouldRender()) {
      return;
    }
    const material = subMesh.getMaterial();
    const ownerMesh = subMesh.getMesh();
    const replacementMesh = subMesh.getReplacementMesh();
    const renderingMesh = subMesh.getRenderingMesh();
    const effectiveMesh = subMesh.getEffectiveMesh();
    const scene = this._scene;
    const engine2 = scene.getEngine();
    effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
    if (!material) {
      return;
    }
    if (!this._canRenderMesh(renderingMesh, material)) {
      return;
    }
    let sideOrientation = material._getEffectiveOrientation(renderingMesh);
    const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();
    if (mainDeterminant < 0) {
      sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
    }
    const reverse = sideOrientation === Material.ClockWiseSideOrientation;
    engine2.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits);
    const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);
    if (batch.mustReturn) {
      return;
    }
    if (!this._shouldRenderMesh(renderingMesh)) {
      return;
    }
    const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;
    this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
    this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);
    if (this._useMeshMaterial(renderingMesh)) {
      subMesh.getMaterial()._glowModeEnabled = true;
      renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || undefined);
      subMesh.getMaterial()._glowModeEnabled = false;
    } else if (this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
      const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId];
      let drawWrapper = subMesh._getDrawWrapper();
      if (!drawWrapper && renderingMaterial) {
        drawWrapper = renderingMaterial._getDrawWrapper();
      }
      if (!drawWrapper) {
        return;
      }
      const effect = drawWrapper.effect;
      engine2.enableEffect(drawWrapper);
      if (!hardwareInstancedRendering) {
        renderingMesh._bind(subMesh, effect, material.fillMode);
      }
      if (!renderingMaterial) {
        effect.setMatrix("viewProjection", scene.getTransformMatrix());
        effect.setMatrix("world", effectiveMesh.getWorldMatrix());
        effect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
      } else {
        renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);
      }
      if (!renderingMaterial) {
        const needAlphaTest = material.needAlphaTestingForMesh(effectiveMesh);
        const diffuseTexture = material.getAlphaTestTexture();
        const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);
        if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
          effect.setTexture("diffuseSampler", diffuseTexture);
          const textureMatrix = diffuseTexture.getTextureMatrix();
          if (textureMatrix) {
            effect.setMatrix("diffuseMatrix", textureMatrix);
          }
        }
        const opacityTexture = material.opacityTexture;
        if (opacityTexture) {
          effect.setTexture("opacitySampler", opacityTexture);
          effect.setFloat("opacityIntensity", opacityTexture.level);
          const textureMatrix = opacityTexture.getTextureMatrix();
          if (textureMatrix) {
            effect.setMatrix("opacityMatrix", textureMatrix);
          }
        }
        if (this._emissiveTextureAndColor.texture) {
          effect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
          effect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
        }
        if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
          const skeleton2 = renderingMesh.skeleton;
          if (skeleton2.isUsingTextureForMatrices) {
            const boneTexture = skeleton2.getTransformMatrixTexture(renderingMesh);
            if (!boneTexture) {
              return;
            }
            effect.setTexture("boneSampler", boneTexture);
            effect.setFloat("boneTextureWidth", 4 * (skeleton2.bones.length + 1));
          } else {
            effect.setMatrices("mBones", skeleton2.getTransformMatrices(renderingMesh));
          }
        }
        BindMorphTargetParameters(renderingMesh, effect);
        if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
          renderingMesh.morphTargetManager._bind(effect);
        }
        if (enableAlphaMode) {
          engine2.setAlphaMode(material.alphaMode);
        }
        effect.setFloat("glowIntensity", this.getEffectIntensity(renderingMesh));
        bindClipPlane(effect, material, scene);
      }
      renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world));
    } else {
      this._objectRenderer.resetRefreshCounter();
    }
    this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);
  }
  _useMeshMaterial(_mesh) {
    return false;
  }
  _rebuild() {
    const vb = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vb) {
      vb._rebuild();
    }
    this._generateIndexBuffer();
  }
  dispose() {
    const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vertexBuffer) {
      vertexBuffer.dispose();
      this._vertexBuffers[VertexBuffer.PositionKind] = null;
    }
    if (this._indexBuffer) {
      this._scene.getEngine()._releaseBuffer(this._indexBuffer);
      this._indexBuffer = null;
    }
    for (const drawWrapper of this._mergeDrawWrapper) {
      drawWrapper.dispose();
    }
    this._mergeDrawWrapper = [];
    this._objectRenderer.dispose();
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    this.onBeforeRenderLayerObservable.clear();
    this.onBeforeComposeObservable.clear();
    this.onBeforeRenderMeshToEffect.clear();
    this.onAfterRenderMeshToEffect.clear();
    this.onAfterComposeObservable.clear();
  }
}
ThinEffectLayer.ForceGLSL = false;

// node_modules/@babylonjs/core/Layers/thinGlowLayer.js
init_math_color();
class ThinGlowLayer extends ThinEffectLayer {
  get ldrMerge() {
    return this._options.ldrMerge;
  }
  set blurKernelSize(value) {
    if (value === this._options.blurKernelSize) {
      return;
    }
    this._options.blurKernelSize = value;
    const effectiveKernel = this._getEffectiveBlurKernelSize();
    this._horizontalBlurPostprocess1.kernel = effectiveKernel;
    this._verticalBlurPostprocess1.kernel = effectiveKernel;
    this._horizontalBlurPostprocess2.kernel = effectiveKernel;
    this._verticalBlurPostprocess2.kernel = effectiveKernel;
  }
  get blurKernelSize() {
    return this._options.blurKernelSize;
  }
  set intensity(value) {
    this._intensity = value;
  }
  get intensity() {
    return this._intensity;
  }
  constructor(name213, scene, options, dontCheckIfReady = false) {
    super(name213, scene, false, dontCheckIfReady);
    this._intensity = 1;
    this._includedOnlyMeshes = [];
    this._excludedMeshes = [];
    this._meshesUsingTheirOwnMaterials = [];
    this._renderPassId = 0;
    this.neutralColor = new Color4(0, 0, 0, 1);
    this._options = {
      mainTextureRatio: 0.5,
      mainTextureFixedSize: 0,
      mainTextureType: 0,
      blurKernelSize: 32,
      camera: null,
      renderingGroupId: -1,
      ldrMerge: false,
      alphaBlendingMode: 1,
      ...options
    };
    this._init(this._options);
    if (dontCheckIfReady) {
      this._createTextureAndPostProcesses();
    }
  }
  getClassName() {
    return "GlowLayer";
  }
  async _importShadersAsync() {
    if (this._shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_glowMapMerge_fragment(), exports_glowMapMerge_fragment)),
        Promise.resolve().then(() => (init_glowMapMerge_vertex(), exports_glowMapMerge_vertex)),
        Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), exports_glowBlurPostProcess_fragment))
      ]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_glowMapMerge_fragment2(), exports_glowMapMerge_fragment2)), Promise.resolve().then(() => (init_glowMapMerge_vertex2(), exports_glowMapMerge_vertex2)), Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), exports_glowBlurPostProcess_fragment2))]);
    }
    await super._importShadersAsync();
  }
  getEffectName() {
    return ThinGlowLayer.EffectName;
  }
  _createMergeEffect() {
    let defines = `#define EMISSIVE 
`;
    if (this._options.ldrMerge) {
      defines += `#define LDR 
`;
    }
    return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], defines, undefined, undefined, undefined, undefined, this.shaderLanguage, this._shadersLoaded ? undefined : async () => {
      await this._importShadersAsync();
      this._shadersLoaded = true;
    });
  }
  _createTextureAndPostProcesses() {
    const effectiveKernel = this._getEffectiveBlurKernelSize();
    this._horizontalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerHBP1", this._scene.getEngine(), new Vector2(1, 0), effectiveKernel);
    this._verticalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerVBP1", this._scene.getEngine(), new Vector2(0, 1), effectiveKernel);
    this._horizontalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerHBP2", this._scene.getEngine(), new Vector2(1, 0), effectiveKernel);
    this._verticalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerVBP2", this._scene.getEngine(), new Vector2(0, 1), effectiveKernel);
    this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  }
  _getEffectiveBlurKernelSize() {
    return this._options.blurKernelSize / 2;
  }
  isReady(subMesh, useInstances) {
    const material = subMesh.getMaterial();
    const mesh = subMesh.getRenderingMesh();
    if (!material || !mesh) {
      return false;
    }
    const emissiveTexture = material.emissiveTexture;
    return super._isSubMeshReady(subMesh, useInstances, emissiveTexture);
  }
  _canRenderMesh(_mesh, _material) {
    return true;
  }
  _internalCompose(effect) {
    this.bindTexturesForCompose(effect);
    effect.setFloat("offset", this._intensity);
    const engine2 = this._engine;
    const previousStencilBuffer = engine2.getStencilBuffer();
    engine2.setStencilBuffer(false);
    engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
    engine2.setStencilBuffer(previousStencilBuffer);
  }
  _setEmissiveTextureAndColor(mesh, subMesh, material) {
    let textureLevel = 1;
    if (this.customEmissiveTextureSelector) {
      this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
    } else {
      if (material) {
        this._emissiveTextureAndColor.texture = material.emissiveTexture;
        if (this._emissiveTextureAndColor.texture) {
          textureLevel = this._emissiveTextureAndColor.texture.level;
        }
      } else {
        this._emissiveTextureAndColor.texture = null;
      }
    }
    if (this.customEmissiveColorSelector) {
      this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
    } else {
      if (material.emissiveColor) {
        const emissiveIntensity = material.emissiveIntensity ?? 1;
        textureLevel *= emissiveIntensity;
        this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha);
      } else {
        this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
      }
    }
  }
  _shouldRenderMesh(mesh) {
    return this.hasMesh(mesh);
  }
  _addCustomEffectDefines(defines) {
    defines.push("#define GLOW");
  }
  addExcludedMesh(mesh) {
    if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
      this._excludedMeshes.push(mesh.uniqueId);
    }
  }
  removeExcludedMesh(mesh) {
    const index = this._excludedMeshes.indexOf(mesh.uniqueId);
    if (index !== -1) {
      this._excludedMeshes.splice(index, 1);
    }
  }
  addIncludedOnlyMesh(mesh) {
    if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
      this._includedOnlyMeshes.push(mesh.uniqueId);
    }
  }
  removeIncludedOnlyMesh(mesh) {
    const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
    if (index !== -1) {
      this._includedOnlyMeshes.splice(index, 1);
    }
  }
  hasMesh(mesh) {
    if (!super.hasMesh(mesh)) {
      return false;
    }
    if (this._includedOnlyMeshes.length) {
      return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
    }
    if (this._excludedMeshes.length) {
      return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
    }
    return true;
  }
  _useMeshMaterial(mesh) {
    if (mesh.material?._supportGlowLayer) {
      return true;
    }
    if (this._meshesUsingTheirOwnMaterials.length == 0) {
      return false;
    }
    return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1;
  }
  referenceMeshToUseItsOwnMaterial(mesh) {
    mesh.resetDrawCache(this._renderPassId);
    this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId);
    mesh.onDisposeObservable.add(() => {
      this._disposeMesh(mesh);
    });
  }
  unReferenceMeshFromUsingItsOwnMaterial(mesh, renderPassId) {
    let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);
    while (index >= 0) {
      this._meshesUsingTheirOwnMaterials.splice(index, 1);
      index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);
    }
    mesh.resetDrawCache(renderPassId);
  }
  _disposeMesh(mesh) {
    this.removeIncludedOnlyMesh(mesh);
    this.removeExcludedMesh(mesh);
  }
}
ThinGlowLayer.EffectName = "GlowLayer";
ThinGlowLayer.DefaultBlurKernelSize = 32;

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/postProcessTask.js
class FrameGraphPostProcessTask extends FrameGraphTask {
  get drawWrapper() {
    return this._postProcessDrawWrapper;
  }
  constructor(name213, frameGraph, postProcess) {
    super(name213, frameGraph);
    this.sourceSamplingMode = 2;
    this.postProcess = postProcess;
    this._postProcessDrawWrapper = this.postProcess.drawWrapper;
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.onTexturesAllocatedObservable.add((context) => {
      context.setTextureSamplingMode(this.sourceTexture, this.sourceSamplingMode);
    });
  }
  isReady() {
    return this.postProcess.isReady();
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
    if (this.sourceTexture === undefined) {
      throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture is required`);
    }
    const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture);
    sourceTextureCreationOptions.options.samples = 1;
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name, sourceTextureCreationOptions);
    const sourceSize = !sourceTextureCreationOptions.sizeIsPercentage ? textureSizeIsObject(sourceTextureCreationOptions.size) ? sourceTextureCreationOptions.size : { width: sourceTextureCreationOptions.size, height: sourceTextureCreationOptions.size } : this._frameGraph.textureManager.getAbsoluteDimensions(sourceTextureCreationOptions.size);
    this._sourceWidth = sourceSize.width;
    this._sourceHeight = sourceSize.height;
    const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.outputTexture);
    this._outputWidth = outputTextureDescription.size.width;
    this._outputHeight = outputTextureDescription.size.height;
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.addDependencies(this.sourceTexture);
    pass.setRenderTarget(this.outputTexture);
    pass.setExecuteFunc((context) => {
      additionalExecute?.(context);
      context.applyFullScreenEffect(this._postProcessDrawWrapper, () => {
        context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.sourceTexture);
        additionalBindings?.(context);
        this.postProcess.bind();
      });
    });
    if (!skipCreationOfDisabledPasses) {
      const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
      passDisabled.addDependencies(this.sourceTexture);
      passDisabled.setRenderTarget(this.outputTexture);
      passDisabled.setExecuteFunc((context) => {
        context.copyTexture(this.sourceTexture);
      });
    }
    return pass;
  }
  dispose() {
    this.postProcess.dispose();
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/blurTask.js
init_math_vector();

class FrameGraphBlurTask extends FrameGraphPostProcessTask {
  constructor(name213, frameGraph, thinPostProcess) {
    super(name213, frameGraph, thinPostProcess || new ThinBlurPostProcess(name213, frameGraph.engine, new Vector2(1, 0), 10));
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
    const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings);
    this.postProcess.textureWidth = this._outputWidth;
    this.postProcess.textureHeight = this._outputHeight;
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/Layers/baseLayerTask.js
init_math_vector();
class FrameGraphGlowBlurTask extends FrameGraphPostProcessTask {
  constructor(name213, frameGraph, thinPostProcess) {
    super(name213, frameGraph, thinPostProcess || new ThinGlowBlurPostProcess(name213, frameGraph.engine, new Vector2(1, 0), 1));
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
    const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings);
    this.postProcess.textureWidth = this._outputWidth;
    this.postProcess.textureHeight = this._outputHeight;
    return pass;
  }
}

class FrameGraphBaseLayerTask extends FrameGraphTask {
  get name() {
    return this._name;
  }
  set name(name213) {
    this._name = name213;
    if (this._blurX) {
      for (let i = 0;i < this._blurX.length; i++) {
        this._blurX[i].name = `${name213} Blur X${i}`;
        this._blurY[i].name = `${name213} Blur Y${i}`;
      }
    }
    if (this._clearLayerTextures) {
      this._clearLayerTextures.name = name213 + " Clear Layer";
    }
    if (this._objectRendererForLayer) {
      this._objectRendererForLayer.name = name213 + " Render to Layer";
    }
  }
  constructor(name213, frameGraph, scene, layer, numBlurPasses, useCustomBlur = false, _setRenderTargetDepth = false, _notifyBlurObservable = false) {
    super(name213, frameGraph);
    this._setRenderTargetDepth = _setRenderTargetDepth;
    this._notifyBlurObservable = _notifyBlurObservable;
    this._blurX = [];
    this._blurY = [];
    this._onBeforeBlurTask = null;
    this._onAfterBlurTask = null;
    this._onBeforeObservableObserver = null;
    this._onAfterObservableObserver = null;
    this._onAfterRenderingGroupObserver = null;
    this._scene = scene;
    this._engine = scene.getEngine();
    this.layer = layer;
    for (let i = 0;i < numBlurPasses; i++) {
      if (useCustomBlur) {
        this._blurX.push(new FrameGraphGlowBlurTask(`${name213} Blur X${i}`, this._frameGraph, this.layer._postProcesses[1 + i * 2 + 0]));
        this._blurY.push(new FrameGraphGlowBlurTask(`${name213} Blur Y${i}`, this._frameGraph, this.layer._postProcesses[1 + i * 2 + 1]));
      } else {
        this._blurX.push(new FrameGraphBlurTask(`${name213} Blur X${i}`, this._frameGraph, this.layer._postProcesses[i * 2 + 0]));
        this._blurY.push(new FrameGraphBlurTask(`${name213} Blur Y${i}`, this._frameGraph, this.layer._postProcesses[i * 2 + 1]));
      }
    }
    this._clearLayerTextures = new FrameGraphClearTextureTask(name213 + " Clear Layer", frameGraph);
    this._clearLayerTextures.clearColor = true;
    this._clearLayerTextures.clearDepth = true;
    this._objectRendererForLayer = new FrameGraphObjectRendererTask(name213 + " Render to Layer", frameGraph, scene, undefined, this.layer.objectRenderer);
    if (this._notifyBlurObservable) {
      this._onBeforeBlurTask = new FrameGraphExecuteTask(name213 + " On Before Blur", frameGraph);
      this._onAfterBlurTask = new FrameGraphExecuteTask(name213 + " On After Blur", frameGraph);
      this._onBeforeBlurTask.func = () => {
        if (this.layer.onBeforeBlurObservable.hasObservers()) {
          this.layer.onBeforeBlurObservable.notifyObservers(this.layer);
        }
      };
      this._onAfterBlurTask.func = () => {
        if (this.layer.onAfterBlurObservable.hasObservers()) {
          this.layer.onAfterBlurObservable.notifyObservers(this.layer);
        }
      };
    }
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.onTexturesAllocatedObservable.add((context) => {
      for (let i = 0;i < this._blurX.length; i++) {
        this._blurX[i].onTexturesAllocatedObservable.notifyObservers(context);
        this._blurY[i].onTexturesAllocatedObservable.notifyObservers(context);
      }
      context.setTextureSamplingMode(this._blurY[this._blurY.length - 1].targetTexture, 2);
    });
  }
  isReady() {
    return this._objectRendererForLayer.isReady() && this.layer.isLayerReady();
  }
  record() {
    if (this.targetTexture === undefined || this.objectRendererTask === undefined) {
      throw new Error(`${this.constructor.name} "${this.name}": targetTexture and objectRendererTask are required`);
    }
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    let textureSize;
    let textureCreationOptions;
    let colorLayerOutput;
    if (this.layerTexture) {
      colorLayerOutput = this.layerTexture;
      textureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.layerTexture);
      textureSize = getDimensionsFromTextureSize(textureCreationOptions.size);
      textureCreationOptions.size = textureSize;
    } else {
      const targetTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.targetTexture);
      const fixedTextureSize = this.layer._options.mainTextureFixedSize ? Math.max(2, this.layer._options.mainTextureFixedSize) : 0;
      textureSize = getDimensionsFromTextureSize(targetTextureCreationOptions.size);
      textureSize.width = fixedTextureSize || Math.floor(textureSize.width * (this.layer._options.mainTextureRatio || 0.1)) || 1;
      textureSize.height = fixedTextureSize || Math.floor(textureSize.height * (this.layer._options.mainTextureRatio || 0.1)) || 1;
      textureCreationOptions = {
        size: textureSize,
        options: {
          createMipMaps: false,
          types: [this.layer._options.mainTextureType],
          formats: [5],
          samples: 1,
          useSRGBBuffers: [false],
          creationFlags: [0]
        },
        sizeIsPercentage: this.layer._options.mainTextureFixedSize ? false : targetTextureCreationOptions.sizeIsPercentage
      };
      colorLayerOutput = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Color`, textureCreationOptions);
    }
    const textureDepthCreationOptions = {
      size: textureSize,
      options: FrameGraphTextureManager.CloneTextureOptions(textureCreationOptions.options),
      sizeIsPercentage: textureCreationOptions.sizeIsPercentage
    };
    textureDepthCreationOptions.options.formats[0] = 14;
    const depthLayerOutput = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} Depth`, textureDepthCreationOptions);
    this._clearLayerTextures.targetTexture = colorLayerOutput;
    this._clearLayerTextures.depthTexture = depthLayerOutput;
    this._clearLayerTextures.color = this.layer.neutralColor;
    this._clearLayerTextures.clearDepth = true;
    const clearTaskPass = this._clearLayerTextures.record();
    this._objectRendererForLayer.targetTexture = this._clearLayerTextures.outputTexture;
    this._objectRendererForLayer.depthTexture = this._clearLayerTextures.outputDepthTexture;
    this._objectRendererForLayer.camera = this.objectRendererTask.camera;
    this._objectRendererForLayer.objectList = this.objectRendererTask.objectList;
    this._objectRendererForLayer.disableShadows = true;
    const objectRendererForLayerTaskPass = this._objectRendererForLayer.record();
    let blurTextureType = 0;
    if (this._engine.getCaps().textureHalfFloatRender) {
      blurTextureType = 2;
    } else {
      blurTextureType = 0;
    }
    textureCreationOptions.options.types[0] = blurTextureType;
    const blurTextureSizeRatio = this.layer._options.blurTextureSizeRatio !== undefined ? this.layer._options.blurTextureSizeRatio || 0.1 : undefined;
    if (blurTextureSizeRatio !== undefined) {
      textureSize.width = Math.floor(textureSize.width * blurTextureSizeRatio) || 1;
      textureSize.height = Math.floor(textureSize.height * blurTextureSizeRatio) || 1;
    }
    const onBeforeBlurPass = this._onBeforeBlurTask?.record();
    const blurPasses = [];
    for (let i = 0;i < this._blurX.length; i++) {
      const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX[i].name, textureCreationOptions);
      this._blurX[i].sourceTexture = i === 0 ? this._objectRendererForLayer.outputTexture : this._blurY[i - 1].outputTexture;
      this._blurX[i].sourceSamplingMode = 2;
      this._blurX[i].targetTexture = blurXTextureHandle;
      blurPasses.push(this._blurX[i].record(true));
      const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY[i].name, textureCreationOptions);
      this._blurY[i].sourceTexture = this._blurX[i].outputTexture;
      this._blurY[i].sourceSamplingMode = 2;
      this._blurY[i].targetTexture = blurYTextureHandle;
      blurPasses.push(this._blurY[i].record(true));
      textureSize.width = textureSize.width >> 1;
      textureSize.height = textureSize.height >> 1;
    }
    const onAfterBlurPass = this._onAfterBlurTask?.record();
    this.objectRendererTask.objectRenderer.onBeforeRenderObservable.remove(this._onBeforeObservableObserver);
    this._onBeforeObservableObserver = this.objectRendererTask.objectRenderer.onBeforeRenderObservable.add(() => {
      const shouldRender = this.layer.shouldRender();
      clearTaskPass.disabled = !shouldRender;
      objectRendererForLayerTaskPass.disabled = !shouldRender;
      if (onBeforeBlurPass) {
        onBeforeBlurPass.disabled = !shouldRender;
      }
      for (let i = 0;i < blurPasses.length; i++) {
        blurPasses[i].disabled = !shouldRender;
      }
      if (onAfterBlurPass) {
        onAfterBlurPass.disabled = !shouldRender;
      }
      if (shouldRender && this.layer.needStencil()) {
        this._engine.setStencilBuffer(true);
        this._engine.setStencilFunctionReference(1);
      }
    });
    this.objectRendererTask.objectRenderer.onAfterRenderObservable.remove(this._onAfterObservableObserver);
    this._onAfterObservableObserver = this.objectRendererTask.objectRenderer.onAfterRenderObservable.add(() => {
      if (this.layer.shouldRender() && this.layer.needStencil()) {
        this._engine.setStencilBuffer(false);
      }
    });
    this.layer.bindTexturesForCompose = undefined;
    this._clearAfterRenderingGroupObserver();
    const pass = this._frameGraph.addRenderPass(this.name);
    for (let i = 0;i < this._blurY.length; i++) {
      pass.addDependencies(this._blurY[i].outputTexture);
    }
    pass.setRenderTarget(this.outputTexture);
    if (this._setRenderTargetDepth) {
      pass.setRenderTargetDepth(this.objectRendererTask.depthTexture);
    }
    pass.setExecuteFunc((context) => {
      if (!this.layer.bindTexturesForCompose) {
        this.layer.bindTexturesForCompose = (effect) => {
          for (let i = 0;i < this._blurY.length; i++) {
            context.bindTextureHandle(effect, `textureSampler${i > 0 ? i + 1 : ""}`, this._blurY[i].outputTexture);
          }
        };
      }
      if (this.layer._options.renderingGroupId !== -1) {
        if (!this._onAfterRenderingGroupObserver) {
          this._onAfterRenderingGroupObserver = this._scene.onAfterRenderingGroupObservable.add((info) => {
            if (!this.layer.shouldRender() || info.renderingGroupId !== this.layer._options.renderingGroupId || info.renderingManager !== this.objectRendererTask.objectRenderer._renderingManager) {
              return;
            }
            this._objectRendererForLayer.objectList = this.objectRendererTask.objectList;
            context.saveDepthStates();
            context.setDepthStates(false, false);
            context._applyRenderTarget();
            this.layer.compose();
            context.restoreDepthStates();
          });
        }
      } else {
        this._clearAfterRenderingGroupObserver();
        if (this.layer.shouldRender()) {
          this._objectRendererForLayer.objectList = this.objectRendererTask.objectList;
          context.setDepthStates(false, false);
          context._applyRenderTarget();
          this.layer.compose();
        }
      }
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.outputTexture);
    if (this._setRenderTargetDepth) {
      passDisabled.setRenderTargetDepth(this.objectRendererTask.depthTexture);
    }
    passDisabled.setExecuteFunc((_context) => {});
  }
  _clearAfterRenderingGroupObserver() {
    this._scene.onAfterRenderingGroupObservable.remove(this._onAfterRenderingGroupObserver);
    this._onAfterRenderingGroupObserver = null;
  }
  dispose() {
    this._clearAfterRenderingGroupObserver();
    this._clearLayerTextures.dispose();
    this._objectRendererForLayer.dispose();
    this._onBeforeBlurTask?.dispose();
    this._onAfterBlurTask?.dispose();
    this.layer.dispose();
    for (let i = 0;i < this._blurX.length; i++) {
      this._blurX[i].dispose();
      this._blurY[i].dispose();
    }
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/Layers/glowLayerTask.js
class FrameGraphGlowLayerTask extends FrameGraphBaseLayerTask {
  constructor(name213, frameGraph, scene, options) {
    super(name213, frameGraph, scene, new ThinGlowLayer(name213, scene, options, true), 2);
    this.layer._renderPassId = this._objectRendererForLayer.objectRenderer.renderPassId;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Layers/glowLayerBlock.js
class NodeRenderGraphGlowLayerBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name213, frameGraph, scene, ldrMerge = false, layerTextureRatio = 0.5, layerTextureFixedSize, layerTextureType = 0) {
    super(name213, frameGraph, scene);
    this._additionalConstructionParameters = [ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType];
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("layer", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, true, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 0, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock"));
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil);
    this.layer.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this.output._typeConnectionSource = this.target;
    this._frameGraphTask = new FrameGraphGlowLayerTask(this.name, this._frameGraph, this._scene, {
      ldrMerge,
      mainTextureRatio: layerTextureRatio,
      mainTextureFixedSize: layerTextureFixedSize,
      mainTextureType: layerTextureType
    });
  }
  _createTask(ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType) {
    const blurKernelSize = this.blurKernelSize;
    const intensity = this.intensity;
    this._frameGraphTask?.dispose();
    this._frameGraphTask = new FrameGraphGlowLayerTask(this.name, this._frameGraph, this._scene, {
      ldrMerge,
      mainTextureRatio: layerTextureRatio,
      mainTextureFixedSize: layerTextureFixedSize,
      mainTextureType: layerTextureType
    });
    this.blurKernelSize = blurKernelSize;
    this.intensity = intensity;
    this._additionalConstructionParameters = [ldrMerge, layerTextureRatio, layerTextureFixedSize, layerTextureType];
  }
  get ldrMerge() {
    return this._frameGraphTask.layer.ldrMerge;
  }
  set ldrMerge(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(value, options.mainTextureRatio, options.mainTextureFixedSize, options.mainTextureType);
  }
  get layerTextureRatio() {
    return this._frameGraphTask.layer._options.mainTextureRatio;
  }
  set layerTextureRatio(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.ldrMerge, value, options.mainTextureFixedSize, options.mainTextureType);
  }
  get layerTextureFixedSize() {
    return this._frameGraphTask.layer._options.mainTextureFixedSize;
  }
  set layerTextureFixedSize(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.ldrMerge, options.mainTextureRatio, value, options.mainTextureType);
  }
  get layerTextureType() {
    return this._frameGraphTask.layer._options.mainTextureType;
  }
  set layerTextureType(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.ldrMerge, options.mainTextureRatio, options.mainTextureFixedSize, value);
  }
  get blurKernelSize() {
    return this._frameGraphTask.layer.blurKernelSize;
  }
  set blurKernelSize(value) {
    this._frameGraphTask.layer.blurKernelSize = value;
  }
  get intensity() {
    return this._frameGraphTask.layer.intensity;
  }
  set intensity(value) {
    this._frameGraphTask.layer.intensity = value;
  }
  getClassName() {
    return "NodeRenderGraphGlowLayerBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get layer() {
    return this._inputs[1];
  }
  get objectRenderer() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
    this._frameGraphTask.layerTexture = this.layer.connectedPoint?.value;
    this._frameGraphTask.objectRendererTask = this.objectRenderer.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.blurKernelSize = ${this.blurKernelSize};`);
    codes.push(`${this._codeVariableName}.intensity = ${this.intensity};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.blurKernelSize = this.blurKernelSize;
    serializationObject.intensity = this.intensity;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.blurKernelSize = serializationObject.blurKernelSize;
    this.intensity = serializationObject.intensity;
  }
}
__decorate([
  editableInPropertyPage("LDR merge", 0, "PROPERTIES")
], NodeRenderGraphGlowLayerBlock.prototype, "ldrMerge", null);
__decorate([
  editableInPropertyPage("Layer texture ratio", 1, "PROPERTIES")
], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureRatio", null);
__decorate([
  editableInPropertyPage("Layer texture fixed size", 1, "PROPERTIES")
], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureFixedSize", null);
__decorate([
  editableInPropertyPage("Layer texture type", 8, "PROPERTIES")
], NodeRenderGraphGlowLayerBlock.prototype, "layerTextureType", null);
__decorate([
  editableInPropertyPage("Blur kernel size", 2, "PROPERTIES", { min: 1, max: 256 })
], NodeRenderGraphGlowLayerBlock.prototype, "blurKernelSize", null);
__decorate([
  editableInPropertyPage("Intensity", 1, "PROPERTIES", { min: 0, max: 5 })
], NodeRenderGraphGlowLayerBlock.prototype, "intensity", null);
RegisterClass("BABYLON.NodeRenderGraphGlowLayerBlock", NodeRenderGraphGlowLayerBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Layers/highlightLayerBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/Layers/thinHighlightLayer.js
init_math_vector();
init_buffer();
init_thinPassPostProcess();
init_math_color();
class ThinHighlightLayer extends ThinEffectLayer {
  set blurHorizontalSize(value) {
    this._horizontalBlurPostprocess.kernel = value;
    this._options.blurHorizontalSize = value;
  }
  set blurVerticalSize(value) {
    this._verticalBlurPostprocess.kernel = value;
    this._options.blurVerticalSize = value;
  }
  get blurHorizontalSize() {
    return this._horizontalBlurPostprocess.kernel;
  }
  get blurVerticalSize() {
    return this._verticalBlurPostprocess.kernel;
  }
  constructor(name213, scene, options, dontCheckIfReady = false) {
    super(name213, scene, options !== undefined ? !!options.forceGLSL : false);
    this.innerGlow = true;
    this.outerGlow = true;
    this._instanceGlowingMeshStencilReference = ThinHighlightLayer.GlowingMeshStencilReference++;
    this._meshes = {};
    this._excludedMeshes = {};
    this._mainObjectRendererRenderPassId = -1;
    this.neutralColor = ThinHighlightLayer.NeutralColor;
    this._options = {
      mainTextureRatio: 0.5,
      blurTextureSizeRatio: 0.5,
      mainTextureFixedSize: 0,
      blurHorizontalSize: 1,
      blurVerticalSize: 1,
      alphaBlendingMode: 2,
      camera: null,
      renderingGroupId: -1,
      forceGLSL: false,
      mainTextureType: 0,
      isStroke: false,
      ...options
    };
    this._init(this._options);
    this._shouldRender = false;
    if (dontCheckIfReady) {
      this._createTextureAndPostProcesses();
    }
  }
  getClassName() {
    return "HighlightLayer";
  }
  async _importShadersAsync() {
    if (this._shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_glowMapMerge_fragment(), exports_glowMapMerge_fragment)),
        Promise.resolve().then(() => (init_glowMapMerge_vertex(), exports_glowMapMerge_vertex)),
        Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), exports_glowBlurPostProcess_fragment))
      ]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_glowMapMerge_fragment2(), exports_glowMapMerge_fragment2)), Promise.resolve().then(() => (init_glowMapMerge_vertex2(), exports_glowMapMerge_vertex2)), Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), exports_glowBlurPostProcess_fragment2))]);
    }
    await super._importShadersAsync();
  }
  getEffectName() {
    return ThinHighlightLayer.EffectName;
  }
  _numInternalDraws() {
    return 2;
  }
  _createMergeEffect() {
    return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? `#define STROKE 
` : undefined, undefined, undefined, undefined, undefined, this._shaderLanguage, this._shadersLoaded ? undefined : async () => {
      await this._importShadersAsync();
      this._shadersLoaded = true;
    });
  }
  _createTextureAndPostProcesses() {
    if (this._options.alphaBlendingMode === 2) {
      this._downSamplePostprocess = new ThinPassPostProcess("HighlightLayerPPP", this._scene.getEngine());
      this._horizontalBlurPostprocess = new ThinGlowBlurPostProcess("HighlightLayerHBP", this._scene.getEngine(), new Vector2(1, 0), this._options.blurHorizontalSize);
      this._verticalBlurPostprocess = new ThinGlowBlurPostProcess("HighlightLayerVBP", this._scene.getEngine(), new Vector2(0, 1), this._options.blurVerticalSize);
      this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
    } else {
      this._horizontalBlurPostprocess = new ThinBlurPostProcess("HighlightLayerHBP", this._scene.getEngine(), new Vector2(1, 0), this._options.blurHorizontalSize / 2);
      this._verticalBlurPostprocess = new ThinBlurPostProcess("HighlightLayerVBP", this._scene.getEngine(), new Vector2(0, 1), this._options.blurVerticalSize / 2);
      this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
    }
  }
  needStencil() {
    return true;
  }
  isReady(subMesh, useInstances) {
    const material = subMesh.getMaterial();
    const mesh = subMesh.getRenderingMesh();
    if (!material || !mesh || !this._meshes) {
      return false;
    }
    let emissiveTexture = null;
    const highlightLayerMesh = this._meshes[mesh.uniqueId];
    if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
      emissiveTexture = material.emissiveTexture;
    }
    return super._isSubMeshReady(subMesh, useInstances, emissiveTexture);
  }
  _canRenderMesh(_mesh, _material) {
    return true;
  }
  _internalCompose(effect, renderIndex) {
    this.bindTexturesForCompose(effect);
    const engine2 = this._engine;
    engine2.cacheStencilState();
    engine2.setStencilOperationPass(7681);
    engine2.setStencilOperationFail(7680);
    engine2.setStencilOperationDepthFail(7680);
    engine2.setStencilMask(0);
    engine2.setStencilBuffer(true);
    engine2.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
    if (this.outerGlow && renderIndex === 0) {
      effect.setFloat("offset", 0);
      engine2.setStencilFunction(517);
      engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
    }
    if (this.innerGlow && renderIndex === 1) {
      effect.setFloat("offset", 1);
      engine2.setStencilFunction(514);
      engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
    }
    engine2.restoreStencilState();
  }
  _setEmissiveTextureAndColor(mesh, _subMesh, material) {
    const highlightLayerMesh = this._meshes[mesh.uniqueId];
    if (highlightLayerMesh) {
      this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1);
    } else {
      this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
    }
    if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
      this._emissiveTextureAndColor.texture = material.emissiveTexture;
      this._emissiveTextureAndColor.color.set(1, 1, 1, 1);
    } else {
      this._emissiveTextureAndColor.texture = null;
    }
  }
  shouldRender() {
    return this._meshes && super.shouldRender() ? true : false;
  }
  _shouldRenderMesh(mesh) {
    if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
      return false;
    }
    return super.hasMesh(mesh);
  }
  _addCustomEffectDefines(defines) {
    defines.push("#define HIGHLIGHT");
  }
  addExcludedMesh(mesh) {
    if (!this._excludedMeshes) {
      return;
    }
    const meshExcluded = this._excludedMeshes[mesh.uniqueId];
    if (!meshExcluded) {
      const obj = {
        mesh,
        beforeBind: null,
        afterRender: null,
        stencilState: false
      };
      obj.beforeBind = mesh.onBeforeBindObservable.add((mesh2) => {
        if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) {
          return;
        }
        obj.stencilState = mesh2.getEngine().getStencilBuffer();
        mesh2.getEngine().setStencilBuffer(false);
      });
      obj.afterRender = mesh.onAfterRenderObservable.add((mesh2) => {
        if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) {
          return;
        }
        mesh2.getEngine().setStencilBuffer(obj.stencilState);
      });
      this._excludedMeshes[mesh.uniqueId] = obj;
    }
  }
  removeExcludedMesh(mesh) {
    if (!this._excludedMeshes) {
      return;
    }
    const meshExcluded = this._excludedMeshes[mesh.uniqueId];
    if (meshExcluded) {
      if (meshExcluded.beforeBind) {
        mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);
      }
      if (meshExcluded.afterRender) {
        mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
      }
    }
    this._excludedMeshes[mesh.uniqueId] = null;
  }
  hasMesh(mesh) {
    if (!this._meshes || !super.hasMesh(mesh)) {
      return false;
    }
    return !!this._meshes[mesh.uniqueId];
  }
  addMesh(mesh, color, glowEmissiveOnly = false) {
    if (!this._meshes) {
      return;
    }
    const meshHighlight = this._meshes[mesh.uniqueId];
    if (meshHighlight) {
      meshHighlight.color = color;
    } else {
      this._meshes[mesh.uniqueId] = {
        mesh,
        color,
        observerHighlight: mesh.onBeforeBindObservable.add((mesh2) => {
          if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) {
            return;
          }
          if (this.isEnabled) {
            if (this._excludedMeshes && this._excludedMeshes[mesh2.uniqueId]) {
              this._defaultStencilReference(mesh2);
            } else {
              mesh2.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
            }
          }
        }),
        observerDefault: mesh.onAfterRenderObservable.add((mesh2) => {
          if (this._mainObjectRendererRenderPassId !== -1 && this._mainObjectRendererRenderPassId !== this._engine.currentRenderPassId) {
            return;
          }
          if (this.isEnabled) {
            this._defaultStencilReference(mesh2);
          }
        }),
        glowEmissiveOnly
      };
      mesh.onDisposeObservable.add(() => {
        this._disposeMesh(mesh);
      });
    }
    this._shouldRender = true;
  }
  removeMesh(mesh) {
    if (!this._meshes) {
      return;
    }
    const meshHighlight = this._meshes[mesh.uniqueId];
    if (meshHighlight) {
      if (meshHighlight.observerHighlight) {
        mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
      }
      if (meshHighlight.observerDefault) {
        mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
      }
      delete this._meshes[mesh.uniqueId];
    }
    this._shouldRender = false;
    for (const meshHighlightToCheck in this._meshes) {
      if (this._meshes[meshHighlightToCheck]) {
        this._shouldRender = true;
        break;
      }
    }
  }
  removeAllMeshes() {
    if (!this._meshes) {
      return;
    }
    for (const uniqueId in this._meshes) {
      if (Object.prototype.hasOwnProperty.call(this._meshes, uniqueId)) {
        const mesh = this._meshes[uniqueId];
        if (mesh) {
          this.removeMesh(mesh.mesh);
        }
      }
    }
  }
  _defaultStencilReference(mesh) {
    mesh.getScene().getEngine().setStencilFunctionReference(ThinHighlightLayer.NormalMeshStencilReference);
  }
  _disposeMesh(mesh) {
    this.removeMesh(mesh);
    this.removeExcludedMesh(mesh);
  }
  dispose() {
    if (this._meshes) {
      for (const id in this._meshes) {
        const meshHighlight = this._meshes[id];
        if (meshHighlight && meshHighlight.mesh) {
          if (meshHighlight.observerHighlight) {
            meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
          }
          if (meshHighlight.observerDefault) {
            meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
          }
        }
      }
      this._meshes = null;
    }
    if (this._excludedMeshes) {
      for (const id in this._excludedMeshes) {
        const meshHighlight = this._excludedMeshes[id];
        if (meshHighlight) {
          if (meshHighlight.beforeBind) {
            meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);
          }
          if (meshHighlight.afterRender) {
            meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
          }
        }
      }
      this._excludedMeshes = null;
    }
    super.dispose();
  }
}
ThinHighlightLayer.EffectName = "HighlightLayer";
ThinHighlightLayer.NeutralColor = new Color4(0, 0, 0, 0);
ThinHighlightLayer.GlowingMeshStencilReference = 2;
ThinHighlightLayer.NormalMeshStencilReference = 1;

// node_modules/@babylonjs/core/FrameGraph/Tasks/Layers/highlightLayerTask.js
class FrameGraphHighlightLayerTask extends FrameGraphBaseLayerTask {
  constructor(name213, frameGraph, scene, options) {
    const alphaBlendingMode = options?.alphaBlendingMode ?? 2;
    super(name213, frameGraph, scene, new ThinHighlightLayer(name213, scene, options, true), 1, alphaBlendingMode === 2, true, true);
  }
  record() {
    if (!this.objectRendererTask.depthTexture) {
      throw new Error(`FrameGraphHighlightLayerTask "${this.name}": objectRendererTask must have a depthTexture input`);
    }
    const depthTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.objectRendererTask.depthTexture);
    if (!depthTextureCreationOptions.options.formats || !HasStencilAspect(depthTextureCreationOptions.options.formats[0])) {
      throw new Error(`FrameGraphHighlightLayerTask "${this.name}": objectRendererTask depthTexture must have a stencil aspect`);
    }
    super.record();
    this.layer._mainObjectRendererRenderPassId = this.objectRendererTask.objectRenderer.renderPassId;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Layers/highlightLayerBlock.js
class NodeRenderGraphHighlightLayerBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name213, frameGraph, scene, layerTextureRatio = 0.5, layerTextureFixedSize, blurTextureSizeRatio = 0.5, isStroke = false, layerTextureType = 0) {
    super(name213, frameGraph, scene);
    this._additionalConstructionParameters = [layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType];
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("layer", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("objectRenderer", NodeRenderGraphBlockConnectionPointTypes.Object, true, new NodeRenderGraphConnectionPointCustomObject("objectRenderer", this, 0, NodeRenderGraphBaseObjectRendererBlock, "NodeRenderGraphBaseObjectRendererBlock"));
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBufferDepthStencil);
    this.layer.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this.output._typeConnectionSource = this.target;
    this._frameGraphTask = new FrameGraphHighlightLayerTask(this.name, this._frameGraph, this._scene, {
      mainTextureRatio: layerTextureRatio,
      mainTextureFixedSize: layerTextureFixedSize,
      blurTextureSizeRatio,
      isStroke,
      mainTextureType: layerTextureType
    });
  }
  _createTask(layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType) {
    const blurHorizontalSize = this.blurHorizontalSize;
    const blurVerticalSize = this.blurVerticalSize;
    this._frameGraphTask?.dispose();
    this._frameGraphTask = new FrameGraphHighlightLayerTask(this.name, this._frameGraph, this._scene, {
      mainTextureRatio: layerTextureRatio,
      mainTextureFixedSize: layerTextureFixedSize,
      blurTextureSizeRatio,
      isStroke,
      mainTextureType: layerTextureType
    });
    this.blurHorizontalSize = blurHorizontalSize;
    this.blurVerticalSize = blurVerticalSize;
    this._additionalConstructionParameters = [layerTextureRatio, layerTextureFixedSize, blurTextureSizeRatio, isStroke, layerTextureType];
  }
  get layerTextureRatio() {
    return this._frameGraphTask.layer._options.mainTextureRatio;
  }
  set layerTextureRatio(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(value, options.mainTextureFixedSize, options.blurTextureSizeRatio, options.isStroke, options.mainTextureType);
  }
  get layerTextureFixedSize() {
    return this._frameGraphTask.layer._options.mainTextureFixedSize;
  }
  set layerTextureFixedSize(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.mainTextureRatio, value, options.blurTextureSizeRatio, options.isStroke, options.mainTextureType);
  }
  get blurTextureSizeRatio() {
    return this._frameGraphTask.layer._options.blurTextureSizeRatio;
  }
  set blurTextureSizeRatio(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, value, options.isStroke, options.mainTextureType);
  }
  get isStroke() {
    return this._frameGraphTask.layer._options.isStroke;
  }
  set isStroke(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, options.blurTextureSizeRatio, value, options.mainTextureType);
  }
  get layerTextureType() {
    return this._frameGraphTask.layer._options.mainTextureType;
  }
  set layerTextureType(value) {
    const options = this._frameGraphTask.layer._options;
    this._createTask(options.mainTextureRatio, options.mainTextureFixedSize, options.blurTextureSizeRatio, options.isStroke, value);
  }
  get blurHorizontalSize() {
    return this._frameGraphTask.layer.blurHorizontalSize;
  }
  set blurHorizontalSize(value) {
    this._frameGraphTask.layer.blurHorizontalSize = value;
  }
  get blurVerticalSize() {
    return this._frameGraphTask.layer.blurVerticalSize;
  }
  set blurVerticalSize(value) {
    this._frameGraphTask.layer.blurVerticalSize = value;
  }
  getClassName() {
    return "NodeRenderGraphHighlightLayerBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get layer() {
    return this._inputs[1];
  }
  get objectRenderer() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
    this._frameGraphTask.layerTexture = this.layer.connectedPoint?.value;
    this._frameGraphTask.objectRendererTask = this.objectRenderer.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.blurHorizontalSize = ${this.blurHorizontalSize};`);
    codes.push(`${this._codeVariableName}.blurVerticalSize = ${this.blurVerticalSize};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.blurHorizontalSize = this.blurHorizontalSize;
    serializationObject.blurVerticalSize = this.blurVerticalSize;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.blurHorizontalSize = serializationObject.blurHorizontalSize;
    this.blurVerticalSize = serializationObject.blurVerticalSize;
  }
}
__decorate([
  editableInPropertyPage("Layer texture ratio", 1, "PROPERTIES")
], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureRatio", null);
__decorate([
  editableInPropertyPage("Layer texture fixed size", 1, "PROPERTIES")
], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureFixedSize", null);
__decorate([
  editableInPropertyPage("Blur texture size ratio", 1, "PROPERTIES")
], NodeRenderGraphHighlightLayerBlock.prototype, "blurTextureSizeRatio", null);
__decorate([
  editableInPropertyPage("Is stroke", 0, "PROPERTIES")
], NodeRenderGraphHighlightLayerBlock.prototype, "isStroke", null);
__decorate([
  editableInPropertyPage("Layer texture type", 8, "PROPERTIES")
], NodeRenderGraphHighlightLayerBlock.prototype, "layerTextureType", null);
__decorate([
  editableInPropertyPage("Blur horizontal size", 1, "PROPERTIES", { min: 0, max: 4 })
], NodeRenderGraphHighlightLayerBlock.prototype, "blurHorizontalSize", null);
__decorate([
  editableInPropertyPage("Blur vertical size", 1, "PROPERTIES", { min: 0, max: 4 })
], NodeRenderGraphHighlightLayerBlock.prototype, "blurVerticalSize", null);
RegisterClass("BABYLON.NodeRenderGraphHighlightLayerBlock", NodeRenderGraphHighlightLayerBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/anaglyphPostProcessBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/anaglyphTask.js
class FrameGraphAnaglyphTask extends FrameGraphPostProcessTask {
  constructor(name213, frameGraph, thinPostProcess) {
    super(name213, frameGraph, thinPostProcess || new ThinAnaglyphPostProcess(name213, frameGraph.engine));
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.leftTexture === undefined) {
      throw new Error(`FrameGraphAnaglyphTask "${this.name}": sourceTexture and leftTexture are required`);
    }
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "leftSampler", this.leftTexture);
    });
    pass.addDependencies(this.leftTexture);
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/basePostProcessBlock.js
init_tslib_es6();
class NodeRenderGraphBasePostProcessBlock extends NodeRenderGraphBlock {
  constructor(name213, frameGraph, scene) {
    super(name213, frameGraph, scene);
    this.registerInput("source", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.source.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll);
  }
  _finalizeInputOutputRegistering() {
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.output._typeConnectionSource = () => {
      return this.target.isConnected ? this.target : this.source;
    };
  }
  get sourceSamplingMode() {
    return this._frameGraphTask.sourceSamplingMode;
  }
  set sourceSamplingMode(value) {
    this._frameGraphTask.sourceSamplingMode = value;
  }
  getClassName() {
    return "NodeRenderGraphBasePostProcessBlock";
  }
  get source() {
    return this._inputs[0];
  }
  get target() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.sourceTexture = this.source.connectedPoint?.value;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.sourceSamplingMode = ${this.sourceSamplingMode};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.sourceSamplingMode = this.sourceSamplingMode;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.sourceSamplingMode = serializationObject.sourceSamplingMode;
  }
}
__decorate([
  editableInPropertyPage("Source sampling mode", 6, "PROPERTIES")
], NodeRenderGraphBasePostProcessBlock.prototype, "sourceSamplingMode", null);

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/anaglyphPostProcessBlock.js
class NodeRenderGraphAnaglyphPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name213, frameGraph, scene) {
    super(name213, frameGraph, scene);
    this.registerInput("leftTexture", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.leftTexture.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphAnaglyphTask(this.name, frameGraph, new ThinAnaglyphPostProcess(name213, scene.getEngine()));
  }
  getClassName() {
    return "NodeRenderGraphAnaglyphPostProcessBlock";
  }
  get leftTexture() {
    return this._inputs[2];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._frameGraphTask.leftTexture = this.leftTexture.connectedPoint?.value;
  }
}
RegisterClass("BABYLON.NodeRenderGraphAnaglyphPostProcessBlock", NodeRenderGraphAnaglyphPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/blackAndWhitePostProcessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinBlackAndWhitePostProcess.js
init_effectRenderer();
init_engine();

class ThinBlackAndWhitePostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_blackAndWhite_fragment(), exports_blackAndWhite_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_blackAndWhite_fragment2(), exports_blackAndWhite_fragment2)));
    }
  }
  constructor(name215, engine2 = null, options) {
    super({
      ...options,
      name: name215,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinBlackAndWhitePostProcess.FragmentUrl,
      uniforms: ThinBlackAndWhitePostProcess.Uniforms
    });
    this.degree = 1;
  }
  bind() {
    super.bind();
    this._drawWrapper.effect.setFloat("degree", this.degree);
  }
}
ThinBlackAndWhitePostProcess.FragmentUrl = "blackAndWhite";
ThinBlackAndWhitePostProcess.Uniforms = ["degree"];

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/blackAndWhiteTask.js
class FrameGraphBlackAndWhiteTask extends FrameGraphPostProcessTask {
  constructor(name215, frameGraph, thinPostProcess) {
    super(name215, frameGraph, thinPostProcess || new ThinBlackAndWhitePostProcess(name215, frameGraph.engine));
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/blackAndWhitePostProcessBlock.js
class NodeRenderGraphBlackAndWhitePostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name215, frameGraph, scene) {
    super(name215, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphBlackAndWhiteTask(this.name, frameGraph, new ThinBlackAndWhitePostProcess(name215, scene.getEngine()));
  }
  get degree() {
    return this._frameGraphTask.postProcess.degree;
  }
  set degree(value) {
    this._frameGraphTask.postProcess.degree = value;
  }
  getClassName() {
    return "NodeRenderGraphBlackAndWhitePostProcessBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.degree = ${this.degree};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.degree = this.degree;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.degree = serializationObject.degree;
  }
}
__decorate([
  editableInPropertyPage("Degree", 1, "PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphBlackAndWhitePostProcessBlock.prototype, "degree", null);
RegisterClass("BABYLON.NodeRenderGraphBlackAndWhitePostProcessBlock", NodeRenderGraphBlackAndWhitePostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/bloomPostProcessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinBloomMergePostProcess.js
init_effectRenderer();
init_engine();

class ThinBloomMergePostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_bloomMerge_fragment(), exports_bloomMerge_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_bloomMerge_fragment2(), exports_bloomMerge_fragment2)));
    }
  }
  constructor(name217, engine2 = null, options) {
    super({
      ...options,
      name: name217,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinBloomMergePostProcess.FragmentUrl,
      uniforms: ThinBloomMergePostProcess.Uniforms,
      samplers: ThinBloomMergePostProcess.Samplers
    });
    this.weight = 1;
  }
  bind() {
    super.bind();
    this._drawWrapper.effect.setFloat("bloomWeight", this.weight);
  }
}
ThinBloomMergePostProcess.FragmentUrl = "bloomMerge";
ThinBloomMergePostProcess.Uniforms = ["bloomWeight"];
ThinBloomMergePostProcess.Samplers = ["bloomBlur"];

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/bloomMergeTask.js
class FrameGraphBloomMergeTask extends FrameGraphPostProcessTask {
  constructor(name217, frameGraph, thinPostProcess) {
    super(name217, frameGraph, thinPostProcess || new ThinBloomMergePostProcess(name217, frameGraph.engine));
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.blurTexture === undefined) {
      throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture and blurTexture are required`);
    }
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "bloomBlur", this.blurTexture);
    });
    pass.addDependencies(this.blurTexture);
    return pass;
  }
}

// node_modules/@babylonjs/core/PostProcesses/thinBloomEffect.js
init_math_vector();

// node_modules/@babylonjs/core/PostProcesses/thinExtractHighlightsPostProcess.js
init_effectRenderer();
init_math_constants();
init_engine();

class ThinExtractHighlightsPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_extractHighlights_fragment(), exports_extractHighlights_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_extractHighlights_fragment2(), exports_extractHighlights_fragment2)));
    }
  }
  constructor(name219, engine2 = null, options) {
    super({
      ...options,
      name: name219,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinExtractHighlightsPostProcess.FragmentUrl,
      uniforms: ThinExtractHighlightsPostProcess.Uniforms
    });
    this.threshold = 0.9;
    this._exposure = 1;
  }
  bind() {
    super.bind();
    const effect = this._drawWrapper.effect;
    effect.setFloat("threshold", Math.pow(this.threshold, ToGammaSpace));
    effect.setFloat("exposure", this._exposure);
  }
}
ThinExtractHighlightsPostProcess.FragmentUrl = "extractHighlights";
ThinExtractHighlightsPostProcess.Uniforms = ["threshold", "exposure"];

// node_modules/@babylonjs/core/PostProcesses/thinBloomEffect.js
class ThinBloomEffect {
  get threshold() {
    return this._downscale.threshold;
  }
  set threshold(value) {
    this._downscale.threshold = value;
  }
  get weight() {
    return this._merge.weight;
  }
  set weight(value) {
    this._merge.weight = value;
  }
  get kernel() {
    return this._blurX.kernel / this.scale;
  }
  set kernel(value) {
    this._blurX.kernel = value * this.scale;
    this._blurY.kernel = value * this.scale;
  }
  constructor(name219, engine2, scale, blockCompilation = false) {
    this.scale = scale;
    this._downscale = new ThinExtractHighlightsPostProcess(name219 + "_downscale", engine2, { blockCompilation });
    this._blurX = new ThinBlurPostProcess(name219 + "_blurX", engine2, new Vector2(1, 0), 10, { blockCompilation });
    this._blurY = new ThinBlurPostProcess(name219 + "_blurY", engine2, new Vector2(0, 1), 10, { blockCompilation });
    this._merge = new ThinBloomMergePostProcess(name219 + "_merge", engine2, { blockCompilation });
  }
  isReady() {
    return this._downscale.isReady() && this._blurX.isReady() && this._blurY.isReady() && this._merge.isReady();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/extractHighlightsTask.js
class FrameGraphExtractHighlightsTask extends FrameGraphPostProcessTask {
  constructor(name219, frameGraph, thinPostProcess) {
    super(name219, frameGraph, thinPostProcess || new ThinExtractHighlightsPostProcess(name219, frameGraph.engine));
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/bloomTask.js
class FrameGraphBloomTask extends FrameGraphTask {
  get name() {
    return this._name;
  }
  set name(name219) {
    this._name = name219;
    if (this._downscale) {
      this._downscale.name = `${name219} Downscale`;
    }
    if (this._blurX) {
      this._blurX.name = `${name219} Blur X`;
    }
    if (this._blurY) {
      this._blurY.name = `${name219} Blur Y`;
    }
    if (this._merge) {
      this._merge.name = `${name219} Merge`;
    }
  }
  constructor(name219, frameGraph, weight, kernel, threshold, hdr = false, bloomScale = 0.5) {
    super(name219, frameGraph);
    this.sourceSamplingMode = 2;
    this.hdr = hdr;
    this._defaultPipelineTextureType = 0;
    if (hdr) {
      const caps = frameGraph.engine.getCaps();
      if (caps.textureHalfFloatRender) {
        this._defaultPipelineTextureType = 2;
      } else if (caps.textureFloatRender) {
        this._defaultPipelineTextureType = 1;
      }
    }
    this.bloom = new ThinBloomEffect(name219, frameGraph.engine, bloomScale);
    this.bloom.threshold = threshold;
    this.bloom.kernel = kernel;
    this.bloom.weight = weight;
    this._downscale = new FrameGraphExtractHighlightsTask(`${name219} Downscale`, this._frameGraph, this.bloom._downscale);
    this._blurX = new FrameGraphBlurTask(`${name219} Blur X`, this._frameGraph, this.bloom._blurX);
    this._blurY = new FrameGraphBlurTask(`${name219} Blur Y`, this._frameGraph, this.bloom._blurY);
    this._merge = new FrameGraphBloomMergeTask(`${name219} Merge`, this._frameGraph, this.bloom._merge);
    this.onTexturesAllocatedObservable.add((context) => {
      this._downscale.onTexturesAllocatedObservable.notifyObservers(context);
      this._blurX.onTexturesAllocatedObservable.notifyObservers(context);
      this._blurY.onTexturesAllocatedObservable.notifyObservers(context);
      this._merge.onTexturesAllocatedObservable.notifyObservers(context);
    });
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  isReady() {
    return this.bloom.isReady();
  }
  record() {
    if (this.sourceTexture === undefined) {
      throw new Error("FrameGraphBloomTask: sourceTexture is required");
    }
    const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture);
    const textureCreationOptions = {
      size: {
        width: Math.floor(sourceTextureDescription.size.width * this.bloom.scale) || 1,
        height: Math.floor(sourceTextureDescription.size.height * this.bloom.scale) || 1
      },
      options: {
        createMipMaps: false,
        types: [this._defaultPipelineTextureType],
        formats: [5],
        samples: 1,
        useSRGBBuffers: [false],
        labels: [""]
      },
      sizeIsPercentage: false
    };
    const downscaleTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._downscale.name, textureCreationOptions);
    this._downscale.sourceTexture = this.sourceTexture;
    this._downscale.sourceSamplingMode = 2;
    this._downscale.targetTexture = downscaleTextureHandle;
    this._downscale.record(true);
    const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX.name, textureCreationOptions);
    this._blurX.sourceTexture = downscaleTextureHandle;
    this._blurX.sourceSamplingMode = 2;
    this._blurX.targetTexture = blurXTextureHandle;
    this._blurX.record(true);
    const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY.name, textureCreationOptions);
    this._blurY.sourceTexture = blurXTextureHandle;
    this._blurY.sourceSamplingMode = 2;
    this._blurY.targetTexture = blurYTextureHandle;
    this._blurY.record(true);
    const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture);
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this._merge.name, sourceTextureCreationOptions);
    this._merge.sourceTexture = this.sourceTexture;
    this._merge.sourceSamplingMode = this.sourceSamplingMode;
    this._merge.blurTexture = blurYTextureHandle;
    this._merge.targetTexture = this.outputTexture;
    this._merge.record(true);
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.addDependencies(this.sourceTexture);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((context) => {
      context.copyTexture(this.sourceTexture);
    });
  }
  dispose() {
    this._downscale.dispose();
    this._blurX.dispose();
    this._blurY.dispose();
    this._merge.dispose();
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/bloomPostProcessBlock.js
class NodeRenderGraphBloomPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name219, frameGraph, scene, hdr = false, bloomScale = 0.5) {
    super(name219, frameGraph, scene);
    this._additionalConstructionParameters = [hdr, bloomScale];
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphBloomTask(this.name, frameGraph, 0.75, 64, 0.2, hdr, bloomScale);
  }
  _createTask(bloomScale, hdr) {
    const sourceSamplingMode = this._frameGraphTask.sourceSamplingMode;
    const threshold = this._frameGraphTask.bloom.threshold;
    const weight = this._frameGraphTask.bloom.weight;
    const kernel = this._frameGraphTask.bloom.kernel;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphBloomTask(this.name, this._frameGraph, weight, kernel, threshold, hdr, bloomScale);
    this._frameGraphTask.sourceSamplingMode = sourceSamplingMode;
    this._additionalConstructionParameters = [hdr, bloomScale];
  }
  get bloomScale() {
    return this._frameGraphTask.bloom.scale;
  }
  set bloomScale(value) {
    this._createTask(value, this._frameGraphTask.hdr);
  }
  get hdr() {
    return this._frameGraphTask.hdr;
  }
  set hdr(value) {
    this._createTask(this._frameGraphTask.bloom.scale, value);
  }
  get threshold() {
    return this._frameGraphTask.bloom.threshold;
  }
  set threshold(value) {
    this._frameGraphTask.bloom.threshold = value;
  }
  get weight() {
    return this._frameGraphTask.bloom.weight;
  }
  set weight(value) {
    this._frameGraphTask.bloom.weight = value;
  }
  get kernel() {
    return this._frameGraphTask.bloom.kernel;
  }
  set kernel(value) {
    this._frameGraphTask.bloom.kernel = value;
  }
  getClassName() {
    return "NodeRenderGraphBloomPostProcessBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.threshold = ${this.threshold};`);
    codes.push(`${this._codeVariableName}.weight = ${this.weight};`);
    codes.push(`${this._codeVariableName}.kernel = ${this.kernel};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.threshold = this.threshold;
    serializationObject.weight = this.weight;
    serializationObject.kernel = this.kernel;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.threshold = serializationObject.threshold;
    this.weight = serializationObject.weight;
    this.kernel = serializationObject.kernel;
  }
}
__decorate([
  editableInPropertyPage("Bloom scale", 1, "PROPERTIES")
], NodeRenderGraphBloomPostProcessBlock.prototype, "bloomScale", null);
__decorate([
  editableInPropertyPage("HDR", 0, "PROPERTIES")
], NodeRenderGraphBloomPostProcessBlock.prototype, "hdr", null);
__decorate([
  editableInPropertyPage("Threshold", 1, "PROPERTIES", { min: 0, max: 2 })
], NodeRenderGraphBloomPostProcessBlock.prototype, "threshold", null);
__decorate([
  editableInPropertyPage("Weight", 1, "PROPERTIES", { min: 0, max: 3 })
], NodeRenderGraphBloomPostProcessBlock.prototype, "weight", null);
__decorate([
  editableInPropertyPage("Kernel", 2, "PROPERTIES", { min: 1, max: 128 })
], NodeRenderGraphBloomPostProcessBlock.prototype, "kernel", null);
RegisterClass("BABYLON.NodeRenderGraphBloomPostProcessBlock", NodeRenderGraphBloomPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/blurPostProcessBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
class NodeRenderGraphBlurPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name219, frameGraph, scene) {
    super(name219, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphBlurTask(this.name, frameGraph, new ThinBlurPostProcess(name219, scene.getEngine(), new Vector2(1, 0), 32));
  }
  get direction() {
    return this._frameGraphTask.postProcess.direction;
  }
  set direction(value) {
    this._frameGraphTask.postProcess.direction = value;
  }
  get kernel() {
    return this._frameGraphTask.postProcess.kernel;
  }
  set kernel(value) {
    this._frameGraphTask.postProcess.kernel = value;
  }
  getClassName() {
    return "NodeRenderGraphBlurPostProcessBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`);
    codes.push(`${this._codeVariableName}.kernel = ${this.kernel};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.direction = this.direction.asArray();
    serializationObject.kernel = this.kernel;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.direction.fromArray(serializationObject.direction);
    this.kernel = serializationObject.kernel;
  }
}
__decorate([
  editableInPropertyPage("Direction", 3, "PROPERTIES")
], NodeRenderGraphBlurPostProcessBlock.prototype, "direction", null);
__decorate([
  editableInPropertyPage("Kernel", 2, "PROPERTIES", { min: 1, max: 256 })
], NodeRenderGraphBlurPostProcessBlock.prototype, "kernel", null);
RegisterClass("BABYLON.NodeRenderGraphBlurPostProcessBlock", NodeRenderGraphBlurPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/chromaticAberrationPostProcessBlock.js
init_tslib_es6();
init_math_vector();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinChromaticAberrationPostProcess.js
init_effectRenderer();
init_engine();
init_math_vector();

class ThinChromaticAberrationPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_chromaticAberration_fragment(), exports_chromaticAberration_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_chromaticAberration_fragment2(), exports_chromaticAberration_fragment2)));
    }
  }
  constructor(name221, engine2 = null, options) {
    super({
      ...options,
      name: name221,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinChromaticAberrationPostProcess.FragmentUrl,
      uniforms: ThinChromaticAberrationPostProcess.Uniforms
    });
    this.aberrationAmount = 30;
    this.radialIntensity = 0;
    this.direction = new Vector2(0.707, 0.707);
    this.centerPosition = new Vector2(0.5, 0.5);
  }
  bind() {
    super.bind();
    const effect = this._drawWrapper.effect;
    effect.setFloat("chromatic_aberration", this.aberrationAmount);
    effect.setFloat("screen_width", this.screenWidth);
    effect.setFloat("screen_height", this.screenHeight);
    effect.setFloat("radialIntensity", this.radialIntensity);
    effect.setFloat2("direction", this.direction.x, this.direction.y);
    effect.setFloat2("centerPosition", this.centerPosition.x, this.centerPosition.y);
  }
}
ThinChromaticAberrationPostProcess.FragmentUrl = "chromaticAberration";
ThinChromaticAberrationPostProcess.Uniforms = ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"];

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/chromaticAberrationTask.js
class FrameGraphChromaticAberrationTask extends FrameGraphPostProcessTask {
  constructor(name221, frameGraph, thinPostProcess) {
    super(name221, frameGraph, thinPostProcess || new ThinChromaticAberrationPostProcess(name221, frameGraph.engine));
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
    const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings);
    this.postProcess.screenWidth = this._sourceWidth;
    this.postProcess.screenHeight = this._sourceHeight;
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/chromaticAberrationPostProcessBlock.js
class NodeRenderGraphChromaticAberrationPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name221, frameGraph, scene) {
    super(name221, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphChromaticAberrationTask(this.name, frameGraph, new ThinChromaticAberrationPostProcess(name221, scene.getEngine()));
  }
  get aberrationAmount() {
    return this._frameGraphTask.postProcess.aberrationAmount;
  }
  set aberrationAmount(value) {
    this._frameGraphTask.postProcess.aberrationAmount = value;
  }
  get radialIntensity() {
    return this._frameGraphTask.postProcess.radialIntensity;
  }
  set radialIntensity(value) {
    this._frameGraphTask.postProcess.radialIntensity = value;
  }
  get direction() {
    return this._frameGraphTask.postProcess.direction;
  }
  set direction(value) {
    this._frameGraphTask.postProcess.direction = value;
  }
  getClassName() {
    return "NodeRenderGraphChromaticAberrationPostProcessBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.aberrationAmount = ${this.aberrationAmount};`);
    codes.push(`${this._codeVariableName}.radialIntensity = ${this.radialIntensity};`);
    codes.push(`${this._codeVariableName}.direction = new BABYLON.Vector2(${this.direction.x}, ${this.direction.y});`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.aberrationAmount = this.aberrationAmount;
    serializationObject.radialIntensity = this.radialIntensity;
    serializationObject.direction = this.direction.asArray();
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.aberrationAmount = serializationObject.aberrationAmount;
    this.radialIntensity = serializationObject.radialIntensity;
    this.direction = Vector2.FromArray(serializationObject.direction);
  }
}
__decorate([
  editableInPropertyPage("Amount", 1, "PROPERTIES", { min: -1000, max: 1000 })
], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "aberrationAmount", null);
__decorate([
  editableInPropertyPage("Radial intensity", 1, "PROPERTIES", { min: 0.1, max: 5 })
], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "radialIntensity", null);
__decorate([
  editableInPropertyPage("Direction", 3, "PROPERTIES")
], NodeRenderGraphChromaticAberrationPostProcessBlock.prototype, "direction", null);
RegisterClass("BABYLON.NodeRenderGraphChromaticAberrationPostProcessBlock", NodeRenderGraphChromaticAberrationPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/circleOfConfusionPostProcessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinCircleOfConfusionPostProcess.js
init_effectRenderer();
init_engine();

class ThinCircleOfConfusionPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_circleOfConfusion_fragment(), exports_circleOfConfusion_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_circleOfConfusion_fragment2(), exports_circleOfConfusion_fragment2)));
    }
  }
  constructor(name223, engine2 = null, options) {
    super({
      ...options,
      name: name223,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinCircleOfConfusionPostProcess.FragmentUrl,
      uniforms: ThinCircleOfConfusionPostProcess.Uniforms,
      samplers: ThinCircleOfConfusionPostProcess.Samplers,
      defines: options?.depthNotNormalized ? ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : undefined
    });
    this.lensSize = 50;
    this.fStop = 1.4;
    this.focusDistance = 2000;
    this.focalLength = 50;
  }
  bind() {
    super.bind();
    const options = this.options;
    const effect = this._drawWrapper.effect;
    if (!options.depthNotNormalized) {
      effect.setFloat2("cameraMinMaxZ", this.camera.minZ, this.camera.maxZ - this.camera.minZ);
    }
    const aperture = this.lensSize / this.fStop;
    const cocPrecalculation = aperture * this.focalLength / (this.focusDistance - this.focalLength);
    effect.setFloat("focusDistance", this.focusDistance);
    effect.setFloat("cocPrecalculation", cocPrecalculation);
  }
}
ThinCircleOfConfusionPostProcess.FragmentUrl = "circleOfConfusion";
ThinCircleOfConfusionPostProcess.Uniforms = ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"];
ThinCircleOfConfusionPostProcess.Samplers = ["depthSampler"];
ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized = "#define COC_DEPTH_NOT_NORMALIZED";

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/circleOfConfusionTask.js
class FrameGraphCircleOfConfusionTask extends FrameGraphPostProcessTask {
  constructor(name223, frameGraph, thinPostProcess) {
    super(name223, frameGraph, thinPostProcess || new ThinCircleOfConfusionPostProcess(name223, frameGraph.engine));
    this.depthSamplingMode = 2;
    this.onTexturesAllocatedObservable.add((context) => {
      context.setTextureSamplingMode(this.depthTexture, this.depthSamplingMode);
    });
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.depthTexture === undefined || this.camera === undefined) {
      throw new Error(`FrameGraphCircleOfConfusionTask "${this.name}": sourceTexture, depthTexture and camera are required`);
    }
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      this.postProcess.camera = this.camera;
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "depthSampler", this.depthTexture);
    });
    pass.addDependencies(this.depthTexture);
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/circleOfConfusionPostProcessBlock.js
class NodeRenderGraphCircleOfConfusionPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name223, frameGraph, scene) {
    super(name223, frameGraph, scene);
    this.registerInput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphCircleOfConfusionTask(this.name, frameGraph, new ThinCircleOfConfusionPostProcess(name223, scene.getEngine(), { depthNotNormalized: true }));
  }
  get depthSamplingMode() {
    return this._frameGraphTask.depthSamplingMode;
  }
  set depthSamplingMode(value) {
    this._frameGraphTask.depthSamplingMode = value;
  }
  get lensSize() {
    return this._frameGraphTask.postProcess.lensSize;
  }
  set lensSize(value) {
    this._frameGraphTask.postProcess.lensSize = value;
  }
  get fStop() {
    return this._frameGraphTask.postProcess.fStop;
  }
  set fStop(value) {
    this._frameGraphTask.postProcess.fStop = value;
  }
  get focusDistance() {
    return this._frameGraphTask.postProcess.focusDistance;
  }
  set focusDistance(value) {
    this._frameGraphTask.postProcess.focusDistance = value;
  }
  get focalLength() {
    return this._frameGraphTask.postProcess.focalLength;
  }
  set focalLength(value) {
    this._frameGraphTask.postProcess.focalLength = value;
  }
  getClassName() {
    return "NodeRenderGraphCircleOfConfusionPostProcessBlock";
  }
  get geomViewDepth() {
    return this._inputs[2];
  }
  get camera() {
    return this._inputs[3];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._frameGraphTask.depthTexture = this.geomViewDepth.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`);
    codes.push(`${this._codeVariableName}.fStop = ${this.fStop};`);
    codes.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`);
    codes.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`);
    codes.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.lensSize = this.lensSize;
    serializationObject.fStop = this.fStop;
    serializationObject.focusDistance = this.focusDistance;
    serializationObject.focalLength = this.focalLength;
    serializationObject.depthSamplingMode = this.depthSamplingMode;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.lensSize = serializationObject.lensSize;
    this.fStop = serializationObject.fStop;
    this.focusDistance = serializationObject.focusDistance;
    this.focalLength = serializationObject.focalLength;
    this.depthSamplingMode = serializationObject.depthSamplingMode;
  }
}
__decorate([
  editableInPropertyPage("Depth sampling mode", 6, "PROPERTIES")
], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "depthSamplingMode", null);
__decorate([
  editableInPropertyPage("Lens size", 1, "PROPERTIES")
], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "lensSize", null);
__decorate([
  editableInPropertyPage("F-Stop", 1, "PROPERTIES")
], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "fStop", null);
__decorate([
  editableInPropertyPage("Focus distance", 1, "PROPERTIES")
], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "focusDistance", null);
__decorate([
  editableInPropertyPage("Focal length", 1, "PROPERTIES")
], NodeRenderGraphCircleOfConfusionPostProcessBlock.prototype, "focalLength", null);
RegisterClass("BABYLON.NodeRenderGraphCircleOfConfusionPostProcessBlock", NodeRenderGraphCircleOfConfusionPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/depthOfFieldPostProcessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldMergePostProcess.js
init_effectRenderer();
init_engine();

class ThinDepthOfFieldMergePostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_depthOfFieldMerge_fragment(), exports_depthOfFieldMerge_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_depthOfFieldMerge_fragment2(), exports_depthOfFieldMerge_fragment2)));
    }
  }
  constructor(name225, engine2 = null, options) {
    super({
      ...options,
      name: name225,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinDepthOfFieldMergePostProcess.FragmentUrl,
      samplers: ThinDepthOfFieldMergePostProcess.Samplers
    });
  }
}
ThinDepthOfFieldMergePostProcess.FragmentUrl = "depthOfFieldMerge";
ThinDepthOfFieldMergePostProcess.Samplers = ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"];

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/depthOfFieldMergeTask.js
class FrameGraphDepthOfFieldMergeTask extends FrameGraphPostProcessTask {
  constructor(name225, frameGraph, thinPostProcess) {
    super(name225, frameGraph, thinPostProcess || new ThinDepthOfFieldMergePostProcess(name225, frameGraph.engine));
    this.blurSteps = [];
    this.onTexturesAllocatedObservable.add((context) => {
      context.setTextureSamplingMode(this.blurSteps[this.blurSteps.length - 1], 2);
    });
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.circleOfConfusionTexture === undefined || this.blurSteps.length === 0) {
      throw new Error(`FrameGraphBloomMergeTask "${this.name}": sourceTexture, circleOfConfusionTexture and blurSteps are required`);
    }
    this.postProcess.updateEffect("#define BLUR_LEVEL " + (this.blurSteps.length - 1) + `
`);
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "circleOfConfusionSampler", this.circleOfConfusionTexture);
      this.blurSteps.forEach((handle, index) => {
        context.bindTextureHandle(this._postProcessDrawWrapper.effect, "blurStep" + (this.blurSteps.length - index - 1), handle);
      });
    });
    pass.addDependencies(this.circleOfConfusionTexture);
    pass.addDependencies(this.blurSteps);
    return pass;
  }
}

// node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldBlurPostProcess.js
class ThinDepthOfFieldBlurPostProcess extends ThinBlurPostProcess {
  constructor(name225, engine2 = null, direction, kernel, options) {
    super(name225, engine2, direction, kernel, {
      ...options,
      defines: `#define DOF 1
`
    });
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/depthOfFieldBlurTask.js
init_math_vector();

class FrameGraphDepthOfFieldBlurTask extends FrameGraphBlurTask {
  constructor(name225, frameGraph, thinPostProcess) {
    super(name225, frameGraph, thinPostProcess || new ThinDepthOfFieldBlurPostProcess(name225, frameGraph.engine, new Vector2(1, 0), 10));
    this.circleOfConfusionSamplingMode = 2;
    this.onTexturesAllocatedObservable.add((context) => {
      context.setTextureSamplingMode(this.circleOfConfusionTexture, this.circleOfConfusionSamplingMode);
    });
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.circleOfConfusionTexture === undefined) {
      throw new Error(`FrameGraphDepthOfFieldBlurTask "${this.name}": sourceTexture and circleOfConfusionTexture are required`);
    }
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "circleOfConfusionSampler", this.circleOfConfusionTexture);
    });
    pass.addDependencies(this.circleOfConfusionTexture);
    return pass;
  }
}

// node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldEffect.js
init_math_vector();
var ThinDepthOfFieldEffectBlurLevel;
(function(ThinDepthOfFieldEffectBlurLevel2) {
  ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["Low"] = 0] = "Low";
  ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["Medium"] = 1] = "Medium";
  ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["High"] = 2] = "High";
})(ThinDepthOfFieldEffectBlurLevel || (ThinDepthOfFieldEffectBlurLevel = {}));

class ThinDepthOfFieldEffect {
  set focalLength(value) {
    this._circleOfConfusion.focalLength = value;
  }
  get focalLength() {
    return this._circleOfConfusion.focalLength;
  }
  set fStop(value) {
    this._circleOfConfusion.fStop = value;
  }
  get fStop() {
    return this._circleOfConfusion.fStop;
  }
  set focusDistance(value) {
    this._circleOfConfusion.focusDistance = value;
  }
  get focusDistance() {
    return this._circleOfConfusion.focusDistance;
  }
  set lensSize(value) {
    this._circleOfConfusion.lensSize = value;
  }
  get lensSize() {
    return this._circleOfConfusion.lensSize;
  }
  constructor(name225, engine2, blurLevel = 0, depthNotNormalized = false, blockCompilation = false) {
    this._depthOfFieldBlurX = [];
    this._depthOfFieldBlurY = [];
    this._circleOfConfusion = new ThinCircleOfConfusionPostProcess(name225, engine2, { depthNotNormalized, blockCompilation });
    this.blurLevel = blurLevel;
    let blurCount = 1;
    let kernelSize = 15;
    switch (blurLevel) {
      case 2: {
        blurCount = 3;
        kernelSize = 51;
        break;
      }
      case 1: {
        blurCount = 2;
        kernelSize = 31;
        break;
      }
      default: {
        kernelSize = 15;
        blurCount = 1;
        break;
      }
    }
    const adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
    let ratio = 1;
    for (let i = 0;i < blurCount; i++) {
      this._depthOfFieldBlurY.push([new ThinBlurPostProcess(name225, engine2, new Vector2(0, 1), adjustedKernelSize, { blockCompilation }), ratio]);
      ratio = 0.75 / Math.pow(2, i);
      this._depthOfFieldBlurX.push([new ThinBlurPostProcess(name225, engine2, new Vector2(1, 0), adjustedKernelSize, { blockCompilation }), ratio]);
    }
    this._dofMerge = new ThinDepthOfFieldMergePostProcess(name225, engine2, { blockCompilation });
  }
  isReady() {
    let isReady = this._circleOfConfusion.isReady() && this._dofMerge.isReady();
    for (let i = 0;i < this._depthOfFieldBlurX.length; i++) {
      isReady = isReady && this._depthOfFieldBlurX[i][0].isReady() && this._depthOfFieldBlurY[i][0].isReady();
    }
    return isReady;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/depthOfFieldTask.js
class FrameGraphDepthOfFieldTask extends FrameGraphTask {
  get name() {
    return this._name;
  }
  set name(name225) {
    this._name = name225;
    if (this._circleOfConfusion) {
      this._circleOfConfusion.name = `${name225} Circle of Confusion`;
    }
    if (this._blurX) {
      for (let i = 0;i < this._blurX.length; i++) {
        this._blurX[i].name = `${name225} Blur X${i}`;
        this._blurY[i].name = `${name225} Blur Y${i}`;
      }
    }
    if (this._merge) {
      this._merge.name = `${name225} Merge`;
    }
  }
  constructor(name225, frameGraph, blurLevel = 0, hdr = false) {
    super(name225, frameGraph);
    this.sourceSamplingMode = 2;
    this.depthSamplingMode = 2;
    this._blurX = [];
    this._blurY = [];
    this._engine = frameGraph.engine;
    this.hdr = hdr;
    this._defaultPipelineTextureType = 0;
    if (hdr) {
      const caps = frameGraph.engine.getCaps();
      if (caps.textureHalfFloatRender) {
        this._defaultPipelineTextureType = 2;
      } else if (caps.textureFloatRender) {
        this._defaultPipelineTextureType = 1;
      }
    }
    this.depthOfField = new ThinDepthOfFieldEffect(name225, frameGraph.engine, blurLevel, true);
    this._circleOfConfusion = new FrameGraphCircleOfConfusionTask(`${name225} Circle of Confusion`, this._frameGraph, this.depthOfField._circleOfConfusion);
    const blurCount = this.depthOfField._depthOfFieldBlurX.length;
    for (let i = 0;i < blurCount; i++) {
      this._blurX.push(new FrameGraphDepthOfFieldBlurTask(`${name225} Blur X${i}`, this._frameGraph, this.depthOfField._depthOfFieldBlurX[i][0]));
      this._blurY.push(new FrameGraphDepthOfFieldBlurTask(`${name225} Blur Y${i}`, this._frameGraph, this.depthOfField._depthOfFieldBlurY[i][0]));
    }
    this._merge = new FrameGraphDepthOfFieldMergeTask(`${name225} Merge`, this._frameGraph, this.depthOfField._dofMerge);
    this.onTexturesAllocatedObservable.add((context) => {
      this._circleOfConfusion.onTexturesAllocatedObservable.notifyObservers(context);
      for (let i = 0;i < blurCount; i++) {
        this._blurX[i].onTexturesAllocatedObservable.notifyObservers(context);
        this._blurY[i].onTexturesAllocatedObservable.notifyObservers(context);
      }
      this._merge.onTexturesAllocatedObservable.notifyObservers(context);
    });
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  isReady() {
    return this.depthOfField.isReady();
  }
  record() {
    if (this.sourceTexture === undefined || this.depthTexture === undefined || this.camera === undefined) {
      throw new Error("FrameGraphDepthOfFieldTask: sourceTexture, depthTexture and camera are required");
    }
    const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture);
    const textureSize = {
      width: sourceTextureDescription.size.width,
      height: sourceTextureDescription.size.height
    };
    const circleOfConfusionTextureFormat = this._engine.isWebGPU || this._engine.version > 1 ? 6 : 5;
    const textureCreationOptions = {
      size: textureSize,
      options: {
        createMipMaps: false,
        types: [this._defaultPipelineTextureType],
        formats: [circleOfConfusionTextureFormat],
        samples: 1,
        useSRGBBuffers: [false],
        labels: [""]
      },
      sizeIsPercentage: false
    };
    const circleOfConfusionTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._circleOfConfusion.name, textureCreationOptions);
    this._circleOfConfusion.sourceTexture = this.sourceTexture;
    this._circleOfConfusion.depthTexture = this.depthTexture;
    this._circleOfConfusion.depthSamplingMode = this.depthSamplingMode;
    this._circleOfConfusion.camera = this.camera;
    this._circleOfConfusion.targetTexture = circleOfConfusionTextureHandle;
    this._circleOfConfusion.record(true);
    textureCreationOptions.options.formats = [5];
    const blurSteps = [];
    for (let i = 0;i < this._blurX.length; i++) {
      const ratio = this.depthOfField._depthOfFieldBlurX[i][1];
      textureSize.width = Math.floor(sourceTextureDescription.size.width * ratio) || 1;
      textureSize.height = Math.floor(sourceTextureDescription.size.height * ratio) || 1;
      textureCreationOptions.options.labels[0] = "step " + (i + 1);
      const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurY[i].name, textureCreationOptions);
      this._blurY[i].sourceTexture = i === 0 ? this.sourceTexture : this._blurX[i - 1].outputTexture;
      this._blurY[i].sourceSamplingMode = 2;
      this._blurY[i].circleOfConfusionTexture = circleOfConfusionTextureHandle;
      this._blurY[i].targetTexture = blurYTextureHandle;
      this._blurY[i].record(true);
      const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._blurX[i].name, textureCreationOptions);
      this._blurX[i].sourceTexture = this._blurY[i].outputTexture;
      this._blurX[i].sourceSamplingMode = 2;
      this._blurX[i].circleOfConfusionTexture = circleOfConfusionTextureHandle;
      this._blurX[i].targetTexture = blurXTextureHandle;
      this._blurX[i].record(true);
      blurSteps.push(blurXTextureHandle);
    }
    const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture);
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this._merge.name, sourceTextureCreationOptions);
    this._merge.sourceTexture = this.sourceTexture;
    this._merge.sourceSamplingMode = this.sourceSamplingMode;
    this._merge.circleOfConfusionTexture = circleOfConfusionTextureHandle;
    this._merge.blurSteps = blurSteps;
    this._merge.targetTexture = this.outputTexture;
    this._merge.record(true);
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.addDependencies(this.sourceTexture);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((context) => {
      context.copyTexture(this.sourceTexture);
    });
  }
  dispose() {
    this._circleOfConfusion.dispose();
    for (let i = 0;i < this._blurX.length; i++) {
      this._blurX[i].dispose();
      this._blurY[i].dispose();
    }
    this._merge.dispose();
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/depthOfFieldPostProcessBlock.js
class NodeRenderGraphDepthOfFieldPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name225, frameGraph, scene, blurLevel = 0, hdr = false) {
    super(name225, frameGraph, scene);
    this._additionalConstructionParameters = [blurLevel, hdr];
    this.registerInput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphDepthOfFieldTask(this.name, frameGraph, blurLevel, hdr);
  }
  _createTask(blurLevel, hdr) {
    const sourceSamplingMode = this._frameGraphTask.sourceSamplingMode;
    const depthSamplingMode = this._frameGraphTask.depthSamplingMode;
    const focalLength = this._frameGraphTask.depthOfField.focalLength;
    const fStop = this._frameGraphTask.depthOfField.fStop;
    const focusDistance = this._frameGraphTask.depthOfField.focusDistance;
    const lensSize = this._frameGraphTask.depthOfField.lensSize;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphDepthOfFieldTask(this.name, this._frameGraph, blurLevel, hdr);
    this._frameGraphTask.sourceSamplingMode = sourceSamplingMode;
    this._frameGraphTask.depthSamplingMode = depthSamplingMode;
    this._frameGraphTask.depthOfField.focalLength = focalLength;
    this._frameGraphTask.depthOfField.fStop = fStop;
    this._frameGraphTask.depthOfField.focusDistance = focusDistance;
    this._frameGraphTask.depthOfField.lensSize = lensSize;
    this._additionalConstructionParameters = [blurLevel, hdr];
  }
  get blurLevel() {
    return this._frameGraphTask.depthOfField.blurLevel;
  }
  set blurLevel(value) {
    this._createTask(value, this._frameGraphTask.hdr);
  }
  get hdr() {
    return this._frameGraphTask.hdr;
  }
  set hdr(value) {
    this._createTask(this._frameGraphTask.depthOfField.blurLevel, value);
  }
  get depthSamplingMode() {
    return this._frameGraphTask.depthSamplingMode;
  }
  set depthSamplingMode(value) {
    this._frameGraphTask.depthSamplingMode = value;
  }
  get focalLength() {
    return this._frameGraphTask.depthOfField.focalLength;
  }
  set focalLength(value) {
    this._frameGraphTask.depthOfField.focalLength = value;
  }
  get fStop() {
    return this._frameGraphTask.depthOfField.fStop;
  }
  set fStop(value) {
    this._frameGraphTask.depthOfField.fStop = value;
  }
  get focusDistance() {
    return this._frameGraphTask.depthOfField.focusDistance;
  }
  set focusDistance(value) {
    this._frameGraphTask.depthOfField.focusDistance = value;
  }
  get lensSize() {
    return this._frameGraphTask.depthOfField.lensSize;
  }
  set lensSize(value) {
    this._frameGraphTask.depthOfField.lensSize = value;
  }
  getClassName() {
    return "NodeRenderGraphDepthOfFieldPostProcessBlock";
  }
  get geomViewDepth() {
    return this._inputs[2];
  }
  get camera() {
    return this._inputs[3];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.depthTexture = this.geomViewDepth.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.lensSize = ${this.lensSize};`);
    codes.push(`${this._codeVariableName}.fStop = ${this.fStop};`);
    codes.push(`${this._codeVariableName}.focusDistance = ${this.focusDistance};`);
    codes.push(`${this._codeVariableName}.focalLength = ${this.focalLength};`);
    codes.push(`${this._codeVariableName}.depthSamplingMode = ${this.depthSamplingMode};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.lensSize = this.lensSize;
    serializationObject.fStop = this.fStop;
    serializationObject.focusDistance = this.focusDistance;
    serializationObject.focalLength = this.focalLength;
    serializationObject.depthSamplingMode = this.depthSamplingMode;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.lensSize = serializationObject.lensSize;
    this.fStop = serializationObject.fStop;
    this.focusDistance = serializationObject.focusDistance;
    this.focalLength = serializationObject.focalLength;
    this.depthSamplingMode = serializationObject.depthSamplingMode;
  }
}
__decorate([
  editableInPropertyPage("Blur level", 4, "PROPERTIES", {
    options: [
      { label: "Low", value: 0 },
      { label: "Medium", value: 1 },
      { label: "High", value: 2 }
    ]
  })
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "blurLevel", null);
__decorate([
  editableInPropertyPage("HDR", 0, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "hdr", null);
__decorate([
  editableInPropertyPage("Depth sampling mode", 6, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "depthSamplingMode", null);
__decorate([
  editableInPropertyPage("Focal length", 1, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "focalLength", null);
__decorate([
  editableInPropertyPage("F-Stop", 1, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "fStop", null);
__decorate([
  editableInPropertyPage("Focus distance", 1, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "focusDistance", null);
__decorate([
  editableInPropertyPage("Lens size", 1, "PROPERTIES")
], NodeRenderGraphDepthOfFieldPostProcessBlock.prototype, "lensSize", null);
RegisterClass("BABYLON.NodeRenderGraphDepthOfFieldPostProcessBlock", NodeRenderGraphDepthOfFieldPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/extractHighlightsPostProcessBlock.js
init_tslib_es6();
init_typeStore();
class NodeRenderGraphExtractHighlightsPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name225, frameGraph, scene) {
    super(name225, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphExtractHighlightsTask(this.name, frameGraph, new ThinExtractHighlightsPostProcess(name225, scene.getEngine()));
  }
  get threshold() {
    return this._frameGraphTask.postProcess.threshold;
  }
  set threshold(value) {
    this._frameGraphTask.postProcess.threshold = value;
  }
  getClassName() {
    return "NodeRenderGraphExtractHighlightsPostProcessBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.threshold = ${this.threshold};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.threshold = this.threshold;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.threshold = serializationObject.threshold;
  }
}
__decorate([
  editableInPropertyPage("Threshold", 1, "PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphExtractHighlightsPostProcessBlock.prototype, "threshold", null);
RegisterClass("BABYLON.NodeRenderGraphExtractHighlightsPostProcessBlock", NodeRenderGraphExtractHighlightsPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/passPostProcessBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/passTask.js
init_thinPassPostProcess();

class FrameGraphPassTask extends FrameGraphPostProcessTask {
  constructor(name225, frameGraph, thinPostProcess) {
    super(name225, frameGraph, thinPostProcess || new ThinPassPostProcess(name225, frameGraph.engine));
  }
}

class FrameGraphPassCubeTask extends FrameGraphPostProcessTask {
  constructor(name225, frameGraph, thinPostProcess) {
    super(name225, frameGraph, thinPostProcess || new ThinPassCubePostProcess(name225, frameGraph.engine));
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/passPostProcessBlock.js
init_thinPassPostProcess();
class NodeRenderGraphPassPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name225, frameGraph, scene) {
    super(name225, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphPassTask(this.name, frameGraph, new ThinPassPostProcess(name225, scene.getEngine()));
  }
  getClassName() {
    return "NodeRenderGraphPassPostProcessBlock";
  }
}
RegisterClass("BABYLON.NodeRenderGraphPassPostProcessBlock", NodeRenderGraphPassPostProcessBlock);

class NodeRenderGraphPassCubePostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name225, frameGraph, scene) {
    super(name225, frameGraph, scene);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphPassCubeTask(this.name, frameGraph, new ThinPassCubePostProcess(name225, scene.getEngine()));
  }
  getClassName() {
    return "NodeRenderGraphPassCubePostProcessBlock";
  }
}
RegisterClass("BABYLON.NodeRenderGraphPassCubePostProcessBlock", NodeRenderGraphPassCubePostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/ssrPostProcessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/thinSSRRenderingPipeline.js
init_math_vector();

// node_modules/@babylonjs/core/PostProcesses/thinSSRPostProcess.js
init_engine();
init_effectRenderer();
init_math_vector();
var trs = Matrix.Compose(new Vector3(0.5, 0.5, 0.5), Quaternion.Identity(), new Vector3(0.5, 0.5, 0.5));
var trsWebGPU = Matrix.Compose(new Vector3(0.5, 0.5, 1), Quaternion.Identity(), new Vector3(0.5, 0.5, 0));

class ThinSSRPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2_fragment(), exports_screenSpaceReflection2_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2_fragment2(), exports_screenSpaceReflection2_fragment2)));
    }
  }
  get reflectivityThreshold() {
    return this._reflectivityThreshold;
  }
  set reflectivityThreshold(threshold) {
    if (threshold === this._reflectivityThreshold) {
      return;
    }
    if (threshold === 0 && this._reflectivityThreshold !== 0 || threshold !== 0 && this._reflectivityThreshold === 0) {
      this._reflectivityThreshold = threshold;
      this._updateEffectDefines();
    } else {
      this._reflectivityThreshold = threshold;
    }
  }
  get useBlur() {
    return this._useBlur;
  }
  set useBlur(blur) {
    if (this._useBlur === blur) {
      return;
    }
    this._useBlur = blur;
    this._updateEffectDefines();
  }
  get enableSmoothReflections() {
    return this._enableSmoothReflections;
  }
  set enableSmoothReflections(enabled) {
    if (enabled === this._enableSmoothReflections) {
      return;
    }
    this._enableSmoothReflections = enabled;
    this._updateEffectDefines();
  }
  get environmentTexture() {
    return this._environmentTexture;
  }
  set environmentTexture(texture) {
    this._environmentTexture = texture;
    this._updateEffectDefines();
  }
  get environmentTextureIsProbe() {
    return this._environmentTextureIsProbe;
  }
  set environmentTextureIsProbe(isProbe) {
    this._environmentTextureIsProbe = isProbe;
    this._updateEffectDefines();
  }
  get attenuateScreenBorders() {
    return this._attenuateScreenBorders;
  }
  set attenuateScreenBorders(attenuate) {
    if (this._attenuateScreenBorders === attenuate) {
      return;
    }
    this._attenuateScreenBorders = attenuate;
    this._updateEffectDefines();
  }
  get attenuateIntersectionDistance() {
    return this._attenuateIntersectionDistance;
  }
  set attenuateIntersectionDistance(attenuate) {
    if (this._attenuateIntersectionDistance === attenuate) {
      return;
    }
    this._attenuateIntersectionDistance = attenuate;
    this._updateEffectDefines();
  }
  get attenuateIntersectionIterations() {
    return this._attenuateIntersectionIterations;
  }
  set attenuateIntersectionIterations(attenuate) {
    if (this._attenuateIntersectionIterations === attenuate) {
      return;
    }
    this._attenuateIntersectionIterations = attenuate;
    this._updateEffectDefines();
  }
  get attenuateFacingCamera() {
    return this._attenuateFacingCamera;
  }
  set attenuateFacingCamera(attenuate) {
    if (this._attenuateFacingCamera === attenuate) {
      return;
    }
    this._attenuateFacingCamera = attenuate;
    this._updateEffectDefines();
  }
  get attenuateBackfaceReflection() {
    return this._attenuateBackfaceReflection;
  }
  set attenuateBackfaceReflection(attenuate) {
    if (this._attenuateBackfaceReflection === attenuate) {
      return;
    }
    this._attenuateBackfaceReflection = attenuate;
    this._updateEffectDefines();
  }
  get clipToFrustum() {
    return this._clipToFrustum;
  }
  set clipToFrustum(clip) {
    if (this._clipToFrustum === clip) {
      return;
    }
    this._clipToFrustum = clip;
    this._updateEffectDefines();
  }
  get useFresnel() {
    return this._useFresnel;
  }
  set useFresnel(fresnel) {
    if (this._useFresnel === fresnel) {
      return;
    }
    this._useFresnel = fresnel;
    this._updateEffectDefines();
  }
  get enableAutomaticThicknessComputation() {
    return this._enableAutomaticThicknessComputation;
  }
  set enableAutomaticThicknessComputation(automatic) {
    if (this._enableAutomaticThicknessComputation === automatic) {
      return;
    }
    this._enableAutomaticThicknessComputation = automatic;
    this._updateEffectDefines();
  }
  get inputTextureColorIsInGammaSpace() {
    return this._inputTextureColorIsInGammaSpace;
  }
  set inputTextureColorIsInGammaSpace(gammaSpace) {
    if (this._inputTextureColorIsInGammaSpace === gammaSpace) {
      return;
    }
    this._inputTextureColorIsInGammaSpace = gammaSpace;
    this._updateEffectDefines();
  }
  get generateOutputInGammaSpace() {
    return this._generateOutputInGammaSpace;
  }
  set generateOutputInGammaSpace(gammaSpace) {
    if (this._generateOutputInGammaSpace === gammaSpace) {
      return;
    }
    this._generateOutputInGammaSpace = gammaSpace;
    this._updateEffectDefines();
  }
  get debug() {
    return this._debug;
  }
  set debug(value) {
    if (this._debug === value) {
      return;
    }
    this._debug = value;
    this._updateEffectDefines();
  }
  get textureWidth() {
    return this._textureWidth;
  }
  set textureWidth(width) {
    if (this._textureWidth === width) {
      return;
    }
    this._textureWidth = width;
  }
  get textureHeight() {
    return this._textureHeight;
  }
  set textureHeight(height) {
    if (this._textureHeight === height) {
      return;
    }
    this._textureHeight = height;
  }
  get useScreenspaceDepth() {
    return this._useScreenspaceDepth;
  }
  set useScreenspaceDepth(value) {
    if (this._useScreenspaceDepth === value) {
      return;
    }
    this._useScreenspaceDepth = value;
    this._updateEffectDefines();
  }
  get normalsAreInWorldSpace() {
    return this._normalsAreInWorldSpace;
  }
  set normalsAreInWorldSpace(value) {
    if (this._normalsAreInWorldSpace === value) {
      return;
    }
    this._normalsAreInWorldSpace = value;
    this._updateEffectDefines();
  }
  get normalsAreUnsigned() {
    return this._normalsAreUnsigned;
  }
  set normalsAreUnsigned(value) {
    if (this._normalsAreUnsigned === value) {
      return;
    }
    this._normalsAreUnsigned = value;
    this._updateEffectDefines();
  }
  constructor(name231, scene, options) {
    super({
      ...options,
      name: name231,
      engine: scene.getEngine() || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinSSRPostProcess.FragmentUrl,
      uniforms: ThinSSRPostProcess.Uniforms,
      samplers: ThinSSRPostProcess.Samplers,
      shaderLanguage: scene.getEngine().isWebGPU ? 1 : 0
    });
    this.isSSRSupported = true;
    this.maxDistance = 1000;
    this.step = 1;
    this.thickness = 0.5;
    this.strength = 1;
    this.reflectionSpecularFalloffExponent = 1;
    this.maxSteps = 1000;
    this.roughnessFactor = 0.2;
    this.selfCollisionNumSkip = 1;
    this._reflectivityThreshold = 0.04;
    this._useBlur = false;
    this._enableSmoothReflections = false;
    this._environmentTextureIsProbe = false;
    this._attenuateScreenBorders = true;
    this._attenuateIntersectionDistance = true;
    this._attenuateIntersectionIterations = true;
    this._attenuateFacingCamera = false;
    this._attenuateBackfaceReflection = false;
    this._clipToFrustum = true;
    this._useFresnel = false;
    this._enableAutomaticThicknessComputation = false;
    this._inputTextureColorIsInGammaSpace = true;
    this._generateOutputInGammaSpace = true;
    this._debug = false;
    this._textureWidth = 0;
    this._textureHeight = 0;
    this.camera = null;
    this._useScreenspaceDepth = false;
    this._normalsAreInWorldSpace = false;
    this._normalsAreUnsigned = false;
    this._scene = scene;
    this._updateEffectDefines();
  }
  bind() {
    super.bind();
    const effect = this._drawWrapper.effect;
    const camera2 = this.camera;
    if (!camera2) {
      return;
    }
    const viewMatrix = camera2.getViewMatrix();
    const projectionMatrix = camera2.getProjectionMatrix();
    projectionMatrix.invertToRef(TmpVectors.Matrix[0]);
    viewMatrix.invertToRef(TmpVectors.Matrix[1]);
    effect.setMatrix("projection", projectionMatrix);
    effect.setMatrix("view", viewMatrix);
    effect.setMatrix("invView", TmpVectors.Matrix[1]);
    effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]);
    effect.setFloat("thickness", this.thickness);
    effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent);
    effect.setFloat("strength", this.strength);
    effect.setFloat("stepSize", this.step);
    effect.setFloat("maxSteps", this.maxSteps);
    effect.setFloat("roughnessFactor", this.roughnessFactor);
    effect.setFloat("nearPlaneZ", camera2.minZ);
    effect.setFloat("farPlaneZ", camera2.maxZ);
    effect.setFloat("maxDistance", this.maxDistance);
    effect.setFloat("selfCollisionNumSkip", this.selfCollisionNumSkip);
    effect.setFloat("reflectivityThreshold", this._reflectivityThreshold);
    Matrix.ScalingToRef(this.textureWidth, this.textureHeight, 1, TmpVectors.Matrix[2]);
    projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? trsWebGPU : trs, TmpVectors.Matrix[3]);
    TmpVectors.Matrix[3].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[4]);
    effect.setMatrix("projectionPixel", TmpVectors.Matrix[4]);
    if (this._environmentTexture) {
      effect.setTexture("envCubeSampler", this._environmentTexture);
      if (this._environmentTexture.boundingBoxSize) {
        effect.setVector3("vReflectionPosition", this._environmentTexture.boundingBoxPosition);
        effect.setVector3("vReflectionSize", this._environmentTexture.boundingBoxSize);
      }
    }
  }
  _updateEffectDefines() {
    const defines = [];
    if (this.isSSRSupported) {
      defines.push("#define SSR_SUPPORTED");
    }
    if (this._enableSmoothReflections) {
      defines.push("#define SSRAYTRACE_ENABLE_REFINEMENT");
    }
    if (this._scene.useRightHandedSystem) {
      defines.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE");
    }
    if (this._useScreenspaceDepth) {
      defines.push("#define SSRAYTRACE_SCREENSPACE_DEPTH");
    }
    if (this._environmentTexture) {
      defines.push("#define SSR_USE_ENVIRONMENT_CUBE");
      if (this._environmentTexture.boundingBoxSize) {
        defines.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC");
      }
      if (this._environmentTexture.gammaSpace) {
        defines.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE");
      }
    }
    if (this._environmentTextureIsProbe) {
      defines.push("#define SSR_INVERTCUBICMAP");
    }
    if (this._enableAutomaticThicknessComputation) {
      defines.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER");
    }
    if (this._attenuateScreenBorders) {
      defines.push("#define SSR_ATTENUATE_SCREEN_BORDERS");
    }
    if (this._attenuateIntersectionDistance) {
      defines.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE");
    }
    if (this._attenuateIntersectionIterations) {
      defines.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS");
    }
    if (this._attenuateFacingCamera) {
      defines.push("#define SSR_ATTENUATE_FACING_CAMERA");
    }
    if (this._attenuateBackfaceReflection) {
      defines.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION");
    }
    if (this._clipToFrustum) {
      defines.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM");
    }
    if (this.useBlur) {
      defines.push("#define SSR_USE_BLUR");
    }
    if (this._debug) {
      defines.push("#define SSRAYTRACE_DEBUG");
    }
    if (this._inputTextureColorIsInGammaSpace) {
      defines.push("#define SSR_INPUT_IS_GAMMA_SPACE");
    }
    if (this._generateOutputInGammaSpace) {
      defines.push("#define SSR_OUTPUT_IS_GAMMA_SPACE");
    }
    if (this._useFresnel) {
      defines.push("#define SSR_BLEND_WITH_FRESNEL");
    }
    if (this._reflectivityThreshold === 0) {
      defines.push("#define SSR_DISABLE_REFLECTIVITY_TEST");
    }
    if (this._normalsAreInWorldSpace) {
      defines.push("#define SSR_NORMAL_IS_IN_WORLDSPACE");
    }
    if (this._normalsAreUnsigned) {
      defines.push("#define SSR_DECODE_NORMAL");
    }
    if (this.camera && this.camera.mode === 1) {
      defines.push("#define ORTHOGRAPHIC_CAMERA");
    }
    this.updateEffect(defines.join(`
`));
  }
}
ThinSSRPostProcess.FragmentUrl = "screenSpaceReflection2";
ThinSSRPostProcess.Uniforms = [
  "projection",
  "invProjectionMatrix",
  "view",
  "invView",
  "thickness",
  "reflectionSpecularFalloffExponent",
  "strength",
  "stepSize",
  "maxSteps",
  "roughnessFactor",
  "projectionPixel",
  "nearPlaneZ",
  "farPlaneZ",
  "maxDistance",
  "selfCollisionNumSkip",
  "vReflectionPosition",
  "vReflectionSize",
  "backSizeFactor",
  "reflectivityThreshold"
];
ThinSSRPostProcess.Samplers = ["textureSampler", "normalSampler", "reflectivitySampler", "depthSampler", "envCubeSampler", "backDepthSampler"];

// node_modules/@babylonjs/core/PostProcesses/thinSSRBlurPostProcess.js
init_effectRenderer();
init_engine();
init_math_vector();

class ThinSSRBlurPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2Blur_fragment(), exports_screenSpaceReflection2Blur_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2Blur_fragment2(), exports_screenSpaceReflection2Blur_fragment2)));
    }
  }
  constructor(name233, engine2 = null, direction, blurStrength, options) {
    super({
      ...options,
      name: name233,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinSSRBlurPostProcess.FragmentUrl,
      uniforms: ThinSSRBlurPostProcess.Uniforms,
      samplers: ThinSSRBlurPostProcess.Samplers
    });
    this.textureWidth = 0;
    this.textureHeight = 0;
    this.direction = new Vector2(1, 0);
    this.blurStrength = 0.03;
    if (direction !== undefined) {
      this.direction = direction;
    }
    if (blurStrength !== undefined) {
      this.blurStrength = blurStrength;
    }
  }
  bind() {
    super.bind();
    this._drawWrapper.effect.setFloat2("texelOffsetScale", 1 / this.textureWidth * this.direction.x * this.blurStrength, 1 / this.textureHeight * this.direction.y * this.blurStrength);
  }
}
ThinSSRBlurPostProcess.FragmentUrl = "screenSpaceReflection2Blur";
ThinSSRBlurPostProcess.Uniforms = ["texelOffsetScale"];
ThinSSRBlurPostProcess.Samplers = ["textureSampler"];

// node_modules/@babylonjs/core/PostProcesses/thinSSRBlurCombinerPostProcess.js
init_effectRenderer();
init_engine();
init_math_vector();

class ThinSSRBlurCombinerPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2BlurCombiner_fragment(), exports_screenSpaceReflection2BlurCombiner_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_screenSpaceReflection2BlurCombiner_fragment2(), exports_screenSpaceReflection2BlurCombiner_fragment2)));
    }
  }
  constructor(name235, engine2 = null, options) {
    super({
      ...options,
      name: name235,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinSSRBlurCombinerPostProcess.FragmentUrl,
      uniforms: ThinSSRBlurCombinerPostProcess.Uniforms,
      samplers: ThinSSRBlurCombinerPostProcess.Samplers
    });
    this.strength = 1;
    this.reflectionSpecularFalloffExponent = 1;
    this.camera = null;
    this._useFresnel = false;
    this._useScreenspaceDepth = false;
    this._inputTextureColorIsInGammaSpace = true;
    this._generateOutputInGammaSpace = true;
    this._debug = false;
    this._reflectivityThreshold = 0.04;
    this._normalsAreInWorldSpace = false;
    this._normalsAreUnsigned = false;
    this._updateEffectDefines();
  }
  get useFresnel() {
    return this._useFresnel;
  }
  set useFresnel(fresnel) {
    if (this._useFresnel === fresnel) {
      return;
    }
    this._useFresnel = fresnel;
    this._updateEffectDefines();
  }
  get useScreenspaceDepth() {
    return this._useScreenspaceDepth;
  }
  set useScreenspaceDepth(value) {
    if (this._useScreenspaceDepth === value) {
      return;
    }
    this._useScreenspaceDepth = value;
    this._updateEffectDefines();
  }
  get inputTextureColorIsInGammaSpace() {
    return this._inputTextureColorIsInGammaSpace;
  }
  set inputTextureColorIsInGammaSpace(gammaSpace) {
    if (this._inputTextureColorIsInGammaSpace === gammaSpace) {
      return;
    }
    this._inputTextureColorIsInGammaSpace = gammaSpace;
    this._updateEffectDefines();
  }
  get generateOutputInGammaSpace() {
    return this._generateOutputInGammaSpace;
  }
  set generateOutputInGammaSpace(gammaSpace) {
    if (this._generateOutputInGammaSpace === gammaSpace) {
      return;
    }
    this._generateOutputInGammaSpace = gammaSpace;
    this._updateEffectDefines();
  }
  get debug() {
    return this._debug;
  }
  set debug(value) {
    if (this._debug === value) {
      return;
    }
    this._debug = value;
    this._updateEffectDefines();
  }
  get reflectivityThreshold() {
    return this._reflectivityThreshold;
  }
  set reflectivityThreshold(threshold) {
    if (threshold === this._reflectivityThreshold) {
      return;
    }
    if (threshold === 0 && this._reflectivityThreshold !== 0 || threshold !== 0 && this._reflectivityThreshold === 0) {
      this._reflectivityThreshold = threshold;
      this._updateEffectDefines();
    } else {
      this._reflectivityThreshold = threshold;
    }
  }
  get normalsAreInWorldSpace() {
    return this._normalsAreInWorldSpace;
  }
  set normalsAreInWorldSpace(value) {
    if (this._normalsAreInWorldSpace === value) {
      return;
    }
    this._normalsAreInWorldSpace = value;
    this._updateEffectDefines();
  }
  get normalsAreUnsigned() {
    return this._normalsAreUnsigned;
  }
  set normalsAreUnsigned(value) {
    if (this._normalsAreUnsigned === value) {
      return;
    }
    this._normalsAreUnsigned = value;
    this._updateEffectDefines();
  }
  bind() {
    super.bind();
    const effect = this._drawWrapper.effect;
    effect.setFloat("strength", this.strength);
    effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent);
    effect.setFloat("reflectivityThreshold", this.reflectivityThreshold);
    if (this.useFresnel && this.camera) {
      const projectionMatrix = this.camera.getProjectionMatrix();
      projectionMatrix.invertToRef(TmpVectors.Matrix[0]);
      effect.setMatrix("projection", projectionMatrix);
      effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]);
      effect.setMatrix("view", this.camera.getViewMatrix());
      if (this.useScreenspaceDepth) {
        effect.setFloat("nearPlaneZ", this.camera.minZ);
        effect.setFloat("farPlaneZ", this.camera.maxZ);
      }
    }
  }
  _updateEffectDefines() {
    let defines = "";
    if (this._debug) {
      defines += `#define SSRAYTRACE_DEBUG
`;
    }
    if (this._inputTextureColorIsInGammaSpace) {
      defines += `#define SSR_INPUT_IS_GAMMA_SPACE
`;
    }
    if (this._generateOutputInGammaSpace) {
      defines += `#define SSR_OUTPUT_IS_GAMMA_SPACE
`;
    }
    if (this._useFresnel) {
      defines += `#define SSR_BLEND_WITH_FRESNEL
`;
    }
    if (this._useScreenspaceDepth) {
      defines += `#define SSRAYTRACE_SCREENSPACE_DEPTH
`;
    }
    if (this._reflectivityThreshold === 0) {
      defines += `#define SSR_DISABLE_REFLECTIVITY_TEST
`;
    }
    if (this._normalsAreInWorldSpace) {
      defines += `#define SSR_NORMAL_IS_IN_WORLDSPACE
`;
    }
    if (this._normalsAreUnsigned) {
      defines += `#define SSR_DECODE_NORMAL
`;
    }
    this.updateEffect(defines);
  }
}
ThinSSRBlurCombinerPostProcess.FragmentUrl = "screenSpaceReflection2BlurCombiner";
ThinSSRBlurCombinerPostProcess.Uniforms = [
  "strength",
  "reflectionSpecularFalloffExponent",
  "reflectivityThreshold",
  "projection",
  "invProjectionMatrix",
  "nearPlaneZ",
  "farPlaneZ",
  "view"
];
ThinSSRBlurCombinerPostProcess.Samplers = ["textureSampler", "depthSampler", "normalSampler", "mainSampler", "reflectivitySampler"];

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/thinSSRRenderingPipeline.js
class ThinSSRRenderingPipeline {
  get isSSRSupported() {
    return this._ssrPostProcess.isSSRSupported;
  }
  set isSSRSupported(supported) {
    this._ssrPostProcess.isSSRSupported = supported;
  }
  get maxDistance() {
    return this._ssrPostProcess.maxDistance;
  }
  set maxDistance(distance) {
    this._ssrPostProcess.maxDistance = distance;
  }
  get step() {
    return this._ssrPostProcess.step;
  }
  set step(step) {
    this._ssrPostProcess.step = step;
  }
  get thickness() {
    return this._ssrPostProcess.thickness;
  }
  set thickness(thickness) {
    this._ssrPostProcess.thickness = thickness;
  }
  get strength() {
    return this._ssrPostProcess.strength;
  }
  set strength(strength) {
    this._ssrPostProcess.strength = strength;
    this._ssrBlurCombinerPostProcess.strength = strength;
  }
  get reflectionSpecularFalloffExponent() {
    return this._ssrPostProcess.reflectionSpecularFalloffExponent;
  }
  set reflectionSpecularFalloffExponent(exponent) {
    this._ssrPostProcess.reflectionSpecularFalloffExponent = exponent;
    this._ssrBlurCombinerPostProcess.reflectionSpecularFalloffExponent = exponent;
  }
  get maxSteps() {
    return this._ssrPostProcess.maxSteps;
  }
  set maxSteps(steps) {
    this._ssrPostProcess.maxSteps = steps;
  }
  get roughnessFactor() {
    return this._ssrPostProcess.roughnessFactor;
  }
  set roughnessFactor(factor) {
    this._ssrPostProcess.roughnessFactor = factor;
  }
  get selfCollisionNumSkip() {
    return this._ssrPostProcess.selfCollisionNumSkip;
  }
  set selfCollisionNumSkip(skip) {
    this._ssrPostProcess.selfCollisionNumSkip = skip;
  }
  get reflectivityThreshold() {
    return this._ssrPostProcess.reflectivityThreshold;
  }
  set reflectivityThreshold(threshold) {
    const currentThreshold = this._ssrPostProcess.reflectivityThreshold;
    if (threshold === currentThreshold) {
      return;
    }
    this._ssrPostProcess.reflectivityThreshold = threshold;
    this._ssrBlurCombinerPostProcess.reflectivityThreshold = threshold;
  }
  get blurDispersionStrength() {
    return this._ssrBlurXPostProcess.blurStrength;
  }
  set blurDispersionStrength(strength) {
    if (strength === this._ssrBlurXPostProcess.blurStrength) {
      return;
    }
    this._ssrPostProcess.useBlur = strength > 0;
    this._ssrBlurXPostProcess.blurStrength = strength;
    this._ssrBlurYPostProcess.blurStrength = strength;
  }
  get enableSmoothReflections() {
    return this._ssrPostProcess.enableSmoothReflections;
  }
  set enableSmoothReflections(enabled) {
    this._ssrPostProcess.enableSmoothReflections = enabled;
  }
  get environmentTexture() {
    return this._ssrPostProcess.environmentTexture;
  }
  set environmentTexture(texture) {
    this._ssrPostProcess.environmentTexture = texture;
  }
  get environmentTextureIsProbe() {
    return this._ssrPostProcess.environmentTextureIsProbe;
  }
  set environmentTextureIsProbe(isProbe) {
    this._ssrPostProcess.environmentTextureIsProbe = isProbe;
  }
  get attenuateScreenBorders() {
    return this._ssrPostProcess.attenuateScreenBorders;
  }
  set attenuateScreenBorders(attenuate) {
    this._ssrPostProcess.attenuateScreenBorders = attenuate;
  }
  get attenuateIntersectionDistance() {
    return this._ssrPostProcess.attenuateIntersectionDistance;
  }
  set attenuateIntersectionDistance(attenuate) {
    this._ssrPostProcess.attenuateIntersectionDistance = attenuate;
  }
  get attenuateIntersectionIterations() {
    return this._ssrPostProcess.attenuateIntersectionIterations;
  }
  set attenuateIntersectionIterations(attenuate) {
    this._ssrPostProcess.attenuateIntersectionIterations = attenuate;
  }
  get attenuateFacingCamera() {
    return this._ssrPostProcess.attenuateFacingCamera;
  }
  set attenuateFacingCamera(attenuate) {
    this._ssrPostProcess.attenuateFacingCamera = attenuate;
  }
  get attenuateBackfaceReflection() {
    return this._ssrPostProcess.attenuateBackfaceReflection;
  }
  set attenuateBackfaceReflection(attenuate) {
    this._ssrPostProcess.attenuateBackfaceReflection = attenuate;
  }
  get clipToFrustum() {
    return this._ssrPostProcess.clipToFrustum;
  }
  set clipToFrustum(clip) {
    this._ssrPostProcess.clipToFrustum = clip;
  }
  get useFresnel() {
    return this._ssrPostProcess.useFresnel;
  }
  set useFresnel(fresnel) {
    this._ssrPostProcess.useFresnel = fresnel;
    this._ssrBlurCombinerPostProcess.useFresnel = fresnel;
  }
  get enableAutomaticThicknessComputation() {
    return this._ssrPostProcess.enableAutomaticThicknessComputation;
  }
  set enableAutomaticThicknessComputation(automatic) {
    if (this._ssrPostProcess.enableAutomaticThicknessComputation === automatic) {
      return;
    }
    this._ssrPostProcess.enableAutomaticThicknessComputation = automatic;
  }
  get inputTextureColorIsInGammaSpace() {
    return this._ssrPostProcess.inputTextureColorIsInGammaSpace;
  }
  set inputTextureColorIsInGammaSpace(gammaSpace) {
    if (this._ssrPostProcess.inputTextureColorIsInGammaSpace === gammaSpace) {
      return;
    }
    this._ssrPostProcess.inputTextureColorIsInGammaSpace = gammaSpace;
    this._ssrBlurCombinerPostProcess.inputTextureColorIsInGammaSpace = gammaSpace;
  }
  get generateOutputInGammaSpace() {
    return this._ssrPostProcess.generateOutputInGammaSpace;
  }
  set generateOutputInGammaSpace(gammaSpace) {
    if (this._ssrPostProcess.generateOutputInGammaSpace === gammaSpace) {
      return;
    }
    this._ssrPostProcess.generateOutputInGammaSpace = gammaSpace;
    this._ssrBlurCombinerPostProcess.generateOutputInGammaSpace = gammaSpace;
  }
  get debug() {
    return this._ssrPostProcess.debug;
  }
  set debug(value) {
    if (this._ssrPostProcess.debug === value) {
      return;
    }
    this._ssrPostProcess.debug = value;
    this._ssrBlurCombinerPostProcess.debug = value;
  }
  get camera() {
    return this._ssrPostProcess.camera;
  }
  set camera(camera2) {
    this._ssrPostProcess.camera = camera2;
    this._ssrBlurCombinerPostProcess.camera = camera2;
  }
  get useScreenspaceDepth() {
    return this._ssrPostProcess.useScreenspaceDepth;
  }
  set useScreenspaceDepth(use) {
    this._ssrPostProcess.useScreenspaceDepth = use;
    this._ssrBlurCombinerPostProcess.useScreenspaceDepth = use;
  }
  get normalsAreInWorldSpace() {
    return this._ssrPostProcess.normalsAreInWorldSpace;
  }
  set normalsAreInWorldSpace(normalsAreInWorldSpace) {
    this._ssrPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace;
    this._ssrBlurCombinerPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace;
  }
  get normalsAreUnsigned() {
    return this._ssrPostProcess.normalsAreUnsigned;
  }
  set normalsAreUnsigned(normalsAreUnsigned) {
    this._ssrPostProcess.normalsAreUnsigned = normalsAreUnsigned;
    this._ssrBlurCombinerPostProcess.normalsAreUnsigned = normalsAreUnsigned;
  }
  isReady() {
    return this._ssrPostProcess.isReady() && this._ssrBlurXPostProcess.isReady() && this._ssrBlurYPostProcess.isReady() && this._ssrBlurCombinerPostProcess.isReady();
  }
  constructor(name235, scene) {
    this.ssrDownsample = 0;
    this.blurDownsample = 0;
    this.name = name235;
    this._scene = scene;
    this._ssrPostProcess = new ThinSSRPostProcess(this.name, this._scene);
    this._ssrBlurXPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurX", this._scene.getEngine(), new Vector2(1, 0));
    this._ssrBlurYPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurY", this._scene.getEngine(), new Vector2(0, 1));
    this._ssrBlurCombinerPostProcess = new ThinSSRBlurCombinerPostProcess(this.name + " BlurCombiner", this._scene.getEngine());
    this._ssrPostProcess.useBlur = this._ssrBlurXPostProcess.blurStrength > 0;
  }
  dispose() {
    this._ssrPostProcess?.dispose();
    this._ssrBlurXPostProcess?.dispose();
    this._ssrBlurYPostProcess?.dispose();
    this._ssrBlurCombinerPostProcess?.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/ssrTask.js
class FrameGraphSSRTask extends FrameGraphPostProcessTask {
  constructor(name235, frameGraph, thinPostProcess) {
    super(name235, frameGraph, thinPostProcess || new ThinSSRPostProcess(name235, frameGraph.scene));
    this.onTexturesAllocatedObservable.add((context) => {
      context.setTextureSamplingMode(this.normalTexture, 2);
      context.setTextureSamplingMode(this.depthTexture, 2);
      context.setTextureSamplingMode(this.reflectivityTexture, 2);
      if (this.backDepthTexture) {
        context.setTextureSamplingMode(this.backDepthTexture, 1);
      }
    });
  }
  record(skipCreationOfDisabledPasses = false) {
    if (this.sourceTexture === undefined || this.normalTexture === undefined || this.depthTexture === undefined || this.reflectivityTexture === undefined || this.camera === undefined) {
      throw new Error(`FrameGraphSSRTask "${this.name}": sourceTexture, normalTexture, depthTexture, reflectivityTexture and camera are required`);
    }
    const pass = super.record(skipCreationOfDisabledPasses, undefined, (context) => {
      this.postProcess.camera = this.camera;
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "normalSampler", this.normalTexture);
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "depthSampler", this.depthTexture);
      context.bindTextureHandle(this._postProcessDrawWrapper.effect, "reflectivitySampler", this.reflectivityTexture);
      if (this.backDepthTexture) {
        context.bindTextureHandle(this._postProcessDrawWrapper.effect, "backDepthSampler", this.backDepthTexture);
      }
      if (this.postProcess.enableAutomaticThicknessComputation) {
        this._postProcessDrawWrapper.effect.setFloat("backSizeFactor", 1);
      }
    });
    pass.addDependencies([this.normalTexture, this.depthTexture, this.reflectivityTexture]);
    this.postProcess.textureWidth = this._sourceWidth;
    this.postProcess.textureHeight = this._sourceHeight;
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/ssrBlurTask.js
init_math_vector();

class FrameGraphSSRBlurTask extends FrameGraphPostProcessTask {
  constructor(name235, frameGraph, thinPostProcess) {
    super(name235, frameGraph, thinPostProcess || new ThinSSRBlurPostProcess(name235, frameGraph.engine, new Vector2(1, 0), 0.03));
  }
  record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) {
    const pass = super.record(skipCreationOfDisabledPasses, additionalExecute, additionalBindings);
    this.postProcess.textureWidth = this._sourceWidth;
    this.postProcess.textureHeight = this._sourceHeight;
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/ssrRenderingPipelineTask.js
class FrameGraphSSRRenderingPipelineTask extends FrameGraphTask {
  get camera() {
    return this._camera;
  }
  set camera(camera2) {
    if (camera2 === this._camera) {
      return;
    }
    this._camera = camera2;
    this.ssr.camera = camera2;
  }
  get name() {
    return this._name;
  }
  set name(name235) {
    this._name = name235;
    if (this._ssr) {
      this._ssr.name = `${name235} SSR`;
    }
    if (this._ssrBlurX) {
      this._ssrBlurX.name = `${name235} SSR Blur X`;
    }
    if (this._ssrBlurY) {
      this._ssrBlurY.name = `${name235} SSR Blur Y`;
    }
    if (this._ssrBlurCombiner) {
      this._ssrBlurCombiner.name = `${name235} SSR Blur Combiner`;
    }
  }
  constructor(name235, frameGraph, textureType = 0) {
    super(name235, frameGraph);
    this.sourceSamplingMode = 2;
    this.textureType = textureType;
    this.ssr = new ThinSSRRenderingPipeline(name235, frameGraph.scene);
    this._ssr = new FrameGraphSSRTask(`${name235} SSR`, this._frameGraph, this.ssr._ssrPostProcess);
    this._ssrBlurX = new FrameGraphSSRBlurTask(`${name235} SSR Blur X`, this._frameGraph, this.ssr._ssrBlurXPostProcess);
    this._ssrBlurY = new FrameGraphSSRBlurTask(`${name235} SSR Blur Y`, this._frameGraph, this.ssr._ssrBlurYPostProcess);
    this._ssrBlurCombiner = new FrameGraphPostProcessTask(`${name235} SSR Blur Combiner`, this._frameGraph, this.ssr._ssrBlurCombinerPostProcess);
    this.onTexturesAllocatedObservable.add((context) => {
      this._ssr.onTexturesAllocatedObservable.notifyObservers(context);
      if (this.ssr.blurDispersionStrength !== 0) {
        this._ssrBlurX.onTexturesAllocatedObservable.notifyObservers(context);
        this._ssrBlurY.onTexturesAllocatedObservable.notifyObservers(context);
        this._ssrBlurCombiner.onTexturesAllocatedObservable.notifyObservers(context);
      }
    });
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  isReady() {
    return this.ssr.isReady();
  }
  record() {
    if (this.sourceTexture === undefined || this.normalTexture === undefined || this.depthTexture === undefined || this.reflectivityTexture === undefined || this.camera === undefined) {
      throw new Error(`FrameGraphSSRRenderingPipelineTask "${this.name}": sourceTexture, normalTexture, depthTexture, reflectivityTexture and camera are required`);
    }
    const sourceTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.sourceTexture);
    this._ssr.sourceTexture = this.sourceTexture;
    this._ssr.sourceSamplingMode = this.sourceSamplingMode;
    this._ssr.camera = this.camera;
    this._ssr.normalTexture = this.normalTexture;
    this._ssr.depthTexture = this.depthTexture;
    this._ssr.backDepthTexture = this.backDepthTexture;
    this._ssr.reflectivityTexture = this.reflectivityTexture;
    let ssrTextureHandle;
    const textureSize = {
      width: Math.floor(sourceTextureDescription.size.width / (this.ssr.ssrDownsample + 1)) || 1,
      height: Math.floor(sourceTextureDescription.size.height / (this.ssr.ssrDownsample + 1)) || 1
    };
    const textureCreationOptions = {
      size: textureSize,
      options: {
        createMipMaps: false,
        types: [this.textureType],
        formats: [5],
        samples: 1,
        useSRGBBuffers: [false],
        labels: [""]
      },
      sizeIsPercentage: false
    };
    if (this.ssr.blurDispersionStrength > 0 || !this.targetTexture) {
      ssrTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssr.name, textureCreationOptions);
    }
    if (this.ssr.blurDispersionStrength === 0) {
      this._ssr.targetTexture = this.outputTexture;
      if (ssrTextureHandle !== undefined) {
        this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, ssrTextureHandle);
      } else {
        this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
      }
      this._ssr.record(true);
    } else {
      this._ssr.targetTexture = ssrTextureHandle;
      this._ssr.record(true);
      textureSize.width = Math.floor(sourceTextureDescription.size.width / (this.ssr.blurDownsample + 1)) || 1;
      textureSize.height = Math.floor(sourceTextureDescription.size.height / (this.ssr.blurDownsample + 1)) || 1;
      const sourceTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture);
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name + " Output", sourceTextureCreationOptions);
      const blurXTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssrBlurX.name, textureCreationOptions);
      this._ssrBlurX.sourceTexture = ssrTextureHandle;
      this._ssrBlurX.sourceSamplingMode = 2;
      this._ssrBlurX.targetTexture = blurXTextureHandle;
      this._ssrBlurX.record(true);
      const blurYTextureHandle = this._frameGraph.textureManager.createRenderTargetTexture(this._ssrBlurY.name, textureCreationOptions);
      this._ssrBlurY.sourceTexture = blurXTextureHandle;
      this._ssrBlurY.sourceSamplingMode = 2;
      this._ssrBlurY.targetTexture = blurYTextureHandle;
      this._ssrBlurY.record(true);
      this._ssrBlurCombiner.sourceTexture = this.sourceTexture;
      this._ssrBlurCombiner.sourceSamplingMode = this.sourceSamplingMode;
      this._ssrBlurCombiner.targetTexture = this.outputTexture;
      const combinerPass = this._ssrBlurCombiner.record(true, undefined, (context) => {
        context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "mainSampler", this.sourceTexture);
        context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "textureSampler", blurYTextureHandle);
        context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "reflectivitySampler", this.reflectivityTexture);
        if (this.ssr.useFresnel) {
          context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "normalSampler", this.normalTexture);
          context.bindTextureHandle(this._ssrBlurCombiner.drawWrapper.effect, "depthSampler", this.depthTexture);
        }
      });
      combinerPass.addDependencies(blurYTextureHandle);
    }
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.addDependencies(this.sourceTexture);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((context) => {
      context.copyTexture(this.sourceTexture);
    });
  }
  dispose() {
    this._ssr.dispose();
    this._ssrBlurX.dispose();
    this._ssrBlurY.dispose();
    this._ssrBlurCombiner.dispose();
    this.ssr.dispose();
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/PostProcesses/ssrPostProcessBlock.js
class NodeRenderGraphSSRPostProcessBlock extends NodeRenderGraphBasePostProcessBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name235, frameGraph, scene, textureType = 0) {
    super(name235, frameGraph, scene);
    this._additionalConstructionParameters = [textureType];
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this.registerInput("geomDepth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("geomNormal", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("geomReflectivity", NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity);
    this.registerInput("geomBackDepth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.geomNormal.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal | NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal);
    this.geomDepth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth | NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth);
    this.geomBackDepth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth | NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth);
    this._finalizeInputOutputRegistering();
    this._frameGraphTask = new FrameGraphSSRRenderingPipelineTask(this.name, frameGraph, textureType);
  }
  _createTask(textureType) {
    const sourceSamplingMode = this.sourceSamplingMode;
    const maxDistance = this.maxDistance;
    const step = this.step;
    const thickness = this.thickness;
    const strength = this.strength;
    const reflectionSpecularFalloffExponent = this.reflectionSpecularFalloffExponent;
    const maxSteps = this.maxSteps;
    const roughnessFactor = this.roughnessFactor;
    const selfCollisionNumSkip = this.selfCollisionNumSkip;
    const reflectivityThreshold = this.reflectivityThreshold;
    const ssrDownsample = this.ssrDownsample;
    const blurDispersionStrength = this.blurDispersionStrength;
    const blurDownsample = this.blurDownsample;
    const enableSmoothReflections = this.enableSmoothReflections;
    const attenuateScreenBorders = this.attenuateScreenBorders;
    const attenuateIntersectionDistance = this.attenuateIntersectionDistance;
    const attenuateIntersectionIterations = this.attenuateIntersectionIterations;
    const attenuateFacingCamera = this.attenuateFacingCamera;
    const attenuateBackfaceReflection = this.attenuateBackfaceReflection;
    const clipToFrustum = this.clipToFrustum;
    const enableAutomaticThicknessComputation = this.enableAutomaticThicknessComputation;
    const useFresnel = this.useFresnel;
    const inputTextureColorIsInGammaSpace = this.inputTextureColorIsInGammaSpace;
    const generateOutputInGammaSpace = this.generateOutputInGammaSpace;
    const debug = this.debug;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphSSRRenderingPipelineTask(this.name, this._frameGraph, textureType);
    this.sourceSamplingMode = sourceSamplingMode;
    this.maxDistance = maxDistance;
    this.step = step;
    this.thickness = thickness;
    this.strength = strength;
    this.reflectionSpecularFalloffExponent = reflectionSpecularFalloffExponent;
    this.maxSteps = maxSteps;
    this.roughnessFactor = roughnessFactor;
    this.selfCollisionNumSkip = selfCollisionNumSkip;
    this.reflectivityThreshold = reflectivityThreshold;
    this.ssrDownsample = ssrDownsample;
    this.blurDispersionStrength = blurDispersionStrength;
    this.blurDownsample = blurDownsample;
    this.enableSmoothReflections = enableSmoothReflections;
    this.attenuateScreenBorders = attenuateScreenBorders;
    this.attenuateIntersectionDistance = attenuateIntersectionDistance;
    this.attenuateIntersectionIterations = attenuateIntersectionIterations;
    this.attenuateFacingCamera = attenuateFacingCamera;
    this.attenuateBackfaceReflection = attenuateBackfaceReflection;
    this.clipToFrustum = clipToFrustum;
    this.useFresnel = useFresnel;
    this.enableAutomaticThicknessComputation = enableAutomaticThicknessComputation;
    this.inputTextureColorIsInGammaSpace = inputTextureColorIsInGammaSpace;
    this.generateOutputInGammaSpace = generateOutputInGammaSpace;
    this.debug = debug;
    this._additionalConstructionParameters = [textureType];
  }
  get textureType() {
    return this._frameGraphTask.textureType;
  }
  set textureType(value) {
    this._createTask(value);
  }
  get debug() {
    return this._frameGraphTask.ssr.debug;
  }
  set debug(value) {
    this._frameGraphTask.ssr.debug = value;
  }
  get strength() {
    return this._frameGraphTask.ssr.strength;
  }
  set strength(value) {
    this._frameGraphTask.ssr.strength = value;
  }
  get reflectionSpecularFalloffExponent() {
    return this._frameGraphTask.ssr.reflectionSpecularFalloffExponent;
  }
  set reflectionSpecularFalloffExponent(value) {
    this._frameGraphTask.ssr.reflectionSpecularFalloffExponent = value;
  }
  get reflectivityThreshold() {
    return this._frameGraphTask.ssr.reflectivityThreshold;
  }
  set reflectivityThreshold(value) {
    this._frameGraphTask.ssr.reflectivityThreshold = value;
  }
  get thickness() {
    return this._frameGraphTask.ssr.thickness;
  }
  set thickness(value) {
    this._frameGraphTask.ssr.thickness = value;
  }
  get step() {
    return this._frameGraphTask.ssr.step;
  }
  set step(value) {
    this._frameGraphTask.ssr.step = value;
  }
  get enableSmoothReflections() {
    return this._frameGraphTask.ssr.enableSmoothReflections;
  }
  set enableSmoothReflections(value) {
    this._frameGraphTask.ssr.enableSmoothReflections = value;
  }
  get maxSteps() {
    return this._frameGraphTask.ssr.maxSteps;
  }
  set maxSteps(value) {
    this._frameGraphTask.ssr.maxSteps = value;
  }
  get maxDistance() {
    return this._frameGraphTask.ssr.maxDistance;
  }
  set maxDistance(value) {
    this._frameGraphTask.ssr.maxDistance = value;
  }
  get roughnessFactor() {
    return this._frameGraphTask.ssr.roughnessFactor;
  }
  set roughnessFactor(value) {
    this._frameGraphTask.ssr.roughnessFactor = value;
  }
  get selfCollisionNumSkip() {
    return this._frameGraphTask.ssr.selfCollisionNumSkip;
  }
  set selfCollisionNumSkip(value) {
    this._frameGraphTask.ssr.selfCollisionNumSkip = value;
  }
  get ssrDownsample() {
    return this._frameGraphTask.ssr.ssrDownsample;
  }
  set ssrDownsample(value) {
    this._frameGraphTask.ssr.ssrDownsample = value;
  }
  get clipToFrustum() {
    return this._frameGraphTask.ssr.clipToFrustum;
  }
  set clipToFrustum(value) {
    this._frameGraphTask.ssr.clipToFrustum = value;
  }
  get enableAutomaticThicknessComputation() {
    return this._frameGraphTask.ssr.enableAutomaticThicknessComputation;
  }
  set enableAutomaticThicknessComputation(value) {
    this._frameGraphTask.ssr.enableAutomaticThicknessComputation = value;
  }
  get useFresnel() {
    return this._frameGraphTask.ssr.useFresnel;
  }
  set useFresnel(value) {
    this._frameGraphTask.ssr.useFresnel = value;
  }
  get blurDispersionStrength() {
    return this._frameGraphTask.ssr.blurDispersionStrength;
  }
  set blurDispersionStrength(value) {
    this._frameGraphTask.ssr.blurDispersionStrength = value;
  }
  get blurDownsample() {
    return this._frameGraphTask.ssr.blurDownsample;
  }
  set blurDownsample(value) {
    this._frameGraphTask.ssr.blurDownsample = value;
  }
  get attenuateScreenBorders() {
    return this._frameGraphTask.ssr.attenuateScreenBorders;
  }
  set attenuateScreenBorders(value) {
    this._frameGraphTask.ssr.attenuateScreenBorders = value;
  }
  get attenuateIntersectionDistance() {
    return this._frameGraphTask.ssr.attenuateIntersectionDistance;
  }
  set attenuateIntersectionDistance(value) {
    this._frameGraphTask.ssr.attenuateIntersectionDistance = value;
  }
  get attenuateIntersectionIterations() {
    return this._frameGraphTask.ssr.attenuateIntersectionIterations;
  }
  set attenuateIntersectionIterations(value) {
    this._frameGraphTask.ssr.attenuateIntersectionIterations = value;
  }
  get attenuateFacingCamera() {
    return this._frameGraphTask.ssr.attenuateFacingCamera;
  }
  set attenuateFacingCamera(value) {
    this._frameGraphTask.ssr.attenuateFacingCamera = value;
  }
  get attenuateBackfaceReflection() {
    return this._frameGraphTask.ssr.attenuateBackfaceReflection;
  }
  set attenuateBackfaceReflection(value) {
    this._frameGraphTask.ssr.attenuateBackfaceReflection = value;
  }
  get inputTextureColorIsInGammaSpace() {
    return this._frameGraphTask.ssr.inputTextureColorIsInGammaSpace;
  }
  set inputTextureColorIsInGammaSpace(value) {
    this._frameGraphTask.ssr.inputTextureColorIsInGammaSpace = value;
  }
  get generateOutputInGammaSpace() {
    return this._frameGraphTask.ssr.generateOutputInGammaSpace;
  }
  set generateOutputInGammaSpace(value) {
    this._frameGraphTask.ssr.generateOutputInGammaSpace = value;
  }
  getClassName() {
    return "NodeRenderGraphSSRPostProcessBlock";
  }
  get camera() {
    return this._inputs[2];
  }
  get geomDepth() {
    return this._inputs[3];
  }
  get geomNormal() {
    return this._inputs[4];
  }
  get geomReflectivity() {
    return this._inputs[5];
  }
  get geomBackDepth() {
    return this._inputs[6];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._frameGraphTask.normalTexture = this.geomNormal.connectedPoint?.value;
    this._frameGraphTask.depthTexture = this.geomDepth.connectedPoint?.value;
    this._frameGraphTask.reflectivityTexture = this.geomReflectivity.connectedPoint?.value;
    this._frameGraphTask.backDepthTexture = this.geomBackDepth.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
    if (this.enableAutomaticThicknessComputation) {
      if (!this._frameGraphTask.backDepthTexture) {
        throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires a back depth texture to be connected!`);
      }
      const geomBackDepthOwnerBlock = this.geomBackDepth.connectedPoint.ownerBlock;
      if (geomBackDepthOwnerBlock.getClassName() === "NodeRenderGraphGeometryRendererBlock") {
        const geometryBackFaceRendererBlock = geomBackDepthOwnerBlock;
        if (!geometryBackFaceRendererBlock.reverseCulling) {
          throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires the geometry renderer block for the back depth texture to have reverse culling enabled!`);
        }
        if (this._frameGraphTask.depthTexture) {
          const geomDepthOwnerBlock = this.geomDepth.connectedPoint.ownerBlock;
          if (geomDepthOwnerBlock.getClassName() === "NodeRenderGraphGeometryRendererBlock") {
            const geomDepthConnectionPointType = this.geomDepth.connectedPoint.type;
            const geomBackDepthConnectionPointType = this.geomBackDepth.connectedPoint.type;
            if (geomDepthConnectionPointType !== geomBackDepthConnectionPointType) {
              throw new Error(`SSR post process "${this.name}": Automatic thickness computation requires that geomDepth and geomBackDepth have the same type (view or screen space depth)!`);
            }
          }
        }
      }
    }
    if (this.geomNormal.connectedPoint) {
      if (this.geomNormal.connectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal) {
        this._frameGraphTask.ssr.normalsAreInWorldSpace = true;
        this._frameGraphTask.ssr.normalsAreUnsigned = true;
      }
    }
    if (this.geomDepth.connectedPoint) {
      if (this.geomDepth.connectedPoint.type === NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth) {
        this._frameGraphTask.ssr.useScreenspaceDepth = true;
      }
    }
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.debug = ${this.debug};`);
    codes.push(`${this._codeVariableName}.strength = ${this.strength};`);
    codes.push(`${this._codeVariableName}.reflectionSpecularFalloffExponent = ${this.reflectionSpecularFalloffExponent};`);
    codes.push(`${this._codeVariableName}.reflectivityThreshold = ${this.reflectivityThreshold};`);
    codes.push(`${this._codeVariableName}.thickness = ${this.thickness};`);
    codes.push(`${this._codeVariableName}.step = ${this.step};`);
    codes.push(`${this._codeVariableName}.enableSmoothReflections = ${this.enableSmoothReflections};`);
    codes.push(`${this._codeVariableName}.maxSteps = ${this.maxSteps};`);
    codes.push(`${this._codeVariableName}.maxDistance = ${this.maxDistance};`);
    codes.push(`${this._codeVariableName}.roughnessFactor = ${this.roughnessFactor};`);
    codes.push(`${this._codeVariableName}.selfCollisionNumSkip = ${this.selfCollisionNumSkip};`);
    codes.push(`${this._codeVariableName}.ssrDownsample = ${this.ssrDownsample};`);
    codes.push(`${this._codeVariableName}.clipToFrustum = ${this.clipToFrustum};`);
    codes.push(`${this._codeVariableName}.useFresnel = ${this.useFresnel};`);
    codes.push(`${this._codeVariableName}.enableAutomaticThicknessComputation = ${this.enableAutomaticThicknessComputation};`);
    codes.push(`${this._codeVariableName}.blurDispersionStrength = ${this.blurDispersionStrength};`);
    codes.push(`${this._codeVariableName}.blurDownsample = ${this.blurDownsample};`);
    codes.push(`${this._codeVariableName}.attenuateScreenBorders = ${this.attenuateScreenBorders};`);
    codes.push(`${this._codeVariableName}.attenuateIntersectionDistance = ${this.attenuateIntersectionDistance};`);
    codes.push(`${this._codeVariableName}.attenuateIntersectionIterations = ${this.attenuateIntersectionIterations};`);
    codes.push(`${this._codeVariableName}.attenuateFacingCamera = ${this.attenuateFacingCamera};`);
    codes.push(`${this._codeVariableName}.attenuateBackfaceReflection = ${this.attenuateBackfaceReflection};`);
    codes.push(`${this._codeVariableName}.inputTextureColorIsInGammaSpace = ${this.inputTextureColorIsInGammaSpace};`);
    codes.push(`${this._codeVariableName}.generateOutputInGammaSpace = ${this.generateOutputInGammaSpace};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.debug = this.debug;
    serializationObject.strength = this.strength;
    serializationObject.reflectionSpecularFalloffExponent = this.reflectionSpecularFalloffExponent;
    serializationObject.reflectivityThreshold = this.reflectivityThreshold;
    serializationObject.thickness = this.thickness;
    serializationObject.step = this.step;
    serializationObject.enableSmoothReflections = this.enableSmoothReflections;
    serializationObject.maxSteps = this.maxSteps;
    serializationObject.maxDistance = this.maxDistance;
    serializationObject.roughnessFactor = this.roughnessFactor;
    serializationObject.selfCollisionNumSkip = this.selfCollisionNumSkip;
    serializationObject.ssrDownsample = this.ssrDownsample;
    serializationObject.clipToFrustum = this.clipToFrustum;
    serializationObject.useFresnel = this.useFresnel;
    serializationObject.enableAutomaticThicknessComputation = this.enableAutomaticThicknessComputation;
    serializationObject.blurDispersionStrength = this.blurDispersionStrength;
    serializationObject.blurDownsample = this.blurDownsample;
    serializationObject.attenuateScreenBorders = this.attenuateScreenBorders;
    serializationObject.attenuateIntersectionDistance = this.attenuateIntersectionDistance;
    serializationObject.attenuateIntersectionIterations = this.attenuateIntersectionIterations;
    serializationObject.attenuateFacingCamera = this.attenuateFacingCamera;
    serializationObject.attenuateBackfaceReflection = this.attenuateBackfaceReflection;
    serializationObject.inputTextureColorIsInGammaSpace = this.inputTextureColorIsInGammaSpace;
    serializationObject.generateOutputInGammaSpace = this.generateOutputInGammaSpace;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.debug = serializationObject.debug;
    this.strength = serializationObject.strength;
    this.reflectionSpecularFalloffExponent = serializationObject.reflectionSpecularFalloffExponent;
    this.reflectivityThreshold = serializationObject.reflectivityThreshold;
    this.thickness = serializationObject.thickness;
    this.step = serializationObject.step;
    this.enableSmoothReflections = serializationObject.enableSmoothReflections;
    this.maxSteps = serializationObject.maxSteps;
    this.maxDistance = serializationObject.maxDistance;
    this.roughnessFactor = serializationObject.roughnessFactor;
    this.selfCollisionNumSkip = serializationObject.selfCollisionNumSkip;
    this.ssrDownsample = serializationObject.ssrDownsample;
    this.clipToFrustum = serializationObject.clipToFrustum;
    this.useFresnel = serializationObject.useFresnel;
    this.enableAutomaticThicknessComputation = serializationObject.enableAutomaticThicknessComputation;
    this.blurDispersionStrength = serializationObject.blurDispersionStrength;
    this.blurDownsample = serializationObject.blurDownsample;
    this.attenuateScreenBorders = serializationObject.attenuateScreenBorders;
    this.attenuateIntersectionDistance = serializationObject.attenuateIntersectionDistance;
    this.attenuateIntersectionIterations = serializationObject.attenuateIntersectionIterations;
    this.attenuateFacingCamera = serializationObject.attenuateFacingCamera;
    this.attenuateBackfaceReflection = serializationObject.attenuateBackfaceReflection;
    this.inputTextureColorIsInGammaSpace = serializationObject.inputTextureColorIsInGammaSpace;
    this.generateOutputInGammaSpace = serializationObject.generateOutputInGammaSpace;
  }
}
__decorate([
  editableInPropertyPage("Texture type", 8, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "textureType", null);
__decorate([
  editableInPropertyPage("Debug", 0, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "debug", null);
__decorate([
  editableInPropertyPage("Strength", 1, "SSR", { min: 0, max: 5 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "strength", null);
__decorate([
  editableInPropertyPage("Reflection exponent", 1, "SSR", { min: 0, max: 5 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "reflectionSpecularFalloffExponent", null);
__decorate([
  editableInPropertyPage("Reflectivity threshold", 1, "SSR", { min: 0, max: 1 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "reflectivityThreshold", null);
__decorate([
  editableInPropertyPage("Thickness", 1, "SSR", { min: 0, max: 10 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "thickness", null);
__decorate([
  editableInPropertyPage("Step", 2, "SSR", { min: 1, max: 50 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "step", null);
__decorate([
  editableInPropertyPage("Smooth reflections", 0, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "enableSmoothReflections", null);
__decorate([
  editableInPropertyPage("Max steps", 2, "SSR", { min: 1, max: 3000 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "maxSteps", null);
__decorate([
  editableInPropertyPage("Max distance", 1, "SSR", { min: 1, max: 3000 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "maxDistance", null);
__decorate([
  editableInPropertyPage("Roughness factor", 1, "SSR", { min: 0, max: 1 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "roughnessFactor", null);
__decorate([
  editableInPropertyPage("Self collision skips", 2, "SSR", { min: 1, max: 10 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "selfCollisionNumSkip", null);
__decorate([
  editableInPropertyPage("SSR downsample", 2, "SSR", { min: 0, max: 5 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "ssrDownsample", null);
__decorate([
  editableInPropertyPage("Clip to frustum", 0, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "clipToFrustum", null);
__decorate([
  editableInPropertyPage("Automatic thickness computation", 0, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "enableAutomaticThicknessComputation", null);
__decorate([
  editableInPropertyPage("Use Fresnel", 0, "SSR")
], NodeRenderGraphSSRPostProcessBlock.prototype, "useFresnel", null);
__decorate([
  editableInPropertyPage("Strength", 1, "Blur", { min: 0, max: 0.15 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "blurDispersionStrength", null);
__decorate([
  editableInPropertyPage("Blur downsample", 2, "Blur", { min: 0, max: 5 })
], NodeRenderGraphSSRPostProcessBlock.prototype, "blurDownsample", null);
__decorate([
  editableInPropertyPage("Screen borders", 0, "Attenuations")
], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateScreenBorders", null);
__decorate([
  editableInPropertyPage("Distance", 0, "Attenuations")
], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateIntersectionDistance", null);
__decorate([
  editableInPropertyPage("Step iterations", 0, "Attenuations")
], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateIntersectionIterations", null);
__decorate([
  editableInPropertyPage("Facing camera", 0, "Attenuations")
], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateFacingCamera", null);
__decorate([
  editableInPropertyPage("Backface reflections", 0, "Attenuations")
], NodeRenderGraphSSRPostProcessBlock.prototype, "attenuateBackfaceReflection", null);
__decorate([
  editableInPropertyPage("Input is in gamma space", 0, "Color space")
], NodeRenderGraphSSRPostProcessBlock.prototype, "inputTextureColorIsInGammaSpace", null);
__decorate([
  editableInPropertyPage("Output to gamma space", 0, "Color space")
], NodeRenderGraphSSRPostProcessBlock.prototype, "generateOutputInGammaSpace", null);
RegisterClass("BABYLON.NodeRenderGraphSSRPostProcessBlock", NodeRenderGraphSSRPostProcessBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/csmShadowGeneratorBlock.js
init_tslib_es6();

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/baseShadowGeneratorBlock.js
init_tslib_es6();
class NodeRenderGraphBaseShadowGeneratorBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name235, frameGraph, scene) {
    super(name235, frameGraph, scene);
    this.registerInput("light", NodeRenderGraphBlockConnectionPointTypes.ShadowLight);
    this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this._addDependenciesInput();
    this.registerOutput("generator", NodeRenderGraphBlockConnectionPointTypes.ShadowGenerator);
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.Texture);
  }
  get mapSize() {
    return this._frameGraphTask.mapSize;
  }
  set mapSize(value) {
    this._frameGraphTask.mapSize = value;
  }
  get useFloat32TextureType() {
    return this._frameGraphTask.useFloat32TextureType;
  }
  set useFloat32TextureType(value) {
    this._frameGraphTask.useFloat32TextureType = value;
  }
  get useRedTextureFormat() {
    return this._frameGraphTask.useRedTextureFormat;
  }
  set useRedTextureFormat(value) {
    this._frameGraphTask.useRedTextureFormat = value;
  }
  get bias() {
    return this._frameGraphTask.bias;
  }
  set bias(value) {
    this._frameGraphTask.bias = value;
  }
  get normalBias() {
    return this._frameGraphTask.normalBias;
  }
  set normalBias(value) {
    this._frameGraphTask.normalBias = value;
  }
  get darkness() {
    return this._frameGraphTask.darkness;
  }
  set darkness(value) {
    this._frameGraphTask.darkness = value;
  }
  get filter() {
    return this._frameGraphTask.filter;
  }
  set filter(value) {
    this._frameGraphTask.filter = value;
  }
  get filteringQuality() {
    return this._frameGraphTask.filteringQuality;
  }
  set filteringQuality(value) {
    this._frameGraphTask.filteringQuality = value;
  }
  get transparencyShadow() {
    return this._frameGraphTask.transparencyShadow;
  }
  set transparencyShadow(value) {
    this._frameGraphTask.transparencyShadow = value;
  }
  get enableSoftTransparentShadow() {
    return this._frameGraphTask.enableSoftTransparentShadow;
  }
  set enableSoftTransparentShadow(value) {
    this._frameGraphTask.enableSoftTransparentShadow = value;
  }
  get useOpacityTextureForTransparentShadow() {
    return this._frameGraphTask.useOpacityTextureForTransparentShadow;
  }
  set useOpacityTextureForTransparentShadow(value) {
    this._frameGraphTask.useOpacityTextureForTransparentShadow = value;
  }
  getClassName() {
    return "NodeRenderGraphBaseShadowGeneratorBlock";
  }
  get light() {
    return this._inputs[0];
  }
  get objects() {
    return this._inputs[1];
  }
  get camera() {
    return this._inputs[2];
  }
  get generator() {
    return this._outputs[0];
  }
  get output() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._frameGraphTask.light = this.light.connectedPoint?.value;
    this._frameGraphTask.objectList = this.objects.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
    this.generator.value = this._frameGraphTask;
    this.output.value = this._frameGraphTask.outputTexture;
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.mapSize = ${this.mapSize};`);
    codes.push(`${this._codeVariableName}.useFloat32TextureType = ${this.useFloat32TextureType};`);
    codes.push(`${this._codeVariableName}.useRedTextureFormat = ${this.useRedTextureFormat};`);
    codes.push(`${this._codeVariableName}.bias = ${this.bias};`);
    codes.push(`${this._codeVariableName}.normalBias = ${this.normalBias};`);
    codes.push(`${this._codeVariableName}.darkness = ${this.darkness};`);
    codes.push(`${this._codeVariableName}.filter = ${this.filter};`);
    codes.push(`${this._codeVariableName}.filteringQuality = ${this.filteringQuality};`);
    codes.push(`${this._codeVariableName}.transparencyShadow = ${this.transparencyShadow};`);
    codes.push(`${this._codeVariableName}.enableSoftTransparentShadow = ${this.enableSoftTransparentShadow};`);
    codes.push(`${this._codeVariableName}.useOpacityTextureForTransparentShadow = ${this.useOpacityTextureForTransparentShadow};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.mapSize = this.mapSize;
    serializationObject.useFloat32TextureType = this.useFloat32TextureType;
    serializationObject.useRedTextureFormat = this.useRedTextureFormat;
    serializationObject.bias = this.bias;
    serializationObject.normalBias = this.normalBias;
    serializationObject.darkness = this.darkness;
    serializationObject.filter = this.filter;
    serializationObject.filteringQuality = this.filteringQuality;
    serializationObject.transparencyShadow = this.transparencyShadow;
    serializationObject.enableSoftTransparentShadow = this.enableSoftTransparentShadow;
    serializationObject.useOpacityTextureForTransparentShadow = this.useOpacityTextureForTransparentShadow;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.mapSize = serializationObject.mapSize;
    this.useFloat32TextureType = serializationObject.useFloat32TextureType;
    this.useRedTextureFormat = serializationObject.useRedTextureFormat;
    this.bias = serializationObject.bias;
    this.normalBias = serializationObject.normalBias;
    this.darkness = serializationObject.darkness;
    this.filter = serializationObject.filter;
    this.filteringQuality = serializationObject.filteringQuality;
    this.transparencyShadow = serializationObject.transparencyShadow;
    this.enableSoftTransparentShadow = serializationObject.enableSoftTransparentShadow;
    this.useOpacityTextureForTransparentShadow = serializationObject.useOpacityTextureForTransparentShadow;
  }
}
__decorate([
  editableInPropertyPage("Map size", 4, "PROPERTIES", {
    options: [
      { label: "128", value: 128 },
      { label: "256", value: 256 },
      { label: "512", value: 512 },
      { label: "1024", value: 1024 },
      { label: "2048", value: 2048 },
      { label: "4096", value: 4096 },
      { label: "8192", value: 8192 }
    ]
  })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "mapSize", null);
__decorate([
  editableInPropertyPage("Use 32 bits float texture type", 0, "PROPERTIES")
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useFloat32TextureType", null);
__decorate([
  editableInPropertyPage("Use red texture format", 0, "PROPERTIES")
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useRedTextureFormat", null);
__decorate([
  editableInPropertyPage("Bias", 1, "PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "bias", null);
__decorate([
  editableInPropertyPage("Normal bias", 1, "PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "normalBias", null);
__decorate([
  editableInPropertyPage("Darkness", 1, "PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "darkness", null);
__decorate([
  editableInPropertyPage("Filter", 4, "PROPERTIES", {
    options: [
      { label: "None", value: ShadowGenerator.FILTER_NONE },
      { label: "Exponential", value: ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP },
      { label: "Poisson Sampling", value: ShadowGenerator.FILTER_POISSONSAMPLING },
      { label: "Blur exponential", value: ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP },
      { label: "Close exponential", value: ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP },
      { label: "Blur close exponential", value: ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP },
      { label: "PCF", value: ShadowGenerator.FILTER_PCF },
      { label: "PCSS", value: ShadowGenerator.FILTER_PCSS }
    ]
  })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "filter", null);
__decorate([
  editableInPropertyPage("Filter quality", 4, "PROPERTIES", {
    options: [
      { label: "Low", value: ShadowGenerator.QUALITY_LOW },
      { label: "Medium", value: ShadowGenerator.QUALITY_MEDIUM },
      { label: "High", value: ShadowGenerator.QUALITY_HIGH }
    ]
  })
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "filteringQuality", null);
__decorate([
  editableInPropertyPage("Transparency shadow", 0, "PROPERTIES")
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "transparencyShadow", null);
__decorate([
  editableInPropertyPage("Enable soft transparent shadows", 0, "PROPERTIES")
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "enableSoftTransparentShadow", null);
__decorate([
  editableInPropertyPage("Use opacity texture for transparent shadows", 0, "PROPERTIES")
], NodeRenderGraphBaseShadowGeneratorBlock.prototype, "useOpacityTextureForTransparentShadow", null);

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/csmShadowGeneratorBlock.js
init_typeStore();
class NodeRenderGraphCascadedShadowGeneratorBlock extends NodeRenderGraphBaseShadowGeneratorBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name235, frameGraph, scene) {
    super(name235, frameGraph, scene);
    this._frameGraphTask = new FrameGraphCascadedShadowGeneratorTask(this.name, frameGraph, scene);
  }
  get numCascades() {
    return this._frameGraphTask.numCascades;
  }
  set numCascades(value) {
    this._frameGraphTask.numCascades = value;
  }
  get debug() {
    return this._frameGraphTask.debug;
  }
  set debug(value) {
    this._frameGraphTask.debug = value;
  }
  get stabilizeCascades() {
    return this._frameGraphTask.stabilizeCascades;
  }
  set stabilizeCascades(value) {
    this._frameGraphTask.stabilizeCascades = value;
  }
  get lambda() {
    return this._frameGraphTask.lambda;
  }
  set lambda(value) {
    this._frameGraphTask.lambda = value;
  }
  get cascadeBlendPercentage() {
    return this._frameGraphTask.cascadeBlendPercentage;
  }
  set cascadeBlendPercentage(value) {
    this._frameGraphTask.cascadeBlendPercentage = value;
  }
  get depthClamp() {
    return this._frameGraphTask.depthClamp;
  }
  set depthClamp(value) {
    this._frameGraphTask.depthClamp = value;
  }
  get autoCalcDepthBounds() {
    return this._frameGraphTask.autoCalcDepthBounds;
  }
  set autoCalcDepthBounds(value) {
    this._frameGraphTask.autoCalcDepthBounds = value;
  }
  get shadowMaxZ() {
    return this._frameGraphTask.shadowMaxZ;
  }
  set shadowMaxZ(value) {
    this._frameGraphTask.shadowMaxZ = value;
  }
  getClassName() {
    return "NodeRenderGraphCascadedShadowGeneratorBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.numCascades = ${this.numCascades};`);
    codes.push(`${this._codeVariableName}.debug = ${this.debug};`);
    codes.push(`${this._codeVariableName}.stabilizeCascades = ${this.stabilizeCascades};`);
    codes.push(`${this._codeVariableName}.lambda = ${this.lambda};`);
    codes.push(`${this._codeVariableName}.cascadeBlendPercentage = ${this.cascadeBlendPercentage};`);
    codes.push(`${this._codeVariableName}.depthClamp = ${this.depthClamp};`);
    codes.push(`${this._codeVariableName}.autoCalcDepthBounds = ${this.autoCalcDepthBounds};`);
    codes.push(`${this._codeVariableName}.shadowMaxZ = ${this.shadowMaxZ};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.numCascades = this.numCascades;
    serializationObject.debug = this.debug;
    serializationObject.stabilizeCascades = this.stabilizeCascades;
    serializationObject.lambda = this.lambda;
    serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;
    serializationObject.depthClamp = this.depthClamp;
    serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;
    serializationObject.shadowMaxZ = this.shadowMaxZ;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.numCascades = serializationObject.numCascades;
    this.debug = serializationObject.debug;
    this.stabilizeCascades = serializationObject.stabilizeCascades;
    this.lambda = serializationObject.lambda;
    this.cascadeBlendPercentage = serializationObject.cascadeBlendPercentage;
    this.depthClamp = serializationObject.depthClamp;
    this.autoCalcDepthBounds = serializationObject.autoCalcDepthBounds;
    this.shadowMaxZ = serializationObject.shadowMaxZ;
  }
}
__decorate([
  editableInPropertyPage("Number of cascades", 4, "CSM PROPERTIES", {
    options: [
      { label: "2", value: 2 },
      { label: "3", value: 3 },
      { label: "4", value: 4 }
    ]
  })
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "numCascades", null);
__decorate([
  editableInPropertyPage("Debug mode", 0, "CSM PROPERTIES")
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "debug", null);
__decorate([
  editableInPropertyPage("Stabilize cascades", 0, "CSM PROPERTIES")
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "stabilizeCascades", null);
__decorate([
  editableInPropertyPage("Lambda", 1, "CSM PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "lambda", null);
__decorate([
  editableInPropertyPage("Cascade blend", 1, "CSM PROPERTIES", { min: 0, max: 1 })
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "cascadeBlendPercentage", null);
__decorate([
  editableInPropertyPage("Depth clamp", 0, "CSM PROPERTIES")
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "depthClamp", null);
__decorate([
  editableInPropertyPage("Auto-Calc depth bounds", 0, "CSM PROPERTIES")
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "autoCalcDepthBounds", null);
__decorate([
  editableInPropertyPage("Shadow maxZ", 1, "CSM PROPERTIES")
], NodeRenderGraphCascadedShadowGeneratorBlock.prototype, "shadowMaxZ", null);
RegisterClass("BABYLON.NodeRenderGraphCascadedShadowGeneratorBlock", NodeRenderGraphCascadedShadowGeneratorBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/geometryRendererBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/geometryRendererTask.js
init_math_color();
init_objectRenderer();
var clearColors = [new Color4(0, 0, 0, 0), new Color4(1, 1, 1, 1), new Color4(1e8, 1e8, 1e8, 1e8)];

class FrameGraphGeometryRendererTask extends FrameGraphTask {
  get camera() {
    return this._camera;
  }
  set camera(camera2) {
    this._camera = camera2;
    this._renderer.activeCamera = this.camera;
  }
  get reverseCulling() {
    return this._reverseCulling;
  }
  set reverseCulling(value) {
    this._reverseCulling = value;
    const configuration = MaterialHelperGeometryRendering.GetConfiguration(this._renderer.renderPassId);
    if (configuration) {
      configuration.reverseCulling = value;
    }
  }
  get objectRenderer() {
    return this._renderer;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
    if (this._renderer) {
      this._renderer.name = value;
    }
  }
  constructor(name235, frameGraph, scene, options) {
    super(name235, frameGraph);
    this.depthTest = true;
    this.depthWrite = true;
    this.size = { width: 100, height: 100 };
    this.sizeIsPercentage = true;
    this.samples = 1;
    this._reverseCulling = false;
    this.dontRenderWhenMaterialDepthWriteIsDisabled = true;
    this.textureDescriptions = [];
    this._scene = scene;
    this._engine = this._scene.getEngine();
    this._renderer = new ObjectRenderer(name235, scene, options);
    this._renderer.renderSprites = false;
    this._renderer.renderParticles = false;
    this._renderer.customIsReadyFunction = (mesh, refreshRate, preWarm) => {
      if (this.dontRenderWhenMaterialDepthWriteIsDisabled && mesh.material && mesh.material.disableDepthWrite) {
        return !!preWarm;
      }
      return mesh.isReady(refreshRate === 0);
    };
    this._renderer.onBeforeRenderingManagerRenderObservable.add(() => {
      if (!this._renderer.options.doNotChangeAspectRatio) {
        scene.updateTransformMatrix(true);
      }
    });
    this.name = name235;
    this._clearAttachmentsLayout = new Map;
    this._allAttachmentsLayout = [];
    this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryViewDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryScreenDepthTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryViewNormalTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryWorldNormalTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryLocalPositionTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryWorldPositionTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryAlbedoTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryReflectivityTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryVelocityTexture = this._frameGraph.textureManager.createDanglingHandle();
    this.geometryLinearVelocityTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  get excludedSkinnedMeshFromVelocityTexture() {
    return MaterialHelperGeometryRendering.GetConfiguration(this._renderer.renderPassId).excludedSkinnedMesh;
  }
  isReady() {
    return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight);
  }
  record() {
    if (this.textureDescriptions.length === 0 || this.objectList === undefined) {
      throw new Error(`FrameGraphGeometryRendererTask ${this.name}: object list and at least one geometry texture description must be provided`);
    }
    this._renderer.renderList = this.objectList.meshes;
    this._renderer.particleSystemList = this.objectList.particleSystems;
    const outputTextureHandle = this._createMultiRenderTargetTexture();
    const depthEnabled = this._checkDepthTextureCompatibility();
    this._buildClearAttachmentsLayout();
    this._registerForRenderPassId(this._renderer.renderPassId);
    const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(outputTextureHandle[0]);
    this._textureWidth = outputTextureDescription.size.width;
    this._textureHeight = outputTextureDescription.size.height;
    MaterialHelperGeometryRendering.MarkAsDirty(this._renderer.renderPassId, this.objectList.meshes || this._scene.meshes);
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(outputTextureHandle);
    for (let i = 0;i < this.textureDescriptions.length; i++) {
      const description = this.textureDescriptions[i];
      const handle = outputTextureHandle[i];
      const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type);
      const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index];
      switch (geometryDescription.type) {
        case 5:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryViewDepthTexture, handle);
          break;
        case 10:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryScreenDepthTexture, handle);
          break;
        case 6:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryViewNormalTexture, handle);
          break;
        case 8:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryWorldNormalTexture, handle);
          break;
        case 9:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryLocalPositionTexture, handle);
          break;
        case 1:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryWorldPositionTexture, handle);
          break;
        case 12:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryAlbedoTexture, handle);
          break;
        case 3:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryReflectivityTexture, handle);
          break;
        case 2:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryVelocityTexture, handle);
          break;
        case 11:
          this._frameGraph.textureManager.resolveDanglingHandle(this.geometryLinearVelocityTexture, handle);
          break;
      }
    }
    pass.setRenderTargetDepth(this.depthTexture);
    pass.setExecuteFunc((context) => {
      this._renderer.renderList = this.objectList.meshes;
      this._renderer.particleSystemList = this.objectList.particleSystems;
      context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled);
      this._clearAttachmentsLayout.forEach((layout, clearType) => {
        context.clearColorAttachments(clearColors[clearType], layout);
      });
      context.bindAttachments(this._allAttachmentsLayout);
      context.render(this._renderer, this._textureWidth, this._textureHeight);
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(outputTextureHandle);
    passDisabled.setRenderTargetDepth(this.depthTexture);
    passDisabled.setExecuteFunc((_context) => {});
  }
  dispose() {
    MaterialHelperGeometryRendering.DeleteConfiguration(this._renderer.renderPassId);
    this._renderer.dispose();
    super.dispose();
  }
  _createMultiRenderTargetTexture() {
    const types = [];
    const formats = [];
    const labels = [];
    const useSRGBBuffers = [];
    for (let i = 0;i < this.textureDescriptions.length; i++) {
      const description = this.textureDescriptions[i];
      const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type);
      if (index === -1) {
        throw new Error(`FrameGraphGeometryRendererTask ${this.name}: unknown texture type ${description.type}`);
      }
      types[i] = description.textureType;
      formats[i] = description.textureFormat;
      labels[i] = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index].name;
      useSRGBBuffers[i] = false;
    }
    const baseHandle = this._frameGraph.textureManager.createRenderTargetTexture(this.name, {
      size: this.size,
      sizeIsPercentage: this.sizeIsPercentage,
      options: {
        createMipMaps: false,
        samples: this.samples,
        types,
        formats,
        useSRGBBuffers,
        labels
      }
    });
    const handles = [];
    for (let i = 0;i < this.textureDescriptions.length; i++) {
      handles.push(baseHandle + i);
    }
    return handles;
  }
  _checkDepthTextureCompatibility() {
    let depthEnabled = false;
    if (this.depthTexture !== undefined) {
      if (this.depthTexture === backbufferDepthStencilTextureHandle) {
        throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth/stencil back buffer is not allowed as a depth texture`);
      }
      const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture);
      if (depthTextureDescription.options.samples !== this.samples) {
        throw new Error(`FrameGraphGeometryRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);
      }
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture);
      depthEnabled = true;
    }
    return depthEnabled;
  }
  _buildClearAttachmentsLayout() {
    const clearAttachmentsLayout = new Map;
    const allAttachmentsLayout = [];
    for (let i = 0;i < this.textureDescriptions.length; i++) {
      const description = this.textureDescriptions[i];
      const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type);
      const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index];
      let layout = clearAttachmentsLayout.get(geometryDescription.clearType);
      if (layout === undefined) {
        layout = [];
        clearAttachmentsLayout.set(geometryDescription.clearType, layout);
        for (let j = 0;j < i; j++) {
          layout[j] = false;
        }
      }
      clearAttachmentsLayout.forEach((layout2, clearType) => {
        layout2.push(clearType === geometryDescription.clearType);
      });
      allAttachmentsLayout.push(true);
    }
    this._clearAttachmentsLayout = new Map;
    clearAttachmentsLayout.forEach((layout, clearType) => {
      this._clearAttachmentsLayout.set(clearType, this._engine.buildTextureLayout(layout));
    });
    this._allAttachmentsLayout = this._engine.buildTextureLayout(allAttachmentsLayout);
  }
  _registerForRenderPassId(renderPassId) {
    const configuration = MaterialHelperGeometryRendering.CreateConfiguration(renderPassId);
    for (let i = 0;i < this.textureDescriptions.length; i++) {
      const description = this.textureDescriptions[i];
      const index = MaterialHelperGeometryRendering.GeometryTextureDescriptions.findIndex((f) => f.type === description.type);
      const geometryDescription = MaterialHelperGeometryRendering.GeometryTextureDescriptions[index];
      configuration.defines[geometryDescription.defineIndex] = i;
    }
    configuration.reverseCulling = this.reverseCulling;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/geometryRendererBlock.js
class NodeRenderGraphGeometryRendererBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name235, frameGraph, scene, doNotChangeAspectRatio = true) {
    super(name235, frameGraph, scene);
    this.viewDepthFormat = 6;
    this.viewDepthType = 1;
    this.screenDepthFormat = 6;
    this.screenDepthType = 1;
    this.viewNormalFormat = 5;
    this.viewNormalType = 2;
    this.worldNormalFormat = 5;
    this.worldNormalType = 0;
    this.localPositionFormat = 5;
    this.localPositionType = 2;
    this.worldPositionFormat = 5;
    this.worldPositionType = 2;
    this.albedoFormat = 5;
    this.albedoType = 0;
    this.reflectivityFormat = 5;
    this.reflectivityType = 0;
    this.velocityFormat = 5;
    this.velocityType = 0;
    this.linearVelocityFormat = 5;
    this.linearVelocityType = 0;
    this._additionalConstructionParameters = [doNotChangeAspectRatio];
    this.registerInput("depth", NodeRenderGraphBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this.registerInput("objects", NodeRenderGraphBlockConnectionPointTypes.ObjectList);
    this._addDependenciesInput();
    this.registerOutput("outputDepth", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("geomViewDepth", NodeRenderGraphBlockConnectionPointTypes.TextureViewDepth);
    this.registerOutput("geomScreenDepth", NodeRenderGraphBlockConnectionPointTypes.TextureScreenDepth);
    this.registerOutput("geomViewNormal", NodeRenderGraphBlockConnectionPointTypes.TextureViewNormal);
    this.registerOutput("geomWorldNormal", NodeRenderGraphBlockConnectionPointTypes.TextureWorldNormal);
    this.registerOutput("geomLocalPosition", NodeRenderGraphBlockConnectionPointTypes.TextureLocalPosition);
    this.registerOutput("geomWorldPosition", NodeRenderGraphBlockConnectionPointTypes.TextureWorldPosition);
    this.registerOutput("geomAlbedo", NodeRenderGraphBlockConnectionPointTypes.TextureAlbedo);
    this.registerOutput("geomReflectivity", NodeRenderGraphBlockConnectionPointTypes.TextureReflectivity);
    this.registerOutput("geomVelocity", NodeRenderGraphBlockConnectionPointTypes.TextureVelocity);
    this.registerOutput("geomLinearVelocity", NodeRenderGraphBlockConnectionPointTypes.TextureLinearVelocity);
    this.depth.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureDepthStencilAttachment | NodeRenderGraphBlockConnectionPointTypes.TextureBackBufferDepthStencilAttachment);
    this.outputDepth._typeConnectionSource = this.depth;
    this._frameGraphTask = new FrameGraphGeometryRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio });
  }
  get depthTest() {
    return this._frameGraphTask.depthTest;
  }
  set depthTest(value) {
    this._frameGraphTask.depthTest = value;
  }
  get depthWrite() {
    return this._frameGraphTask.depthWrite;
  }
  set depthWrite(value) {
    this._frameGraphTask.depthWrite = value;
  }
  get doNotChangeAspectRatio() {
    return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio;
  }
  set doNotChangeAspectRatio(value) {
    const disabled = this._frameGraphTask.disabled;
    const depthTest = this.depthTest;
    const depthWrite = this.depthWrite;
    const width = this.width;
    const height = this.height;
    const sizeInPercentage = this.sizeInPercentage;
    const samples = this.samples;
    const reverseCulling = this.reverseCulling;
    const dontRenderWhenMaterialDepthWriteIsDisabled = this.dontRenderWhenMaterialDepthWriteIsDisabled;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphGeometryRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value });
    this._additionalConstructionParameters = [value];
    this.depthTest = depthTest;
    this.depthWrite = depthWrite;
    this.width = width;
    this.height = height;
    this.sizeInPercentage = sizeInPercentage;
    this.samples = samples;
    this.reverseCulling = reverseCulling;
    this.dontRenderWhenMaterialDepthWriteIsDisabled = dontRenderWhenMaterialDepthWriteIsDisabled;
    this._frameGraphTask.disabled = disabled;
  }
  get width() {
    return this._frameGraphTask.size.width;
  }
  set width(value) {
    this._frameGraphTask.size.width = value;
  }
  get height() {
    return this._frameGraphTask.size.height;
  }
  set height(value) {
    this._frameGraphTask.size.height = value;
  }
  get sizeInPercentage() {
    return this._frameGraphTask.sizeIsPercentage;
  }
  set sizeInPercentage(value) {
    this._frameGraphTask.sizeIsPercentage = value;
  }
  get samples() {
    return this._frameGraphTask.samples;
  }
  set samples(value) {
    this._frameGraphTask.samples = value;
  }
  get reverseCulling() {
    return this._frameGraphTask.reverseCulling;
  }
  set reverseCulling(value) {
    this._frameGraphTask.reverseCulling = value;
  }
  get dontRenderWhenMaterialDepthWriteIsDisabled() {
    return this._frameGraphTask.dontRenderWhenMaterialDepthWriteIsDisabled;
  }
  set dontRenderWhenMaterialDepthWriteIsDisabled(value) {
    this._frameGraphTask.dontRenderWhenMaterialDepthWriteIsDisabled = value;
  }
  getClassName() {
    return "NodeRenderGraphGeometryRendererBlock";
  }
  get depth() {
    return this._inputs[0];
  }
  get camera() {
    return this._inputs[1];
  }
  get objects() {
    return this._inputs[2];
  }
  get outputDepth() {
    return this._outputs[0];
  }
  get geomViewDepth() {
    return this._outputs[1];
  }
  get geomScreenDepth() {
    return this._outputs[2];
  }
  get geomViewNormal() {
    return this._outputs[3];
  }
  get geomWorldNormal() {
    return this._outputs[4];
  }
  get geomLocalPosition() {
    return this._outputs[5];
  }
  get geomWorldPosition() {
    return this._outputs[6];
  }
  get geomAlbedo() {
    return this._outputs[7];
  }
  get geomReflectivity() {
    return this._outputs[8];
  }
  get geomVelocity() {
    return this._outputs[9];
  }
  get geomLinearVelocity() {
    return this._outputs[10];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const textureActivation = [
      this.geomViewDepth.isConnected,
      this.geomScreenDepth.isConnected,
      this.geomViewNormal.isConnected,
      this.geomWorldNormal.isConnected,
      this.geomLocalPosition.isConnected,
      this.geomWorldPosition.isConnected,
      this.geomAlbedo.isConnected,
      this.geomReflectivity.isConnected,
      this.geomVelocity.isConnected,
      this.geomLinearVelocity.isConnected
    ];
    if (textureActivation.every((t) => !t)) {
      throw new Error("NodeRenderGraphGeometryRendererBlock: At least one output geometry buffer must be connected");
    }
    this.outputDepth.value = this._frameGraphTask.outputDepthTexture;
    this.geomViewDepth.value = this._frameGraphTask.geometryViewDepthTexture;
    this.geomScreenDepth.value = this._frameGraphTask.geometryScreenDepthTexture;
    this.geomViewNormal.value = this._frameGraphTask.geometryViewNormalTexture;
    this.geomWorldNormal.value = this._frameGraphTask.geometryWorldNormalTexture;
    this.geomLocalPosition.value = this._frameGraphTask.geometryLocalPositionTexture;
    this.geomWorldPosition.value = this._frameGraphTask.geometryWorldPositionTexture;
    this.geomAlbedo.value = this._frameGraphTask.geometryAlbedoTexture;
    this.geomReflectivity.value = this._frameGraphTask.geometryReflectivityTexture;
    this.geomVelocity.value = this._frameGraphTask.geometryVelocityTexture;
    this.geomLinearVelocity.value = this._frameGraphTask.geometryLinearVelocityTexture;
    this._frameGraphTask.depthTexture = this.depth.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
    this._frameGraphTask.objectList = this.objects.connectedPoint?.value;
    this._frameGraphTask.textureDescriptions = [];
    const textureFormats = [
      this.viewDepthFormat,
      this.screenDepthFormat,
      this.viewNormalFormat,
      this.worldNormalFormat,
      this.localPositionFormat,
      this.worldPositionFormat,
      this.albedoFormat,
      this.reflectivityFormat,
      this.velocityFormat,
      this.linearVelocityFormat
    ];
    const textureTypes = [
      this.viewDepthType,
      this.screenDepthType,
      this.viewNormalType,
      this.worldNormalType,
      this.localPositionType,
      this.worldPositionType,
      this.albedoType,
      this.reflectivityType,
      this.velocityType,
      this.linearVelocityType
    ];
    const bufferTypes = [
      5,
      10,
      6,
      8,
      9,
      1,
      12,
      3,
      2,
      11
    ];
    for (let i = 0;i < textureActivation.length; i++) {
      if (textureActivation[i]) {
        this._frameGraphTask.textureDescriptions.push({
          textureFormat: textureFormats[i],
          textureType: textureTypes[i],
          type: bufferTypes[i]
        });
      }
    }
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.depthTest = ${this.depthTest};`);
    codes.push(`${this._codeVariableName}.depthWrite = ${this.depthWrite};`);
    codes.push(`${this._codeVariableName}.samples = ${this.samples};`);
    codes.push(`${this._codeVariableName}.reverseCulling = ${this.reverseCulling};`);
    codes.push(`${this._codeVariableName}.dontRenderWhenMaterialDepthWriteIsDisabled = ${this.dontRenderWhenMaterialDepthWriteIsDisabled};`);
    codes.push(`${this._codeVariableName}.viewDepthFormat = ${this.viewDepthFormat};`);
    codes.push(`${this._codeVariableName}.viewDepthType = ${this.viewDepthType};`);
    codes.push(`${this._codeVariableName}.screenDepthFormat = ${this.screenDepthFormat};`);
    codes.push(`${this._codeVariableName}.screenDepthType = ${this.screenDepthType};`);
    codes.push(`${this._codeVariableName}.localPositionFormat = ${this.localPositionFormat};`);
    codes.push(`${this._codeVariableName}.localPositionType = ${this.localPositionType};`);
    codes.push(`${this._codeVariableName}.worldPositionFormat = ${this.worldPositionFormat};`);
    codes.push(`${this._codeVariableName}.worldPositionType = ${this.worldPositionType};`);
    codes.push(`${this._codeVariableName}.viewNormalFormat = ${this.viewNormalFormat};`);
    codes.push(`${this._codeVariableName}.viewNormalType = ${this.viewNormalType};`);
    codes.push(`${this._codeVariableName}.worldNormalFormat = ${this.worldNormalFormat};`);
    codes.push(`${this._codeVariableName}.worldNormalType = ${this.worldNormalType};`);
    codes.push(`${this._codeVariableName}.albedoFormat = ${this.albedoFormat};`);
    codes.push(`${this._codeVariableName}.albedoType = ${this.albedoType};`);
    codes.push(`${this._codeVariableName}.reflectivityFormat = ${this.reflectivityFormat};`);
    codes.push(`${this._codeVariableName}.reflectivityType = ${this.reflectivityType};`);
    codes.push(`${this._codeVariableName}.velocityFormat = ${this.velocityFormat};`);
    codes.push(`${this._codeVariableName}.velocityType = ${this.velocityType};`);
    codes.push(`${this._codeVariableName}.linearVelocityFormat = ${this.linearVelocityFormat};`);
    codes.push(`${this._codeVariableName}.linearVelocityType = ${this.linearVelocityType};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.depthTest = this.depthTest;
    serializationObject.depthWrite = this.depthWrite;
    serializationObject.samples = this.samples;
    serializationObject.reverseCulling = this.reverseCulling;
    serializationObject.dontRenderWhenMaterialDepthWriteIsDisabled = this.dontRenderWhenMaterialDepthWriteIsDisabled;
    serializationObject.viewDepthFormat = this.viewDepthFormat;
    serializationObject.viewDepthType = this.viewDepthType;
    serializationObject.screenDepthFormat = this.screenDepthFormat;
    serializationObject.screenDepthType = this.screenDepthType;
    serializationObject.localPositionFormat = this.localPositionFormat;
    serializationObject.localPositionType = this.localPositionType;
    serializationObject.worldPositionFormat = this.worldPositionFormat;
    serializationObject.worldPositionType = this.worldPositionType;
    serializationObject.viewNormalFormat = this.viewNormalFormat;
    serializationObject.viewNormalType = this.viewNormalType;
    serializationObject.worldNormalFormat = this.worldNormalFormat;
    serializationObject.worldNormalType = this.worldNormalType;
    serializationObject.albedoFormat = this.albedoFormat;
    serializationObject.albedoType = this.albedoType;
    serializationObject.reflectivityFormat = this.reflectivityFormat;
    serializationObject.reflectivityType = this.reflectivityType;
    serializationObject.velocityFormat = this.velocityFormat;
    serializationObject.velocityType = this.velocityType;
    serializationObject.linearVelocityFormat = this.linearVelocityFormat;
    serializationObject.linearVelocityType = this.linearVelocityType;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.depthTest = serializationObject.depthTest;
    this.depthWrite = serializationObject.depthWrite;
    this.samples = serializationObject.samples;
    this.reverseCulling = serializationObject.reverseCulling;
    this.dontRenderWhenMaterialDepthWriteIsDisabled = serializationObject.dontRenderWhenMaterialDepthWriteIsDisabled;
    this.viewDepthFormat = serializationObject.viewDepthFormat;
    this.viewDepthType = serializationObject.viewDepthType;
    this.screenDepthFormat = serializationObject.screenDepthFormat;
    this.screenDepthType = serializationObject.screenDepthType;
    this.localPositionFormat = serializationObject.localPositionFormat;
    this.localPositionType = serializationObject.localPositionType;
    this.worldPositionFormat = serializationObject.worldPositionFormat;
    this.worldPositionType = serializationObject.worldPositionType;
    this.viewNormalFormat = serializationObject.viewNormalFormat;
    this.viewNormalType = serializationObject.viewNormalType;
    this.worldNormalFormat = serializationObject.worldNormalFormat;
    this.worldNormalType = serializationObject.worldNormalType;
    this.albedoFormat = serializationObject.albedoFormat;
    this.albedoType = serializationObject.albedoType;
    this.reflectivityFormat = serializationObject.reflectivityFormat;
    this.reflectivityType = serializationObject.reflectivityType;
    this.velocityFormat = serializationObject.velocityFormat;
    this.velocityType = serializationObject.velocityType;
    this.linearVelocityFormat = serializationObject.linearVelocityFormat;
    this.linearVelocityType = serializationObject.linearVelocityType;
  }
}
__decorate([
  editableInPropertyPage("Depth test", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "depthTest", null);
__decorate([
  editableInPropertyPage("Depth write", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "depthWrite", null);
__decorate([
  editableInPropertyPage("Do not change aspect ratio", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "doNotChangeAspectRatio", null);
__decorate([
  editableInPropertyPage("Texture width", 2, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "width", null);
__decorate([
  editableInPropertyPage("Texture height", 2, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "height", null);
__decorate([
  editableInPropertyPage("Size is in percentage", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "sizeInPercentage", null);
__decorate([
  editableInPropertyPage("Samples", 2, "PROPERTIES", { min: 1, max: 8 })
], NodeRenderGraphGeometryRendererBlock.prototype, "samples", null);
__decorate([
  editableInPropertyPage("Reverse culling", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "reverseCulling", null);
__decorate([
  editableInPropertyPage("Don't render if material depth write is disabled", 0, "PROPERTIES")
], NodeRenderGraphGeometryRendererBlock.prototype, "dontRenderWhenMaterialDepthWriteIsDisabled", null);
__decorate([
  editableInPropertyPage("View depth format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "viewDepthFormat", undefined);
__decorate([
  editableInPropertyPage("View depth type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "viewDepthType", undefined);
__decorate([
  editableInPropertyPage("Screen depth format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "screenDepthFormat", undefined);
__decorate([
  editableInPropertyPage("Screen depth type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "screenDepthType", undefined);
__decorate([
  editableInPropertyPage("View normal format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "viewNormalFormat", undefined);
__decorate([
  editableInPropertyPage("View normal type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "viewNormalType", undefined);
__decorate([
  editableInPropertyPage("World normal format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "worldNormalFormat", undefined);
__decorate([
  editableInPropertyPage("World normal type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "worldNormalType", undefined);
__decorate([
  editableInPropertyPage("Local position format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "localPositionFormat", undefined);
__decorate([
  editableInPropertyPage("Local position type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "localPositionType", undefined);
__decorate([
  editableInPropertyPage("World position format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "worldPositionFormat", undefined);
__decorate([
  editableInPropertyPage("World position type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "worldPositionType", undefined);
__decorate([
  editableInPropertyPage("Albedo format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "albedoFormat", undefined);
__decorate([
  editableInPropertyPage("Albedo type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "albedoType", undefined);
__decorate([
  editableInPropertyPage("Reflectivity format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "reflectivityFormat", undefined);
__decorate([
  editableInPropertyPage("Reflectivity type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "reflectivityType", undefined);
__decorate([
  editableInPropertyPage("Velocity format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "velocityFormat", undefined);
__decorate([
  editableInPropertyPage("Velocity type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "velocityType", undefined);
__decorate([
  editableInPropertyPage("Linear velocity format", 7, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "linearVelocityFormat", undefined);
__decorate([
  editableInPropertyPage("Linear velocity type", 8, "GEOMETRY BUFFERS")
], NodeRenderGraphGeometryRendererBlock.prototype, "linearVelocityType", undefined);
RegisterClass("BABYLON.NodeRenderGraphGeometryRendererBlock", NodeRenderGraphGeometryRendererBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/shadowGeneratorBlock.js
init_typeStore();
class NodeRenderGraphShadowGeneratorBlock extends NodeRenderGraphBaseShadowGeneratorBlock {
  constructor(name235, frameGraph, scene) {
    super(name235, frameGraph, scene);
    this._frameGraphTask = new FrameGraphShadowGeneratorTask(this.name, frameGraph, scene);
  }
  getClassName() {
    return "NodeRenderGraphShadowGeneratorBlock";
  }
}
RegisterClass("BABYLON.NodeRenderGraphShadowGeneratorBlock", NodeRenderGraphShadowGeneratorBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/taaObjectRendererBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/Maths/halton2DSequence.js
class Halton2DSequence {
  constructor(numSamples, baseX = 2, baseY = 3, width = 1, height = 1) {
    this._curIndex = 0;
    this._sequence = [];
    this._numSamples = 0;
    this.x = 0;
    this.y = 0;
    this._width = width;
    this._height = height;
    this._baseX = baseX;
    this._baseY = baseY;
    this._generateSequence(numSamples);
    this.next();
  }
  regenerate(numSamples) {
    this._generateSequence(numSamples);
    this.next();
  }
  setDimensions(width, height) {
    this._width = width;
    this._height = height;
  }
  next() {
    this.x = this._sequence[this._curIndex] / this._width;
    this.y = this._sequence[this._curIndex + 1] / this._height;
    this._curIndex += 2;
    if (this._curIndex >= this._numSamples * 2) {
      this._curIndex = 0;
    }
  }
  _generateSequence(numSamples) {
    this._sequence = [];
    this._curIndex = 0;
    this._numSamples = numSamples;
    for (let i = 1;i <= numSamples; ++i) {
      this._sequence.push(this._halton(i, this._baseX) - 0.5, this._halton(i, this._baseY) - 0.5);
    }
  }
  _halton(index, base) {
    let fraction = 1;
    let result = 0;
    while (index > 0) {
      fraction /= base;
      result += fraction * (index % base);
      index = ~~(index / base);
    }
    return result;
  }
}

// node_modules/@babylonjs/core/PostProcesses/thinTAAPostProcess.js
init_engine();
init_effectRenderer();

class ThinTAAPostProcess extends EffectWrapper {
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_taa_fragment(), exports_taa_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_taa_fragment2(), exports_taa_fragment2)));
    }
  }
  set samples(samples) {
    if (this._samples === samples) {
      return;
    }
    this._samples = samples;
    this._hs.regenerate(samples);
  }
  get samples() {
    return this._samples;
  }
  get disabled() {
    return this._disabled;
  }
  set disabled(value) {
    if (this._disabled === value) {
      return;
    }
    this._disabled = value;
    this._reset();
  }
  get textureWidth() {
    return this._textureWidth;
  }
  set textureWidth(width) {
    if (this._textureWidth === width) {
      return;
    }
    this._textureWidth = width;
    this._reset();
  }
  get textureHeight() {
    return this._textureHeight;
  }
  set textureHeight(height) {
    if (this._textureHeight === height) {
      return;
    }
    this._textureHeight = height;
    this._reset();
  }
  constructor(name237, engine2 = null, options) {
    super({
      ...options,
      name: name237,
      engine: engine2 || Engine.LastCreatedEngine,
      useShaderStore: true,
      useAsPostProcess: true,
      fragmentShader: ThinTAAPostProcess.FragmentUrl,
      uniforms: ThinTAAPostProcess.Uniforms,
      samplers: ThinTAAPostProcess.Samplers
    });
    this._samples = 8;
    this.factor = 0.05;
    this._disabled = false;
    this._textureWidth = 0;
    this._textureHeight = 0;
    this.disableOnCameraMove = true;
    this._firstUpdate = true;
    this._hs = new Halton2DSequence(this.samples);
  }
  _reset() {
    this._hs.setDimensions(this._textureWidth / 2, this._textureHeight / 2);
    this._hs.next();
    this._firstUpdate = true;
  }
  updateProjectionMatrix() {
    if (this.disabled) {
      return;
    }
    if (this.camera && !this.camera.hasMoved) {
      if (this.camera.mode === Camera.PERSPECTIVE_CAMERA) {
        const projMat = this.camera.getProjectionMatrix();
        projMat.setRowFromFloats(2, this._hs.x, this._hs.y, projMat.m[10], projMat.m[11]);
      } else {
        const projMat = this.camera.getProjectionMatrix(true);
        projMat.setRowFromFloats(3, this._hs.x + projMat.m[12], this._hs.y + projMat.m[13], projMat.m[14], projMat.m[15]);
      }
    }
    this._hs.next();
  }
  bind() {
    super.bind();
    if (this.disabled) {
      return;
    }
    const effect = this._drawWrapper.effect;
    effect.setFloat("factor", this.camera?.hasMoved && this.disableOnCameraMove || this._firstUpdate ? 1 : this.factor);
    this._firstUpdate = false;
  }
}
ThinTAAPostProcess.FragmentUrl = "taa";
ThinTAAPostProcess.Uniforms = ["factor"];
ThinTAAPostProcess.Samplers = ["historySampler"];

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/taaObjectRendererTask.js
class FrameGraphTAAObjectRendererTask extends FrameGraphObjectRendererTask {
  constructor(name237, frameGraph, scene, options) {
    super(name237, frameGraph, scene, options);
    this.postProcess = new ThinTAAPostProcess(`${name237} post-process`, scene.getEngine());
    this._postProcessDrawWrapper = this.postProcess.drawWrapper;
  }
  record() {
    if (this.targetTexture === undefined || this.objectList === undefined) {
      throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: destinationTexture and objectList are required`);
    }
    if (this.targetTexture === backbufferColorTextureHandle || this.depthTexture === backbufferDepthStencilTextureHandle) {
      throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the back buffer color/depth textures are not allowed. Use regular textures instead.`);
    }
    this._renderer.renderList = this.objectList.meshes;
    this._renderer.particleSystemList = this.objectList.particleSystems;
    const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture);
    let depthEnabled = false;
    if (this.depthTexture !== undefined) {
      const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture);
      if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) {
        throw new Error(`FrameGraphTAAObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`);
      }
      depthEnabled = true;
    }
    this.postProcess.camera = this.camera;
    this.postProcess.textureWidth = outputTextureDescription.size.width;
    this.postProcess.textureHeight = outputTextureDescription.size.height;
    const textureCreationOptions = {
      size: outputTextureDescription.size,
      options: {
        createMipMaps: outputTextureDescription.options.createMipMaps,
        types: [2],
        formats: [5],
        samples: 1,
        useSRGBBuffers: [false],
        creationFlags: [0],
        labels: [""]
      },
      sizeIsPercentage: false,
      isHistoryTexture: true
    };
    const pingPongHandle = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} history`, textureCreationOptions);
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, pingPongHandle);
    if (this.depthTexture !== undefined) {
      this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture);
    }
    this._textureWidth = outputTextureDescription.size.width;
    this._textureHeight = outputTextureDescription.size.height;
    let pingPongRenderTargetWrapper;
    this._setLightsForShadow();
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(this.targetTexture);
    pass.setRenderTargetDepth(this.depthTexture);
    pass.setExecuteFunc((context) => {
      this._renderer.renderList = this.objectList.meshes;
      this._renderer.particleSystemList = this.objectList.particleSystems;
      this._renderer.renderInLinearSpace = this.renderInLinearSpace;
      this.postProcess.updateProjectionMatrix();
      context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled);
      if (!this.postProcess.disabled) {
        this._scene.activeCamera = this.camera;
        this._scene.setTransformMatrix(this.camera.getViewMatrix(), this.camera.getProjectionMatrix());
      }
      context.render(this._renderer, this._textureWidth, this._textureHeight);
      this._scene.activeCamera = null;
      pingPongRenderTargetWrapper = pingPongRenderTargetWrapper || context.createRenderTarget(`${this.name} ping/pong`, pingPongHandle);
      context.bindRenderTarget(pingPongRenderTargetWrapper, "frame graph - TAA merge with history texture");
      if (!this.postProcess.disabled) {
        context.applyFullScreenEffect(this._postProcessDrawWrapper, () => {
          this.postProcess.bind();
          context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.targetTexture);
          context.bindTextureHandle(this._postProcessDrawWrapper.effect, "historySampler", pingPongHandle);
        });
      } else {
        context.copyTexture(this.targetTexture);
      }
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setRenderTargetDepth(this.depthTexture);
    passDisabled.setExecuteFunc((context) => {
      context.copyTexture(this.targetTexture);
    });
    return pass;
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/taaObjectRendererBlock.js
class NodeRenderGraphTAAObjectRendererBlock extends NodeRenderGraphBaseObjectRendererBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name237, frameGraph, scene, doNotChangeAspectRatio = true) {
    super(name237, frameGraph, scene);
    this._additionalConstructionParameters = [doNotChangeAspectRatio];
    this._frameGraphTask = new FrameGraphTAAObjectRendererTask(this.name, frameGraph, scene, { doNotChangeAspectRatio });
  }
  get doNotChangeAspectRatio() {
    return this._frameGraphTask.objectRenderer.options.doNotChangeAspectRatio;
  }
  set doNotChangeAspectRatio(value) {
    const disabled = this._frameGraphTask.disabled;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphTAAObjectRendererTask(this.name, this._frameGraph, this._scene, { doNotChangeAspectRatio: value });
    this._additionalConstructionParameters = [value];
    this._frameGraphTask.disabled = disabled;
  }
  get samples() {
    return this._frameGraphTask.postProcess.samples;
  }
  set samples(value) {
    this._frameGraphTask.postProcess.samples = value;
  }
  get factor() {
    return this._frameGraphTask.postProcess.factor;
  }
  set factor(value) {
    this._frameGraphTask.postProcess.factor = value;
  }
  get disableOnCameraMove() {
    return this._frameGraphTask.postProcess.disableOnCameraMove;
  }
  set disableOnCameraMove(value) {
    this._frameGraphTask.postProcess.disableOnCameraMove = value;
  }
  get disableTAA() {
    return this._frameGraphTask.postProcess.disabled;
  }
  set disableTAA(value) {
    this._frameGraphTask.postProcess.disabled = value;
  }
  getClassName() {
    return "NodeRenderGraphTAAObjectRendererBlock";
  }
  _dumpPropertiesCode() {
    const codes = [];
    codes.push(`${this._codeVariableName}.doNotChangeAspectRatio = ${this.doNotChangeAspectRatio};`);
    codes.push(`${this._codeVariableName}.samples = ${this.samples};`);
    codes.push(`${this._codeVariableName}.factor = ${this.factor};`);
    codes.push(`${this._codeVariableName}.disableOnCameraMove = ${this.disableOnCameraMove};`);
    codes.push(`${this._codeVariableName}.disableTAA = ${this.disableTAA};`);
    return super._dumpPropertiesCode() + codes.join(`
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.doNotChangeAspectRatio = this.doNotChangeAspectRatio;
    serializationObject.samples = this.samples;
    serializationObject.factor = this.factor;
    serializationObject.disableOnCameraMove = this.disableOnCameraMove;
    serializationObject.disableTAA = this.disableTAA;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.doNotChangeAspectRatio = serializationObject.doNotChangeAspectRatio;
    this.samples = serializationObject.samples;
    this.factor = serializationObject.factor;
    this.disableOnCameraMove = serializationObject.disableOnCameraMove;
    this.disableTAA = serializationObject.disableTAA;
  }
}
__decorate([
  editableInPropertyPage("Do not change aspect ratio", 0, "PROPERTIES")
], NodeRenderGraphTAAObjectRendererBlock.prototype, "doNotChangeAspectRatio", null);
__decorate([
  editableInPropertyPage("Samples", 2, "TEMPORAL ANTI-ALIASING")
], NodeRenderGraphTAAObjectRendererBlock.prototype, "samples", null);
__decorate([
  editableInPropertyPage("Factor", 1, "TEMPORAL ANTI-ALIASING")
], NodeRenderGraphTAAObjectRendererBlock.prototype, "factor", null);
__decorate([
  editableInPropertyPage("Disable on camera move", 0, "TEMPORAL ANTI-ALIASING")
], NodeRenderGraphTAAObjectRendererBlock.prototype, "disableOnCameraMove", null);
__decorate([
  editableInPropertyPage("Disable TAA", 0, "TEMPORAL ANTI-ALIASING")
], NodeRenderGraphTAAObjectRendererBlock.prototype, "disableTAA", null);
RegisterClass("BABYLON.NodeRenderGraphTAAObjectRendererBlock", NodeRenderGraphTAAObjectRendererBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/utilityLayerRendererBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/utilityLayerRendererTask.js
class FrameGraphUtilityLayerRendererTask extends FrameGraphTask {
  constructor(name237, frameGraph, scene, handleEvents = true) {
    super(name237, frameGraph);
    this.layer = new UtilityLayerRenderer(scene, handleEvents, true);
    this.layer.utilityLayerScene._useCurrentFrameBuffer = true;
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  record() {
    if (!this.targetTexture || !this.camera) {
      throw new Error("FrameGraphUtilityLayerRendererTask: targetTexture and camera are required");
    }
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(this.outputTexture);
    pass.setExecuteFunc((context) => {
      this.layer.setRenderCamera(this.camera);
      context.render(this.layer);
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((_context) => {});
  }
  dispose() {
    this.layer.dispose();
    super.dispose();
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Rendering/utilityLayerRendererBlock.js
class NodeRenderGraphUtilityLayerRendererBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name237, frameGraph, scene, handleEvents = true) {
    super(name237, frameGraph, scene);
    this._additionalConstructionParameters = [handleEvents];
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("camera", NodeRenderGraphBlockConnectionPointTypes.Camera);
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll);
    this.output._typeConnectionSource = this.target;
    this._frameGraphTask = new FrameGraphUtilityLayerRendererTask(name237, frameGraph, scene, handleEvents);
  }
  _createTask(handleEvents) {
    const disabled = this._frameGraphTask.disabled;
    this._frameGraphTask.dispose();
    this._frameGraphTask = new FrameGraphUtilityLayerRendererTask(this.name, this._frameGraph, this._scene, handleEvents);
    this._additionalConstructionParameters = [handleEvents];
    this._frameGraphTask.disabled = disabled;
  }
  get handleEvents() {
    return this._frameGraphTask.layer.handleEvents;
  }
  set handleEvents(value) {
    this._createTask(value);
  }
  getClassName() {
    return "NodeRenderGraphUtilityLayerRendererBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get camera() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
    this._frameGraphTask.camera = this.camera.connectedPoint?.value;
  }
}
__decorate([
  editableInPropertyPage("Handle events", 0, "PROPERTIES")
], NodeRenderGraphUtilityLayerRendererBlock.prototype, "handleEvents", null);
RegisterClass("BABYLON.NodeRenderGraphUtilityLayerRendererBlock", NodeRenderGraphUtilityLayerRendererBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Teleport/teleportInBlock.js
init_typeStore();
class NodeRenderGraphTeleportInBlock extends NodeRenderGraphBlock {
  get endpoints() {
    return this._endpoints;
  }
  constructor(name237, frameGraph, scene) {
    super(name237, frameGraph, scene);
    this._endpoints = [];
    this._isTeleportIn = true;
    this.registerInput("input", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
  }
  getClassName() {
    return "NodeRenderGraphTeleportInBlock";
  }
  get input() {
    return this._inputs[0];
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = super._dumpCode(uniqueNames, alreadyDumped);
    for (const endpoint of this.endpoints) {
      if (alreadyDumped.indexOf(endpoint) === -1) {
        codeString += endpoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString;
  }
  isAnAncestorOfType(type) {
    if (this.getClassName() === type) {
      return true;
    }
    for (const endpoint of this.endpoints) {
      if (endpoint.isAnAncestorOfType(type)) {
        return true;
      }
    }
    return false;
  }
  isAnAncestorOf(block) {
    for (const endpoint of this.endpoints) {
      if (endpoint === block) {
        return true;
      }
      if (endpoint.isAnAncestorOf(block)) {
        return true;
      }
    }
    return false;
  }
  getDescendantOfPredicate(predicate) {
    if (predicate(this)) {
      return this;
    }
    for (const endpoint of this.endpoints) {
      const descendant = endpoint.getDescendantOfPredicate(predicate);
      if (descendant) {
        return descendant;
      }
    }
    return null;
  }
  attachToEndpoint(endpoint) {
    endpoint.detach();
    this._endpoints.push(endpoint);
    endpoint._entryPoint = this;
    endpoint._outputs[0]._typeConnectionSource = this._inputs[0];
    endpoint._tempEntryPointUniqueId = null;
    endpoint.name = "> " + this.name;
  }
  detachFromEndpoint(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index !== -1) {
      this._endpoints.splice(index, 1);
      endpoint._outputs[0]._typeConnectionSource = null;
      endpoint._entryPoint = null;
    }
  }
  dispose() {
    super.dispose();
    for (const endpoint of this._endpoints) {
      this.detachFromEndpoint(endpoint);
    }
    this._endpoints = [];
  }
}
RegisterClass("BABYLON.NodeRenderGraphTeleportInBlock", NodeRenderGraphTeleportInBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Teleport/teleportOutBlock.js
init_typeStore();
class NodeRenderGraphTeleportOutBlock extends NodeRenderGraphBlock {
  constructor(name237, frameGraph, scene) {
    super(name237, frameGraph, scene);
    this._entryPoint = null;
    this._tempEntryPointUniqueId = null;
    this._isTeleportOut = true;
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
  }
  get entryPoint() {
    return this._entryPoint;
  }
  getClassName() {
    return "NodeRenderGraphTeleportOutBlock";
  }
  get output() {
    return this._outputs[0];
  }
  detach() {
    if (!this._entryPoint) {
      return;
    }
    this._entryPoint.detachFromEndpoint(this);
  }
  _buildBlock() {}
  _customBuildStep(state) {
    if (this.entryPoint) {
      this.entryPoint.build(state);
    }
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = "";
    if (this.entryPoint) {
      if (alreadyDumped.indexOf(this.entryPoint) === -1) {
        codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString + super._dumpCode(uniqueNames, alreadyDumped);
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = super._dumpCodeForOutputConnections(alreadyDumped);
    if (this.entryPoint) {
      codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped);
    }
    return codeString;
  }
  clone() {
    const clone = super.clone();
    if (this.entryPoint) {
      this.entryPoint.attachToEndpoint(clone);
    }
    return clone;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (this.entryPoint) {
      codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});
`;
    }
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.entryPoint = this.entryPoint?.uniqueId ?? "";
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this._tempEntryPointUniqueId = serializationObject.entryPoint;
  }
}
RegisterClass("BABYLON.NodeRenderGraphTeleportOutBlock", NodeRenderGraphTeleportOutBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/copyTextureBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Texture/copyToTextureTask.js
class FrameGraphCopyToTextureTask extends FrameGraphTask {
  constructor(name237, frameGraph) {
    super(name237, frameGraph);
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  record() {
    if (this.sourceTexture === undefined || this.targetTexture === undefined) {
      throw new Error(`FrameGraphCopyToTextureTask "${this.name}": sourceTexture and targetTexture are required`);
    }
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.addDependencies(this.sourceTexture);
    pass.setRenderTarget(this.outputTexture);
    pass.setExecuteFunc((context) => {
      context.copyTexture(this.sourceTexture);
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((_context) => {});
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/copyTextureBlock.js
class NodeRenderGraphCopyTextureBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name237, frameGraph, scene) {
    super(name237, frameGraph, scene);
    this.registerInput("source", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.source.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAll);
    this.output._typeConnectionSource = this.target;
    this._frameGraphTask = new FrameGraphCopyToTextureTask(name237, frameGraph);
  }
  getClassName() {
    return "NodeRenderGraphCopyTextureBlock";
  }
  get source() {
    return this._inputs[0];
  }
  get target() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output.value = this._frameGraphTask.outputTexture;
    this._frameGraphTask.sourceTexture = this.source.connectedPoint?.value;
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
  }
}
RegisterClass("BABYLON.NodeRenderGraphCopyTextureBlock", NodeRenderGraphCopyTextureBlock);
// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/generateMipmapsBlock.js
init_typeStore();

// node_modules/@babylonjs/core/FrameGraph/Tasks/Texture/generateMipMapsTask.js
class FrameGraphGenerateMipMapsTask extends FrameGraphTask {
  constructor(name237, frameGraph) {
    super(name237, frameGraph);
    this.outputTexture = this._frameGraph.textureManager.createDanglingHandle();
  }
  record() {
    if (this.targetTexture === undefined) {
      throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: targetTexture is required`);
    }
    this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture);
    const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.targetTexture);
    if (!outputTextureDescription.options.createMipMaps) {
      throw new Error(`FrameGraphGenerateMipMapsTask ${this.name}: targetTexture must have createMipMaps set to true`);
    }
    const pass = this._frameGraph.addRenderPass(this.name);
    pass.setRenderTarget(this.outputTexture);
    pass.setExecuteFunc((context) => {
      context.generateMipMaps();
    });
    const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true);
    passDisabled.setRenderTarget(this.outputTexture);
    passDisabled.setExecuteFunc((_context) => {});
  }
}

// node_modules/@babylonjs/core/FrameGraph/Node/Blocks/Textures/generateMipmapsBlock.js
class NodeRenderGraphGenerateMipmapsBlock extends NodeRenderGraphBlock {
  get task() {
    return this._frameGraphTask;
  }
  constructor(name237, frameGraph, scene) {
    super(name237, frameGraph, scene);
    this.registerInput("target", NodeRenderGraphBlockConnectionPointTypes.AutoDetect);
    this._addDependenciesInput();
    this.registerOutput("output", NodeRenderGraphBlockConnectionPointTypes.BasedOnInput);
    this.target.addExcludedConnectionPointFromAllowedTypes(NodeRenderGraphBlockConnectionPointTypes.TextureAllButBackBuffer);
    this.output._typeConnectionSource = this.target;
    this._frameGraphTask = new FrameGraphGenerateMipMapsTask(name237, frameGraph);
  }
  getClassName() {
    return "NodeRenderGraphGenerateMipmapsBlock";
  }
  get target() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._propagateInputValueToOutput(this.target, this.output);
    this._frameGraphTask.targetTexture = this.target.connectedPoint?.value;
  }
}
RegisterClass("BABYLON.NodeRenderGraphGenerateMipmapsBlock", NodeRenderGraphGenerateMipmapsBlock);
// node_modules/@babylonjs/core/Gizmos/axisScaleGizmo.js
init_observable();
init_math_vector();
init_math_color();
init_math_constants();

class AxisScaleGizmo extends Gizmo {
  get coloredMaterial() {
    return this._coloredMaterial;
  }
  get hoverMaterial() {
    return this._hoverMaterial;
  }
  get disableMaterial() {
    return this._disableMaterial;
  }
  constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1, hoverColor = Color3.Yellow(), disableColor = Color3.Gray()) {
    super(gizmoLayer);
    this._pointerObserver = null;
    this.snapDistance = 0;
    this.onSnapObservable = new Observable;
    this.uniformScaling = false;
    this.sensitivity = 1;
    this.dragScale = 1;
    this.incrementalSnap = false;
    this._isEnabled = true;
    this._parent = null;
    this._dragging = false;
    this._tmpVector = new Vector3(0, 0, 0);
    this._incrementalStartupValue = Vector3.Zero();
    this._parent = parent;
    this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._coloredMaterial.diffuseColor = color;
    this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));
    this._hoverMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._hoverMaterial.diffuseColor = hoverColor;
    this._disableMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._disableMaterial.diffuseColor = disableColor;
    this._disableMaterial.alpha = 0.4;
    this._gizmoMesh = new Mesh("axis", gizmoLayer.utilityLayerScene);
    const { arrowMesh, arrowTail } = this._createGizmoMesh(this._gizmoMesh, thickness);
    const collider2 = this._createGizmoMesh(this._gizmoMesh, thickness + 4, true);
    this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis));
    this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);
    this._gizmoMesh.scaling.scaleInPlace(1 / 3);
    const nodePosition = arrowMesh.position.clone();
    const linePosition = arrowTail.position.clone();
    const lineScale = arrowTail.scaling.clone();
    const increaseGizmoMesh = (dragDistance) => {
      const dragStrength = dragDistance * (3 / this._rootMesh.scaling.length()) * 6;
      arrowMesh.position.z += dragStrength / 3.5;
      arrowTail.scaling.y += dragStrength;
      this.dragScale = arrowTail.scaling.y;
      arrowTail.position.z = arrowMesh.position.z / 2;
    };
    const resetGizmoMesh = () => {
      arrowMesh.position.set(nodePosition.x, nodePosition.y, nodePosition.z);
      arrowTail.position.set(linePosition.x, linePosition.y, linePosition.z);
      arrowTail.scaling.set(lineScale.x, lineScale.y, lineScale.z);
      this.dragScale = arrowTail.scaling.y;
      this._dragging = false;
    };
    this.dragBehavior = new PointerDragBehavior({ dragAxis });
    this.dragBehavior.moveAttached = false;
    this.dragBehavior.updateDragPlane = false;
    this._rootMesh.addBehavior(this.dragBehavior);
    let currentSnapDragDistance = 0;
    let currentSnapDragDistanceIncremental = 0;
    const tmpSnapEvent = { snapDistance: 0 };
    this.dragBehavior.onDragObservable.add((event) => {
      if (this.attachedNode) {
        const dragStrength = this.sensitivity * event.dragDistance * (this.scaleRatio * 3 / this._rootMesh.scaling.length());
        const tmpVector = this._tmpVector;
        let snapped = false;
        let dragSteps = 0;
        if (this.uniformScaling) {
          tmpVector.setAll(0.57735);
        } else {
          tmpVector.copyFrom(dragAxis);
        }
        if (this.snapDistance == 0) {
          tmpVector.scaleToRef(dragStrength, tmpVector);
        } else {
          currentSnapDragDistance += dragStrength;
          currentSnapDragDistanceIncremental += dragStrength;
          const currentSnap = this.incrementalSnap ? currentSnapDragDistanceIncremental : currentSnapDragDistance;
          if (Math.abs(currentSnap) > this.snapDistance) {
            dragSteps = Math.floor(Math.abs(currentSnap) / this.snapDistance);
            if (currentSnap < 0) {
              dragSteps *= -1;
            }
            currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;
            tmpVector.scaleToRef(this.snapDistance * dragSteps, tmpVector);
            snapped = true;
          } else {
            tmpVector.scaleInPlace(0);
          }
        }
        tmpVector.addInPlaceFromFloats(1, 1, 1);
        tmpVector.x = Math.abs(tmpVector.x) < AxisScaleGizmo.MinimumAbsoluteScale ? AxisScaleGizmo.MinimumAbsoluteScale * (tmpVector.x < 0 ? -1 : 1) : tmpVector.x;
        tmpVector.y = Math.abs(tmpVector.y) < AxisScaleGizmo.MinimumAbsoluteScale ? AxisScaleGizmo.MinimumAbsoluteScale * (tmpVector.y < 0 ? -1 : 1) : tmpVector.y;
        tmpVector.z = Math.abs(tmpVector.z) < AxisScaleGizmo.MinimumAbsoluteScale ? AxisScaleGizmo.MinimumAbsoluteScale * (tmpVector.z < 0 ? -1 : 1) : tmpVector.z;
        const transformNode = this.attachedNode._isMesh ? this.attachedNode : undefined;
        if (Math.abs(this.snapDistance) > 0 && this.incrementalSnap) {
          this.attachedNode.getWorldMatrix().decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[2], Gizmo.PreserveScaling ? transformNode : undefined);
          tmpVector.addInPlace(this._incrementalStartupValue);
          tmpVector.addInPlaceFromFloats(-1, -1, -1);
          tmpVector.x = Math.abs(tmpVector.x) * (this._incrementalStartupValue.x > 0 ? 1 : -1);
          tmpVector.y = Math.abs(tmpVector.y) * (this._incrementalStartupValue.y > 0 ? 1 : -1);
          tmpVector.z = Math.abs(tmpVector.z) * (this._incrementalStartupValue.z > 0 ? 1 : -1);
          Matrix.ComposeToRef(tmpVector, TmpVectors.Quaternion[0], TmpVectors.Vector3[2], TmpVectors.Matrix[1]);
        } else {
          Matrix.ScalingToRef(tmpVector.x, tmpVector.y, tmpVector.z, TmpVectors.Matrix[2]);
          TmpVectors.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(), TmpVectors.Matrix[1]);
        }
        TmpVectors.Matrix[1].decompose(TmpVectors.Vector3[1], undefined, undefined, Gizmo.PreserveScaling ? transformNode : undefined);
        const maxScale = 1e5;
        if (Math.abs(TmpVectors.Vector3[1].x) < maxScale && Math.abs(TmpVectors.Vector3[1].y) < maxScale && Math.abs(TmpVectors.Vector3[1].z) < maxScale) {
          this.attachedNode.getWorldMatrix().copyFrom(TmpVectors.Matrix[1]);
        }
        if (snapped) {
          tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;
          this.onSnapObservable.notifyObservers(tmpSnapEvent);
        }
        this._matrixChanged();
      }
    });
    this.dragBehavior.onDragStartObservable.add(() => {
      this._dragging = true;
      const transformNode = this.attachedNode._isMesh ? this.attachedNode : undefined;
      this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue, undefined, undefined, Gizmo.PreserveScaling ? transformNode : undefined);
      currentSnapDragDistance = 0;
      currentSnapDragDistanceIncremental = 0;
    });
    this.dragBehavior.onDragObservable.add((e) => increaseGizmoMesh(e.dragDistance));
    this.dragBehavior.onDragEndObservable.add(resetGizmoMesh);
    parent?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e) => increaseGizmoMesh(e.delta.y));
    parent?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(resetGizmoMesh);
    const cache = {
      gizmoMeshes: [arrowMesh, arrowTail],
      colliderMeshes: [collider2.arrowMesh, collider2.arrowTail],
      material: this._coloredMaterial,
      hoverMaterial: this._hoverMaterial,
      disableMaterial: this._disableMaterial,
      active: false,
      dragBehavior: this.dragBehavior
    };
    this._parent?.addToAxisCache(this._gizmoMesh, cache);
    this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
      if (this._customMeshSet) {
        return;
      }
      let meshCache = this._parent?.getAxisCache(this._gizmoMesh);
      this._isHovered = !!meshCache && !!(meshCache.colliderMeshes.indexOf(pointerInfo?.pickInfo?.pickedMesh) != -1);
      meshCache = this._parent?.getAxisCache(this._rootMesh);
      this._isHovered || (this._isHovered = !!meshCache && !!(meshCache.colliderMeshes.indexOf(pointerInfo?.pickInfo?.pickedMesh) != -1));
      if (!this._parent) {
        const material = this.dragBehavior.enabled ? this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial : this._disableMaterial;
        this._setGizmoMeshMaterial(cache.gizmoMeshes, material);
      }
    });
    this.dragBehavior.onEnabledObservable.add((newState) => {
      this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);
    });
    const light = gizmoLayer._getSharedGizmoLight();
    light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes());
  }
  _createGizmoMesh(parentMesh, thickness, isCollider = false) {
    const arrowMesh = CreateBox("yPosMesh", { size: 0.4 * (1 + (thickness - 1) / 4) }, this.gizmoLayer.utilityLayerScene);
    const arrowTail = CreateCylinder("cylinder", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, this.gizmoLayer.utilityLayerScene);
    arrowMesh.scaling.scaleInPlace(0.1);
    arrowMesh.material = this._coloredMaterial;
    arrowMesh.rotation.x = Math.PI / 2;
    arrowMesh.position.z += 0.3;
    arrowTail.material = this._coloredMaterial;
    arrowTail.position.z += 0.275 / 2;
    arrowTail.rotation.x = Math.PI / 2;
    if (isCollider) {
      arrowMesh.visibility = 0;
      arrowTail.visibility = 0;
    }
    parentMesh.addChild(arrowMesh);
    parentMesh.addChild(arrowTail);
    return { arrowMesh, arrowTail };
  }
  _attachedNodeChanged(value) {
    if (this.dragBehavior) {
      this.dragBehavior.enabled = value ? true : false;
    }
  }
  set isEnabled(value) {
    this._isEnabled = value;
    if (!value) {
      this.attachedMesh = null;
      this.attachedNode = null;
    } else {
      if (this._parent) {
        this.attachedMesh = this._parent.attachedMesh;
        this.attachedNode = this._parent.attachedNode;
      }
    }
  }
  get isEnabled() {
    return this._isEnabled;
  }
  dispose() {
    this.onSnapObservable.clear();
    this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
    this.dragBehavior.detach();
    if (this._gizmoMesh) {
      this._gizmoMesh.dispose();
    }
    [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {
      if (matl) {
        matl.dispose();
      }
    });
    super.dispose();
  }
  setCustomMesh(mesh, useGizmoMaterial = false) {
    super.setCustomMesh(mesh);
    if (useGizmoMaterial) {
      this._rootMesh.getChildMeshes().forEach((m) => {
        m.material = this._coloredMaterial;
        if (m.color) {
          m.color = this._coloredMaterial.diffuseColor;
        }
      });
      this._customMeshSet = false;
    }
  }
}
AxisScaleGizmo.MinimumAbsoluteScale = Epsilon;
// node_modules/@babylonjs/core/Gizmos/boundingBoxGizmo.js
init_observable();
init_logger();
init_math_vector();
init_math_color();
init_math_constants();
var DragOperation;
(function(DragOperation2) {
  DragOperation2[DragOperation2["Rotation"] = 0] = "Rotation";
  DragOperation2[DragOperation2["Scaling"] = 1] = "Scaling";
})(DragOperation || (DragOperation = {}));
// node_modules/@babylonjs/core/Gizmos/gizmoManager.js
init_observable();
init_pointerEvents();
init_math_color();

// node_modules/@babylonjs/core/Gizmos/rotationGizmo.js
init_logger();
init_observable();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Gizmos/planeRotationGizmo.js
init_observable();
init_math_vector();
init_math_color();
init_effect();
init_math_constants();
init_logger();

class PlaneRotationGizmo extends Gizmo {
  get coloredMaterial() {
    return this._coloredMaterial;
  }
  get hoverMaterial() {
    return this._hoverMaterial;
  }
  set rotationColor(color) {
    this._rotationShaderMaterial.setColor3("rotationColor", color);
  }
  get disableMaterial() {
    return this._disableMaterial;
  }
  constructor(planeNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, parent = null, useEulerRotation = false, thickness = 1, hoverColor = Color3.Yellow(), disableColor = Color3.Gray()) {
    super(gizmoLayer);
    this._pointerObserver = null;
    this.snapDistance = 0;
    this.onSnapObservable = new Observable;
    this.angle = 0;
    this.sensitivity = 1;
    this._isEnabled = true;
    this._parent = null;
    this._dragging = false;
    this._angles = new Vector3;
    this._parent = parent;
    this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._coloredMaterial.diffuseColor = color;
    this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));
    this._hoverMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._hoverMaterial.diffuseColor = hoverColor;
    this._hoverMaterial.specularColor = hoverColor;
    this._disableMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene);
    this._disableMaterial.diffuseColor = disableColor;
    this._disableMaterial.alpha = 0.4;
    this._gizmoMesh = new Mesh("", gizmoLayer.utilityLayerScene);
    const { rotationMesh, collider: collider2 } = this._createGizmoMesh(this._gizmoMesh, thickness, tessellation);
    this._rotationDisplayPlane = CreatePlane("rotationDisplay", {
      size: 0.6,
      updatable: false
    }, this.gizmoLayer.utilityLayerScene);
    this._rotationDisplayPlane.rotation.z = Math.PI * 0.5;
    this._rotationDisplayPlane.parent = this._gizmoMesh;
    this._rotationDisplayPlane.setEnabled(false);
    Effect.ShadersStore["rotationGizmoVertexShader"] = PlaneRotationGizmo._RotationGizmoVertexShader;
    Effect.ShadersStore["rotationGizmoFragmentShader"] = PlaneRotationGizmo._RotationGizmoFragmentShader;
    this._rotationShaderMaterial = new ShaderMaterial("shader", this.gizmoLayer.utilityLayerScene, {
      vertex: "rotationGizmo",
      fragment: "rotationGizmo"
    }, {
      attributes: ["position", "uv"],
      uniforms: ["worldViewProjection", "angles", "rotationColor"]
    });
    this._rotationShaderMaterial.backFaceCulling = false;
    this.rotationColor = hoverColor;
    this._rotationDisplayPlane.material = this._rotationShaderMaterial;
    this._rotationDisplayPlane.visibility = 0.999;
    this._gizmoMesh.lookAt(this._rootMesh.position.add(planeNormal));
    this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);
    this._gizmoMesh.scaling.scaleInPlace(1 / 3);
    this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: planeNormal });
    this.dragBehavior.moveAttached = false;
    this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;
    this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
    this._rootMesh.addBehavior(this.dragBehavior);
    const lastDragPosition = new Vector3;
    const rotationMatrix = new Matrix;
    const planeNormalTowardsCamera = new Vector3;
    let localPlaneNormalTowardsCamera = new Vector3;
    this.dragBehavior.onDragStartObservable.add((e) => {
      if (this.attachedNode) {
        lastDragPosition.copyFrom(e.dragPlanePoint);
        this._rotationDisplayPlane.setEnabled(true);
        this._rotationDisplayPlane.getWorldMatrix().invertToRef(rotationMatrix);
        Vector3.TransformCoordinatesToRef(e.dragPlanePoint, rotationMatrix, lastDragPosition);
        this._angles.x = Math.atan2(lastDragPosition.y, lastDragPosition.x) + Math.PI;
        this._angles.y = 0;
        this._angles.z = this.updateGizmoRotationToMatchAttachedMesh ? 1 : 0;
        this._dragging = true;
        lastDragPosition.copyFrom(e.dragPlanePoint);
        this._rotationShaderMaterial.setVector3("angles", this._angles);
        this.angle = 0;
      }
    });
    this.dragBehavior.onDragEndObservable.add(() => {
      this._dragging = false;
      this._rotationDisplayPlane.setEnabled(false);
    });
    const tmpSnapEvent = { snapDistance: 0 };
    let currentSnapDragDistance = 0;
    const tmpMatrix2 = new Matrix;
    const amountToRotate = new Quaternion;
    this.dragBehavior.onDragObservable.add((event) => {
      if (this.attachedNode) {
        const nodeScale = new Vector3(1, 1, 1);
        const nodeQuaternion = new Quaternion(0, 0, 0, 1);
        const nodeTranslation = new Vector3(0, 0, 0);
        const attachedNodeTransform = this._attachedNode;
        if (attachedNodeTransform && attachedNodeTransform.isUsingPivotMatrix && attachedNodeTransform.isUsingPivotMatrix() && attachedNodeTransform.position) {
          attachedNodeTransform.getWorldMatrix().setTranslation(attachedNodeTransform.position);
        }
        this.attachedNode.getWorldMatrix().decompose(nodeScale, nodeQuaternion, nodeTranslation);
        const uniformScaling = Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.y)) <= Epsilon && Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.z)) <= Epsilon;
        if (!uniformScaling && this.updateGizmoRotationToMatchAttachedMesh) {
          Logger.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");
          return;
        }
        nodeQuaternion.normalize();
        const nodeTranslationForOperation = this.updateGizmoPositionToMatchAttachedMesh ? nodeTranslation : this._rootMesh.absolutePosition;
        const newVector = event.dragPlanePoint.subtract(nodeTranslationForOperation).normalize();
        const originalVector = lastDragPosition.subtract(nodeTranslationForOperation).normalize();
        const cross = Vector3.Cross(newVector, originalVector);
        const dot = Vector3.Dot(newVector, originalVector);
        let angle = Math.atan2(cross.length(), dot) * this.sensitivity;
        planeNormalTowardsCamera.copyFrom(planeNormal);
        localPlaneNormalTowardsCamera.copyFrom(planeNormal);
        if (this.updateGizmoRotationToMatchAttachedMesh) {
          nodeQuaternion.toRotationMatrix(rotationMatrix);
          localPlaneNormalTowardsCamera = Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
        }
        let cameraFlipped = false;
        if (gizmoLayer.utilityLayerScene.activeCamera) {
          const camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(nodeTranslationForOperation).normalize();
          if (Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
            planeNormalTowardsCamera.scaleInPlace(-1);
            localPlaneNormalTowardsCamera.scaleInPlace(-1);
            cameraFlipped = true;
          }
        }
        const halfCircleSide = Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0;
        if (halfCircleSide) {
          angle = -angle;
        }
        TmpVectors.Vector3[0].set(angle, 0, 0);
        if (!this.dragBehavior.validateDrag(TmpVectors.Vector3[0])) {
          angle = 0;
        }
        let snapped = false;
        if (this.snapDistance != 0) {
          currentSnapDragDistance += angle;
          if (Math.abs(currentSnapDragDistance) > this.snapDistance) {
            let dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);
            if (currentSnapDragDistance < 0) {
              dragSteps *= -1;
            }
            currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;
            angle = this.snapDistance * dragSteps;
            snapped = true;
          } else {
            angle = 0;
          }
        }
        const quaternionCoefficient = Math.sin(angle / 2);
        amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
        if (tmpMatrix2.determinant() > 0) {
          const tmpVector = new Vector3;
          amountToRotate.toEulerAnglesToRef(tmpVector);
          Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
        }
        if (this.updateGizmoRotationToMatchAttachedMesh) {
          nodeQuaternion.multiplyToRef(amountToRotate, nodeQuaternion);
          nodeQuaternion.normalize();
          Matrix.ComposeToRef(nodeScale, nodeQuaternion, nodeTranslation, this.attachedNode.getWorldMatrix());
        } else {
          amountToRotate.toRotationMatrix(TmpVectors.Matrix[0]);
          const translation = this.attachedNode.getWorldMatrix().getTranslation();
          this.attachedNode.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], this.attachedNode.getWorldMatrix());
          this.attachedNode.getWorldMatrix().setTranslation(translation);
        }
        lastDragPosition.copyFrom(event.dragPlanePoint);
        if (snapped) {
          tmpSnapEvent.snapDistance = angle;
          this.onSnapObservable.notifyObservers(tmpSnapEvent);
        }
        this._angles.y += angle;
        this.angle += cameraFlipped ? -angle : angle;
        this._rotationShaderMaterial.setVector3("angles", this._angles);
        this._matrixChanged();
      }
    });
    const light = gizmoLayer._getSharedGizmoLight();
    light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));
    const cache = {
      colliderMeshes: [collider2],
      gizmoMeshes: [rotationMesh],
      material: this._coloredMaterial,
      hoverMaterial: this._hoverMaterial,
      disableMaterial: this._disableMaterial,
      active: false,
      dragBehavior: this.dragBehavior
    };
    this._parent?.addToAxisCache(this._gizmoMesh, cache);
    this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
      if (this._customMeshSet) {
        return;
      }
      this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;
      this._isHovered = !!(cache.colliderMeshes.indexOf(pointerInfo?.pickInfo?.pickedMesh) != -1);
      if (!this._parent) {
        const material = cache.dragBehavior.enabled ? this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial : this._disableMaterial;
        this._setGizmoMeshMaterial(cache.gizmoMeshes, material);
      }
    });
    this.dragBehavior.onEnabledObservable.add((newState) => {
      this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);
    });
  }
  _createGizmoMesh(parentMesh, thickness, tessellation) {
    const collider2 = CreateTorus("ignore", {
      diameter: 0.6,
      thickness: 0.03 * thickness,
      tessellation
    }, this.gizmoLayer.utilityLayerScene);
    collider2.visibility = 0;
    const rotationMesh = CreateTorus("", {
      diameter: 0.6,
      thickness: 0.005 * thickness,
      tessellation
    }, this.gizmoLayer.utilityLayerScene);
    rotationMesh.material = this._coloredMaterial;
    rotationMesh.rotation.x = Math.PI / 2;
    collider2.rotation.x = Math.PI / 2;
    parentMesh.addChild(rotationMesh, Gizmo.PreserveScaling);
    parentMesh.addChild(collider2, Gizmo.PreserveScaling);
    return { rotationMesh, collider: collider2 };
  }
  _attachedNodeChanged(value) {
    if (this.dragBehavior) {
      this.dragBehavior.enabled = value ? true : false;
    }
  }
  set isEnabled(value) {
    this._isEnabled = value;
    if (!value) {
      this.attachedMesh = null;
    } else {
      if (this._parent) {
        this.attachedMesh = this._parent.attachedMesh;
      }
    }
  }
  get isEnabled() {
    return this._isEnabled;
  }
  dispose() {
    this.onSnapObservable.clear();
    this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
    this.dragBehavior.detach();
    if (this._gizmoMesh) {
      this._gizmoMesh.dispose();
    }
    if (this._rotationDisplayPlane) {
      this._rotationDisplayPlane.dispose();
    }
    if (this._rotationShaderMaterial) {
      this._rotationShaderMaterial.dispose();
    }
    [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {
      if (matl) {
        matl.dispose();
      }
    });
    super.dispose();
  }
}
PlaneRotationGizmo.MaxDragAngle = Math.PI * 9 / 20;
PlaneRotationGizmo._RotationGizmoVertexShader = `
        precision highp float;
        attribute vec3 position;
        attribute vec2 uv;
        uniform mat4 worldViewProjection;
        varying vec3 vPosition;
        varying vec2 vUV;

        void main(void) {
            gl_Position = worldViewProjection * vec4(position, 1.0);
            vUV = uv;
        }`;
PlaneRotationGizmo._RotationGizmoFragmentShader = `
        precision highp float;
        varying vec2 vUV;
        varying vec3 vPosition;
        uniform vec3 angles;
        uniform vec3 rotationColor;

        #define twopi 6.283185307

        void main(void) {
            vec2 uv = vUV - vec2(0.5);
            float angle = atan(uv.y, uv.x) + 3.141592;
            float delta = gl_FrontFacing ? angles.y : -angles.y;
            float begin = angles.x - delta * angles.z;
            float start = (begin < (begin + delta)) ? begin : (begin + delta);
            float end = (begin > (begin + delta)) ? begin : (begin + delta);
            float len = sqrt(dot(uv,uv));
            float opacity = 1. - step(0.5, len);

            float base = abs(floor(start / twopi)) * twopi;
            start += base;
            end += base;

            float intensity = 0.;
            for (int i = 0; i < 5; i++)
            {
                intensity += max(step(start, angle) - step(end, angle), 0.);
                angle += twopi;
            }
            gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;
        }
    `;

// node_modules/@babylonjs/core/Gizmos/positionGizmo.js
init_logger();
init_observable();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Gizmos/planeDragGizmo.js
init_observable();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Gizmos/scaleGizmo.js
init_logger();
init_observable();
init_math_vector();
init_math_color();
// node_modules/@babylonjs/core/Gizmos/lightGizmo.js
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Meshes/Builders/hemisphereBuilder.js
function CreateHemisphere(name237, options = {}, scene) {
  if (!options.diameter) {
    options.diameter = 1;
  }
  if (!options.segments) {
    options.segments = 16;
  }
  const halfSphere = CreateSphere("", { slice: 0.5, diameter: options.diameter, segments: options.segments }, scene);
  const disc = CreateDisc("", { radius: options.diameter / 2, tessellation: options.segments * 3 + (4 - options.segments) }, scene);
  disc.rotation.x = -Math.PI / 2;
  disc.parent = halfSphere;
  const merged = Mesh.MergeMeshes([disc, halfSphere], true);
  merged.name = name237;
  return merged;
}
Mesh.CreateHemisphere = (name237, segments, diameter, scene) => {
  const options = {
    segments,
    diameter
  };
  return CreateHemisphere(name237, options, scene);
};

// node_modules/@babylonjs/core/Lights/spotLight.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_node();
init_texture();
init_typeStore();
Node2.AddNodeConstructor("Light_Type_2", (name237, scene) => {
  return () => new SpotLight(name237, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);
});

class SpotLight extends ShadowLight {
  get iesProfileTexture() {
    return this._iesProfileTexture;
  }
  set iesProfileTexture(value) {
    if (this._iesProfileTexture === value) {
      return;
    }
    this._iesProfileTexture = value;
    if (this._iesProfileTexture && SpotLight._IsTexture(this._iesProfileTexture)) {
      this._iesProfileTexture.onLoadObservable.addOnce(() => {
        this._markMeshesAsLightDirty();
      });
    }
  }
  get angle() {
    return this._angle;
  }
  set angle(value) {
    this._angle = value;
    this._cosHalfAngle = Math.cos(value * 0.5);
    this._projectionTextureProjectionLightDirty = true;
    this.forceProjectionMatrixCompute();
    this._computeAngleValues();
  }
  get innerAngle() {
    return this._innerAngle;
  }
  set innerAngle(value) {
    this._innerAngle = value;
    this._computeAngleValues();
  }
  get shadowAngleScale() {
    return this._shadowAngleScale;
  }
  set shadowAngleScale(value) {
    this._shadowAngleScale = value;
    this.forceProjectionMatrixCompute();
  }
  get projectionTextureMatrix() {
    return this._projectionTextureMatrix;
  }
  get projectionTextureLightNear() {
    return this._projectionTextureLightNear;
  }
  set projectionTextureLightNear(value) {
    this._projectionTextureLightNear = value;
    this._projectionTextureProjectionLightDirty = true;
  }
  get projectionTextureLightFar() {
    return this._projectionTextureLightFar;
  }
  set projectionTextureLightFar(value) {
    this._projectionTextureLightFar = value;
    this._projectionTextureProjectionLightDirty = true;
  }
  get projectionTextureUpDirection() {
    return this._projectionTextureUpDirection;
  }
  set projectionTextureUpDirection(value) {
    this._projectionTextureUpDirection = value;
    this._projectionTextureProjectionLightDirty = true;
  }
  get projectionTexture() {
    return this._projectionTexture;
  }
  set projectionTexture(value) {
    if (this._projectionTexture === value) {
      return;
    }
    this._projectionTexture = value;
    this._projectionTextureDirty = true;
    if (this._projectionTexture && !this._projectionTexture.isReady()) {
      if (SpotLight._IsProceduralTexture(this._projectionTexture)) {
        this._projectionTexture.getEffect().executeWhenCompiled(() => {
          this._markMeshesAsLightDirty();
        });
      } else if (SpotLight._IsTexture(this._projectionTexture)) {
        this._projectionTexture.onLoadObservable.addOnce(() => {
          this._markMeshesAsLightDirty();
        });
      }
    }
  }
  static _IsProceduralTexture(texture) {
    return texture.onGeneratedObservable !== undefined;
  }
  static _IsTexture(texture) {
    return texture.onLoadObservable !== undefined;
  }
  get projectionTextureProjectionLightMatrix() {
    return this._projectionTextureProjectionLightMatrix;
  }
  set projectionTextureProjectionLightMatrix(projection) {
    this._projectionTextureProjectionLightMatrix = projection;
    this._projectionTextureProjectionLightDirty = false;
    this._projectionTextureDirty = true;
  }
  constructor(name237, position, direction, angle, exponent, scene) {
    super(name237, scene);
    this._innerAngle = 0;
    this._iesProfileTexture = null;
    this._projectionTextureMatrix = Matrix.Zero();
    this._projectionTextureLightNear = 0.000001;
    this._projectionTextureLightFar = 1000;
    this._projectionTextureUpDirection = Vector3.Up();
    this._projectionTextureViewLightDirty = true;
    this._projectionTextureProjectionLightDirty = true;
    this._projectionTextureDirty = true;
    this._projectionTextureViewTargetVector = Vector3.Zero();
    this._projectionTextureViewLightMatrix = Matrix.Zero();
    this._projectionTextureProjectionLightMatrix = Matrix.Zero();
    this._projectionTextureScalingMatrix = Matrix.FromValues(0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0.5, 0.5, 0.5, 1);
    this.position = position;
    this.direction = direction;
    this.angle = angle;
    this.exponent = exponent;
  }
  getClassName() {
    return "SpotLight";
  }
  getTypeID() {
    return Light.LIGHTTYPEID_SPOTLIGHT;
  }
  _setDirection(value) {
    super._setDirection(value);
    this._projectionTextureViewLightDirty = true;
  }
  _setPosition(value) {
    super._setPosition(value);
    this._projectionTextureViewLightDirty = true;
  }
  _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
    const activeCamera = this.getScene().activeCamera;
    if (!activeCamera) {
      return;
    }
    this._shadowAngleScale = this._shadowAngleScale || 1;
    const angle = this._shadowAngleScale * this._angle;
    const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
    const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
    const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
    Matrix.PerspectiveFovLHToRef(angle, 1, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);
  }
  _computeProjectionTextureViewLightMatrix() {
    this._projectionTextureViewLightDirty = false;
    this._projectionTextureDirty = true;
    this.getAbsolutePosition().addToRef(this.getShadowDirection(), this._projectionTextureViewTargetVector);
    Matrix.LookAtLHToRef(this.getAbsolutePosition(), this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  }
  _computeProjectionTextureProjectionLightMatrix() {
    this._projectionTextureProjectionLightDirty = false;
    this._projectionTextureDirty = true;
    const lightFar = this.projectionTextureLightFar;
    const lightNear = this.projectionTextureLightNear;
    const P = lightFar / (lightFar - lightNear);
    const Q = -P * lightNear;
    const S = 1 / Math.tan(this._angle / 2);
    const A = 1;
    Matrix.FromValuesToRef(S / A, 0, 0, 0, 0, S, 0, 0, 0, 0, P, 1, 0, 0, Q, 0, this._projectionTextureProjectionLightMatrix);
  }
  _computeProjectionTextureMatrix() {
    this._projectionTextureDirty = false;
    this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
    if (this._projectionTexture instanceof Texture) {
      const u = this._projectionTexture.uScale / 2;
      const v = this._projectionTexture.vScale / 2;
      Matrix.FromValuesToRef(u, 0, 0, 0, 0, v, 0, 0, 0, 0, 0.5, 0, 0.5, 0.5, 0.5, 1, this._projectionTextureScalingMatrix);
    }
    this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("vLightData", 4);
    this._uniformBuffer.addUniform("vLightDiffuse", 4);
    this._uniformBuffer.addUniform("vLightSpecular", 4);
    this._uniformBuffer.addUniform("vLightDirection", 3);
    this._uniformBuffer.addUniform("vLightFalloff", 4);
    this._uniformBuffer.addUniform("shadowsInfo", 3);
    this._uniformBuffer.addUniform("depthValues", 2);
    this._uniformBuffer.create();
  }
  _computeAngleValues() {
    this._lightAngleScale = 1 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle);
    this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  }
  transferTexturesToEffect(effect, lightIndex) {
    if (this.projectionTexture && this.projectionTexture.isReady()) {
      if (this._projectionTextureViewLightDirty) {
        this._computeProjectionTextureViewLightMatrix();
      }
      if (this._projectionTextureProjectionLightDirty) {
        this._computeProjectionTextureProjectionLightMatrix();
      }
      if (this._projectionTextureDirty) {
        this._computeProjectionTextureMatrix();
      }
      effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
      effect.setTexture("projectionLightTexture" + lightIndex, this.projectionTexture);
    }
    if (this._iesProfileTexture && this._iesProfileTexture.isReady()) {
      effect.setTexture("iesLightTexture" + lightIndex, this._iesProfileTexture);
    }
    return this;
  }
  transferToEffect(effect, lightIndex) {
    let normalizeDirection;
    if (this.computeTransformedInformation()) {
      this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
      normalizeDirection = Vector3.Normalize(this.transformedDirection);
    } else {
      this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
      normalizeDirection = Vector3.Normalize(this.direction);
    }
    this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
    this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
    return this;
  }
  transferToNodeMaterialEffect(effect, lightDataUniformName) {
    let normalizeDirection;
    if (this.computeTransformedInformation()) {
      normalizeDirection = Vector3.Normalize(this.transformedDirection);
    } else {
      normalizeDirection = Vector3.Normalize(this.direction);
    }
    if (this.getScene().useRightHandedSystem) {
      effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z);
    } else {
      effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
    }
    return this;
  }
  dispose() {
    super.dispose();
    if (this._projectionTexture) {
      this._projectionTexture.dispose();
    }
    if (this._iesProfileTexture) {
      this._iesProfileTexture.dispose();
      this._iesProfileTexture = null;
    }
  }
  getDepthMinZ(activeCamera) {
    const engine2 = this._scene.getEngine();
    const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera?.minZ ?? 0;
    return engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ;
  }
  getDepthMaxZ(activeCamera) {
    const engine2 = this._scene.getEngine();
    const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera?.maxZ ?? 1e4;
    return engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : maxZ;
  }
  prepareLightSpecificDefines(defines, lightIndex) {
    defines["SPOTLIGHT" + lightIndex] = true;
    defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false;
    defines["IESLIGHTTEXTURE" + lightIndex] = this._iesProfileTexture && this._iesProfileTexture.isReady() ? true : false;
  }
}
__decorate([
  serialize()
], SpotLight.prototype, "angle", null);
__decorate([
  serialize()
], SpotLight.prototype, "innerAngle", null);
__decorate([
  serialize()
], SpotLight.prototype, "shadowAngleScale", null);
__decorate([
  serialize()
], SpotLight.prototype, "exponent", undefined);
__decorate([
  serialize()
], SpotLight.prototype, "projectionTextureLightNear", null);
__decorate([
  serialize()
], SpotLight.prototype, "projectionTextureLightFar", null);
__decorate([
  serialize()
], SpotLight.prototype, "projectionTextureUpDirection", null);
__decorate([
  serializeAsTexture("projectedLightTexture")
], SpotLight.prototype, "_projectionTexture", undefined);
RegisterClass("BABYLON.SpotLight", SpotLight);

// node_modules/@babylonjs/core/Gizmos/lightGizmo.js
init_pointerEvents();
init_observable();
init_logger();

class LightGizmo extends Gizmo {
  constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer) {
    super(gizmoLayer);
    this._cachedPosition = new Vector3;
    this._cachedForward = new Vector3(0, 0, 1);
    this._pointerObserver = null;
    this.onClickedObservable = new Observable;
    this._light = null;
    this.attachedMesh = new Mesh("", this.gizmoLayer.utilityLayerScene);
    this._attachedMeshParent = new TransformNode("parent", this.gizmoLayer.utilityLayerScene);
    this.attachedMesh.parent = this._attachedMeshParent;
    this._material = new StandardMaterial("light", this.gizmoLayer.utilityLayerScene);
    this._material.diffuseColor = new Color3(0.5, 0.5, 0.5);
    this._material.specularColor = new Color3(0.1, 0.1, 0.1);
    this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
      if (!this._light) {
        return;
      }
      this._isHovered = !!(pointerInfo.pickInfo && this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
      if (this._isHovered && pointerInfo.event.button === 0) {
        this.onClickedObservable.notifyObservers(this._light);
      }
    }, PointerEventTypes.POINTERDOWN);
  }
  get attachedNode() {
    return this.attachedMesh;
  }
  set attachedNode(value) {
    Logger.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.");
  }
  set light(light) {
    this._light = light;
    if (light) {
      if (this._lightMesh) {
        this._lightMesh.dispose();
      }
      if (light instanceof HemisphericLight) {
        this._lightMesh = LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene);
      } else if (light instanceof DirectionalLight) {
        this._lightMesh = LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene);
      } else if (light instanceof SpotLight) {
        this._lightMesh = LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene);
      } else {
        this._lightMesh = LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene);
      }
      this._lightMesh.getChildMeshes(false).forEach((m) => {
        m.material = this._material;
      });
      this._lightMesh.parent = this._rootMesh;
      const gizmoLight = this.gizmoLayer._getSharedGizmoLight();
      gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(false));
      this._lightMesh.rotationQuaternion = new Quaternion;
      if (!this.attachedMesh.reservedDataStore) {
        this.attachedMesh.reservedDataStore = {};
      }
      this.attachedMesh.reservedDataStore.lightGizmo = this;
      if (light.parent) {
        this._attachedMeshParent.freezeWorldMatrix(light.parent.getWorldMatrix());
      }
      if (light.position) {
        this.attachedMesh.position.copyFrom(light.position);
        this.attachedMesh.computeWorldMatrix(true);
        this._cachedPosition.copyFrom(this.attachedMesh.position);
      }
      if (light.direction) {
        this.attachedMesh.setDirection(light.direction);
        this.attachedMesh.computeWorldMatrix(true);
        const forward = this._getMeshForward();
        this._cachedForward.copyFrom(forward);
      }
      this._update();
    }
  }
  get light() {
    return this._light;
  }
  get material() {
    return this._material;
  }
  _getMeshForward() {
    let forward = this.attachedMesh.forward;
    if (this.attachedMesh.getScene().useRightHandedSystem) {
      forward.negateToRef(TmpVectors.Vector3[0]);
      forward = TmpVectors.Vector3[0];
    }
    return forward;
  }
  _update() {
    super._update();
    if (!this._light) {
      return;
    }
    if (this._light.parent) {
      this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix());
    }
    if (this._light.position) {
      if (!this.attachedMesh.position.equals(this._cachedPosition)) {
        const position = this.attachedMesh.position;
        this._light.position = new Vector3(position.x, position.y, position.z);
        this._cachedPosition.copyFrom(this.attachedMesh.position);
      } else {
        this.attachedMesh.position.copyFrom(this._light.position);
        this.attachedMesh.computeWorldMatrix(true);
        this._cachedPosition.copyFrom(this.attachedMesh.position);
      }
    }
    if (this._light.direction) {
      const forward = this._getMeshForward();
      if (Vector3.DistanceSquared(forward, this._cachedForward) > 0.0001) {
        const direction = forward;
        this._light.direction = new Vector3(direction.x, direction.y, direction.z);
        this._cachedForward.copyFrom(forward);
      } else if (Vector3.DistanceSquared(forward, this._light.direction) > 0.0001) {
        this.attachedMesh.setDirection(this._light.direction);
        this.attachedMesh.computeWorldMatrix(true);
        this._cachedForward.copyFrom(forward);
      }
    }
  }
  dispose() {
    this.onClickedObservable.clear();
    this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
    this._material.dispose();
    super.dispose();
    this._attachedMeshParent.dispose();
  }
  static _CreateHemisphericLightMesh(scene) {
    const root = new Mesh("hemisphereLight", scene);
    const hemisphere = CreateHemisphere(root.name, { segments: 10, diameter: 1 }, scene);
    hemisphere.position.z = -0.15;
    hemisphere.rotation.x = Math.PI / 2;
    hemisphere.parent = root;
    const lines = this._CreateLightLines(3, scene);
    lines.parent = root;
    root.scaling.scaleInPlace(LightGizmo._Scale);
    root.rotation.x = Math.PI / 2;
    return root;
  }
  static _CreatePointLightMesh(scene) {
    const root = new Mesh("pointLight", scene);
    const sphere = CreateSphere(root.name, { segments: 10, diameter: 1 }, scene);
    sphere.rotation.x = Math.PI / 2;
    sphere.parent = root;
    const lines = this._CreateLightLines(5, scene);
    lines.parent = root;
    root.scaling.scaleInPlace(LightGizmo._Scale);
    root.rotation.x = Math.PI / 2;
    return root;
  }
  static _CreateSpotLightMesh(scene) {
    const root = new Mesh("spotLight", scene);
    const sphere = CreateSphere(root.name, { segments: 10, diameter: 1 }, scene);
    sphere.parent = root;
    const hemisphere = CreateHemisphere(root.name, { segments: 10, diameter: 2 }, scene);
    hemisphere.parent = root;
    hemisphere.rotation.x = -Math.PI / 2;
    const lines = this._CreateLightLines(2, scene);
    lines.parent = root;
    root.scaling.scaleInPlace(LightGizmo._Scale);
    root.rotation.x = Math.PI / 2;
    return root;
  }
  static _CreateDirectionalLightMesh(scene) {
    const root = new Mesh("directionalLight", scene);
    const mesh = new Mesh(root.name, scene);
    mesh.parent = root;
    const sphere = CreateSphere(root.name, { diameter: 1.2, segments: 10 }, scene);
    sphere.parent = mesh;
    const line = CreateCylinder(root.name, {
      updatable: false,
      height: 6,
      diameterTop: 0.3,
      diameterBottom: 0.3,
      tessellation: 6,
      subdivisions: 1
    }, scene);
    line.parent = mesh;
    let left = line.clone(root.name);
    left.scaling.y = 0.5;
    left.position.x += 1.25;
    let right = line.clone(root.name);
    right.scaling.y = 0.5;
    right.position.x += -1.25;
    const arrowHead = CreateCylinder(root.name, {
      updatable: false,
      height: 1,
      diameterTop: 0,
      diameterBottom: 0.6,
      tessellation: 6,
      subdivisions: 1
    }, scene);
    arrowHead.position.y += 3;
    arrowHead.parent = mesh;
    left = arrowHead.clone(root.name);
    left.position.y = 1.5;
    left.position.x += 1.25;
    right = arrowHead.clone(root.name);
    right.position.y = 1.5;
    right.position.x += -1.25;
    mesh.scaling.scaleInPlace(LightGizmo._Scale);
    mesh.rotation.z = Math.PI / 2;
    mesh.rotation.y = Math.PI / 2;
    return root;
  }
}
LightGizmo._Scale = 0.007;
LightGizmo._CreateLightLines = (levels, scene) => {
  const distFromSphere = 1.2;
  const root = new Mesh("root", scene);
  root.rotation.x = Math.PI / 2;
  const linePivot = new Mesh("linePivot", scene);
  linePivot.parent = root;
  const line = CreateCylinder("line", {
    updatable: false,
    height: 2,
    diameterTop: 0.2,
    diameterBottom: 0.3,
    tessellation: 6,
    subdivisions: 1
  }, scene);
  line.position.y = line.scaling.y / 2 + distFromSphere;
  line.parent = linePivot;
  if (levels < 2) {
    return linePivot;
  }
  for (let i = 0;i < 4; i++) {
    const l2 = linePivot.clone("lineParentClone");
    l2.rotation.z = Math.PI / 4;
    l2.rotation.y = Math.PI / 2 + Math.PI / 2 * i;
    l2.getChildMeshes()[0].scaling.y = 0.5;
    l2.getChildMeshes()[0].scaling.x = l2.getChildMeshes()[0].scaling.z = 0.8;
    l2.getChildMeshes()[0].position.y = l2.getChildMeshes()[0].scaling.y / 2 + distFromSphere;
  }
  if (levels < 3) {
    return root;
  }
  for (let i = 0;i < 4; i++) {
    const l2 = linePivot.clone("linePivotClone");
    l2.rotation.z = Math.PI / 2;
    l2.rotation.y = Math.PI / 2 * i;
  }
  if (levels < 4) {
    return root;
  }
  for (let i = 0;i < 4; i++) {
    const l2 = linePivot.clone("linePivotClone");
    l2.rotation.z = Math.PI + Math.PI / 4;
    l2.rotation.y = Math.PI / 2 + Math.PI / 2 * i;
    l2.getChildMeshes()[0].scaling.y = 0.5;
    l2.getChildMeshes()[0].scaling.x = l2.getChildMeshes()[0].scaling.z = 0.8;
    l2.getChildMeshes()[0].position.y = l2.getChildMeshes()[0].scaling.y / 2 + distFromSphere;
  }
  if (levels < 5) {
    return root;
  }
  const l = linePivot.clone("linePivotClone");
  l.rotation.z = Math.PI;
  return root;
};
// node_modules/@babylonjs/core/Gizmos/cameraGizmo.js
init_math_vector();
init_math_color();
init_math();
init_pointerEvents();
init_observable();

class CameraGizmo extends Gizmo {
  constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, gizmoColor, frustumLinesColor) {
    super(gizmoLayer);
    this._pointerObserver = null;
    this.onClickedObservable = new Observable;
    this._camera = null;
    this._invProjection = new Matrix;
    this._material = new StandardMaterial("cameraGizmoMaterial", this.gizmoLayer.utilityLayerScene);
    this._frustumLinesColor = frustumLinesColor;
    this._material.diffuseColor = gizmoColor ?? new Color3(0.5, 0.5, 0.5);
    this._material.specularColor = new Color3(0.1, 0.1, 0.1);
    this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
      if (!this._camera) {
        return;
      }
      this._isHovered = !!(pointerInfo.pickInfo && this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
      if (this._isHovered && pointerInfo.event.button === 0) {
        this.onClickedObservable.notifyObservers(this._camera);
      }
    }, PointerEventTypes.POINTERDOWN);
  }
  get displayFrustum() {
    return this._cameraLinesMesh.isEnabled();
  }
  set displayFrustum(value) {
    this._cameraLinesMesh.setEnabled(value);
  }
  set camera(camera2) {
    this._camera = camera2;
    this.attachedNode = camera2;
    if (camera2) {
      if (!this._customMeshSet) {
        if (this._cameraMesh) {
          this._cameraMesh.dispose();
        }
        this._cameraMesh = CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene);
        this._cameraMesh.getChildMeshes(false).forEach((m) => {
          m.material = this._material;
        });
        this._cameraMesh.parent = this._rootMesh;
      }
      if (this._cameraLinesMesh) {
        this._cameraLinesMesh.dispose();
      }
      const linesColor = this._frustumLinesColor?.toColor4(1) ?? new Color4(1, 1, 1, 1);
      this._cameraLinesMesh = CameraGizmo._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene, linesColor);
      this._cameraLinesMesh.parent = this._rootMesh;
      if (this.gizmoLayer.utilityLayerScene.activeCamera && this.gizmoLayer.utilityLayerScene.activeCamera.maxZ < camera2.maxZ * 1.5) {
        this.gizmoLayer.utilityLayerScene.activeCamera.maxZ = camera2.maxZ * 1.5;
      }
      if (!this.attachedNode.reservedDataStore) {
        this.attachedNode.reservedDataStore = {};
      }
      this.attachedNode.reservedDataStore.cameraGizmo = this;
      const gizmoLight = this.gizmoLayer._getSharedGizmoLight();
      gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(false));
      this._update();
    }
  }
  get camera() {
    return this._camera;
  }
  get material() {
    return this._material;
  }
  _update() {
    super._update();
    if (!this._camera) {
      return;
    }
    this._camera.getProjectionMatrix().invertToRef(this._invProjection);
    this._cameraLinesMesh.setPivotMatrix(this._invProjection, false);
    this._cameraLinesMesh.scaling.x = 1 / this._rootMesh.scaling.x;
    this._cameraLinesMesh.scaling.y = 1 / this._rootMesh.scaling.y;
    this._cameraLinesMesh.scaling.z = 1 / this._rootMesh.scaling.z;
    this._cameraMesh.parent = null;
    this._cameraMesh.rotation.y = Math.PI * 0.5 * (this._camera.getScene().useRightHandedSystem ? 1 : -1);
    this._cameraMesh.parent = this._rootMesh;
  }
  setCustomMesh(mesh) {
    if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
      throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
    }
    if (this._cameraMesh) {
      this._cameraMesh.dispose();
    }
    this._cameraMesh = mesh;
    this._cameraMesh.parent = this._rootMesh;
    this._customMeshSet = true;
  }
  dispose() {
    this.onClickedObservable.clear();
    this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
    if (this._cameraMesh) {
      this._cameraMesh.dispose();
    }
    if (this._cameraLinesMesh) {
      this._cameraLinesMesh.dispose();
    }
    this._material.dispose();
    super.dispose();
  }
  static _CreateCameraMesh(scene) {
    const root = new Mesh("rootCameraGizmo", scene);
    const mesh = new Mesh(root.name, scene);
    mesh.parent = root;
    const box = CreateBox(root.name, { width: 1, height: 0.8, depth: 0.5 }, scene);
    box.parent = mesh;
    const cyl1 = CreateCylinder(root.name, { height: 0.5, diameterTop: 0.8, diameterBottom: 0.8 }, scene);
    cyl1.parent = mesh;
    cyl1.position.y = 0.3;
    cyl1.position.x = -0.6;
    cyl1.rotation.x = Math.PI * 0.5;
    const cyl2 = CreateCylinder(root.name, { height: 0.5, diameterTop: 0.6, diameterBottom: 0.6 }, scene);
    cyl2.parent = mesh;
    cyl2.position.y = 0.5;
    cyl2.position.x = 0.4;
    cyl2.rotation.x = Math.PI * 0.5;
    const cyl3 = CreateCylinder(root.name, { height: 0.5, diameterTop: 0.5, diameterBottom: 0.5 }, scene);
    cyl3.parent = mesh;
    cyl3.position.y = 0;
    cyl3.position.x = 0.6;
    cyl3.rotation.z = Math.PI * 0.5;
    root.scaling.scaleInPlace(CameraGizmo._Scale);
    mesh.position.x = -0.9;
    return root;
  }
  static _CreateCameraFrustum(scene, linesColor) {
    const root = new Mesh("rootCameraGizmo", scene);
    const mesh = new Mesh(root.name, scene);
    mesh.parent = root;
    for (let y = 0;y < 4; y += 2) {
      for (let x = 0;x < 4; x += 2) {
        let line = CreateLines("lines", { points: [new Vector3(-1 + x, -1 + y, -1), new Vector3(-1 + x, -1 + y, 1)], colors: [linesColor, linesColor] }, scene);
        line.parent = mesh;
        line.alwaysSelectAsActiveMesh = true;
        line.isPickable = false;
        line = CreateLines("lines", { points: [new Vector3(-1, -1 + x, -1 + y), new Vector3(1, -1 + x, -1 + y)], colors: [linesColor, linesColor] }, scene);
        line.parent = mesh;
        line.alwaysSelectAsActiveMesh = true;
        line.isPickable = false;
        line = CreateLines("lines", { points: [new Vector3(-1 + x, -1, -1 + y), new Vector3(-1 + x, 1, -1 + y)], colors: [linesColor, linesColor] }, scene);
        line.parent = mesh;
        line.alwaysSelectAsActiveMesh = true;
        line.isPickable = false;
      }
    }
    return root;
  }
}
CameraGizmo._Scale = 0.05;
// node_modules/@babylonjs/core/Helpers/environmentHelper.js
init_observable();
init_math_vector();
init_math_color();
init_baseTexture();
init_texture();

// node_modules/@babylonjs/core/Materials/Textures/mirrorTexture.js
init_math_vector();
init_texture();
init_renderTargetTexture();
init_math_plane();

class MirrorTexture extends RenderTargetTexture {
  set blurRatio(value) {
    if (this._blurRatio === value) {
      return;
    }
    this._blurRatio = value;
    this._preparePostProcesses();
  }
  get blurRatio() {
    return this._blurRatio;
  }
  set adaptiveBlurKernel(value) {
    this._adaptiveBlurKernel = value;
    this._autoComputeBlurKernel();
  }
  set blurKernel(value) {
    this.blurKernelX = value;
    this.blurKernelY = value;
  }
  set blurKernelX(value) {
    if (this._blurKernelX === value) {
      return;
    }
    this._blurKernelX = value;
    this._preparePostProcesses();
  }
  get blurKernelX() {
    return this._blurKernelX;
  }
  set blurKernelY(value) {
    if (this._blurKernelY === value) {
      return;
    }
    this._blurKernelY = value;
    this._preparePostProcesses();
  }
  get blurKernelY() {
    return this._blurKernelY;
  }
  _autoComputeBlurKernel() {
    const engine2 = this.getScene().getEngine();
    const dw = this.getRenderWidth() / engine2.getRenderWidth();
    const dh = this.getRenderHeight() / engine2.getRenderHeight();
    this.blurKernelX = this._adaptiveBlurKernel * dw;
    this.blurKernelY = this._adaptiveBlurKernel * dh;
  }
  _onRatioRescale() {
    if (this._sizeRatio) {
      this.resize(this._initialSizeParameter);
      if (!this._adaptiveBlurKernel) {
        this._preparePostProcesses();
      }
    }
    if (this._adaptiveBlurKernel) {
      this._autoComputeBlurKernel();
    }
  }
  _updateGammaSpace() {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    this.gammaSpace = !scene.imageProcessingConfiguration.isEnabled || !scene.imageProcessingConfiguration.applyByPostProcess;
  }
  constructor(name237, size, scene, generateMipMaps, type = 0, samplingMode = Texture.BILINEAR_SAMPLINGMODE, generateDepthBuffer = true) {
    super(name237, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer);
    this.mirrorPlane = new Plane(0, 1, 0, 1);
    this._transformMatrix = Matrix.Zero();
    this._mirrorMatrix = Matrix.Zero();
    this._adaptiveBlurKernel = 0;
    this._blurKernelX = 0;
    this._blurKernelY = 0;
    this._blurRatio = 1;
    scene = this.getScene();
    if (!scene) {
      return this;
    }
    this.ignoreCameraViewport = true;
    this._updateGammaSpace();
    this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(() => {
      this._updateGammaSpace();
    });
    const engine2 = scene.getEngine();
    if (engine2.supportsUniformBuffers) {
      this._sceneUBO = scene.createSceneUniformBuffer(`Scene for Mirror Texture (name "${name237}")`);
    }
    let saveClipPlane;
    this.onBeforeRenderObservable.add(() => {
      if (this._sceneUBO) {
        this._currentSceneUBO = scene.getSceneUniformBuffer();
        scene.setSceneUniformBuffer(this._sceneUBO);
        scene.getSceneUniformBuffer().unbindEffect();
      }
      Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix);
      this._mirrorMatrix.multiplyToRef(scene.getViewMatrix(), this._transformMatrix);
      scene.setTransformMatrix(this._transformMatrix, scene.getProjectionMatrix());
      saveClipPlane = scene.clipPlane;
      scene.clipPlane = this.mirrorPlane;
      scene._mirroredCameraPosition = Vector3.TransformCoordinates(scene.activeCamera.globalPosition, this._mirrorMatrix);
    });
    this.onAfterRenderObservable.add(() => {
      if (this._sceneUBO) {
        scene.setSceneUniformBuffer(this._currentSceneUBO);
      }
      scene.updateTransformMatrix();
      scene._mirroredCameraPosition = null;
      scene.clipPlane = saveClipPlane;
    });
  }
  _preparePostProcesses() {
    this.clearPostProcesses(true);
    if (this._blurKernelX && this._blurKernelY) {
      const engine2 = this.getScene().getEngine();
      const textureType = engine2.getCaps().textureFloatRender && engine2.getCaps().textureFloatLinearFiltering ? 1 : 2;
      this._blurX = new BlurPostProcess("horizontal blur", new Vector2(1, 0), this._blurKernelX, this._blurRatio, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, textureType);
      this._blurX.autoClear = false;
      if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
        this._blurX.inputTexture = this._renderTarget;
      } else {
        this._blurX.alwaysForcePOT = true;
      }
      this._blurY = new BlurPostProcess("vertical blur", new Vector2(0, 1), this._blurKernelY, this._blurRatio, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, textureType);
      this._blurY.autoClear = false;
      this._blurY.alwaysForcePOT = this._blurRatio !== 1;
      this.addPostProcess(this._blurX);
      this.addPostProcess(this._blurY);
    } else {
      if (this._blurY) {
        this.removePostProcess(this._blurY);
        this._blurY.dispose();
        this._blurY = null;
      }
      if (this._blurX) {
        this.removePostProcess(this._blurX);
        this._blurX.dispose();
        this._blurX = null;
      }
    }
  }
  clone() {
    const scene = this.getScene();
    if (!scene) {
      return this;
    }
    const textureSize = this.getSize();
    const newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
    newTexture.hasAlpha = this.hasAlpha;
    newTexture.level = this.level;
    newTexture.mirrorPlane = this.mirrorPlane.clone();
    if (this.renderList) {
      newTexture.renderList = this.renderList.slice(0);
    }
    return newTexture;
  }
  serialize() {
    if (!this.name) {
      return null;
    }
    const serializationObject = super.serialize();
    serializationObject.mirrorPlane = this.mirrorPlane.asArray();
    return serializationObject;
  }
  dispose() {
    super.dispose();
    const scene = this.getScene();
    if (scene) {
      scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
    }
    this._sceneUBO?.dispose();
  }
}
Texture._CreateMirror = (name237, renderTargetSize, scene, generateMipMaps) => {
  return new MirrorTexture(name237, renderTargetSize, scene, generateMipMaps);
};

// node_modules/@babylonjs/core/Materials/Textures/cubeTexture.js
init_tslib_es6();
init_decorators();
init_tools();
init_math_vector();
init_baseTexture();
init_texture();
init_typeStore();
init_observable();
init_decorators_serialization();
init_abstractEngine_cubeTexture();
var defaultLodScale = 0.8;

class CubeTexture extends BaseTexture {
  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;
  }
  set rotationY(value) {
    this._rotationY = value;
    this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));
  }
  get rotationY() {
    return this._rotationY;
  }
  get noMipmap() {
    return this._noMipmap;
  }
  get forcedExtension() {
    return this._forcedExtension;
  }
  static CreateFromImages(files, scene, noMipmap) {
    let rootUrlKey = "";
    files.forEach((url) => rootUrlKey += url);
    return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  }
  static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) {
    const oldValue = scene.useDelayedTextureLoading;
    scene.useDelayedTextureLoading = false;
    const result = new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
    scene.useDelayedTextureLoading = oldValue;
    return result;
  }
  constructor(rootUrl, sceneOrEngine, extensionsOrOptions = null, noMipmap = false, files = null, onLoad = null, onError = null, format = 5, prefiltered = false, forcedExtension = null, createPolynomials = false, lodScale = defaultLodScale, lodOffset = 0, loaderOptions, useSRGBBuffer) {
    super(sceneOrEngine);
    this.onLoadObservable = new Observable;
    this.boundingBoxPosition = Vector3.Zero();
    this._rotationY = 0;
    this._files = null;
    this._forcedExtension = null;
    this._extensions = null;
    this._textureMatrixRefraction = new Matrix;
    this._buffer = null;
    this.name = rootUrl;
    this.url = rootUrl;
    this._noMipmap = noMipmap;
    this.hasAlpha = false;
    this.isCube = true;
    this._textureMatrix = Matrix.Identity();
    this.coordinatesMode = Texture.CUBIC_MODE;
    let extensions = null;
    let buffer2 = null;
    if (extensionsOrOptions !== null && !Array.isArray(extensionsOrOptions)) {
      extensions = extensionsOrOptions.extensions ?? null;
      this._noMipmap = extensionsOrOptions.noMipmap ?? false;
      files = extensionsOrOptions.files ?? null;
      buffer2 = extensionsOrOptions.buffer ?? null;
      this._format = extensionsOrOptions.format ?? 5;
      prefiltered = extensionsOrOptions.prefiltered ?? false;
      forcedExtension = extensionsOrOptions.forcedExtension ?? null;
      this._createPolynomials = extensionsOrOptions.createPolynomials ?? false;
      this._lodScale = extensionsOrOptions.lodScale ?? defaultLodScale;
      this._lodOffset = extensionsOrOptions.lodOffset ?? 0;
      this._loaderOptions = extensionsOrOptions.loaderOptions;
      this._useSRGBBuffer = extensionsOrOptions.useSRGBBuffer;
      onLoad = extensionsOrOptions.onLoad ?? null;
      onError = extensionsOrOptions.onError ?? null;
    } else {
      this._noMipmap = noMipmap;
      this._format = format;
      this._createPolynomials = createPolynomials;
      extensions = extensionsOrOptions;
      this._loaderOptions = loaderOptions;
      this._useSRGBBuffer = useSRGBBuffer;
      this._lodScale = lodScale;
      this._lodOffset = lodOffset;
    }
    if (!rootUrl && !files) {
      return;
    }
    this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, this.getScene()?.useDelayedTextureLoading, files, buffer2);
  }
  getClassName() {
    return "CubeTexture";
  }
  updateURL(url, forcedExtension = null, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null, buffer2 = null) {
    if (!this.name || this.name.startsWith("data:")) {
      this.name = url;
    }
    this.url = url;
    if (forcedExtension) {
      this._forcedExtension = forcedExtension;
    }
    const lastDot = url.lastIndexOf(".");
    const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
    const isDDS = extension.indexOf(".dds") === 0;
    const isEnv = extension.indexOf(".env") === 0;
    const isBasis = extension.indexOf(".basis") === 0;
    if (isEnv) {
      this.gammaSpace = false;
      this._prefiltered = false;
      this.anisotropicFilteringLevel = 1;
    } else {
      this._prefiltered = prefiltered;
      if (prefiltered) {
        this.gammaSpace = false;
        this.anisotropicFilteringLevel = 1;
      }
    }
    if (files) {
      this._files = files;
    } else {
      if (!isBasis && !isEnv && !isDDS && !extensions) {
        extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
      }
      this._files = this._files || [];
      this._files.length = 0;
      if (extensions) {
        for (let index = 0;index < extensions.length; index++) {
          this._files.push(url + extensions[index]);
        }
        this._extensions = extensions;
      }
    }
    this._buffer = buffer2;
    if (delayLoad) {
      this.delayLoadState = 4;
      this._delayedOnLoad = onLoad;
      this._delayedOnError = onError;
    } else {
      this._loadTexture(onLoad, onError);
    }
  }
  delayLoad(forcedExtension) {
    if (this.delayLoadState !== 4) {
      return;
    }
    if (forcedExtension) {
      this._forcedExtension = forcedExtension;
    }
    this.delayLoadState = 1;
    this._loadTexture(this._delayedOnLoad, this._delayedOnError);
  }
  getReflectionTextureMatrix() {
    return this._textureMatrix;
  }
  setReflectionTextureMatrix(value) {
    if (value.updateFlag === this._textureMatrix.updateFlag) {
      return;
    }
    if (value.isIdentity() !== this._textureMatrix.isIdentity()) {
      this.getScene()?.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);
    }
    this._textureMatrix = value;
    if (!this.getScene()?.useRightHandedSystem) {
      return;
    }
    const scale = TmpVectors.Vector3[0];
    const quat = TmpVectors.Quaternion[0];
    const trans = TmpVectors.Vector3[1];
    this._textureMatrix.decompose(scale, quat, trans);
    quat.z *= -1;
    quat.w *= -1;
    Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction);
  }
  getRefractionTextureMatrix() {
    return this.getScene()?.useRightHandedSystem ? this._textureMatrixRefraction : this._textureMatrix;
  }
  _loadTexture(onLoad = null, onError = null) {
    const scene = this.getScene();
    const oldTexture = this._texture;
    this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube);
    const onLoadProcessing = () => {
      this.onLoadObservable.notifyObservers(this);
      if (oldTexture) {
        oldTexture.dispose();
        this.getScene()?.markAllMaterialsAsDirty(1);
      }
      if (onLoad) {
        onLoad();
      }
    };
    const errorHandler = (message, exception) => {
      this._loadingError = true;
      this._errorObject = { message, exception };
      if (onError) {
        onError(message, exception);
      }
      Texture.OnTextureLoadErrorObservable.notifyObservers(this);
    };
    if (!this._texture) {
      if (this._prefiltered) {
        this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials);
      } else {
        this._texture = this._getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, onLoad, errorHandler, this._format, this._forcedExtension, false, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer, this._buffer);
      }
      this._texture?.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this));
    } else {
      if (this._texture.isReady) {
        Tools.SetImmediate(() => onLoadProcessing());
      } else {
        this._texture.onLoadedObservable.add(() => onLoadProcessing());
      }
    }
  }
  static Parse(parsedTexture, scene, rootUrl) {
    const texture = SerializationHelper.Parse(() => {
      let prefiltered = false;
      if (parsedTexture.prefiltered) {
        prefiltered = parsedTexture.prefiltered;
      }
      return new CubeTexture(rootUrl + (parsedTexture.url ?? parsedTexture.name), scene, parsedTexture.extensions, false, parsedTexture.files || null, null, null, undefined, prefiltered, parsedTexture.forcedExtension);
    }, parsedTexture, scene);
    if (parsedTexture.boundingBoxPosition) {
      texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);
    }
    if (parsedTexture.boundingBoxSize) {
      texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);
    }
    if (parsedTexture.animations) {
      for (let animationIndex = 0;animationIndex < parsedTexture.animations.length; animationIndex++) {
        const parsedAnimation = parsedTexture.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          texture.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
    }
    return texture;
  }
  clone() {
    let uniqueId = 0;
    const newCubeTexture = SerializationHelper.Clone(() => {
      const cubeTexture = new CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files);
      uniqueId = cubeTexture.uniqueId;
      return cubeTexture;
    }, this);
    newCubeTexture.uniqueId = uniqueId;
    return newCubeTexture;
  }
}
__decorate([
  serialize()
], CubeTexture.prototype, "url", undefined);
__decorate([
  serializeAsVector3()
], CubeTexture.prototype, "boundingBoxPosition", undefined);
__decorate([
  serializeAsVector3()
], CubeTexture.prototype, "boundingBoxSize", null);
__decorate([
  serialize("rotationY")
], CubeTexture.prototype, "rotationY", null);
__decorate([
  serialize("files")
], CubeTexture.prototype, "_files", undefined);
__decorate([
  serialize("forcedExtension")
], CubeTexture.prototype, "_forcedExtension", undefined);
__decorate([
  serialize("extensions")
], CubeTexture.prototype, "_extensions", undefined);
__decorate([
  serializeAsMatrix("textureMatrix")
], CubeTexture.prototype, "_textureMatrix", undefined);
__decorate([
  serializeAsMatrix("textureMatrixRefraction")
], CubeTexture.prototype, "_textureMatrixRefraction", undefined);
Texture._CubeTextureParser = CubeTexture.Parse;
RegisterClass("BABYLON.CubeTexture", CubeTexture);

// node_modules/@babylonjs/core/Materials/Background/backgroundMaterial.js
init_tslib_es6();
init_decorators();
init_smartArray();
init_logger();
init_math_vector();
init_buffer();
init_imageProcessingConfiguration();
init_texture();
init_typeStore();
init_math_color();
init_materialHelper_functions();
init_decorators_serialization();

class BackgroundMaterialDefines extends MaterialDefines {
  constructor() {
    super();
    this.DIFFUSE = false;
    this.DIFFUSEDIRECTUV = 0;
    this.GAMMADIFFUSE = false;
    this.DIFFUSEHASALPHA = false;
    this.OPACITYFRESNEL = false;
    this.REFLECTIONBLUR = false;
    this.REFLECTIONFRESNEL = false;
    this.REFLECTIONFALLOFF = false;
    this.TEXTURELODSUPPORT = false;
    this.PREMULTIPLYALPHA = false;
    this.USERGBCOLOR = false;
    this.USEHIGHLIGHTANDSHADOWCOLORS = false;
    this.BACKMAT_SHADOWONLY = false;
    this.NOISE = false;
    this.REFLECTIONBGR = false;
    this.PROJECTED_GROUND = false;
    this.IMAGEPROCESSING = false;
    this.VIGNETTE = false;
    this.VIGNETTEBLENDMODEMULTIPLY = false;
    this.VIGNETTEBLENDMODEOPAQUE = false;
    this.TONEMAPPING = 0;
    this.CONTRAST = false;
    this.COLORCURVES = false;
    this.COLORGRADING = false;
    this.COLORGRADING3D = false;
    this.SAMPLER3DGREENDEPTH = false;
    this.SAMPLER3DBGRMAP = false;
    this.DITHER = false;
    this.IMAGEPROCESSINGPOSTPROCESS = false;
    this.SKIPFINALCOLORCLAMP = false;
    this.EXPOSURE = false;
    this.MULTIVIEW = false;
    this.REFLECTION = false;
    this.REFLECTIONMAP_3D = false;
    this.REFLECTIONMAP_SPHERICAL = false;
    this.REFLECTIONMAP_PLANAR = false;
    this.REFLECTIONMAP_CUBIC = false;
    this.REFLECTIONMAP_PROJECTION = false;
    this.REFLECTIONMAP_SKYBOX = false;
    this.REFLECTIONMAP_EXPLICIT = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
    this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
    this.INVERTCUBICMAP = false;
    this.REFLECTIONMAP_OPPOSITEZ = false;
    this.LODINREFLECTIONALPHA = false;
    this.GAMMAREFLECTION = false;
    this.RGBDREFLECTION = false;
    this.EQUIRECTANGULAR_RELFECTION_FOV = false;
    this.MAINUV1 = false;
    this.MAINUV2 = false;
    this.UV1 = false;
    this.UV2 = false;
    this.CLIPPLANE = false;
    this.CLIPPLANE2 = false;
    this.CLIPPLANE3 = false;
    this.CLIPPLANE4 = false;
    this.CLIPPLANE5 = false;
    this.CLIPPLANE6 = false;
    this.POINTSIZE = false;
    this.FOG = false;
    this.NORMAL = false;
    this.NUM_BONE_INFLUENCERS = 0;
    this.BonesPerMesh = 0;
    this.INSTANCES = false;
    this.SHADOWFLOAT = false;
    this.LOGARITHMICDEPTH = false;
    this.NONUNIFORMSCALING = false;
    this.ALPHATEST = false;
    this.rebuild();
  }
}

class BackgroundMaterial extends PushMaterial {
  get _perceptualColor() {
    return this.__perceptualColor;
  }
  set _perceptualColor(value) {
    this.__perceptualColor = value;
    this._computePrimaryColorFromPerceptualColor();
    this._markAllSubMeshesAsLightsDirty();
  }
  get primaryColorShadowLevel() {
    return this._primaryColorShadowLevel;
  }
  set primaryColorShadowLevel(value) {
    this._primaryColorShadowLevel = value;
    this._computePrimaryColors();
    this._markAllSubMeshesAsLightsDirty();
  }
  get primaryColorHighlightLevel() {
    return this._primaryColorHighlightLevel;
  }
  set primaryColorHighlightLevel(value) {
    this._primaryColorHighlightLevel = value;
    this._computePrimaryColors();
    this._markAllSubMeshesAsLightsDirty();
  }
  set reflectionStandardFresnelWeight(value) {
    let reflectionWeight = value;
    if (reflectionWeight < 0.5) {
      reflectionWeight = reflectionWeight * 2;
      this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
      this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
    } else {
      reflectionWeight = reflectionWeight * 2 - 1;
      this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
      this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
    }
  }
  get fovMultiplier() {
    return this._fovMultiplier;
  }
  set fovMultiplier(value) {
    if (isNaN(value)) {
      value = 1;
    }
    this._fovMultiplier = Math.max(0, Math.min(2, value));
  }
  _attachImageProcessingConfiguration(configuration) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (!configuration) {
      this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
    } else {
      this._imageProcessingConfiguration = configuration;
    }
    if (this._imageProcessingConfiguration) {
      this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
        this._computePrimaryColorFromPerceptualColor();
        this._markAllSubMeshesAsImageProcessingDirty();
      });
    }
  }
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    this._attachImageProcessingConfiguration(value);
    this._markAllSubMeshesAsTexturesDirty();
  }
  get cameraColorCurvesEnabled() {
    return this.imageProcessingConfiguration.colorCurvesEnabled;
  }
  set cameraColorCurvesEnabled(value) {
    this.imageProcessingConfiguration.colorCurvesEnabled = value;
  }
  get cameraColorGradingEnabled() {
    return this.imageProcessingConfiguration.colorGradingEnabled;
  }
  set cameraColorGradingEnabled(value) {
    this.imageProcessingConfiguration.colorGradingEnabled = value;
  }
  get cameraToneMappingEnabled() {
    return this._imageProcessingConfiguration.toneMappingEnabled;
  }
  set cameraToneMappingEnabled(value) {
    this._imageProcessingConfiguration.toneMappingEnabled = value;
  }
  get cameraExposure() {
    return this._imageProcessingConfiguration.exposure;
  }
  set cameraExposure(value) {
    this._imageProcessingConfiguration.exposure = value;
  }
  get cameraContrast() {
    return this._imageProcessingConfiguration.contrast;
  }
  set cameraContrast(value) {
    this._imageProcessingConfiguration.contrast = value;
  }
  get cameraColorGradingTexture() {
    return this._imageProcessingConfiguration.colorGradingTexture;
  }
  set cameraColorGradingTexture(value) {
    this.imageProcessingConfiguration.colorGradingTexture = value;
  }
  get cameraColorCurves() {
    return this.imageProcessingConfiguration.colorCurves;
  }
  set cameraColorCurves(value) {
    this.imageProcessingConfiguration.colorCurves = value;
  }
  constructor(name247, scene, forceGLSL = false) {
    super(name247, scene, undefined, forceGLSL);
    this.primaryColor = Color3.White();
    this._primaryColorShadowLevel = 0;
    this._primaryColorHighlightLevel = 0;
    this.reflectionTexture = null;
    this.reflectionBlur = 0;
    this.diffuseTexture = null;
    this._shadowLights = null;
    this.shadowLights = null;
    this.shadowLevel = 0;
    this.sceneCenter = Vector3.Zero();
    this.opacityFresnel = true;
    this.reflectionFresnel = false;
    this.reflectionFalloffDistance = 0;
    this.reflectionAmount = 1;
    this.reflectionReflectance0 = 0.05;
    this.reflectionReflectance90 = 0.5;
    this.useRGBColor = true;
    this.enableNoise = false;
    this._fovMultiplier = 1;
    this.useEquirectangularFOV = false;
    this._maxSimultaneousLights = 4;
    this.maxSimultaneousLights = 4;
    this._shadowOnly = false;
    this.shadowOnly = false;
    this._imageProcessingObserver = null;
    this.switchToBGR = false;
    this._enableGroundProjection = false;
    this.enableGroundProjection = false;
    this.projectedGroundRadius = 1000;
    this.projectedGroundHeight = 10;
    this._renderTargets = new SmartArray(16);
    this._reflectionControls = Vector4.Zero();
    this._white = Color3.White();
    this._primaryShadowColor = Color3.Black();
    this._primaryHighlightColor = Color3.Black();
    this._shadersLoaded = false;
    this._attachImageProcessingConfiguration(null);
    this.getRenderTargetTextures = () => {
      this._renderTargets.reset();
      if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
        this._renderTargets.push(this._diffuseTexture);
      }
      if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
        this._renderTargets.push(this._reflectionTexture);
      }
      return this._renderTargets;
    };
  }
  get hasRenderTargetTextures() {
    if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
      return true;
    }
    if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
      return true;
    }
    return false;
  }
  needAlphaTesting() {
    return true;
  }
  needAlphaBlending() {
    return this.alpha < 1 || this._diffuseTexture != null && this._diffuseTexture.hasAlpha || this._shadowOnly;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances = false) {
    const drawWrapper = subMesh._drawWrapper;
    if (drawWrapper.effect && this.isFrozen) {
      if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    if (!subMesh.materialDefines) {
      subMesh.materialDefines = new BackgroundMaterialDefines;
    }
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (this._isReadyForSubMesh(subMesh)) {
      return true;
    }
    const engine2 = scene.getEngine();
    PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
    defines._needNormals = true;
    PrepareDefinesForMultiview(scene, defines);
    if (defines._areTexturesDirty) {
      defines._needUVs = false;
      if (scene.texturesEnabled) {
        if (scene.getEngine().getCaps().textureLOD) {
          defines.TEXTURELODSUPPORT = true;
        }
        if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
          if (!this._diffuseTexture.isReadyOrNotBlocking()) {
            return false;
          }
          PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
          defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
          defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
          defines.OPACITYFRESNEL = this._opacityFresnel;
        } else {
          defines.DIFFUSE = false;
          defines.DIFFUSEDIRECTUV = 0;
          defines.DIFFUSEHASALPHA = false;
          defines.GAMMADIFFUSE = false;
          defines.OPACITYFRESNEL = false;
        }
        const reflectionTexture = this._reflectionTexture;
        if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
          if (!reflectionTexture.isReadyOrNotBlocking()) {
            return false;
          }
          defines.REFLECTION = true;
          defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
          defines.RGBDREFLECTION = reflectionTexture.isRGBD;
          defines.REFLECTIONBLUR = this._reflectionBlur > 0;
          defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
          defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
          defines.REFLECTIONBGR = this.switchToBGR;
          if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {
            defines.INVERTCUBICMAP = true;
          }
          defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
          defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
          switch (reflectionTexture.coordinatesMode) {
            case Texture.EXPLICIT_MODE:
              defines.REFLECTIONMAP_EXPLICIT = true;
              break;
            case Texture.PLANAR_MODE:
              defines.REFLECTIONMAP_PLANAR = true;
              break;
            case Texture.PROJECTION_MODE:
              defines.REFLECTIONMAP_PROJECTION = true;
              break;
            case Texture.SKYBOX_MODE:
              defines.REFLECTIONMAP_SKYBOX = true;
              break;
            case Texture.SPHERICAL_MODE:
              defines.REFLECTIONMAP_SPHERICAL = true;
              break;
            case Texture.EQUIRECTANGULAR_MODE:
              defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
              break;
            case Texture.FIXED_EQUIRECTANGULAR_MODE:
              defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
              break;
            case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
              defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
              break;
            case Texture.CUBIC_MODE:
            case Texture.INVCUBIC_MODE:
            default:
              defines.REFLECTIONMAP_CUBIC = true;
              break;
          }
          if (this.reflectionFresnel) {
            defines.REFLECTIONFRESNEL = true;
            defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
            this._reflectionControls.x = this.reflectionAmount;
            this._reflectionControls.y = this.reflectionReflectance0;
            this._reflectionControls.z = this.reflectionReflectance90;
            this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
          } else {
            defines.REFLECTIONFRESNEL = false;
            defines.REFLECTIONFALLOFF = false;
          }
        } else {
          defines.REFLECTION = false;
          defines.REFLECTIONFRESNEL = false;
          defines.REFLECTIONFALLOFF = false;
          defines.REFLECTIONBLUR = false;
          defines.REFLECTIONMAP_3D = false;
          defines.REFLECTIONMAP_SPHERICAL = false;
          defines.REFLECTIONMAP_PLANAR = false;
          defines.REFLECTIONMAP_CUBIC = false;
          defines.REFLECTIONMAP_PROJECTION = false;
          defines.REFLECTIONMAP_SKYBOX = false;
          defines.REFLECTIONMAP_EXPLICIT = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
          defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
          defines.INVERTCUBICMAP = false;
          defines.REFLECTIONMAP_OPPOSITEZ = false;
          defines.LODINREFLECTIONALPHA = false;
          defines.GAMMAREFLECTION = false;
          defines.RGBDREFLECTION = false;
        }
      }
      defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;
      defines.USERGBCOLOR = this._useRGBColor;
      defines.NOISE = this._enableNoise;
    }
    if (defines._areLightsDirty) {
      defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
      defines.BACKMAT_SHADOWONLY = this._shadowOnly;
    }
    if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
      if (!this._imageProcessingConfiguration.isReady()) {
        return false;
      }
      this._imageProcessingConfiguration.prepareDefines(defines);
    }
    if (defines._areMiscDirty) {
      if (defines.REFLECTIONMAP_3D && this._enableGroundProjection) {
        defines.PROJECTED_GROUND = true;
        defines.REFLECTIONMAP_SKYBOX = true;
      } else {
        defines.PROJECTED_GROUND = false;
      }
    }
    PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines);
    PrepareDefinesForFrameBoundValues(scene, engine2, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
    if (PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
      if (mesh) {
        if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
          mesh.createNormals(true);
          Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
        }
      }
    }
    if (defines.isDirty) {
      defines.markAsProcessed();
      scene.resetCachedMaterial();
      const fallbacks = new EffectFallbacks;
      if (defines.FOG) {
        fallbacks.addFallback(0, "FOG");
      }
      if (defines.POINTSIZE) {
        fallbacks.addFallback(1, "POINTSIZE");
      }
      if (defines.MULTIVIEW) {
        fallbacks.addFallback(0, "MULTIVIEW");
      }
      HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
      const attribs = [VertexBuffer.PositionKind];
      if (defines.NORMAL) {
        attribs.push(VertexBuffer.NormalKind);
      }
      if (defines.UV1) {
        attribs.push(VertexBuffer.UVKind);
      }
      if (defines.UV2) {
        attribs.push(VertexBuffer.UV2Kind);
      }
      PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
      PrepareAttributesForInstances(attribs, defines);
      const uniforms = [
        "world",
        "view",
        "viewProjection",
        "vEyePosition",
        "vLightsType",
        "vFogInfos",
        "vFogColor",
        "pointSize",
        "mBones",
        "vPrimaryColor",
        "vPrimaryColorShadow",
        "vReflectionInfos",
        "reflectionMatrix",
        "vReflectionMicrosurfaceInfos",
        "fFovMultiplier",
        "shadowLevel",
        "alpha",
        "vBackgroundCenter",
        "vReflectionControl",
        "vDiffuseInfos",
        "diffuseMatrix",
        "projectedGroundInfos",
        "logarithmicDepthConstant"
      ];
      addClipPlaneUniforms(uniforms);
      const samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
      const uniformBuffers = ["Material", "Scene"];
      if (ImageProcessingConfiguration) {
        ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
        ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
      }
      PrepareUniformsAndSamplersList({
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines,
        maxSimultaneousLights: this._maxSimultaneousLights
      });
      const join6 = defines.toString();
      const effect = scene.getEngine().createEffect("background", {
        attributes: attribs,
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: this.onCompiled,
        onError: this.onError,
        indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights },
        shaderLanguage: this._shaderLanguage,
        extraInitializationsAsync: this._shadersLoaded ? undefined : async () => {
          if (this.shaderLanguage === 1) {
            await Promise.all([Promise.resolve().then(() => (init_background_vertex(), exports_background_vertex)), Promise.resolve().then(() => (init_background_fragment(), exports_background_fragment))]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_background_vertex2(), exports_background_vertex2)), Promise.resolve().then(() => (init_background_fragment2(), exports_background_fragment2))]);
          }
          this._shadersLoaded = true;
        }
      }, engine2);
      subMesh.setEffect(effect, defines, this._materialContext);
      this.buildUniformLayout();
    }
    if (!subMesh.effect || !subMesh.effect.isReady()) {
      return false;
    }
    defines._renderId = scene.getRenderId();
    drawWrapper._wasPreviouslyReady = true;
    drawWrapper._wasPreviouslyUsingInstances = useInstances;
    this._checkScenePerformancePriority();
    return true;
  }
  _computePrimaryColorFromPerceptualColor() {
    if (!this.__perceptualColor) {
      return;
    }
    this._primaryColor.copyFrom(this.__perceptualColor);
    this._primaryColor.toLinearSpaceToRef(this._primaryColor, this.getScene().getEngine().useExactSrgbConversions);
    if (this._imageProcessingConfiguration) {
      this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
    }
    this._computePrimaryColors();
  }
  _computePrimaryColors() {
    if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
      return;
    }
    this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
    this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
    this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
    this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
    this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  }
  buildUniformLayout() {
    this._uniformBuffer.addUniform("vPrimaryColor", 4);
    this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
    this._uniformBuffer.addUniform("vDiffuseInfos", 2);
    this._uniformBuffer.addUniform("vReflectionInfos", 2);
    this._uniformBuffer.addUniform("diffuseMatrix", 16);
    this._uniformBuffer.addUniform("reflectionMatrix", 16);
    this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
    this._uniformBuffer.addUniform("fFovMultiplier", 1);
    this._uniformBuffer.addUniform("pointSize", 1);
    this._uniformBuffer.addUniform("shadowLevel", 1);
    this._uniformBuffer.addUniform("alpha", 1);
    this._uniformBuffer.addUniform("vBackgroundCenter", 3);
    this._uniformBuffer.addUniform("vReflectionControl", 4);
    this._uniformBuffer.addUniform("projectedGroundInfos", 2);
    this._uniformBuffer.create();
  }
  unbind() {
    if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
      this._uniformBuffer.setTexture("diffuseSampler", null);
    }
    if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
      this._uniformBuffer.setTexture("reflectionSampler", null);
    }
    super.unbind();
  }
  bindOnlyWorldMatrix(world) {
    this._activeEffect.setMatrix("world", world);
  }
  bindForSubMesh(world, mesh, subMesh) {
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (!defines) {
      return;
    }
    const effect = subMesh.effect;
    if (!effect) {
      return;
    }
    this._activeEffect = effect;
    this.bindOnlyWorldMatrix(world);
    BindBonesParameters(mesh, this._activeEffect);
    const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
    if (mustRebind) {
      this._uniformBuffer.bindToEffect(effect, "Material");
      this.bindViewProjection(effect);
      const reflectionTexture = this._reflectionTexture;
      if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync || subMesh._drawWrapper._forceRebindOnNextCall) {
        if (scene.texturesEnabled) {
          if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
            this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
            BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
          }
          if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
            this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
            this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
            this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
          }
        }
        if (this.shadowLevel > 0) {
          this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
        }
        this._uniformBuffer.updateFloat("alpha", this.alpha);
        if (this.pointsCloud) {
          this._uniformBuffer.updateFloat("pointSize", this.pointSize);
        }
        if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
          this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1);
          this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1);
        } else {
          this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1);
        }
      }
      this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
      if (scene.texturesEnabled) {
        if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
          this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
        }
        if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
          if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
          } else if (!defines.REFLECTIONBLUR) {
            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
          } else {
            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
            this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
            this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
          }
          if (defines.REFLECTIONFRESNEL) {
            this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
            this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
          }
        }
        if (defines.PROJECTED_GROUND) {
          this._uniformBuffer.updateFloat2("projectedGroundInfos", this.projectedGroundRadius, this.projectedGroundHeight);
        }
      }
      bindClipPlane(this._activeEffect, this, scene);
      scene.bindEyePosition(effect);
    } else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
      this._uniformBuffer.bindToEffect(effect, "Material");
      this._needToBindSceneUbo = true;
    }
    if (mustRebind || !this.isFrozen) {
      if (scene.lightsEnabled) {
        BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);
      }
      this.bindView(effect);
      BindFogParameters(scene, mesh, this._activeEffect, true);
      if (this._useLogarithmicDepth) {
        BindLogDepth(defines, effect, scene);
      }
      if (this._imageProcessingConfiguration) {
        this._imageProcessingConfiguration.bind(this._activeEffect);
      }
    }
    this._afterBind(mesh, this._activeEffect, subMesh);
    this._uniformBuffer.update();
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    if (this._reflectionTexture === texture) {
      return true;
    }
    if (this._diffuseTexture === texture) {
      return true;
    }
    return false;
  }
  dispose(forceDisposeEffect = false, forceDisposeTextures = false) {
    if (forceDisposeTextures) {
      if (this.diffuseTexture) {
        this.diffuseTexture.dispose();
      }
      if (this.reflectionTexture) {
        this.reflectionTexture.dispose();
      }
    }
    this._renderTargets.dispose();
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    super.dispose(forceDisposeEffect);
  }
  clone(name247) {
    return SerializationHelper.Clone(() => new BackgroundMaterial(name247, this.getScene()), this);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.customType = "BABYLON.BackgroundMaterial";
    return serializationObject;
  }
  getClassName() {
    return "BackgroundMaterial";
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl);
  }
}
BackgroundMaterial.StandardReflectance0 = 0.05;
BackgroundMaterial.StandardReflectance90 = 0.5;
__decorate([
  serializeAsColor3()
], BackgroundMaterial.prototype, "_primaryColor", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "primaryColor", undefined);
__decorate([
  serializeAsColor3()
], BackgroundMaterial.prototype, "__perceptualColor", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_primaryColorShadowLevel", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
__decorate([
  serializeAsTexture()
], BackgroundMaterial.prototype, "_reflectionTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionTexture", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionBlur", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionBlur", undefined);
__decorate([
  serializeAsTexture()
], BackgroundMaterial.prototype, "_diffuseTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "diffuseTexture", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "shadowLights", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_shadowLevel", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "shadowLevel", undefined);
__decorate([
  serializeAsVector3()
], BackgroundMaterial.prototype, "_sceneCenter", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "sceneCenter", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_opacityFresnel", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "opacityFresnel", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionFresnel", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionFresnel", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionFalloffDistance", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionFalloffDistance", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionAmount", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionAmount", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionReflectance0", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionReflectance0", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_reflectionReflectance90", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionReflectance90", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_useRGBColor", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "useRGBColor", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_enableNoise", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "enableNoise", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_maxSimultaneousLights", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "maxSimultaneousLights", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "_shadowOnly", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "shadowOnly", undefined);
__decorate([
  serializeAsImageProcessingConfiguration()
], BackgroundMaterial.prototype, "_imageProcessingConfiguration", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], BackgroundMaterial.prototype, "enableGroundProjection", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "projectedGroundRadius", undefined);
__decorate([
  serialize()
], BackgroundMaterial.prototype, "projectedGroundHeight", undefined);
RegisterClass("BABYLON.BackgroundMaterial", BackgroundMaterial);

// node_modules/@babylonjs/core/Helpers/environmentHelper.js
init_math_plane();
init_tools();

class EnvironmentHelper {
  static _GetDefaultOptions(scene) {
    return {
      createGround: true,
      groundSize: 15,
      groundTexture: Tools.GetAssetUrl(this._GroundTextureCDNUrl),
      groundColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),
      groundOpacity: 0.9,
      enableGroundShadow: true,
      groundShadowLevel: 0.5,
      enableGroundMirror: false,
      groundMirrorSizeRatio: 0.3,
      groundMirrorBlurKernel: 64,
      groundMirrorAmount: 1,
      groundMirrorFresnelWeight: 1,
      groundMirrorFallOffDistance: 0,
      groundMirrorTextureType: 0,
      groundYBias: 0.00001,
      createSkybox: true,
      skyboxSize: 20,
      skyboxTexture: Tools.GetAssetUrl(this._SkyboxTextureCDNUrl),
      skyboxColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),
      backgroundYRotation: 0,
      sizeAuto: true,
      rootPosition: Vector3.Zero(),
      setupImageProcessing: true,
      environmentTexture: Tools.GetAssetUrl(this._EnvironmentTextureCDNUrl),
      cameraExposure: 0.8,
      cameraContrast: 1.2,
      toneMappingEnabled: true
    };
  }
  get rootMesh() {
    return this._rootMesh;
  }
  get skybox() {
    return this._skybox;
  }
  get skyboxTexture() {
    return this._skyboxTexture;
  }
  get skyboxMaterial() {
    return this._skyboxMaterial;
  }
  get ground() {
    return this._ground;
  }
  get groundTexture() {
    return this._groundTexture;
  }
  get groundMirror() {
    return this._groundMirror;
  }
  get groundMirrorRenderList() {
    if (this._groundMirror) {
      return this._groundMirror.renderList;
    }
    return null;
  }
  get groundMaterial() {
    return this._groundMaterial;
  }
  constructor(options, scene) {
    this._errorHandler = (message, exception) => {
      this.onErrorObservable.notifyObservers({ message, exception });
    };
    this._options = {
      ...EnvironmentHelper._GetDefaultOptions(scene),
      ...options
    };
    this._scene = scene;
    this.onErrorObservable = new Observable;
    this._setupBackground();
    this._setupImageProcessing();
  }
  updateOptions(options) {
    const newOptions = {
      ...this._options,
      ...options
    };
    if (this._ground && !newOptions.createGround) {
      this._ground.dispose();
      this._ground = null;
    }
    if (this._groundMaterial && !newOptions.createGround) {
      this._groundMaterial.dispose();
      this._groundMaterial = null;
    }
    if (this._groundTexture) {
      if (this._options.groundTexture != newOptions.groundTexture) {
        this._groundTexture.dispose();
        this._groundTexture = null;
      }
    }
    if (this._skybox && !newOptions.createSkybox) {
      this._skybox.dispose();
      this._skybox = null;
    }
    if (this._skyboxMaterial && !newOptions.createSkybox) {
      this._skyboxMaterial.dispose();
      this._skyboxMaterial = null;
    }
    if (this._skyboxTexture) {
      if (this._options.skyboxTexture != newOptions.skyboxTexture) {
        this._skyboxTexture.dispose();
        this._skyboxTexture = null;
      }
    }
    if (this._groundMirror && !newOptions.enableGroundMirror) {
      this._groundMirror.dispose();
      this._groundMirror = null;
    }
    if (this._scene.environmentTexture) {
      if (this._options.environmentTexture != newOptions.environmentTexture) {
        this._scene.environmentTexture.dispose();
      }
    }
    this._options = newOptions;
    this._setupBackground();
    this._setupImageProcessing();
  }
  setMainColor(color) {
    if (this.groundMaterial) {
      this.groundMaterial.primaryColor = color;
    }
    if (this.skyboxMaterial) {
      this.skyboxMaterial.primaryColor = color;
    }
    if (this.groundMirror) {
      this.groundMirror.clearColor = new Color4(color.r, color.g, color.b, 1);
    }
  }
  _setupImageProcessing() {
    if (this._options.setupImageProcessing) {
      this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
      this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
      this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
      this._setupEnvironmentTexture();
    }
  }
  _setupEnvironmentTexture() {
    if (this._scene.environmentTexture) {
      return;
    }
    if (this._options.environmentTexture instanceof BaseTexture) {
      this._scene.environmentTexture = this._options.environmentTexture;
      return;
    }
    const environmentTexture = CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
    this._scene.environmentTexture = environmentTexture;
  }
  _setupBackground() {
    if (!this._rootMesh) {
      this._rootMesh = new Mesh("BackgroundHelper", this._scene);
    }
    this._rootMesh.rotation.y = this._options.backgroundYRotation;
    const sceneSize = this._getSceneSize();
    if (this._options.createGround) {
      this._setupGround(sceneSize);
      this._setupGroundMaterial();
      this._setupGroundDiffuseTexture();
      if (this._options.enableGroundMirror) {
        this._setupGroundMirrorTexture(sceneSize);
      }
      this._setupMirrorInGroundMaterial();
    }
    if (this._options.createSkybox) {
      this._setupSkybox(sceneSize);
      this._setupSkyboxMaterial();
      this._setupSkyboxReflectionTexture();
    }
    this._rootMesh.position.x = sceneSize.rootPosition.x;
    this._rootMesh.position.z = sceneSize.rootPosition.z;
    this._rootMesh.position.y = sceneSize.rootPosition.y;
  }
  _getSceneSize() {
    let groundSize = this._options.groundSize;
    let skyboxSize = this._options.skyboxSize;
    let rootPosition = this._options.rootPosition;
    if (!this._scene.meshes || this._scene.meshes.length === 1) {
      return { groundSize, skyboxSize, rootPosition };
    }
    const sceneExtends = this._scene.getWorldExtends((mesh) => {
      return mesh !== this._ground && mesh !== this._rootMesh && mesh !== this._skybox;
    });
    const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
    if (this._options.sizeAuto) {
      if (this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) {
        groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
        skyboxSize = groundSize;
      }
      const sceneDiagonalLenght = sceneDiagonal.length();
      if (sceneDiagonalLenght > groundSize) {
        groundSize = sceneDiagonalLenght * 2;
        skyboxSize = groundSize;
      }
      groundSize *= 1.1;
      skyboxSize *= 1.5;
      rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
      rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
    }
    return { groundSize, skyboxSize, rootPosition };
  }
  _setupGround(sceneSize) {
    if (!this._ground || this._ground.isDisposed()) {
      this._ground = CreatePlane("BackgroundPlane", { size: sceneSize.groundSize }, this._scene);
      this._ground.rotation.x = Math.PI / 2;
      this._ground.isPickable = false;
      this._ground.parent = this._rootMesh;
      this._ground.onDisposeObservable.add(() => {
        this._ground = null;
      });
    }
    this._ground.receiveShadows = this._options.enableGroundShadow;
  }
  _setupGroundMaterial() {
    if (!this._groundMaterial) {
      this._groundMaterial = new BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
    }
    this._groundMaterial.alpha = this._options.groundOpacity;
    this._groundMaterial.alphaMode = 8;
    this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
    this._groundMaterial.primaryColor = this._options.groundColor;
    this._groundMaterial.useRGBColor = false;
    this._groundMaterial.enableNoise = true;
    if (this._ground) {
      this._ground.material = this._groundMaterial;
    }
  }
  _setupGroundDiffuseTexture() {
    if (!this._groundMaterial) {
      return;
    }
    if (this._groundTexture) {
      return;
    }
    if (this._options.groundTexture instanceof BaseTexture) {
      this._groundMaterial.diffuseTexture = this._options.groundTexture;
      return;
    }
    this._groundTexture = new Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
    this._groundTexture.gammaSpace = false;
    this._groundTexture.hasAlpha = true;
    this._groundMaterial.diffuseTexture = this._groundTexture;
  }
  _setupGroundMirrorTexture(sceneSize) {
    const wrapping = Texture.CLAMP_ADDRESSMODE;
    if (!this._groundMirror) {
      this._groundMirror = new MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, Texture.BILINEAR_SAMPLINGMODE, true);
      this._groundMirror.mirrorPlane = new Plane(0, -1, 0, sceneSize.rootPosition.y);
      this._groundMirror.anisotropicFilteringLevel = 1;
      this._groundMirror.wrapU = wrapping;
      this._groundMirror.wrapV = wrapping;
      if (this._groundMirror.renderList) {
        for (let i = 0;i < this._scene.meshes.length; i++) {
          const mesh = this._scene.meshes[i];
          if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) {
            this._groundMirror.renderList.push(mesh);
          }
        }
      }
    }
    const gammaGround = this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);
    this._groundMirror.clearColor = new Color4(gammaGround.r, gammaGround.g, gammaGround.b, 1);
    this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  }
  _setupMirrorInGroundMaterial() {
    if (this._groundMaterial) {
      this._groundMaterial.reflectionTexture = this._groundMirror;
      this._groundMaterial.reflectionFresnel = true;
      this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
      this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
      this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
    }
  }
  _setupSkybox(sceneSize) {
    if (!this._skybox || this._skybox.isDisposed()) {
      this._skybox = CreateBox("BackgroundSkybox", { size: sceneSize.skyboxSize, sideOrientation: Mesh.BACKSIDE }, this._scene);
      this._skybox.isPickable = false;
      this._skybox.onDisposeObservable.add(() => {
        this._skybox = null;
      });
    }
    this._skybox.parent = this._rootMesh;
  }
  _setupSkyboxMaterial() {
    if (!this._skybox) {
      return;
    }
    if (!this._skyboxMaterial) {
      this._skyboxMaterial = new BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
    }
    this._skyboxMaterial.useRGBColor = false;
    this._skyboxMaterial.primaryColor = this._options.skyboxColor;
    this._skyboxMaterial.enableNoise = true;
    this._skybox.material = this._skyboxMaterial;
  }
  _setupSkyboxReflectionTexture() {
    if (!this._skyboxMaterial) {
      return;
    }
    if (this._skyboxTexture) {
      return;
    }
    if (this._options.skyboxTexture instanceof BaseTexture) {
      this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
      return;
    }
    this._skyboxTexture = new CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
    this._skyboxTexture.coordinatesMode = Texture.SKYBOX_MODE;
    this._skyboxTexture.gammaSpace = false;
    this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  }
  dispose() {
    if (this._groundMaterial) {
      this._groundMaterial.dispose(true, true);
    }
    if (this._skyboxMaterial) {
      this._skyboxMaterial.dispose(true, true);
    }
    this._rootMesh.dispose(false);
  }
}
EnvironmentHelper._GroundTextureCDNUrl = "https://assets.babylonjs.com/core/environments/backgroundGround.png";
EnvironmentHelper._SkyboxTextureCDNUrl = "https://assets.babylonjs.com/core/environments/backgroundSkybox.dds";
EnvironmentHelper._EnvironmentTextureCDNUrl = "https://assets.babylonjs.com/core/environments/environmentSpecular.env";
// node_modules/@babylonjs/core/Helpers/photoDome.js
init_texture();

// node_modules/@babylonjs/core/Helpers/textureDome.js
init_texture();
init_observable();
init_math_vector();
init_math();

class TextureDome extends TransformNode {
  get texture() {
    return this._texture;
  }
  set texture(newTexture) {
    if (this._texture === newTexture) {
      return;
    }
    this._texture = newTexture;
    if (this._useDirectMapping) {
      this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;
      this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;
      this._material.diffuseTexture = this._texture;
    } else {
      this._texture.coordinatesMode = Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
      this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;
      this._material.reflectionTexture = this._texture;
    }
    this._changeTextureMode(this._textureMode);
  }
  get mesh() {
    return this._mesh;
  }
  get fovMultiplier() {
    return this._material.fovMultiplier;
  }
  set fovMultiplier(value) {
    this._material.fovMultiplier = value;
  }
  get textureMode() {
    return this._textureMode;
  }
  set textureMode(value) {
    if (this._textureMode === value) {
      return;
    }
    this._changeTextureMode(value);
  }
  get halfDome() {
    return this._halfDome;
  }
  set halfDome(enabled) {
    this._halfDome = enabled;
    this._halfDomeMask.setEnabled(enabled);
    this._changeTextureMode(this._textureMode);
  }
  set crossEye(enabled) {
    this._crossEye = enabled;
    this._changeTextureMode(this._textureMode);
  }
  get crossEye() {
    return this._crossEye;
  }
  get material() {
    return this._material;
  }
  constructor(name247, textureUrlOrElement, options, scene, onError = null) {
    super(name247, scene);
    this.onError = onError;
    this._halfDome = false;
    this._crossEye = false;
    this._useDirectMapping = false;
    this._textureMode = TextureDome.MODE_MONOSCOPIC;
    this._onBeforeCameraRenderObserver = null;
    this.onLoadErrorObservable = new Observable;
    this.onLoadObservable = new Observable;
    scene = this.getScene();
    name247 = name247 || "textureDome";
    options.resolution = Math.abs(options.resolution) | 0 || 32;
    options.clickToPlay = Boolean(options.clickToPlay);
    options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
    options.loop = options.loop === undefined ? true : Boolean(options.loop);
    options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
    if (options.useDirectMapping === undefined) {
      this._useDirectMapping = true;
    } else {
      this._useDirectMapping = options.useDirectMapping;
    }
    if (options.faceForward === undefined) {
      options.faceForward = true;
    }
    this._setReady(false);
    if (!options.mesh) {
      this._mesh = CreateSphere(name247 + "_mesh", { segments: options.resolution, diameter: options.size, updatable: false, sideOrientation: Mesh.BACKSIDE }, scene);
    } else {
      this._mesh = options.mesh;
    }
    const material = this._material = new BackgroundMaterial(name247 + "_material", scene);
    material.useEquirectangularFOV = true;
    material.fovMultiplier = 1;
    material.opacityFresnel = false;
    const texture = this._initTexture(textureUrlOrElement, scene, options);
    this.texture = texture;
    this._mesh.material = material;
    this._mesh.parent = this;
    this._halfDomeMask = CreateSphere("", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: Mesh.BACKSIDE }, scene);
    this._halfDomeMask.rotate(Axis.X, -Math.PI / 2);
    this._halfDomeMask.parent = this._mesh;
    this._halfDome = !!options.halfDomeMode;
    this._halfDomeMask.setEnabled(this._halfDome);
    this._crossEye = !!options.crossEyeMode;
    this._texture.anisotropicFilteringLevel = 1;
    this._texture.onLoadObservable.addOnce(() => {
      this._setReady(true);
    });
    if (options.faceForward && scene.activeCamera) {
      const camera2 = scene.activeCamera;
      const forward = Vector3.Forward();
      const direction = Vector3.TransformNormal(forward, camera2.getViewMatrix());
      direction.normalize();
      this.rotation.y = Math.acos(Vector3.Dot(forward, direction));
    }
    this._changeTextureMode(this._textureMode);
  }
  _changeTextureMode(value) {
    this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
    this._textureMode = value;
    this._texture.uScale = 1;
    this._texture.vScale = 1;
    this._texture.uOffset = 0;
    this._texture.vOffset = 0;
    this._texture.vAng = 0;
    switch (value) {
      case TextureDome.MODE_MONOSCOPIC:
        if (this._halfDome) {
          this._texture.uScale = 2;
          this._texture.uOffset = -1;
        }
        break;
      case TextureDome.MODE_SIDEBYSIDE: {
        this._texture.uScale = this._halfDome ? 0.99999 : 0.5;
        const rightOffset = this._halfDome ? 0 : 0.5;
        const leftOffset = this._halfDome ? -0.5 : 0;
        this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera2) => {
          let isRightCamera = camera2.isRightCamera;
          if (this._crossEye) {
            isRightCamera = !isRightCamera;
          }
          if (isRightCamera) {
            this._texture.uOffset = rightOffset;
          } else {
            this._texture.uOffset = leftOffset;
          }
        });
        break;
      }
      case TextureDome.MODE_TOPBOTTOM:
        this._texture.vScale = this._halfDome ? 0.99999 : 0.5;
        this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera2) => {
          let isRightCamera = camera2.isRightCamera;
          if (this._crossEye) {
            isRightCamera = !isRightCamera;
          }
          this._texture.vOffset = isRightCamera ? 0.5 : 0;
        });
        break;
    }
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this._texture.dispose();
    this._mesh.dispose();
    this._material.dispose();
    this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
    this.onLoadErrorObservable.clear();
    this.onLoadObservable.clear();
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
}
TextureDome.MODE_MONOSCOPIC = 0;
TextureDome.MODE_TOPBOTTOM = 1;
TextureDome.MODE_SIDEBYSIDE = 2;

// node_modules/@babylonjs/core/Helpers/photoDome.js
class PhotoDome extends TextureDome {
  get photoTexture() {
    return this.texture;
  }
  set photoTexture(value) {
    this.texture = value;
  }
  get imageMode() {
    return this.textureMode;
  }
  set imageMode(value) {
    this.textureMode = value;
  }
  _initTexture(urlsOrElement, scene, options) {
    return new Texture(urlsOrElement, scene, !options.generateMipMaps, !this._useDirectMapping, undefined, () => {
      this.onLoadObservable.notifyObservers();
    }, (message, exception) => {
      this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
      if (this.onError) {
        this.onError(message, exception);
      }
    });
  }
}
PhotoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;
PhotoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;
PhotoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;
// node_modules/@babylonjs/core/Helpers/sceneHelpers.js
init_logger();
init_scene();
init_math_vector();
init_texture();

// node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js
init_tslib_es6();
init_decorators();

// node_modules/@babylonjs/core/Misc/brdfTextureTools.js
init_texture();
init_rgbdTextureTools();
var _environmentBRDFBase64Texture = "data:image/png;base64, ";
var _instanceNumber = 0;
var GetEnvironmentBRDFTexture = (scene) => {
  if (!scene.environmentBRDFTexture) {
    const useDelayedTextureLoading = scene.useDelayedTextureLoading;
    scene.useDelayedTextureLoading = false;
    const previousState = scene._blockEntityCollection;
    scene._blockEntityCollection = false;
    const texture = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, scene, true, false, Texture.BILINEAR_SAMPLINGMODE);
    scene._blockEntityCollection = previousState;
    const texturesCache = scene.getEngine().getLoadedTexturesCache();
    const index = texturesCache.indexOf(texture.getInternalTexture());
    if (index !== -1) {
      texturesCache.splice(index, 1);
    }
    texture.isRGBD = true;
    texture.wrapU = Texture.CLAMP_ADDRESSMODE;
    texture.wrapV = Texture.CLAMP_ADDRESSMODE;
    scene.environmentBRDFTexture = texture;
    scene.useDelayedTextureLoading = useDelayedTextureLoading;
    RGBDTextureTools.ExpandRGBDTexture(texture);
    const observer2 = scene.getEngine().onContextRestoredObservable.add(() => {
      texture.isRGBD = true;
      const oo = scene.onBeforeRenderObservable.add(() => {
        if (texture.isReady()) {
          scene.onBeforeRenderObservable.remove(oo);
          RGBDTextureTools.ExpandRGBDTexture(texture);
        }
      });
    });
    scene.onDisposeObservable.add(() => {
      scene.getEngine().onContextRestoredObservable.remove(observer2);
    });
  }
  return scene.environmentBRDFTexture;
};

// node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js
init_math_color();

// node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js
init_tslib_es6();
init_decorators();
init_logger();
init_smartArray();
init_scene();
init_math_vector();
init_buffer();

// node_modules/@babylonjs/core/Materials/PBR/pbrBRDFConfiguration.js
init_tslib_es6();
init_decorators();
class MaterialBRDFDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.BRDF_V_HEIGHT_CORRELATED = false;
    this.MS_BRDF_ENERGY_CONSERVATION = false;
    this.SPHERICAL_HARMONICS = false;
    this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;
    this.MIX_IBL_RADIANCE_WITH_IRRADIANCE = true;
  }
}

class PBRBRDFConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsMiscDirty() {
    this._internalMarkAllSubMeshesAsMiscDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "PBRBRDF", 90, new MaterialBRDFDefines, addToPluginList);
    this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
    this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
    this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
    this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
    this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
    this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
    this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
    this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
    this._mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE;
    this.mixIblRadianceWithIrradiance = PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE;
    this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];
    this._enable(true);
  }
  prepareDefines(defines) {
    defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated;
    defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated;
    defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics;
    defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation;
    defines.MIX_IBL_RADIANCE_WITH_IRRADIANCE = this._mixIblRadianceWithIrradiance;
  }
  getClassName() {
    return "PBRBRDFConfiguration";
  }
}
PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true;
PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true;
PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true;
PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true;
PBRBRDFConfiguration.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE = true;
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useEnergyConservation", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSphericalHarmonics", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSpecularGlossinessInputEnergyConservation", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "mixIblRadianceWithIrradiance", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js
init_math_color();
init_imageProcessingConfiguration();
init_texture();
init_baseTexture_polynomial();

// node_modules/@babylonjs/core/Materials/PBR/pbrClearCoatConfiguration.js
init_tslib_es6();
init_decorators();
init_math_color();
init_materialHelper_functions();

class MaterialClearCoatDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.CLEARCOAT = false;
    this.CLEARCOAT_DEFAULTIOR = false;
    this.CLEARCOAT_TEXTURE = false;
    this.CLEARCOAT_TEXTURE_ROUGHNESS = false;
    this.CLEARCOAT_TEXTUREDIRECTUV = 0;
    this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;
    this.CLEARCOAT_BUMP = false;
    this.CLEARCOAT_BUMPDIRECTUV = 0;
    this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
    this.CLEARCOAT_REMAP_F0 = false;
    this.CLEARCOAT_TINT = false;
    this.CLEARCOAT_TINT_TEXTURE = false;
    this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
    this.CLEARCOAT_TINT_GAMMATEXTURE = false;
  }
}

class PBRClearCoatConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "PBRClearCoat", 100, new MaterialClearCoatDefines, addToPluginList);
    this._isEnabled = false;
    this.isEnabled = false;
    this.intensity = 1;
    this.roughness = 0;
    this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
    this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
    this._texture = null;
    this.texture = null;
    this._useRoughnessFromMainTexture = true;
    this.useRoughnessFromMainTexture = true;
    this._textureRoughness = null;
    this.textureRoughness = null;
    this._remapF0OnInterfaceChange = true;
    this.remapF0OnInterfaceChange = true;
    this._bumpTexture = null;
    this.bumpTexture = null;
    this._isTintEnabled = false;
    this.isTintEnabled = false;
    this.tintColor = Color3.White();
    this.tintColorAtDistance = 1;
    this.tintThickness = 1;
    this._tintTexture = null;
    this.tintTexture = null;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
  }
  isReadyForSubMesh(defines, scene, engine2) {
    if (!this._isEnabled) {
      return true;
    }
    const disableBumpMap = this._material._disableBumpMap;
    if (defines._areTexturesDirty) {
      if (scene.texturesEnabled) {
        if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
          if (!this._texture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {
          if (!this._textureRoughness.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (engine2.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {
          if (!this._bumpTexture.isReady()) {
            return false;
          }
        }
        if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
          if (!this._tintTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
      }
    }
    return true;
  }
  prepareDefinesBeforeAttributes(defines, scene) {
    if (this._isEnabled) {
      defines.CLEARCOAT = true;
      defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;
      defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange;
      if (defines._areTexturesDirty) {
        if (scene.texturesEnabled) {
          if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
            PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE");
          } else {
            defines.CLEARCOAT_TEXTURE = false;
          }
          if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {
            PrepareDefinesForMergedUV(this._textureRoughness, defines, "CLEARCOAT_TEXTURE_ROUGHNESS");
          } else {
            defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;
          }
          if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) {
            PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP");
          } else {
            defines.CLEARCOAT_BUMP = false;
          }
          defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction;
          if (this._isTintEnabled) {
            defines.CLEARCOAT_TINT = true;
            if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
              PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE");
              defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace;
            } else {
              defines.CLEARCOAT_TINT_TEXTURE = false;
            }
          } else {
            defines.CLEARCOAT_TINT = false;
            defines.CLEARCOAT_TINT_TEXTURE = false;
          }
        }
      }
    } else {
      defines.CLEARCOAT = false;
      defines.CLEARCOAT_TEXTURE = false;
      defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;
      defines.CLEARCOAT_BUMP = false;
      defines.CLEARCOAT_TINT = false;
      defines.CLEARCOAT_TINT_TEXTURE = false;
      defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
      defines.CLEARCOAT_DEFAULTIOR = false;
      defines.CLEARCOAT_TEXTUREDIRECTUV = 0;
      defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;
      defines.CLEARCOAT_BUMPDIRECTUV = 0;
      defines.CLEARCOAT_REMAP_F0 = false;
      defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
      defines.CLEARCOAT_TINT_GAMMATEXTURE = false;
    }
  }
  bindForSubMesh(uniformBuffer, scene, engine2, subMesh) {
    if (!this._isEnabled) {
      return;
    }
    const defines = subMesh.materialDefines;
    const isFrozen = this._material.isFrozen;
    const disableBumpMap = this._material._disableBumpMap;
    const invertNormalMapX = this._material._invertNormalMapX;
    const invertNormalMapY = this._material._invertNormalMapY;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) {
        uniformBuffer.updateFloat4("vClearCoatInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0);
        if (this._texture) {
          BindTextureMatrix(this._texture, uniformBuffer, "clearCoat");
        }
        if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) {
          BindTextureMatrix(this._textureRoughness, uniformBuffer, "clearCoatRoughness");
        }
      }
      if (this._bumpTexture && engine2.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) {
        uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level);
        BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump");
        if (scene._mirroredCameraPosition) {
          uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1 : -1, invertNormalMapY ? 1 : -1);
        } else {
          uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1 : 1, invertNormalMapY ? -1 : 1);
        }
      }
      if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
        uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level);
        BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint");
      }
      uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness);
      const a = 1 - this._indexOfRefraction;
      const b = 1 + this._indexOfRefraction;
      const f0 = Math.pow(-a / b, 2);
      const eta = 1 / this._indexOfRefraction;
      uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b);
      if (this._isTintEnabled) {
        uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness));
        uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance));
      }
    }
    if (scene.texturesEnabled) {
      if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {
        uniformBuffer.setTexture("clearCoatSampler", this._texture);
      }
      if (this._textureRoughness && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) {
        uniformBuffer.setTexture("clearCoatRoughnessSampler", this._textureRoughness);
      }
      if (this._bumpTexture && engine2.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {
        uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture);
      }
      if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {
        uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture);
      }
    }
  }
  hasTexture(texture) {
    if (this._texture === texture) {
      return true;
    }
    if (this._textureRoughness === texture) {
      return true;
    }
    if (this._bumpTexture === texture) {
      return true;
    }
    if (this._tintTexture === texture) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._texture) {
      activeTextures.push(this._texture);
    }
    if (this._textureRoughness) {
      activeTextures.push(this._textureRoughness);
    }
    if (this._bumpTexture) {
      activeTextures.push(this._bumpTexture);
    }
    if (this._tintTexture) {
      activeTextures.push(this._tintTexture);
    }
  }
  getAnimatables(animatables) {
    if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
      animatables.push(this._texture);
    }
    if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {
      animatables.push(this._textureRoughness);
    }
    if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
      animatables.push(this._bumpTexture);
    }
    if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) {
      animatables.push(this._tintTexture);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._texture?.dispose();
      this._textureRoughness?.dispose();
      this._bumpTexture?.dispose();
      this._tintTexture?.dispose();
    }
  }
  getClassName() {
    return "PBRClearCoatConfiguration";
  }
  addFallbacks(defines, fallbacks, currentRank) {
    if (defines.CLEARCOAT_BUMP) {
      fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP");
    }
    if (defines.CLEARCOAT_TINT) {
      fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT");
    }
    if (defines.CLEARCOAT) {
      fallbacks.addFallback(currentRank++, "CLEARCOAT");
    }
    return currentRank;
  }
  getSamplers(samplers) {
    samplers.push("clearCoatSampler", "clearCoatRoughnessSampler", "clearCoatBumpSampler", "clearCoatTintSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vClearCoatParams", size: 2, type: "vec2" },
        { name: "vClearCoatRefractionParams", size: 4, type: "vec4" },
        { name: "vClearCoatInfos", size: 4, type: "vec4" },
        { name: "clearCoatMatrix", size: 16, type: "mat4" },
        { name: "clearCoatRoughnessMatrix", size: 16, type: "mat4" },
        { name: "vClearCoatBumpInfos", size: 2, type: "vec2" },
        { name: "vClearCoatTangentSpaceParams", size: 2, type: "vec2" },
        { name: "clearCoatBumpMatrix", size: 16, type: "mat4" },
        { name: "vClearCoatTintParams", size: 4, type: "vec4" },
        { name: "clearCoatColorAtDistance", size: 1, type: "float" },
        { name: "vClearCoatTintInfos", size: 2, type: "vec2" },
        { name: "clearCoatTintMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
PBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5;
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "isEnabled", undefined);
__decorate([
  serialize()
], PBRClearCoatConfiguration.prototype, "intensity", undefined);
__decorate([
  serialize()
], PBRClearCoatConfiguration.prototype, "roughness", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "indexOfRefraction", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "texture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "useRoughnessFromMainTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "textureRoughness", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "remapF0OnInterfaceChange", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "bumpTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "isTintEnabled", undefined);
__decorate([
  serializeAsColor3()
], PBRClearCoatConfiguration.prototype, "tintColor", undefined);
__decorate([
  serialize()
], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", undefined);
__decorate([
  serialize()
], PBRClearCoatConfiguration.prototype, "tintThickness", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "tintTexture", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrIridescenceConfiguration.js
init_tslib_es6();
init_decorators();
init_materialHelper_functions();

class MaterialIridescenceDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.IRIDESCENCE = false;
    this.IRIDESCENCE_TEXTURE = false;
    this.IRIDESCENCE_TEXTUREDIRECTUV = 0;
    this.IRIDESCENCE_THICKNESS_TEXTURE = false;
    this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;
  }
}

class PBRIridescenceConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "PBRIridescence", 110, new MaterialIridescenceDefines, addToPluginList);
    this._isEnabled = false;
    this.isEnabled = false;
    this.intensity = 1;
    this.minimumThickness = PBRIridescenceConfiguration._DefaultMinimumThickness;
    this.maximumThickness = PBRIridescenceConfiguration._DefaultMaximumThickness;
    this.indexOfRefraction = PBRIridescenceConfiguration._DefaultIndexOfRefraction;
    this._texture = null;
    this.texture = null;
    this._thicknessTexture = null;
    this.thicknessTexture = null;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
  }
  isReadyForSubMesh(defines, scene) {
    if (!this._isEnabled) {
      return true;
    }
    if (defines._areTexturesDirty) {
      if (scene.texturesEnabled) {
        if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
          if (!this._texture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
          if (!this._thicknessTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
      }
    }
    return true;
  }
  prepareDefinesBeforeAttributes(defines, scene) {
    if (this._isEnabled) {
      defines.IRIDESCENCE = true;
      if (defines._areTexturesDirty) {
        if (scene.texturesEnabled) {
          if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
            PrepareDefinesForMergedUV(this._texture, defines, "IRIDESCENCE_TEXTURE");
          } else {
            defines.IRIDESCENCE_TEXTURE = false;
          }
          if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
            PrepareDefinesForMergedUV(this._thicknessTexture, defines, "IRIDESCENCE_THICKNESS_TEXTURE");
          } else {
            defines.IRIDESCENCE_THICKNESS_TEXTURE = false;
          }
        }
      }
    } else {
      defines.IRIDESCENCE = false;
      defines.IRIDESCENCE_TEXTURE = false;
      defines.IRIDESCENCE_THICKNESS_TEXTURE = false;
      defines.IRIDESCENCE_TEXTUREDIRECTUV = 0;
      defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;
    }
  }
  bindForSubMesh(uniformBuffer, scene) {
    if (!this._isEnabled) {
      return;
    }
    const isFrozen = this._material.isFrozen;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) {
        uniformBuffer.updateFloat4("vIridescenceInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._thicknessTexture?.coordinatesIndex ?? 0, this._thicknessTexture?.level ?? 0);
        if (this._texture) {
          BindTextureMatrix(this._texture, uniformBuffer, "iridescence");
        }
        if (this._thicknessTexture) {
          BindTextureMatrix(this._thicknessTexture, uniformBuffer, "iridescenceThickness");
        }
      }
      uniformBuffer.updateFloat4("vIridescenceParams", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness);
    }
    if (scene.texturesEnabled) {
      if (this._texture && MaterialFlags.IridescenceTextureEnabled) {
        uniformBuffer.setTexture("iridescenceSampler", this._texture);
      }
      if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {
        uniformBuffer.setTexture("iridescenceThicknessSampler", this._thicknessTexture);
      }
    }
  }
  hasTexture(texture) {
    if (this._texture === texture) {
      return true;
    }
    if (this._thicknessTexture === texture) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._texture) {
      activeTextures.push(this._texture);
    }
    if (this._thicknessTexture) {
      activeTextures.push(this._thicknessTexture);
    }
  }
  getAnimatables(animatables) {
    if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
      animatables.push(this._texture);
    }
    if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
      animatables.push(this._thicknessTexture);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._texture?.dispose();
      this._thicknessTexture?.dispose();
    }
  }
  getClassName() {
    return "PBRIridescenceConfiguration";
  }
  addFallbacks(defines, fallbacks, currentRank) {
    if (defines.IRIDESCENCE) {
      fallbacks.addFallback(currentRank++, "IRIDESCENCE");
    }
    return currentRank;
  }
  getSamplers(samplers) {
    samplers.push("iridescenceSampler", "iridescenceThicknessSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vIridescenceParams", size: 4, type: "vec4" },
        { name: "vIridescenceInfos", size: 4, type: "vec4" },
        { name: "iridescenceMatrix", size: 16, type: "mat4" },
        { name: "iridescenceThicknessMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
PBRIridescenceConfiguration._DefaultMinimumThickness = 100;
PBRIridescenceConfiguration._DefaultMaximumThickness = 400;
PBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3;
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRIridescenceConfiguration.prototype, "isEnabled", undefined);
__decorate([
  serialize()
], PBRIridescenceConfiguration.prototype, "intensity", undefined);
__decorate([
  serialize()
], PBRIridescenceConfiguration.prototype, "minimumThickness", undefined);
__decorate([
  serialize()
], PBRIridescenceConfiguration.prototype, "maximumThickness", undefined);
__decorate([
  serialize()
], PBRIridescenceConfiguration.prototype, "indexOfRefraction", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRIridescenceConfiguration.prototype, "texture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRIridescenceConfiguration.prototype, "thicknessTexture", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrAnisotropicConfiguration.js
init_tslib_es6();
init_decorators();
init_buffer();
init_math_vector();
init_materialHelper_functions();

class MaterialAnisotropicDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.ANISOTROPIC = false;
    this.ANISOTROPIC_TEXTURE = false;
    this.ANISOTROPIC_TEXTUREDIRECTUV = 0;
    this.ANISOTROPIC_LEGACY = false;
    this.MAINUV1 = false;
  }
}

class PBRAnisotropicConfiguration extends MaterialPluginBase {
  set angle(value) {
    this.direction.x = Math.cos(value);
    this.direction.y = Math.sin(value);
  }
  get angle() {
    return Math.atan2(this.direction.y, this.direction.x);
  }
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  _markAllSubMeshesAsMiscDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsMiscDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "PBRAnisotropic", 110, new MaterialAnisotropicDefines, addToPluginList);
    this._isEnabled = false;
    this.isEnabled = false;
    this.intensity = 1;
    this.direction = new Vector2(1, 0);
    this._texture = null;
    this.texture = null;
    this._legacy = false;
    this.legacy = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
    this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];
  }
  isReadyForSubMesh(defines, scene) {
    if (!this._isEnabled) {
      return true;
    }
    if (defines._areTexturesDirty) {
      if (scene.texturesEnabled) {
        if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
          if (!this._texture.isReadyOrNotBlocking()) {
            return false;
          }
        }
      }
    }
    return true;
  }
  prepareDefinesBeforeAttributes(defines, scene, mesh) {
    if (this._isEnabled) {
      defines.ANISOTROPIC = this._isEnabled;
      if (this._isEnabled && !mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
        defines._needUVs = true;
        defines.MAINUV1 = true;
      }
      if (defines._areTexturesDirty) {
        if (scene.texturesEnabled) {
          if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
            PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE");
          } else {
            defines.ANISOTROPIC_TEXTURE = false;
          }
        }
      }
      if (defines._areMiscDirty) {
        defines.ANISOTROPIC_LEGACY = this._legacy;
      }
    } else {
      defines.ANISOTROPIC = false;
      defines.ANISOTROPIC_TEXTURE = false;
      defines.ANISOTROPIC_TEXTUREDIRECTUV = 0;
      defines.ANISOTROPIC_LEGACY = false;
    }
  }
  bindForSubMesh(uniformBuffer, scene) {
    if (!this._isEnabled) {
      return;
    }
    const isFrozen = this._material.isFrozen;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
        uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level);
        BindTextureMatrix(this._texture, uniformBuffer, "anisotropy");
      }
      uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity);
    }
    if (scene.texturesEnabled) {
      if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {
        uniformBuffer.setTexture("anisotropySampler", this._texture);
      }
    }
  }
  hasTexture(texture) {
    if (this._texture === texture) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._texture) {
      activeTextures.push(this._texture);
    }
  }
  getAnimatables(animatables) {
    if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
      animatables.push(this._texture);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      if (this._texture) {
        this._texture.dispose();
      }
    }
  }
  getClassName() {
    return "PBRAnisotropicConfiguration";
  }
  addFallbacks(defines, fallbacks, currentRank) {
    if (defines.ANISOTROPIC) {
      fallbacks.addFallback(currentRank++, "ANISOTROPIC");
    }
    return currentRank;
  }
  getSamplers(samplers) {
    samplers.push("anisotropySampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vAnisotropy", size: 3, type: "vec3" },
        { name: "vAnisotropyInfos", size: 2, type: "vec2" },
        { name: "anisotropyMatrix", size: 16, type: "mat4" }
      ]
    };
  }
  parse(source, scene, rootUrl) {
    super.parse(source, scene, rootUrl);
    if (source.legacy === undefined) {
      this.legacy = true;
    }
  }
}
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRAnisotropicConfiguration.prototype, "isEnabled", undefined);
__decorate([
  serialize()
], PBRAnisotropicConfiguration.prototype, "intensity", undefined);
__decorate([
  serializeAsVector2()
], PBRAnisotropicConfiguration.prototype, "direction", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRAnisotropicConfiguration.prototype, "texture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRAnisotropicConfiguration.prototype, "legacy", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrSheenConfiguration.js
init_tslib_es6();
init_decorators();
init_math_color();
init_materialHelper_functions();

class MaterialSheenDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.SHEEN = false;
    this.SHEEN_TEXTURE = false;
    this.SHEEN_GAMMATEXTURE = false;
    this.SHEEN_TEXTURE_ROUGHNESS = false;
    this.SHEEN_TEXTUREDIRECTUV = 0;
    this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;
    this.SHEEN_LINKWITHALBEDO = false;
    this.SHEEN_ROUGHNESS = false;
    this.SHEEN_ALBEDOSCALING = false;
    this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
  }
}

class PBRSheenConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "Sheen", 120, new MaterialSheenDefines, addToPluginList);
    this._isEnabled = false;
    this.isEnabled = false;
    this._linkSheenWithAlbedo = false;
    this.linkSheenWithAlbedo = false;
    this.intensity = 1;
    this.color = Color3.White();
    this._texture = null;
    this.texture = null;
    this._useRoughnessFromMainTexture = true;
    this.useRoughnessFromMainTexture = true;
    this._roughness = null;
    this.roughness = null;
    this._textureRoughness = null;
    this.textureRoughness = null;
    this._albedoScaling = false;
    this.albedoScaling = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
  }
  isReadyForSubMesh(defines, scene) {
    if (!this._isEnabled) {
      return true;
    }
    if (defines._areTexturesDirty) {
      if (scene.texturesEnabled) {
        if (this._texture && MaterialFlags.SheenTextureEnabled) {
          if (!this._texture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {
          if (!this._textureRoughness.isReadyOrNotBlocking()) {
            return false;
          }
        }
      }
    }
    return true;
  }
  prepareDefinesBeforeAttributes(defines, scene) {
    if (this._isEnabled) {
      defines.SHEEN = true;
      defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo;
      defines.SHEEN_ROUGHNESS = this._roughness !== null;
      defines.SHEEN_ALBEDOSCALING = this._albedoScaling;
      defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;
      if (defines._areTexturesDirty) {
        if (scene.texturesEnabled) {
          if (this._texture && MaterialFlags.SheenTextureEnabled) {
            PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE");
            defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace;
          } else {
            defines.SHEEN_TEXTURE = false;
          }
          if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {
            PrepareDefinesForMergedUV(this._textureRoughness, defines, "SHEEN_TEXTURE_ROUGHNESS");
          } else {
            defines.SHEEN_TEXTURE_ROUGHNESS = false;
          }
        }
      }
    } else {
      defines.SHEEN = false;
      defines.SHEEN_TEXTURE = false;
      defines.SHEEN_TEXTURE_ROUGHNESS = false;
      defines.SHEEN_LINKWITHALBEDO = false;
      defines.SHEEN_ROUGHNESS = false;
      defines.SHEEN_ALBEDOSCALING = false;
      defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;
      defines.SHEEN_GAMMATEXTURE = false;
      defines.SHEEN_TEXTUREDIRECTUV = 0;
      defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;
    }
  }
  bindForSubMesh(uniformBuffer, scene, engine2, subMesh) {
    if (!this._isEnabled) {
      return;
    }
    const defines = subMesh.materialDefines;
    const isFrozen = this._material.isFrozen;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) {
        uniformBuffer.updateFloat4("vSheenInfos", this._texture?.coordinatesIndex ?? 0, this._texture?.level ?? 0, this._textureRoughness?.coordinatesIndex ?? 0, this._textureRoughness?.level ?? 0);
        if (this._texture) {
          BindTextureMatrix(this._texture, uniformBuffer, "sheen");
        }
        if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) {
          BindTextureMatrix(this._textureRoughness, uniformBuffer, "sheenRoughness");
        }
      }
      uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity);
      if (this._roughness !== null) {
        uniformBuffer.updateFloat("vSheenRoughness", this._roughness);
      }
    }
    if (scene.texturesEnabled) {
      if (this._texture && MaterialFlags.SheenTextureEnabled) {
        uniformBuffer.setTexture("sheenSampler", this._texture);
      }
      if (this._textureRoughness && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) {
        uniformBuffer.setTexture("sheenRoughnessSampler", this._textureRoughness);
      }
    }
  }
  hasTexture(texture) {
    if (this._texture === texture) {
      return true;
    }
    if (this._textureRoughness === texture) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._texture) {
      activeTextures.push(this._texture);
    }
    if (this._textureRoughness) {
      activeTextures.push(this._textureRoughness);
    }
  }
  getAnimatables(animatables) {
    if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
      animatables.push(this._texture);
    }
    if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {
      animatables.push(this._textureRoughness);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      this._texture?.dispose();
      this._textureRoughness?.dispose();
    }
  }
  getClassName() {
    return "PBRSheenConfiguration";
  }
  addFallbacks(defines, fallbacks, currentRank) {
    if (defines.SHEEN) {
      fallbacks.addFallback(currentRank++, "SHEEN");
    }
    return currentRank;
  }
  getSamplers(samplers) {
    samplers.push("sheenSampler", "sheenRoughnessSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vSheenColor", size: 4, type: "vec4" },
        { name: "vSheenRoughness", size: 1, type: "float" },
        { name: "vSheenInfos", size: 4, type: "vec4" },
        { name: "sheenMatrix", size: 16, type: "mat4" },
        { name: "sheenRoughnessMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "isEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", undefined);
__decorate([
  serialize()
], PBRSheenConfiguration.prototype, "intensity", undefined);
__decorate([
  serializeAsColor3()
], PBRSheenConfiguration.prototype, "color", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "texture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "useRoughnessFromMainTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "roughness", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "textureRoughness", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "albedoScaling", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrSubSurfaceConfiguration.js
init_tslib_es6();
init_decorators();
init_math_color();
init_math_vector();
init_materialHelper_functions();

class MaterialSubSurfaceDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.SUBSURFACE = false;
    this.SS_REFRACTION = false;
    this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
    this.SS_TRANSLUCENCY = false;
    this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
    this.SS_SCATTERING = false;
    this.SS_DISPERSION = false;
    this.SS_THICKNESSANDMASK_TEXTURE = false;
    this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
    this.SS_HAS_THICKNESS = false;
    this.SS_REFRACTIONINTENSITY_TEXTURE = false;
    this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;
    this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
    this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;
    this.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
    this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0;
    this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false;
    this.SS_REFRACTIONMAP_3D = false;
    this.SS_REFRACTIONMAP_OPPOSITEZ = false;
    this.SS_LODINREFRACTIONALPHA = false;
    this.SS_GAMMAREFRACTION = false;
    this.SS_RGBDREFRACTION = false;
    this.SS_LINEARSPECULARREFRACTION = false;
    this.SS_LINKREFRACTIONTOTRANSPARENCY = false;
    this.SS_ALBEDOFORREFRACTIONTINT = false;
    this.SS_ALBEDOFORTRANSLUCENCYTINT = false;
    this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
    this.SS_USE_THICKNESS_AS_DEPTH = false;
    this.SS_USE_GLTF_TEXTURES = false;
  }
}

class PBRSubSurfaceConfiguration extends MaterialPluginBase {
  get scatteringDiffusionProfile() {
    if (!this._scene.subSurfaceConfiguration) {
      return null;
    }
    return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex];
  }
  set scatteringDiffusionProfile(c) {
    if (!this._scene.enableSubSurfaceForPrePass()) {
      return;
    }
    if (c) {
      this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c);
    }
  }
  get volumeIndexOfRefraction() {
    if (this._volumeIndexOfRefraction >= 1) {
      return this._volumeIndexOfRefraction;
    }
    return this._indexOfRefraction;
  }
  set volumeIndexOfRefraction(value) {
    if (value >= 1) {
      this._volumeIndexOfRefraction = value;
    } else {
      this._volumeIndexOfRefraction = -1;
    }
  }
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  _markScenePrePassDirty() {
    this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
    this._internalMarkScenePrePassDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "PBRSubSurface", 130, new MaterialSubSurfaceDefines, addToPluginList);
    this._isRefractionEnabled = false;
    this.isRefractionEnabled = false;
    this._isTranslucencyEnabled = false;
    this.isTranslucencyEnabled = false;
    this._isDispersionEnabled = false;
    this.isDispersionEnabled = false;
    this._isScatteringEnabled = false;
    this.isScatteringEnabled = false;
    this._scatteringDiffusionProfileIndex = 0;
    this.refractionIntensity = 1;
    this.translucencyIntensity = 1;
    this.useAlbedoToTintRefraction = false;
    this.useAlbedoToTintTranslucency = false;
    this._thicknessTexture = null;
    this.thicknessTexture = null;
    this._refractionTexture = null;
    this.refractionTexture = null;
    this._indexOfRefraction = 1.5;
    this.indexOfRefraction = 1.5;
    this._volumeIndexOfRefraction = -1;
    this._invertRefractionY = false;
    this.invertRefractionY = false;
    this._linkRefractionWithTransparency = false;
    this.linkRefractionWithTransparency = false;
    this.minimumThickness = 0;
    this.maximumThickness = 1;
    this.useThicknessAsDepth = false;
    this.tintColor = Color3.White();
    this.tintColorAtDistance = 1;
    this.dispersion = 0;
    this.diffusionDistance = Color3.White();
    this._useMaskFromThicknessTexture = false;
    this.useMaskFromThicknessTexture = false;
    this._refractionIntensityTexture = null;
    this.refractionIntensityTexture = null;
    this._translucencyIntensityTexture = null;
    this.translucencyIntensityTexture = null;
    this.translucencyColor = null;
    this._translucencyColorTexture = null;
    this.translucencyColorTexture = null;
    this._useGltfStyleTextures = true;
    this.useGltfStyleTextures = true;
    this._scene = material.getScene();
    this.registerForExtraEvents = true;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
    this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32];
  }
  isReadyForSubMesh(defines, scene) {
    if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
      return true;
    }
    if (defines._areTexturesDirty) {
      if (scene.texturesEnabled) {
        if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
          if (!this._thicknessTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) {
          if (!this._translucencyColorTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) {
          if (!this._translucencyIntensityTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        const refractionTexture = this._getRefractionTexture(scene);
        if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
          if (!refractionTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
      }
    }
    return true;
  }
  prepareDefinesBeforeAttributes(defines, scene) {
    if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
      defines.SUBSURFACE = false;
      defines.SS_DISPERSION = false;
      defines.SS_TRANSLUCENCY = false;
      defines.SS_SCATTERING = false;
      defines.SS_REFRACTION = false;
      defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
      defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
      defines.SS_THICKNESSANDMASK_TEXTURE = false;
      defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
      defines.SS_HAS_THICKNESS = false;
      defines.SS_REFRACTIONINTENSITY_TEXTURE = false;
      defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;
      defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
      defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;
      defines.SS_REFRACTIONMAP_3D = false;
      defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
      defines.SS_LODINREFRACTIONALPHA = false;
      defines.SS_GAMMAREFRACTION = false;
      defines.SS_RGBDREFRACTION = false;
      defines.SS_LINEARSPECULARREFRACTION = false;
      defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
      defines.SS_ALBEDOFORREFRACTIONTINT = false;
      defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;
      defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
      defines.SS_USE_THICKNESS_AS_DEPTH = false;
      defines.SS_USE_GLTF_TEXTURES = false;
      defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
      defines.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV = 0;
      defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = false;
      return;
    }
    if (defines._areTexturesDirty) {
      defines.SUBSURFACE = true;
      defines.SS_DISPERSION = this._isDispersionEnabled;
      defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;
      defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = false;
      defines.SS_SCATTERING = this._isScatteringEnabled;
      defines.SS_THICKNESSANDMASK_TEXTURE = false;
      defines.SS_REFRACTIONINTENSITY_TEXTURE = false;
      defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;
      defines.SS_HAS_THICKNESS = false;
      defines.SS_USE_GLTF_TEXTURES = false;
      defines.SS_REFRACTION = false;
      defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = false;
      defines.SS_REFRACTIONMAP_3D = false;
      defines.SS_GAMMAREFRACTION = false;
      defines.SS_RGBDREFRACTION = false;
      defines.SS_LINEARSPECULARREFRACTION = false;
      defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
      defines.SS_LODINREFRACTIONALPHA = false;
      defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
      defines.SS_ALBEDOFORREFRACTIONTINT = false;
      defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;
      defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;
      defines.SS_USE_THICKNESS_AS_DEPTH = false;
      defines.SS_TRANSLUCENCYCOLOR_TEXTURE = false;
      if (defines._areTexturesDirty) {
        if (scene.texturesEnabled) {
          if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
            PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE");
          }
          if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled) {
            PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, "SS_REFRACTIONINTENSITY_TEXTURE");
          }
          if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled) {
            PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, "SS_TRANSLUCENCYINTENSITY_TEXTURE");
          }
          if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled) {
            PrepareDefinesForMergedUV(this._translucencyColorTexture, defines, "SS_TRANSLUCENCYCOLOR_TEXTURE");
            defines.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA = this._translucencyColorTexture.gammaSpace;
          }
        }
      }
      defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0;
      defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures;
      defines.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._refractionIntensityTexture;
      defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS = this._useMaskFromThicknessTexture && !this._translucencyIntensityTexture;
      if (this._isRefractionEnabled) {
        if (scene.texturesEnabled) {
          const refractionTexture = this._getRefractionTexture(scene);
          if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
            defines.SS_REFRACTION = true;
            defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;
            defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;
            defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;
            defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD;
            defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ;
            defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
            defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;
            defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction;
            defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize;
            defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth;
          }
        }
      }
      if (this._isTranslucencyEnabled) {
        defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency;
      }
    }
  }
  hardBindForSubMesh(uniformBuffer, scene, engine2, subMesh) {
    if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
      return;
    }
    if (this.maximumThickness === 0 && this.minimumThickness === 0) {
      uniformBuffer.updateFloat2("vThicknessParam", 0, 0);
    } else {
      subMesh.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);
      const thicknessScale = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z));
      uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale);
    }
  }
  bindForSubMesh(uniformBuffer, scene, engine2, subMesh) {
    if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {
      return;
    }
    const defines = subMesh.materialDefines;
    const isFrozen = this._material.isFrozen;
    const realTimeFiltering = this._material.realTimeFiltering;
    const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE;
    const refractionTexture = this._getRefractionTexture(scene);
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
        uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);
        BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness");
      }
      if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {
        uniformBuffer.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level);
        BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, "refractionIntensity");
      }
      if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) {
        uniformBuffer.updateFloat2("vTranslucencyColorInfos", this._translucencyColorTexture.coordinatesIndex, this._translucencyColorTexture.level);
        BindTextureMatrix(this._translucencyColorTexture, uniformBuffer, "translucencyColor");
      }
      if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {
        uniformBuffer.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level);
        BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, "translucencyIntensity");
      }
      if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
        uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getRefractionTextureMatrix());
        let depth = 1;
        if (!refractionTexture.isCube) {
          if (refractionTexture.depth) {
            depth = refractionTexture.depth;
          }
        }
        const width = refractionTexture.getSize().width;
        const refractionIor = this.volumeIndexOfRefraction;
        uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1);
        uniformBuffer.updateFloat4("vRefractionMicrosurfaceInfos", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1 / this.indexOfRefraction);
        if (realTimeFiltering) {
          uniformBuffer.updateFloat2("vRefractionFilteringInfo", width, Math.log2(width));
        }
        if (refractionTexture.boundingBoxSize) {
          const cubeTexture = refractionTexture;
          uniformBuffer.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition);
          uniformBuffer.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize);
        }
      }
      if (this._isScatteringEnabled) {
        uniformBuffer.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex);
      }
      uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance);
      uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance));
      uniformBuffer.updateColor4("vTranslucencyColor", this.translucencyColor ?? this.tintColor, 0);
      uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0);
      uniformBuffer.updateFloat("dispersion", this.dispersion);
    }
    if (scene.texturesEnabled) {
      if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {
        uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture);
      }
      if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {
        uniformBuffer.setTexture("refractionIntensitySampler", this._refractionIntensityTexture);
      }
      if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {
        uniformBuffer.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture);
      }
      if (this._translucencyColorTexture && MaterialFlags.TranslucencyColorTextureEnabled && defines.SS_TRANSLUCENCYCOLOR_TEXTURE) {
        uniformBuffer.setTexture("translucencyColorSampler", this._translucencyColorTexture);
      }
      if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {
        if (lodBasedMicrosurface) {
          uniformBuffer.setTexture("refractionSampler", refractionTexture);
        } else {
          uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
          uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
          uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
        }
      }
    }
  }
  _getRefractionTexture(scene) {
    if (this._refractionTexture) {
      return this._refractionTexture;
    }
    if (this._isRefractionEnabled) {
      return scene.environmentTexture;
    }
    return null;
  }
  get disableAlphaBlending() {
    return this._isRefractionEnabled && this._linkRefractionWithTransparency;
  }
  fillRenderTargetTextures(renderTargets) {
    if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
      renderTargets.push(this._refractionTexture);
    }
  }
  hasTexture(texture) {
    if (this._thicknessTexture === texture) {
      return true;
    }
    if (this._refractionTexture === texture) {
      return true;
    }
    if (this._refractionIntensityTexture === texture) {
      return true;
    }
    if (this._translucencyIntensityTexture === texture) {
      return true;
    }
    if (this._translucencyColorTexture === texture) {
      return true;
    }
    return false;
  }
  hasRenderTargetTextures() {
    if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
      return true;
    }
    return false;
  }
  getActiveTextures(activeTextures) {
    if (this._thicknessTexture) {
      activeTextures.push(this._thicknessTexture);
    }
    if (this._refractionTexture) {
      activeTextures.push(this._refractionTexture);
    }
    if (this._translucencyColorTexture) {
      activeTextures.push(this._translucencyColorTexture);
    }
    if (this._translucencyIntensityTexture) {
      activeTextures.push(this._translucencyIntensityTexture);
    }
  }
  getAnimatables(animatables) {
    if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
      animatables.push(this._thicknessTexture);
    }
    if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
      animatables.push(this._refractionTexture);
    }
    if (this._translucencyColorTexture && this._translucencyColorTexture.animations && this._translucencyColorTexture.animations.length > 0) {
      animatables.push(this._translucencyColorTexture);
    }
    if (this._translucencyIntensityTexture && this._translucencyIntensityTexture.animations && this._translucencyIntensityTexture.animations.length > 0) {
      animatables.push(this._translucencyIntensityTexture);
    }
  }
  dispose(forceDisposeTextures) {
    if (forceDisposeTextures) {
      if (this._thicknessTexture) {
        this._thicknessTexture.dispose();
      }
      if (this._refractionTexture) {
        this._refractionTexture.dispose();
      }
      if (this._translucencyColorTexture) {
        this._translucencyColorTexture.dispose();
      }
      if (this._translucencyIntensityTexture) {
        this._translucencyIntensityTexture.dispose();
      }
    }
  }
  getClassName() {
    return "PBRSubSurfaceConfiguration";
  }
  addFallbacks(defines, fallbacks, currentRank) {
    if (defines.SS_SCATTERING) {
      fallbacks.addFallback(currentRank++, "SS_SCATTERING");
    }
    if (defines.SS_TRANSLUCENCY) {
      fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY");
    }
    return currentRank;
  }
  getSamplers(samplers) {
    samplers.push("thicknessSampler", "refractionIntensitySampler", "translucencyIntensitySampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh", "translucencyColorSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vRefractionMicrosurfaceInfos", size: 4, type: "vec4" },
        { name: "vRefractionFilteringInfo", size: 2, type: "vec2" },
        { name: "vTranslucencyIntensityInfos", size: 2, type: "vec2" },
        { name: "vRefractionInfos", size: 4, type: "vec4" },
        { name: "refractionMatrix", size: 16, type: "mat4" },
        { name: "vThicknessInfos", size: 2, type: "vec2" },
        { name: "vRefractionIntensityInfos", size: 2, type: "vec2" },
        { name: "thicknessMatrix", size: 16, type: "mat4" },
        { name: "refractionIntensityMatrix", size: 16, type: "mat4" },
        { name: "translucencyIntensityMatrix", size: 16, type: "mat4" },
        { name: "vThicknessParam", size: 2, type: "vec2" },
        { name: "vDiffusionDistance", size: 3, type: "vec3" },
        { name: "vTintColor", size: 4, type: "vec4" },
        { name: "vSubSurfaceIntensity", size: 3, type: "vec3" },
        { name: "vRefractionPosition", size: 3, type: "vec3" },
        { name: "vRefractionSize", size: 3, type: "vec3" },
        { name: "scatteringDiffusionProfile", size: 1, type: "float" },
        { name: "dispersion", size: 1, type: "float" },
        { name: "vTranslucencyColor", size: 4, type: "vec4" },
        { name: "vTranslucencyColorInfos", size: 2, type: "vec2" },
        { name: "translucencyColorMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "isDispersionEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markScenePrePassDirty")
], PBRSubSurfaceConfiguration.prototype, "isScatteringEnabled", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "_scatteringDiffusionProfileIndex", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintRefraction", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintTranslucency", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "refractionTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "_volumeIndexOfRefraction", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", null);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "minimumThickness", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "maximumThickness", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "useThicknessAsDepth", undefined);
__decorate([
  serializeAsColor3()
], PBRSubSurfaceConfiguration.prototype, "tintColor", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", undefined);
__decorate([
  serialize()
], PBRSubSurfaceConfiguration.prototype, "dispersion", undefined);
__decorate([
  serializeAsColor3()
], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "refractionIntensityTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "translucencyIntensityTexture", undefined);
__decorate([
  serializeAsColor3()
], PBRSubSurfaceConfiguration.prototype, "translucencyColor", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "translucencyColorTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "useGltfStyleTextures", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js
init_materialHelper_functions();
var onCreatedEffectParameters3 = { effect: null, subMesh: null };

class PBRMaterialDefines extends MaterialDefines {
  constructor(externalProperties) {
    super(externalProperties);
    this.PBR = true;
    this.NUM_SAMPLES = "0";
    this.REALTIME_FILTERING = false;
    this.IBL_CDF_FILTERING = false;
    this.MAINUV1 = false;
    this.MAINUV2 = false;
    this.MAINUV3 = false;
    this.MAINUV4 = false;
    this.MAINUV5 = false;
    this.MAINUV6 = false;
    this.UV1 = false;
    this.UV2 = false;
    this.UV3 = false;
    this.UV4 = false;
    this.UV5 = false;
    this.UV6 = false;
    this.ALBEDO = false;
    this.GAMMAALBEDO = false;
    this.ALBEDODIRECTUV = 0;
    this.VERTEXCOLOR = false;
    this.BASEWEIGHT = false;
    this.BASEWEIGHTDIRECTUV = 0;
    this.BAKED_VERTEX_ANIMATION_TEXTURE = false;
    this.AMBIENT = false;
    this.AMBIENTDIRECTUV = 0;
    this.AMBIENTINGRAYSCALE = false;
    this.OPACITY = false;
    this.VERTEXALPHA = false;
    this.OPACITYDIRECTUV = 0;
    this.OPACITYRGB = false;
    this.ALPHATEST = false;
    this.DEPTHPREPASS = false;
    this.ALPHABLEND = false;
    this.ALPHAFROMALBEDO = false;
    this.ALPHATESTVALUE = "0.5";
    this.SPECULAROVERALPHA = false;
    this.RADIANCEOVERALPHA = false;
    this.ALPHAFRESNEL = false;
    this.LINEARALPHAFRESNEL = false;
    this.PREMULTIPLYALPHA = false;
    this.EMISSIVE = false;
    this.EMISSIVEDIRECTUV = 0;
    this.GAMMAEMISSIVE = false;
    this.REFLECTIVITY = false;
    this.REFLECTIVITY_GAMMA = false;
    this.REFLECTIVITYDIRECTUV = 0;
    this.SPECULARTERM = false;
    this.MICROSURFACEFROMREFLECTIVITYMAP = false;
    this.MICROSURFACEAUTOMATIC = false;
    this.LODBASEDMICROSFURACE = false;
    this.MICROSURFACEMAP = false;
    this.MICROSURFACEMAPDIRECTUV = 0;
    this.METALLICWORKFLOW = false;
    this.ROUGHNESSSTOREINMETALMAPALPHA = false;
    this.ROUGHNESSSTOREINMETALMAPGREEN = false;
    this.METALLNESSSTOREINMETALMAPBLUE = false;
    this.AOSTOREINMETALMAPRED = false;
    this.METALLIC_REFLECTANCE = false;
    this.METALLIC_REFLECTANCE_GAMMA = false;
    this.METALLIC_REFLECTANCEDIRECTUV = 0;
    this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false;
    this.REFLECTANCE = false;
    this.REFLECTANCE_GAMMA = false;
    this.REFLECTANCEDIRECTUV = 0;
    this.ENVIRONMENTBRDF = false;
    this.ENVIRONMENTBRDF_RGBD = false;
    this.NORMAL = false;
    this.TANGENT = false;
    this.BUMP = false;
    this.BUMPDIRECTUV = 0;
    this.OBJECTSPACE_NORMALMAP = false;
    this.PARALLAX = false;
    this.PARALLAX_RHS = false;
    this.PARALLAXOCCLUSION = false;
    this.NORMALXYSCALE = true;
    this.LIGHTMAP = false;
    this.LIGHTMAPDIRECTUV = 0;
    this.USELIGHTMAPASSHADOWMAP = false;
    this.GAMMALIGHTMAP = false;
    this.RGBDLIGHTMAP = false;
    this.REFLECTION = false;
    this.REFLECTIONMAP_3D = false;
    this.REFLECTIONMAP_SPHERICAL = false;
    this.REFLECTIONMAP_PLANAR = false;
    this.REFLECTIONMAP_CUBIC = false;
    this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
    this.REFLECTIONMAP_PROJECTION = false;
    this.REFLECTIONMAP_SKYBOX = false;
    this.REFLECTIONMAP_EXPLICIT = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR = false;
    this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
    this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
    this.INVERTCUBICMAP = false;
    this.USESPHERICALFROMREFLECTIONMAP = false;
    this.USEIRRADIANCEMAP = false;
    this.USESPHERICALINVERTEX = false;
    this.REFLECTIONMAP_OPPOSITEZ = false;
    this.LODINREFLECTIONALPHA = false;
    this.GAMMAREFLECTION = false;
    this.RGBDREFLECTION = false;
    this.LINEARSPECULARREFLECTION = false;
    this.RADIANCEOCCLUSION = false;
    this.HORIZONOCCLUSION = false;
    this.INSTANCES = false;
    this.THIN_INSTANCES = false;
    this.INSTANCESCOLOR = false;
    this.PREPASS = false;
    this.PREPASS_COLOR = false;
    this.PREPASS_COLOR_INDEX = -1;
    this.PREPASS_IRRADIANCE = false;
    this.PREPASS_IRRADIANCE_INDEX = -1;
    this.PREPASS_ALBEDO = false;
    this.PREPASS_ALBEDO_INDEX = -1;
    this.PREPASS_ALBEDO_SQRT = false;
    this.PREPASS_ALBEDO_SQRT_INDEX = -1;
    this.PREPASS_DEPTH = false;
    this.PREPASS_DEPTH_INDEX = -1;
    this.PREPASS_SCREENSPACE_DEPTH = false;
    this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1;
    this.PREPASS_NORMAL = false;
    this.PREPASS_NORMAL_INDEX = -1;
    this.PREPASS_NORMAL_WORLDSPACE = false;
    this.PREPASS_WORLD_NORMAL = false;
    this.PREPASS_WORLD_NORMAL_INDEX = -1;
    this.PREPASS_POSITION = false;
    this.PREPASS_POSITION_INDEX = -1;
    this.PREPASS_LOCAL_POSITION = false;
    this.PREPASS_LOCAL_POSITION_INDEX = -1;
    this.PREPASS_VELOCITY = false;
    this.PREPASS_VELOCITY_INDEX = -1;
    this.PREPASS_VELOCITY_LINEAR = false;
    this.PREPASS_VELOCITY_LINEAR_INDEX = -1;
    this.PREPASS_REFLECTIVITY = false;
    this.PREPASS_REFLECTIVITY_INDEX = -1;
    this.SCENE_MRT_COUNT = 0;
    this.NUM_BONE_INFLUENCERS = 0;
    this.BonesPerMesh = 0;
    this.BONETEXTURE = false;
    this.BONES_VELOCITY_ENABLED = false;
    this.NONUNIFORMSCALING = false;
    this.MORPHTARGETS = false;
    this.MORPHTARGETS_POSITION = false;
    this.MORPHTARGETS_NORMAL = false;
    this.MORPHTARGETS_TANGENT = false;
    this.MORPHTARGETS_UV = false;
    this.MORPHTARGETS_UV2 = false;
    this.MORPHTARGETS_COLOR = false;
    this.MORPHTARGETTEXTURE_HASPOSITIONS = false;
    this.MORPHTARGETTEXTURE_HASNORMALS = false;
    this.MORPHTARGETTEXTURE_HASTANGENTS = false;
    this.MORPHTARGETTEXTURE_HASUVS = false;
    this.MORPHTARGETTEXTURE_HASUV2S = false;
    this.MORPHTARGETTEXTURE_HASCOLORS = false;
    this.NUM_MORPH_INFLUENCERS = 0;
    this.MORPHTARGETS_TEXTURE = false;
    this.IMAGEPROCESSING = false;
    this.VIGNETTE = false;
    this.VIGNETTEBLENDMODEMULTIPLY = false;
    this.VIGNETTEBLENDMODEOPAQUE = false;
    this.TONEMAPPING = 0;
    this.CONTRAST = false;
    this.COLORCURVES = false;
    this.COLORGRADING = false;
    this.COLORGRADING3D = false;
    this.SAMPLER3DGREENDEPTH = false;
    this.SAMPLER3DBGRMAP = false;
    this.DITHER = false;
    this.IMAGEPROCESSINGPOSTPROCESS = false;
    this.SKIPFINALCOLORCLAMP = false;
    this.EXPOSURE = false;
    this.MULTIVIEW = false;
    this.ORDER_INDEPENDENT_TRANSPARENCY = false;
    this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;
    this.USEPHYSICALLIGHTFALLOFF = false;
    this.USEGLTFLIGHTFALLOFF = false;
    this.TWOSIDEDLIGHTING = false;
    this.SHADOWFLOAT = false;
    this.CLIPPLANE = false;
    this.CLIPPLANE2 = false;
    this.CLIPPLANE3 = false;
    this.CLIPPLANE4 = false;
    this.CLIPPLANE5 = false;
    this.CLIPPLANE6 = false;
    this.POINTSIZE = false;
    this.FOG = false;
    this.LOGARITHMICDEPTH = false;
    this.CAMERA_ORTHOGRAPHIC = false;
    this.CAMERA_PERSPECTIVE = false;
    this.AREALIGHTSUPPORTED = true;
    this.FORCENORMALFORWARD = false;
    this.SPECULARAA = false;
    this.UNLIT = false;
    this.DECAL_AFTER_DETAIL = false;
    this.DEBUGMODE = 0;
    this.rebuild();
  }
  reset() {
    super.reset();
    this.ALPHATESTVALUE = "0.5";
    this.PBR = true;
    this.NORMALXYSCALE = true;
  }
}

class PBRBaseMaterial extends PushMaterial {
  get realTimeFiltering() {
    return this._realTimeFiltering;
  }
  set realTimeFiltering(b) {
    this._realTimeFiltering = b;
    this.markAsDirty(1);
  }
  get realTimeFilteringQuality() {
    return this._realTimeFilteringQuality;
  }
  set realTimeFilteringQuality(n) {
    this._realTimeFilteringQuality = n;
    this.markAsDirty(1);
  }
  get canRenderToMRT() {
    return true;
  }
  _attachImageProcessingConfiguration(configuration) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (!configuration) {
      this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
    } else {
      this._imageProcessingConfiguration = configuration;
    }
    if (this._imageProcessingConfiguration) {
      this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
        this._markAllSubMeshesAsImageProcessingDirty();
      });
    }
  }
  constructor(name325, scene, forceGLSL = false) {
    super(name325, scene, undefined, forceGLSL || PBRBaseMaterial.ForceGLSL);
    this._directIntensity = 1;
    this._emissiveIntensity = 1;
    this._environmentIntensity = 1;
    this._specularIntensity = 1;
    this._lightingInfos = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);
    this._disableBumpMap = false;
    this._albedoTexture = null;
    this._baseWeightTexture = null;
    this._ambientTexture = null;
    this._ambientTextureStrength = 1;
    this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
    this._opacityTexture = null;
    this._reflectionTexture = null;
    this._emissiveTexture = null;
    this._reflectivityTexture = null;
    this._metallicTexture = null;
    this._metallic = null;
    this._roughness = null;
    this._metallicF0Factor = 1;
    this._metallicReflectanceColor = Color3.White();
    this._useOnlyMetallicFromMetallicReflectanceTexture = false;
    this._metallicReflectanceTexture = null;
    this._reflectanceTexture = null;
    this._microSurfaceTexture = null;
    this._bumpTexture = null;
    this._lightmapTexture = null;
    this._ambientColor = new Color3(0, 0, 0);
    this._albedoColor = new Color3(1, 1, 1);
    this._baseWeight = 1;
    this._reflectivityColor = new Color3(1, 1, 1);
    this._reflectionColor = new Color3(1, 1, 1);
    this._emissiveColor = new Color3(0, 0, 0);
    this._microSurface = 0.9;
    this._useLightmapAsShadowmap = false;
    this._useHorizonOcclusion = true;
    this._useRadianceOcclusion = true;
    this._useAlphaFromAlbedoTexture = false;
    this._useSpecularOverAlpha = true;
    this._useMicroSurfaceFromReflectivityMapAlpha = false;
    this._useRoughnessFromMetallicTextureAlpha = true;
    this._useRoughnessFromMetallicTextureGreen = false;
    this._useMetallnessFromMetallicTextureBlue = false;
    this._useAmbientOcclusionFromMetallicTextureRed = false;
    this._useAmbientInGrayScale = false;
    this._useAutoMicroSurfaceFromReflectivityMap = false;
    this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
    this._useRadianceOverAlpha = true;
    this._useObjectSpaceNormalMap = false;
    this._useParallax = false;
    this._useParallaxOcclusion = false;
    this._parallaxScaleBias = 0.05;
    this._disableLighting = false;
    this._maxSimultaneousLights = 4;
    this._invertNormalMapX = false;
    this._invertNormalMapY = false;
    this._twoSidedLighting = false;
    this._alphaCutOff = 0.4;
    this._useAlphaFresnel = false;
    this._useLinearAlphaFresnel = false;
    this._environmentBRDFTexture = null;
    this._forceIrradianceInFragment = false;
    this._realTimeFiltering = false;
    this._realTimeFilteringQuality = 8;
    this._forceNormalForward = false;
    this._enableSpecularAntiAliasing = false;
    this._imageProcessingObserver = null;
    this._renderTargets = new SmartArray(16);
    this._globalAmbientColor = new Color3(0, 0, 0);
    this._unlit = false;
    this._applyDecalMapAfterDetailMap = false;
    this._debugMode = 0;
    this._shadersLoaded = false;
    this._breakShaderLoadedCheck = false;
    this.debugMode = 0;
    this.debugLimit = -1;
    this.debugFactor = 1;
    this._cacheHasRenderTargetTextures = false;
    this.brdf = new PBRBRDFConfiguration(this);
    this.clearCoat = new PBRClearCoatConfiguration(this);
    this.iridescence = new PBRIridescenceConfiguration(this);
    this.anisotropy = new PBRAnisotropicConfiguration(this);
    this.sheen = new PBRSheenConfiguration(this);
    this.subSurface = new PBRSubSurfaceConfiguration(this);
    this.detailMap = new DetailMapConfiguration(this);
    this._attachImageProcessingConfiguration(null);
    this.getRenderTargetTextures = () => {
      this._renderTargets.reset();
      if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
        this._renderTargets.push(this._reflectionTexture);
      }
      this._eventInfo.renderTargets = this._renderTargets;
      this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);
      return this._renderTargets;
    };
    this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());
    this.prePassConfiguration = new PrePassConfiguration;
  }
  get hasRenderTargetTextures() {
    if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
      return true;
    }
    return this._cacheHasRenderTargetTextures;
  }
  get isPrePassCapable() {
    return !this.disableDepthWrite;
  }
  getClassName() {
    return "PBRBaseMaterial";
  }
  get _disableAlphaBlending() {
    return this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST || this.subSurface?.disableAlphaBlending;
  }
  needAlphaBlending() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsBlend;
    }
    if (this._disableAlphaBlending) {
      return false;
    }
    return this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture();
  }
  needAlphaTesting() {
    if (this._hasTransparencyMode) {
      return this._transparencyModeIsTest;
    }
    if (this.subSurface?.disableAlphaBlending) {
      return false;
    }
    return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
  }
  _shouldUseAlphaFromAlbedoTexture() {
    return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;
  }
  _hasAlphaChannel() {
    return this._albedoTexture != null && this._albedoTexture.hasAlpha || this._opacityTexture != null;
  }
  getAlphaTestTexture() {
    return this._albedoTexture;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances) {
    if (!this._uniformBufferLayoutBuilt) {
      this.buildUniformLayout();
    }
    const drawWrapper = subMesh._drawWrapper;
    if (drawWrapper.effect && this.isFrozen) {
      if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    if (!subMesh.materialDefines) {
      this._callbackPluginEventGeneric(4, this._eventInfo);
      subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames);
    }
    const defines = subMesh.materialDefines;
    if (this._isReadyForSubMesh(subMesh)) {
      return true;
    }
    const scene = this.getScene();
    const engine2 = scene.getEngine();
    if (defines._areTexturesDirty) {
      this._eventInfo.hasRenderTargetTextures = false;
      this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);
      this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;
      if (scene.texturesEnabled) {
        if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
          if (!this._albedoTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
          if (!this._baseWeightTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
          if (!this._ambientTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
          if (!this._opacityTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        const reflectionTexture = this._getReflectionTexture();
        if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
          if (!reflectionTexture.isReadyOrNotBlocking()) {
            return false;
          }
          if (reflectionTexture.irradianceTexture) {
            if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {
              return false;
            }
          } else {
            if (!reflectionTexture.sphericalPolynomial && reflectionTexture.getInternalTexture()?._sphericalPolynomialPromise) {
              return false;
            }
          }
        }
        if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
          if (!this._lightmapTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
          if (!this._emissiveTexture.isReadyOrNotBlocking()) {
            return false;
          }
        }
        if (MaterialFlags.SpecularTextureEnabled) {
          if (this._metallicTexture) {
            if (!this._metallicTexture.isReadyOrNotBlocking()) {
              return false;
            }
          } else if (this._reflectivityTexture) {
            if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
              return false;
            }
          }
          if (this._metallicReflectanceTexture) {
            if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {
              return false;
            }
          }
          if (this._reflectanceTexture) {
            if (!this._reflectanceTexture.isReadyOrNotBlocking()) {
              return false;
            }
          }
          if (this._microSurfaceTexture) {
            if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
              return false;
            }
          }
        }
        if (engine2.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
          if (!this._bumpTexture.isReady()) {
            return false;
          }
        }
        if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
          if (!this._environmentBRDFTexture.isReady()) {
            return false;
          }
        }
      }
    }
    this._eventInfo.isReadyForSubMesh = true;
    this._eventInfo.defines = defines;
    this._eventInfo.subMesh = subMesh;
    this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);
    if (!this._eventInfo.isReadyForSubMesh) {
      return false;
    }
    if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
      if (!this._imageProcessingConfiguration.isReady()) {
        return false;
      }
    }
    if (defines["AREALIGHTUSED"]) {
      for (let index = 0;index < mesh.lightSources.length; index++) {
        if (!mesh.lightSources[index]._isReady()) {
          return false;
        }
      }
    }
    if (!engine2.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      mesh.createNormals(true);
      Logger.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
    }
    const previousEffect = subMesh.effect;
    const lightDisposed = defines._areLightsDisposed;
    let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
    let forceWasNotReadyPreviously = false;
    if (effect) {
      if (this._onEffectCreatedObservable) {
        onCreatedEffectParameters3.effect = effect;
        onCreatedEffectParameters3.subMesh = subMesh;
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters3);
      }
      if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
        effect = previousEffect;
        defines.markAsUnprocessed();
        forceWasNotReadyPreviously = this.isFrozen;
        if (lightDisposed) {
          defines._areLightsDisposed = true;
          return false;
        }
      } else {
        scene.resetCachedMaterial();
        subMesh.setEffect(effect, defines, this._materialContext);
      }
    }
    if (!subMesh.effect || !subMesh.effect.isReady()) {
      return false;
    }
    defines._renderId = scene.getRenderId();
    drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;
    drawWrapper._wasPreviouslyUsingInstances = !!useInstances;
    this._checkScenePerformancePriority();
    return true;
  }
  isMetallicWorkflow() {
    if (this._metallic != null || this._roughness != null || this._metallicTexture) {
      return true;
    }
    return false;
  }
  _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) {
    this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);
    if (!defines.isDirty) {
      return null;
    }
    defines.markAsProcessed();
    const scene = this.getScene();
    const engine2 = scene.getEngine();
    const fallbacks = new EffectFallbacks;
    let fallbackRank = 0;
    if (defines.USESPHERICALINVERTEX) {
      fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
    }
    if (defines.FOG) {
      fallbacks.addFallback(fallbackRank, "FOG");
    }
    if (defines.SPECULARAA) {
      fallbacks.addFallback(fallbackRank, "SPECULARAA");
    }
    if (defines.POINTSIZE) {
      fallbacks.addFallback(fallbackRank, "POINTSIZE");
    }
    if (defines.LOGARITHMICDEPTH) {
      fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
    }
    if (defines.PARALLAX) {
      fallbacks.addFallback(fallbackRank, "PARALLAX");
    }
    if (defines.PARALLAX_RHS) {
      fallbacks.addFallback(fallbackRank, "PARALLAX_RHS");
    }
    if (defines.PARALLAXOCCLUSION) {
      fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
    }
    if (defines.ENVIRONMENTBRDF) {
      fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
    }
    if (defines.TANGENT) {
      fallbacks.addFallback(fallbackRank++, "TANGENT");
    }
    if (defines.BUMP) {
      fallbacks.addFallback(fallbackRank++, "BUMP");
    }
    fallbackRank = HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
    if (defines.SPECULARTERM) {
      fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
    }
    if (defines.USESPHERICALFROMREFLECTIONMAP) {
      fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
    }
    if (defines.USEIRRADIANCEMAP) {
      fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP");
    }
    if (defines.LIGHTMAP) {
      fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
    }
    if (defines.NORMAL) {
      fallbacks.addFallback(fallbackRank++, "NORMAL");
    }
    if (defines.AMBIENT) {
      fallbacks.addFallback(fallbackRank++, "AMBIENT");
    }
    if (defines.EMISSIVE) {
      fallbacks.addFallback(fallbackRank++, "EMISSIVE");
    }
    if (defines.VERTEXCOLOR) {
      fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
    }
    if (defines.MORPHTARGETS) {
      fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
    }
    if (defines.MULTIVIEW) {
      fallbacks.addFallback(0, "MULTIVIEW");
    }
    const attribs = [VertexBuffer.PositionKind];
    if (defines.NORMAL) {
      attribs.push(VertexBuffer.NormalKind);
    }
    if (defines.TANGENT) {
      attribs.push(VertexBuffer.TangentKind);
    }
    for (let i = 1;i <= 6; ++i) {
      if (defines["UV" + i]) {
        attribs.push(`uv${i === 1 ? "" : i}`);
      }
    }
    if (defines.VERTEXCOLOR) {
      attribs.push(VertexBuffer.ColorKind);
    }
    PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
    PrepareAttributesForInstances(attribs, defines);
    PrepareAttributesForMorphTargets(attribs, mesh, defines);
    PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);
    let shaderName = "pbr";
    const uniforms = [
      "world",
      "view",
      "viewProjection",
      "vEyePosition",
      "vLightsType",
      "vAmbientColor",
      "vAlbedoColor",
      "baseWeight",
      "vReflectivityColor",
      "vMetallicReflectanceFactors",
      "vEmissiveColor",
      "visibility",
      "vReflectionColor",
      "vFogInfos",
      "vFogColor",
      "pointSize",
      "vAlbedoInfos",
      "vBaseWeightInfos",
      "vAmbientInfos",
      "vOpacityInfos",
      "vReflectionInfos",
      "vReflectionPosition",
      "vReflectionSize",
      "vEmissiveInfos",
      "vReflectivityInfos",
      "vReflectionFilteringInfo",
      "vMetallicReflectanceInfos",
      "vReflectanceInfos",
      "vMicroSurfaceSamplerInfos",
      "vBumpInfos",
      "vLightmapInfos",
      "mBones",
      "albedoMatrix",
      "baseWeightMatrix",
      "ambientMatrix",
      "opacityMatrix",
      "reflectionMatrix",
      "emissiveMatrix",
      "reflectivityMatrix",
      "normalMatrix",
      "microSurfaceSamplerMatrix",
      "bumpMatrix",
      "lightmapMatrix",
      "metallicReflectanceMatrix",
      "reflectanceMatrix",
      "vLightingIntensity",
      "logarithmicDepthConstant",
      "vSphericalX",
      "vSphericalY",
      "vSphericalZ",
      "vSphericalXX_ZZ",
      "vSphericalYY_ZZ",
      "vSphericalZZ",
      "vSphericalXY",
      "vSphericalYZ",
      "vSphericalZX",
      "vSphericalL00",
      "vSphericalL1_1",
      "vSphericalL10",
      "vSphericalL11",
      "vSphericalL2_2",
      "vSphericalL2_1",
      "vSphericalL20",
      "vSphericalL21",
      "vSphericalL22",
      "vReflectionMicrosurfaceInfos",
      "vTangentSpaceParams",
      "boneTextureWidth",
      "vDebugMode",
      "morphTargetTextureInfo",
      "morphTargetTextureIndices"
    ];
    const samplers = [
      "albedoSampler",
      "baseWeightSampler",
      "reflectivitySampler",
      "ambientSampler",
      "emissiveSampler",
      "bumpSampler",
      "lightmapSampler",
      "opacitySampler",
      "reflectionSampler",
      "reflectionSamplerLow",
      "reflectionSamplerHigh",
      "irradianceSampler",
      "microSurfaceSampler",
      "environmentBrdfSampler",
      "boneSampler",
      "metallicReflectanceSampler",
      "reflectanceSampler",
      "morphTargets",
      "oitDepthSampler",
      "oitFrontColorSampler",
      "icdfSampler",
      "areaLightsLTC1Sampler",
      "areaLightsLTC2Sampler"
    ];
    const uniformBuffers = ["Material", "Scene", "Mesh"];
    const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS };
    this._eventInfo.fallbacks = fallbacks;
    this._eventInfo.fallbackRank = fallbackRank;
    this._eventInfo.defines = defines;
    this._eventInfo.uniforms = uniforms;
    this._eventInfo.attributes = attribs;
    this._eventInfo.samplers = samplers;
    this._eventInfo.uniformBuffersNames = uniformBuffers;
    this._eventInfo.customCode = undefined;
    this._eventInfo.mesh = mesh;
    this._eventInfo.indexParameters = indexParameters;
    this._callbackPluginEventGeneric(128, this._eventInfo);
    MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers);
    PrePassConfiguration.AddUniforms(uniforms);
    PrePassConfiguration.AddSamplers(samplers);
    addClipPlaneUniforms(uniforms);
    if (ImageProcessingConfiguration) {
      ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
      ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
    }
    PrepareUniformsAndSamplersList({
      uniformsNames: uniforms,
      uniformBuffersNames: uniformBuffers,
      samplers,
      defines,
      maxSimultaneousLights: this._maxSimultaneousLights
    });
    const csnrOptions = {};
    if (this.customShaderNameResolve) {
      shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
    }
    const join6 = defines.toString();
    const effect = engine2.createEffect(shaderName, {
      attributes: attribs,
      uniformsNames: uniforms,
      uniformBuffersNames: uniformBuffers,
      samplers,
      defines: join6,
      fallbacks,
      onCompiled,
      onError,
      indexParameters,
      processFinalCode: csnrOptions.processFinalCode,
      processCodeAfterIncludes: this._eventInfo.customCode,
      multiTarget: defines.PREPASS,
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: this._shadersLoaded ? undefined : async () => {
        if (this.shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_pbr_vertex(), exports_pbr_vertex)), Promise.resolve().then(() => (init_pbr_fragment(), exports_pbr_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_pbr_vertex2(), exports_pbr_vertex2)), Promise.resolve().then(() => (init_pbr_fragment2(), exports_pbr_fragment2))]);
        }
        this._shadersLoaded = true;
      }
    }, engine2);
    this._eventInfo.customCode = undefined;
    return effect;
  }
  _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) {
    const scene = this.getScene();
    const engine2 = scene.getEngine();
    PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
    defines._needNormals = true;
    PrepareDefinesForMultiview(scene, defines);
    const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;
    PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);
    PrepareDefinesForOIT(scene, defines, oit);
    MaterialHelperGeometryRendering.PrepareDefines(engine2.currentRenderPassId, mesh, defines);
    defines.METALLICWORKFLOW = this.isMetallicWorkflow();
    if (defines._areTexturesDirty) {
      defines._needUVs = false;
      for (let i = 1;i <= 6; ++i) {
        defines["MAINUV" + i] = false;
      }
      if (scene.texturesEnabled) {
        defines.ALBEDODIRECTUV = 0;
        defines.BASEWEIGHTDIRECTUV = 0;
        defines.AMBIENTDIRECTUV = 0;
        defines.OPACITYDIRECTUV = 0;
        defines.EMISSIVEDIRECTUV = 0;
        defines.REFLECTIVITYDIRECTUV = 0;
        defines.MICROSURFACEMAPDIRECTUV = 0;
        defines.METALLIC_REFLECTANCEDIRECTUV = 0;
        defines.REFLECTANCEDIRECTUV = 0;
        defines.BUMPDIRECTUV = 0;
        defines.LIGHTMAPDIRECTUV = 0;
        if (engine2.getCaps().textureLOD) {
          defines.LODBASEDMICROSFURACE = true;
        }
        if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
          PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
          defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;
        } else {
          defines.ALBEDO = false;
        }
        if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
          PrepareDefinesForMergedUV(this._baseWeightTexture, defines, "BASEWEIGHT");
        } else {
          defines.BASEWEIGHT = false;
        }
        if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
          PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
          defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
        } else {
          defines.AMBIENT = false;
        }
        if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
          PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
          defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
        } else {
          defines.OPACITY = false;
        }
        const reflectionTexture = this._getReflectionTexture();
        if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
          defines.REFLECTION = true;
          defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
          defines.RGBDREFLECTION = reflectionTexture.isRGBD;
          defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
          defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;
          if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {
            defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality;
            if (engine2._features.needTypeSuffixInShaderConstants) {
              defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u";
            }
            defines.REALTIME_FILTERING = true;
            if (this.getScene().iblCdfGenerator) {
              defines.IBL_CDF_FILTERING = true;
            }
          } else {
            defines.REALTIME_FILTERING = false;
          }
          defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;
          defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
          defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
          defines.REFLECTIONMAP_CUBIC = false;
          defines.REFLECTIONMAP_EXPLICIT = false;
          defines.REFLECTIONMAP_PLANAR = false;
          defines.REFLECTIONMAP_PROJECTION = false;
          defines.REFLECTIONMAP_SKYBOX = false;
          defines.REFLECTIONMAP_SPHERICAL = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
          defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
          switch (reflectionTexture.coordinatesMode) {
            case Texture.EXPLICIT_MODE:
              defines.REFLECTIONMAP_EXPLICIT = true;
              break;
            case Texture.PLANAR_MODE:
              defines.REFLECTIONMAP_PLANAR = true;
              break;
            case Texture.PROJECTION_MODE:
              defines.REFLECTIONMAP_PROJECTION = true;
              break;
            case Texture.SKYBOX_MODE:
              defines.REFLECTIONMAP_SKYBOX = true;
              break;
            case Texture.SPHERICAL_MODE:
              defines.REFLECTIONMAP_SPHERICAL = true;
              break;
            case Texture.EQUIRECTANGULAR_MODE:
              defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
              break;
            case Texture.FIXED_EQUIRECTANGULAR_MODE:
              defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
              break;
            case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
              defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
              break;
            case Texture.CUBIC_MODE:
            case Texture.INVCUBIC_MODE:
            default:
              defines.REFLECTIONMAP_CUBIC = true;
              defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
              break;
          }
          if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
            if (reflectionTexture.irradianceTexture) {
              defines.USEIRRADIANCEMAP = true;
              defines.USESPHERICALFROMREFLECTIONMAP = false;
              defines.USESPHERICALINVERTEX = false;
            } else if (reflectionTexture.isCube) {
              defines.USESPHERICALFROMREFLECTIONMAP = true;
              defines.USEIRRADIANCEMAP = false;
              if (this._forceIrradianceInFragment || this.realTimeFiltering || this._twoSidedLighting || engine2.getCaps().maxVaryingVectors <= 8) {
                defines.USESPHERICALINVERTEX = false;
              } else {
                defines.USESPHERICALINVERTEX = true;
              }
            }
          }
        } else {
          defines.REFLECTION = false;
          defines.REFLECTIONMAP_3D = false;
          defines.REFLECTIONMAP_SPHERICAL = false;
          defines.REFLECTIONMAP_PLANAR = false;
          defines.REFLECTIONMAP_CUBIC = false;
          defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
          defines.REFLECTIONMAP_PROJECTION = false;
          defines.REFLECTIONMAP_SKYBOX = false;
          defines.REFLECTIONMAP_EXPLICIT = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
          defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
          defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
          defines.INVERTCUBICMAP = false;
          defines.USESPHERICALFROMREFLECTIONMAP = false;
          defines.USEIRRADIANCEMAP = false;
          defines.USESPHERICALINVERTEX = false;
          defines.REFLECTIONMAP_OPPOSITEZ = false;
          defines.LODINREFLECTIONALPHA = false;
          defines.GAMMAREFLECTION = false;
          defines.RGBDREFLECTION = false;
          defines.LINEARSPECULARREFLECTION = false;
        }
        if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
          PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
          defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
          defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
          defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
        } else {
          defines.LIGHTMAP = false;
        }
        if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
          PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
          defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace;
        } else {
          defines.EMISSIVE = false;
        }
        if (MaterialFlags.SpecularTextureEnabled) {
          if (this._metallicTexture) {
            PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
            defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
            defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
            defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
            defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
            defines.REFLECTIVITY_GAMMA = false;
          } else if (this._reflectivityTexture) {
            PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
            defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
            defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
            defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace;
          } else {
            defines.REFLECTIVITY = false;
          }
          if (this._metallicReflectanceTexture || this._reflectanceTexture) {
            defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture;
            if (this._metallicReflectanceTexture) {
              PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE");
              defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace;
            } else {
              defines.METALLIC_REFLECTANCE = false;
            }
            if (this._reflectanceTexture && (!this._metallicReflectanceTexture || this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture)) {
              PrepareDefinesForMergedUV(this._reflectanceTexture, defines, "REFLECTANCE");
              defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace;
            } else {
              defines.REFLECTANCE = false;
            }
          } else {
            defines.METALLIC_REFLECTANCE = false;
            defines.REFLECTANCE = false;
          }
          if (this._microSurfaceTexture) {
            PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
          } else {
            defines.MICROSURFACEMAP = false;
          }
        } else {
          defines.REFLECTIVITY = false;
          defines.MICROSURFACEMAP = false;
        }
        if (engine2.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
          PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
          if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
            defines.PARALLAX = true;
            defines.PARALLAX_RHS = scene.useRightHandedSystem;
            defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
          } else {
            defines.PARALLAX = false;
          }
          defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
        } else {
          defines.BUMP = false;
          defines.PARALLAX = false;
          defines.PARALLAX_RHS = false;
          defines.PARALLAXOCCLUSION = false;
          defines.OBJECTSPACE_NORMALMAP = false;
        }
        if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
          defines.ENVIRONMENTBRDF = true;
          defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;
        } else {
          defines.ENVIRONMENTBRDF = false;
          defines.ENVIRONMENTBRDF_RGBD = false;
        }
        if (this._shouldUseAlphaFromAlbedoTexture()) {
          defines.ALPHAFROMALBEDO = true;
        } else {
          defines.ALPHAFROMALBEDO = false;
        }
      }
      defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
      if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
        defines.USEPHYSICALLIGHTFALLOFF = false;
        defines.USEGLTFLIGHTFALLOFF = false;
      } else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
        defines.USEPHYSICALLIGHTFALLOFF = false;
        defines.USEGLTFLIGHTFALLOFF = true;
      } else {
        defines.USEPHYSICALLIGHTFALLOFF = true;
        defines.USEGLTFLIGHTFALLOFF = false;
      }
      defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
      if (!this.backFaceCulling && this._twoSidedLighting) {
        defines.TWOSIDEDLIGHTING = true;
      } else {
        defines.TWOSIDEDLIGHTING = false;
      }
      defines.SPECULARAA = engine2.getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
    }
    if (defines._areTexturesDirty || defines._areMiscDirty) {
      defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? "." : ""}`;
      defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;
      defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
      defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
      defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
    }
    if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
      this._imageProcessingConfiguration.prepareDefines(defines);
    }
    defines.FORCENORMALFORWARD = this._forceNormalForward;
    defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
    defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
    if (defines._areMiscDirty) {
      PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap);
      defines.UNLIT = this._unlit || (this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind);
      defines.DEBUGMODE = this._debugMode;
    }
    PrepareDefinesForFrameBoundValues(scene, engine2, this, defines, useInstances ? true : false, useClipPlane, useThinInstances);
    this._eventInfo.defines = defines;
    this._eventInfo.mesh = mesh;
    this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);
    PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);
    this._callbackPluginEventPrepareDefines(this._eventInfo);
  }
  forceCompilation(mesh, onCompiled, options) {
    const localOptions = {
      clipPlane: false,
      useInstances: false,
      ...options
    };
    if (!this._uniformBufferLayoutBuilt) {
      this.buildUniformLayout();
    }
    this._callbackPluginEventGeneric(4, this._eventInfo);
    const checkReady = () => {
      if (this._breakShaderLoadedCheck) {
        return;
      }
      const defines = new PBRMaterialDefines(this._eventInfo.defineNames);
      const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances);
      if (this._onEffectCreatedObservable) {
        onCreatedEffectParameters3.effect = effect;
        onCreatedEffectParameters3.subMesh = null;
        this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters3);
      }
      if (effect.isReady()) {
        if (onCompiled) {
          onCompiled(this);
        }
      } else {
        effect.onCompileObservable.add(() => {
          if (onCompiled) {
            onCompiled(this);
          }
        });
      }
    };
    checkReady();
  }
  buildUniformLayout() {
    const ubo = this._uniformBuffer;
    ubo.addUniform("vAlbedoInfos", 2);
    ubo.addUniform("vBaseWeightInfos", 2);
    ubo.addUniform("vAmbientInfos", 4);
    ubo.addUniform("vOpacityInfos", 2);
    ubo.addUniform("vEmissiveInfos", 2);
    ubo.addUniform("vLightmapInfos", 2);
    ubo.addUniform("vReflectivityInfos", 3);
    ubo.addUniform("vMicroSurfaceSamplerInfos", 2);
    ubo.addUniform("vReflectionInfos", 2);
    ubo.addUniform("vReflectionFilteringInfo", 2);
    ubo.addUniform("vReflectionPosition", 3);
    ubo.addUniform("vReflectionSize", 3);
    ubo.addUniform("vBumpInfos", 3);
    ubo.addUniform("albedoMatrix", 16);
    ubo.addUniform("baseWeightMatrix", 16);
    ubo.addUniform("ambientMatrix", 16);
    ubo.addUniform("opacityMatrix", 16);
    ubo.addUniform("emissiveMatrix", 16);
    ubo.addUniform("lightmapMatrix", 16);
    ubo.addUniform("reflectivityMatrix", 16);
    ubo.addUniform("microSurfaceSamplerMatrix", 16);
    ubo.addUniform("bumpMatrix", 16);
    ubo.addUniform("vTangentSpaceParams", 2);
    ubo.addUniform("reflectionMatrix", 16);
    ubo.addUniform("vReflectionColor", 3);
    ubo.addUniform("vAlbedoColor", 4);
    ubo.addUniform("baseWeight", 1);
    ubo.addUniform("vLightingIntensity", 4);
    ubo.addUniform("vReflectionMicrosurfaceInfos", 3);
    ubo.addUniform("pointSize", 1);
    ubo.addUniform("vReflectivityColor", 4);
    ubo.addUniform("vEmissiveColor", 3);
    ubo.addUniform("vAmbientColor", 3);
    ubo.addUniform("vDebugMode", 2);
    ubo.addUniform("vMetallicReflectanceFactors", 4);
    ubo.addUniform("vMetallicReflectanceInfos", 2);
    ubo.addUniform("metallicReflectanceMatrix", 16);
    ubo.addUniform("vReflectanceInfos", 2);
    ubo.addUniform("reflectanceMatrix", 16);
    ubo.addUniform("vSphericalL00", 3);
    ubo.addUniform("vSphericalL1_1", 3);
    ubo.addUniform("vSphericalL10", 3);
    ubo.addUniform("vSphericalL11", 3);
    ubo.addUniform("vSphericalL2_2", 3);
    ubo.addUniform("vSphericalL2_1", 3);
    ubo.addUniform("vSphericalL20", 3);
    ubo.addUniform("vSphericalL21", 3);
    ubo.addUniform("vSphericalL22", 3);
    ubo.addUniform("vSphericalX", 3);
    ubo.addUniform("vSphericalY", 3);
    ubo.addUniform("vSphericalZ", 3);
    ubo.addUniform("vSphericalXX_ZZ", 3);
    ubo.addUniform("vSphericalYY_ZZ", 3);
    ubo.addUniform("vSphericalZZ", 3);
    ubo.addUniform("vSphericalXY", 3);
    ubo.addUniform("vSphericalYZ", 3);
    ubo.addUniform("vSphericalZX", 3);
    super.buildUniformLayout();
  }
  bindForSubMesh(world, mesh, subMesh) {
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (!defines) {
      return;
    }
    const effect = subMesh.effect;
    if (!effect) {
      return;
    }
    this._activeEffect = effect;
    mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
    mesh.transferToEffect(world);
    const engine2 = scene.getEngine();
    this._uniformBuffer.bindToEffect(effect, "Material");
    this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);
    MaterialHelperGeometryRendering.Bind(engine2.currentRenderPassId, this._activeEffect, mesh, world, this);
    this._eventInfo.subMesh = subMesh;
    this._callbackPluginEventHardBindForSubMesh(this._eventInfo);
    if (defines.OBJECTSPACE_NORMALMAP) {
      world.toNormalMatrix(this._normalMatrix);
      this.bindOnlyNormalMatrix(this._normalMatrix);
    }
    const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
    BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration);
    let reflectionTexture = null;
    const ubo = this._uniformBuffer;
    if (mustRebind) {
      this.bindViewProjection(effect);
      reflectionTexture = this._getReflectionTexture();
      if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) {
        if (scene.texturesEnabled) {
          if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
            ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
            BindTextureMatrix(this._albedoTexture, ubo, "albedo");
          }
          if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
            ubo.updateFloat2("vBaseWeightInfos", this._baseWeightTexture.coordinatesIndex, this._baseWeightTexture.level);
            BindTextureMatrix(this._baseWeightTexture, ubo, "baseWeight");
          }
          if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
            ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
            BindTextureMatrix(this._ambientTexture, ubo, "ambient");
          }
          if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
            ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
            BindTextureMatrix(this._opacityTexture, ubo, "opacity");
          }
          if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
            ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
            ubo.updateFloat2("vReflectionInfos", reflectionTexture.level * scene.iblIntensity, 0);
            if (reflectionTexture.boundingBoxSize) {
              const cubeTexture = reflectionTexture;
              ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
              ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
            }
            if (this.realTimeFiltering) {
              const width = reflectionTexture.getSize().width;
              ubo.updateFloat2("vReflectionFilteringInfo", width, Math.log2(width));
            }
            if (!defines.USEIRRADIANCEMAP) {
              const polynomials = reflectionTexture.sphericalPolynomial;
              if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
                if (defines.SPHERICAL_HARMONICS) {
                  const preScaledHarmonics = polynomials.preScaledHarmonics;
                  ubo.updateVector3("vSphericalL00", preScaledHarmonics.l00);
                  ubo.updateVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
                  ubo.updateVector3("vSphericalL10", preScaledHarmonics.l10);
                  ubo.updateVector3("vSphericalL11", preScaledHarmonics.l11);
                  ubo.updateVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
                  ubo.updateVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
                  ubo.updateVector3("vSphericalL20", preScaledHarmonics.l20);
                  ubo.updateVector3("vSphericalL21", preScaledHarmonics.l21);
                  ubo.updateVector3("vSphericalL22", preScaledHarmonics.l22);
                } else {
                  ubo.updateFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
                  ubo.updateFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
                  ubo.updateFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
                  ubo.updateFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
                  ubo.updateFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
                  ubo.updateFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
                  ubo.updateFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
                  ubo.updateFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
                  ubo.updateFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
                }
              }
            }
            ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
          }
          if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
            ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
            BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
          }
          if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
            ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
            BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
          }
          if (MaterialFlags.SpecularTextureEnabled) {
            if (this._metallicTexture) {
              ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
              BindTextureMatrix(this._metallicTexture, ubo, "reflectivity");
            } else if (this._reflectivityTexture) {
              ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1);
              BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity");
            }
            if (this._metallicReflectanceTexture) {
              ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);
              BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance");
            }
            if (this._reflectanceTexture && defines.REFLECTANCE) {
              ubo.updateFloat2("vReflectanceInfos", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level);
              BindTextureMatrix(this._reflectanceTexture, ubo, "reflectance");
            }
            if (this._microSurfaceTexture) {
              ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
              BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler");
            }
          }
          if (this._bumpTexture && engine2.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
            ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
            BindTextureMatrix(this._bumpTexture, ubo, "bump");
            if (scene._mirroredCameraPosition) {
              ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1);
            } else {
              ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1);
            }
          }
        }
        if (this.pointsCloud) {
          ubo.updateFloat("pointSize", this.pointSize);
        }
        if (defines.METALLICWORKFLOW) {
          TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic;
          TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness;
          ubo.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1);
          const ior = this.subSurface?._indexOfRefraction ?? 1.5;
          const outsideIOR = 1;
          const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);
          this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);
          const metallicF90 = this._metallicF0Factor;
          ubo.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], metallicF90);
        } else {
          ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
        }
        ubo.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly);
        ubo.updateColor3("vReflectionColor", this._reflectionColor);
        if (!defines.SS_REFRACTION && this.subSurface?._linkRefractionWithTransparency) {
          ubo.updateColor4("vAlbedoColor", this._albedoColor, 1);
        } else {
          ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha);
        }
        ubo.updateFloat("baseWeight", this._baseWeight);
        this._lightingInfos.x = this._directIntensity;
        this._lightingInfos.y = this._emissiveIntensity;
        this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;
        this._lightingInfos.w = this._specularIntensity;
        ubo.updateVector4("vLightingIntensity", this._lightingInfos);
        scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
        ubo.updateColor3("vAmbientColor", this._globalAmbientColor);
        ubo.updateFloat2("vDebugMode", this.debugLimit, this.debugFactor);
      }
      if (scene.texturesEnabled) {
        if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {
          ubo.setTexture("albedoSampler", this._albedoTexture);
        }
        if (this._baseWeightTexture && MaterialFlags.BaseWeightTextureEnabled) {
          ubo.setTexture("baseWeightSampler", this._baseWeightTexture);
        }
        if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {
          ubo.setTexture("ambientSampler", this._ambientTexture);
        }
        if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {
          ubo.setTexture("opacitySampler", this._opacityTexture);
        }
        if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
          if (defines.LODBASEDMICROSFURACE) {
            ubo.setTexture("reflectionSampler", reflectionTexture);
          } else {
            ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
            ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
            ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
          }
          if (defines.USEIRRADIANCEMAP) {
            ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture);
          }
          const cdfGenerator = this.getScene().iblCdfGenerator;
          if (this.realTimeFiltering && cdfGenerator) {
            ubo.setTexture("icdfSampler", cdfGenerator.getIcdfTexture());
          }
        }
        if (defines.ENVIRONMENTBRDF) {
          ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
        }
        if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {
          ubo.setTexture("emissiveSampler", this._emissiveTexture);
        }
        if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {
          ubo.setTexture("lightmapSampler", this._lightmapTexture);
        }
        if (MaterialFlags.SpecularTextureEnabled) {
          if (this._metallicTexture) {
            ubo.setTexture("reflectivitySampler", this._metallicTexture);
          } else if (this._reflectivityTexture) {
            ubo.setTexture("reflectivitySampler", this._reflectivityTexture);
          }
          if (this._metallicReflectanceTexture) {
            ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture);
          }
          if (this._reflectanceTexture && defines.REFLECTANCE) {
            ubo.setTexture("reflectanceSampler", this._reflectanceTexture);
          }
          if (this._microSurfaceTexture) {
            ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture);
          }
        }
        if (this._bumpTexture && engine2.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {
          ubo.setTexture("bumpSampler", this._bumpTexture);
        }
      }
      if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {
        this.getScene().depthPeelingRenderer.bind(effect);
      }
      this._eventInfo.subMesh = subMesh;
      this._callbackPluginEventBindForSubMesh(this._eventInfo);
      bindClipPlane(this._activeEffect, this, scene);
      this.bindEyePosition(effect);
    } else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
      this._needToBindSceneUbo = true;
    }
    if (mustRebind || !this.isFrozen) {
      if (scene.lightsEnabled && !this._disableLighting) {
        BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);
      }
      if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE || reflectionTexture || this.subSurface.refractionTexture || mesh.receiveShadows || defines.PREPASS) {
        this.bindView(effect);
      }
      BindFogParameters(scene, mesh, this._activeEffect, true);
      if (defines.NUM_MORPH_INFLUENCERS) {
        BindMorphTargetParameters(mesh, this._activeEffect);
      }
      if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {
        mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES);
      }
      this._imageProcessingConfiguration.bind(this._activeEffect);
      BindLogDepth(defines, this._activeEffect, scene);
    }
    this._afterBind(mesh, this._activeEffect, subMesh);
    ubo.update();
  }
  getAnimatables() {
    const results = super.getAnimatables();
    if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
      results.push(this._albedoTexture);
    }
    if (this._baseWeightTexture && this._baseWeightTexture.animations && this._baseWeightTexture.animations.length > 0) {
      results.push(this._baseWeightTexture);
    }
    if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
      results.push(this._ambientTexture);
    }
    if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
      results.push(this._opacityTexture);
    }
    if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
      results.push(this._reflectionTexture);
    }
    if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
      results.push(this._emissiveTexture);
    }
    if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
      results.push(this._metallicTexture);
    } else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
      results.push(this._reflectivityTexture);
    }
    if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
      results.push(this._bumpTexture);
    }
    if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
      results.push(this._lightmapTexture);
    }
    if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) {
      results.push(this._metallicReflectanceTexture);
    }
    if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) {
      results.push(this._reflectanceTexture);
    }
    if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) {
      results.push(this._microSurfaceTexture);
    }
    return results;
  }
  _getReflectionTexture() {
    if (this._reflectionTexture) {
      return this._reflectionTexture;
    }
    return this.getScene().environmentTexture;
  }
  getActiveTextures() {
    const activeTextures = super.getActiveTextures();
    if (this._albedoTexture) {
      activeTextures.push(this._albedoTexture);
    }
    if (this._baseWeightTexture) {
      activeTextures.push(this._baseWeightTexture);
    }
    if (this._ambientTexture) {
      activeTextures.push(this._ambientTexture);
    }
    if (this._opacityTexture) {
      activeTextures.push(this._opacityTexture);
    }
    if (this._reflectionTexture) {
      activeTextures.push(this._reflectionTexture);
    }
    if (this._emissiveTexture) {
      activeTextures.push(this._emissiveTexture);
    }
    if (this._reflectivityTexture) {
      activeTextures.push(this._reflectivityTexture);
    }
    if (this._metallicTexture) {
      activeTextures.push(this._metallicTexture);
    }
    if (this._metallicReflectanceTexture) {
      activeTextures.push(this._metallicReflectanceTexture);
    }
    if (this._reflectanceTexture) {
      activeTextures.push(this._reflectanceTexture);
    }
    if (this._microSurfaceTexture) {
      activeTextures.push(this._microSurfaceTexture);
    }
    if (this._bumpTexture) {
      activeTextures.push(this._bumpTexture);
    }
    if (this._lightmapTexture) {
      activeTextures.push(this._lightmapTexture);
    }
    return activeTextures;
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    if (this._albedoTexture === texture) {
      return true;
    }
    if (this._baseWeightTexture === texture) {
      return true;
    }
    if (this._ambientTexture === texture) {
      return true;
    }
    if (this._opacityTexture === texture) {
      return true;
    }
    if (this._reflectionTexture === texture) {
      return true;
    }
    if (this._emissiveTexture === texture) {
      return true;
    }
    if (this._reflectivityTexture === texture) {
      return true;
    }
    if (this._metallicTexture === texture) {
      return true;
    }
    if (this._metallicReflectanceTexture === texture) {
      return true;
    }
    if (this._reflectanceTexture === texture) {
      return true;
    }
    if (this._microSurfaceTexture === texture) {
      return true;
    }
    if (this._bumpTexture === texture) {
      return true;
    }
    if (this._lightmapTexture === texture) {
      return true;
    }
    return false;
  }
  setPrePassRenderer() {
    if (!this.subSurface?.isScatteringEnabled) {
      return false;
    }
    const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass();
    if (subSurfaceConfiguration) {
      subSurfaceConfiguration.enabled = true;
    }
    return true;
  }
  dispose(forceDisposeEffect, forceDisposeTextures) {
    this._breakShaderLoadedCheck = true;
    if (forceDisposeTextures) {
      if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {
        this._environmentBRDFTexture.dispose();
      }
      this._albedoTexture?.dispose();
      this._baseWeightTexture?.dispose();
      this._ambientTexture?.dispose();
      this._opacityTexture?.dispose();
      this._reflectionTexture?.dispose();
      this._emissiveTexture?.dispose();
      this._metallicTexture?.dispose();
      this._reflectivityTexture?.dispose();
      this._bumpTexture?.dispose();
      this._lightmapTexture?.dispose();
      this._metallicReflectanceTexture?.dispose();
      this._reflectanceTexture?.dispose();
      this._microSurfaceTexture?.dispose();
    }
    this._renderTargets.dispose();
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    super.dispose(forceDisposeEffect, forceDisposeTextures);
  }
}
PBRBaseMaterial.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE;
PBRBaseMaterial.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST;
PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND;
PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND;
PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;
PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
PBRBaseMaterial.ForceGLSL = false;
__decorate([
  serializeAsImageProcessingConfiguration()
], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRBaseMaterial.prototype, "debugMode", undefined);

// node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js
init_typeStore();
init_decorators_serialization();

class PBRMaterial extends PBRBaseMaterial {
  get refractionTexture() {
    return this.subSurface.refractionTexture;
  }
  set refractionTexture(value) {
    this.subSurface.refractionTexture = value;
    if (value) {
      this.subSurface.isRefractionEnabled = true;
    } else if (!this.subSurface.linkRefractionWithTransparency) {
      this.subSurface.isRefractionEnabled = false;
    }
  }
  get indexOfRefraction() {
    return this.subSurface.indexOfRefraction;
  }
  set indexOfRefraction(value) {
    this.subSurface.indexOfRefraction = value;
  }
  get invertRefractionY() {
    return this.subSurface.invertRefractionY;
  }
  set invertRefractionY(value) {
    this.subSurface.invertRefractionY = value;
  }
  get linkRefractionWithTransparency() {
    return this.subSurface.linkRefractionWithTransparency;
  }
  set linkRefractionWithTransparency(value) {
    this.subSurface.linkRefractionWithTransparency = value;
    if (value) {
      this.subSurface.isRefractionEnabled = true;
    }
  }
  get usePhysicalLightFalloff() {
    return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  }
  set usePhysicalLightFalloff(value) {
    if (value !== this.usePhysicalLightFalloff) {
      this._markAllSubMeshesAsTexturesDirty();
      if (value) {
        this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
      } else {
        this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
      }
    }
  }
  get useGLTFLightFalloff() {
    return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  }
  set useGLTFLightFalloff(value) {
    if (value !== this.useGLTFLightFalloff) {
      this._markAllSubMeshesAsTexturesDirty();
      if (value) {
        this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF;
      } else {
        this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
      }
    }
  }
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    this._attachImageProcessingConfiguration(value);
    this._markAllSubMeshesAsTexturesDirty();
  }
  get cameraColorCurvesEnabled() {
    return this.imageProcessingConfiguration.colorCurvesEnabled;
  }
  set cameraColorCurvesEnabled(value) {
    this.imageProcessingConfiguration.colorCurvesEnabled = value;
  }
  get cameraColorGradingEnabled() {
    return this.imageProcessingConfiguration.colorGradingEnabled;
  }
  set cameraColorGradingEnabled(value) {
    this.imageProcessingConfiguration.colorGradingEnabled = value;
  }
  get cameraToneMappingEnabled() {
    return this._imageProcessingConfiguration.toneMappingEnabled;
  }
  set cameraToneMappingEnabled(value) {
    this._imageProcessingConfiguration.toneMappingEnabled = value;
  }
  get cameraExposure() {
    return this._imageProcessingConfiguration.exposure;
  }
  set cameraExposure(value) {
    this._imageProcessingConfiguration.exposure = value;
  }
  get cameraContrast() {
    return this._imageProcessingConfiguration.contrast;
  }
  set cameraContrast(value) {
    this._imageProcessingConfiguration.contrast = value;
  }
  get cameraColorGradingTexture() {
    return this._imageProcessingConfiguration.colorGradingTexture;
  }
  set cameraColorGradingTexture(value) {
    this._imageProcessingConfiguration.colorGradingTexture = value;
  }
  get cameraColorCurves() {
    return this._imageProcessingConfiguration.colorCurves;
  }
  set cameraColorCurves(value) {
    this._imageProcessingConfiguration.colorCurves = value;
  }
  constructor(name325, scene, forceGLSL = false) {
    super(name325, scene, forceGLSL);
    this.directIntensity = 1;
    this.emissiveIntensity = 1;
    this.environmentIntensity = 1;
    this.specularIntensity = 1;
    this.disableBumpMap = false;
    this.ambientTextureStrength = 1;
    this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
    this.metallicF0Factor = 1;
    this.metallicReflectanceColor = Color3.White();
    this.useOnlyMetallicFromMetallicReflectanceTexture = false;
    this.ambientColor = new Color3(0, 0, 0);
    this.albedoColor = new Color3(1, 1, 1);
    this.baseWeight = 1;
    this.reflectivityColor = new Color3(1, 1, 1);
    this.reflectionColor = new Color3(1, 1, 1);
    this.emissiveColor = new Color3(0, 0, 0);
    this.microSurface = 1;
    this.useLightmapAsShadowmap = false;
    this.useAlphaFromAlbedoTexture = false;
    this.forceAlphaTest = false;
    this.alphaCutOff = 0.4;
    this.useSpecularOverAlpha = true;
    this.useMicroSurfaceFromReflectivityMapAlpha = false;
    this.useRoughnessFromMetallicTextureAlpha = true;
    this.useRoughnessFromMetallicTextureGreen = false;
    this.useMetallnessFromMetallicTextureBlue = false;
    this.useAmbientOcclusionFromMetallicTextureRed = false;
    this.useAmbientInGrayScale = false;
    this.useAutoMicroSurfaceFromReflectivityMap = false;
    this.useRadianceOverAlpha = true;
    this.useObjectSpaceNormalMap = false;
    this.useParallax = false;
    this.useParallaxOcclusion = false;
    this.parallaxScaleBias = 0.05;
    this.disableLighting = false;
    this.forceIrradianceInFragment = false;
    this.maxSimultaneousLights = 4;
    this.invertNormalMapX = false;
    this.invertNormalMapY = false;
    this.twoSidedLighting = false;
    this.useAlphaFresnel = false;
    this.useLinearAlphaFresnel = false;
    this.environmentBRDFTexture = null;
    this.forceNormalForward = false;
    this.enableSpecularAntiAliasing = false;
    this.useHorizonOcclusion = true;
    this.useRadianceOcclusion = true;
    this.unlit = false;
    this.applyDecalMapAfterDetailMap = false;
    this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());
  }
  getClassName() {
    return "PBRMaterial";
  }
  clone(name325, cloneTexturesOnlyOnce = true, rootUrl = "") {
    const clone = SerializationHelper.Clone(() => new PBRMaterial(name325, this.getScene()), this, { cloneTexturesOnlyOnce });
    clone.id = name325;
    clone.name = name325;
    this.stencil.copyTo(clone.stencil);
    this._clonePlugins(clone, rootUrl);
    return clone;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.customType = "BABYLON.PBRMaterial";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const material = SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl);
    if (source.stencil) {
      material.stencil.parse(source.stencil, scene, rootUrl);
    }
    Material._ParsePlugins(source, material, scene, rootUrl);
    if (source.clearCoat) {
      material.clearCoat.parse(source.clearCoat, scene, rootUrl);
    }
    if (source.anisotropy) {
      material.anisotropy.parse(source.anisotropy, scene, rootUrl);
    }
    if (source.brdf) {
      material.brdf.parse(source.brdf, scene, rootUrl);
    }
    if (source.sheen) {
      material.sheen.parse(source.sheen, scene, rootUrl);
    }
    if (source.subSurface) {
      material.subSurface.parse(source.subSurface, scene, rootUrl);
    }
    if (source.iridescence) {
      material.iridescence.parse(source.iridescence, scene, rootUrl);
    }
    return material;
  }
}
PBRMaterial.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE;
PBRMaterial.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST;
PBRMaterial.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND;
PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND;
PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "directIntensity", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveIntensity", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentIntensity", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "specularIntensity", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "disableBumpMap", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "baseWeightTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTextureStrength", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "opacityTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallic", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "roughness", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicF0Factor", undefined);
__decorate([
  serializeAsColor3(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicReflectanceColor", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useOnlyMetallicFromMetallicReflectanceTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicReflectanceTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectanceTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurfaceTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "bumpTexture", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRMaterial.prototype, "lightmapTexture", undefined);
__decorate([
  serializeAsColor3("ambient"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientColor", undefined);
__decorate([
  serializeAsColor3("albedo"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoColor", undefined);
__decorate([
  serialize("baseWeight"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "baseWeight", undefined);
__decorate([
  serializeAsColor3("reflectivity"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityColor", undefined);
__decorate([
  serializeAsColor3("reflection"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionColor", undefined);
__decorate([
  serializeAsColor3("emissive"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveColor", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurface", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLightmapAsShadowmap", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "forceAlphaTest", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "alphaCutOff", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useSpecularOverAlpha", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientInGrayScale", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", undefined);
__decorate([
  serialize()
], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
__decorate([
  serialize()
], PBRMaterial.prototype, "useGLTFLightFalloff", null);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOverAlpha", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useObjectSpaceNormalMap", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallax", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallaxOcclusion", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "parallaxScaleBias", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "disableLighting", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceIrradianceInFragment", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "maxSimultaneousLights", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapX", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapY", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "twoSidedLighting", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAlphaFresnel", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLinearAlphaFresnel", undefined);
__decorate([
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentBRDFTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceNormalForward", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "enableSpecularAntiAliasing", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useHorizonOcclusion", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOcclusion", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRMaterial.prototype, "unlit", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRMaterial.prototype, "applyDecalMapAfterDetailMap", undefined);
RegisterClass("BABYLON.PBRMaterial", PBRMaterial);

// node_modules/@babylonjs/core/Helpers/sceneHelpers.js
init_ddsTextureLoader();
init_envTextureLoader();
init_ktxTextureLoader();

// node_modules/@babylonjs/core/XR/webXRExperienceHelper.js
init_observable();

// node_modules/@babylonjs/core/XR/webXRCamera.js
init_math_vector();
init_observable();

class WebXRCamera extends FreeCamera {
  constructor(name325, scene, _xrSessionManager) {
    super(name325, Vector3.Zero(), scene);
    this._xrSessionManager = _xrSessionManager;
    this._firstFrame = false;
    this._referenceQuaternion = Quaternion.Identity();
    this._referencedPosition = new Vector3;
    this._trackingState = 0;
    this.onXRCameraInitializedObservable = new Observable;
    this.onBeforeCameraTeleport = new Observable;
    this.onAfterCameraTeleport = new Observable;
    this.onTrackingStateChanged = new Observable;
    this.compensateOnFirstFrame = true;
    this._rotate180 = new Quaternion(0, 1, 0, 0);
    this.minZ = 0.1;
    this.rotationQuaternion = new Quaternion;
    this.cameraRigMode = Camera.RIG_MODE_CUSTOM;
    this.updateUpVectorFromRotation = true;
    this._updateNumberOfRigCameras(1);
    this.freezeProjectionMatrix();
    this._deferOnly = true;
    this._xrSessionManager.onXRSessionInit.add(() => {
      this._referencedPosition.copyFromFloats(0, 0, 0);
      this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);
      this._firstFrame = this.compensateOnFirstFrame;
      this._xrSessionManager.onWorldScaleFactorChangedObservable.add(() => {
        if (!this._xrSessionManager.currentFrame) {
          return;
        }
        this._updateDepthNearFar();
      });
    });
    this._xrSessionManager.onXRFrameObservable.add(() => {
      if (this._firstFrame) {
        this._updateFromXRSession();
      }
      if (this.onXRCameraInitializedObservable.hasObservers()) {
        this.onXRCameraInitializedObservable.notifyObservers(this);
        this.onXRCameraInitializedObservable.clear();
      }
      if (this._deferredUpdated) {
        this.position.copyFrom(this._deferredPositionUpdate);
        this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate);
      }
      this._updateReferenceSpace();
      this._updateFromXRSession();
    }, undefined, true);
  }
  get trackingState() {
    return this._trackingState;
  }
  _setTrackingState(newState) {
    if (this._trackingState !== newState) {
      this._trackingState = newState;
      this.onTrackingStateChanged.notifyObservers(newState);
    }
  }
  get realWorldHeight() {
    const basePose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);
    if (basePose && basePose.transform) {
      return basePose.transform.position.y * this._xrSessionManager.worldScalingFactor;
    } else {
      return 0;
    }
  }
  _updateForDualEyeDebugging() {
    this._updateNumberOfRigCameras(2);
    this.rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1);
    this.rigCameras[0].outputRenderTarget = null;
    this.rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1);
    this.rigCameras[1].outputRenderTarget = null;
  }
  setTransformationFromNonVRCamera(otherCamera = this.getScene().activeCamera, resetToBaseReferenceSpace = true) {
    if (!otherCamera || otherCamera === this) {
      return;
    }
    const mat = otherCamera.computeWorldMatrix();
    mat.decompose(undefined, this.rotationQuaternion, this.position);
    this.position.y = 0;
    Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion);
    this._firstFrame = true;
    if (resetToBaseReferenceSpace) {
      this._xrSessionManager.resetReferenceSpace();
    }
  }
  getClassName() {
    return "WebXRCamera";
  }
  setTarget(target) {
    const tmpVector = TmpVectors.Vector3[1];
    target.subtractToRef(this.position, tmpVector);
    tmpVector.y = 0;
    tmpVector.normalize();
    const yRotation = Math.atan2(tmpVector.x, tmpVector.z);
    this.rotationQuaternion.toEulerAnglesToRef(tmpVector);
    Quaternion.FromEulerAnglesToRef(tmpVector.x, yRotation, tmpVector.z, this.rotationQuaternion);
  }
  dispose() {
    super.dispose();
    this._lastXRViewerPose = undefined;
    this.onTrackingStateChanged.clear();
  }
  _updateDepthNearFar() {
    const far = (this.maxZ || 1e4) * this._xrSessionManager.worldScalingFactor;
    const xrRenderState = {
      depthFar: far,
      depthNear: this.minZ
    };
    this._xrSessionManager.updateRenderState(xrRenderState);
    this._cache.minZ = this.minZ;
    this._cache.maxZ = far;
  }
  _updateFromXRSession() {
    const pose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);
    this._lastXRViewerPose = pose || undefined;
    if (!pose) {
      this._setTrackingState(0);
      return;
    }
    const trackingState = pose.emulatedPosition ? 1 : 2;
    this._setTrackingState(trackingState);
    if (this.minZ !== this._cache.minZ || this.maxZ !== this._cache.maxZ) {
      this._updateDepthNearFar();
    }
    if (pose.transform) {
      const orientation = pose.transform.orientation;
      if (pose.transform.orientation.x === undefined) {
        return;
      }
      const pos = pose.transform.position;
      this._referencedPosition.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);
      this._referenceQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
      if (!this._scene.useRightHandedSystem) {
        this._referencedPosition.z *= -1;
        this._referenceQuaternion.z *= -1;
        this._referenceQuaternion.w *= -1;
      } else {
        this._referenceQuaternion.multiplyInPlace(this._rotate180);
      }
      if (this._firstFrame) {
        this._firstFrame = false;
        this.position.y += this._referencedPosition.y;
        this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);
      } else {
        this.rotationQuaternion.copyFrom(this._referenceQuaternion);
        this.position.copyFrom(this._referencedPosition);
      }
    }
    if (this.rigCameras.length !== pose.views.length) {
      this._updateNumberOfRigCameras(pose.views.length);
    }
    pose.views.forEach((view, i) => {
      const currentRig = this.rigCameras[i];
      if (!currentRig.isLeftCamera && !currentRig.isRightCamera) {
        if (view.eye === "right") {
          currentRig._isRightCamera = true;
        } else if (view.eye === "left") {
          currentRig._isLeftCamera = true;
        }
      }
      const customRenderTargets = this.getScene().customRenderTargets;
      for (let i2 = 0;i2 < customRenderTargets.length; i2++) {
        const rt = customRenderTargets[i2];
        if (currentRig.customRenderTargets.indexOf(rt) === -1) {
          currentRig.customRenderTargets.push(rt);
        }
      }
      const pos = view.transform.position;
      const orientation = view.transform.orientation;
      currentRig.parent = this.parent;
      currentRig.position.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);
      currentRig.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
      if (!this._scene.useRightHandedSystem) {
        currentRig.position.z *= -1;
        currentRig.rotationQuaternion.z *= -1;
        currentRig.rotationQuaternion.w *= -1;
      } else {
        currentRig.rotationQuaternion.multiplyInPlace(this._rotate180);
      }
      Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, currentRig._projectionMatrix);
      if (!this._scene.useRightHandedSystem) {
        currentRig._projectionMatrix.toggleProjectionMatrixHandInPlace();
      }
      const fov = Math.atan2(1, view.projectionMatrix[5]) * 2;
      currentRig.fov = fov;
      if (i === 0) {
        this.fov = fov;
        this._projectionMatrix.copyFrom(currentRig._projectionMatrix);
      }
      const renderTargetTexture = this._xrSessionManager.getRenderTargetTextureForView(view);
      this._renderingMultiview = renderTargetTexture?._texture?.isMultiview || false;
      if (this._renderingMultiview) {
        if (i == 0) {
          this._xrSessionManager.trySetViewportForView(this.viewport, view);
          this.outputRenderTarget = renderTargetTexture;
        }
      } else {
        this._xrSessionManager.trySetViewportForView(currentRig.viewport, view);
        currentRig.outputRenderTarget = renderTargetTexture || this._xrSessionManager.getRenderTargetTextureForView(view);
      }
      currentRig.layerMask = this.layerMask;
    });
  }
  _updateNumberOfRigCameras(viewCount = 1) {
    while (this.rigCameras.length < viewCount) {
      const newCamera = new TargetCamera("XR-RigCamera: " + this.rigCameras.length, Vector3.Zero(), this.getScene());
      newCamera.minZ = 0.1;
      newCamera.rotationQuaternion = new Quaternion;
      newCamera.updateUpVectorFromRotation = true;
      newCamera.isRigCamera = true;
      newCamera.rigParent = this;
      newCamera.freezeProjectionMatrix();
      this.rigCameras.push(newCamera);
    }
    while (this.rigCameras.length > viewCount) {
      const removedCamera = this.rigCameras.pop();
      if (removedCamera) {
        removedCamera.dispose();
      }
    }
  }
  _updateReferenceSpace() {
    if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) {
      const referencedMat = TmpVectors.Matrix[0];
      const poseMat = TmpVectors.Matrix[1];
      const transformMat = TmpVectors.Matrix[2];
      Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, referencedMat);
      Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this.rotationQuaternion, this.position, poseMat);
      referencedMat.invert().multiplyToRef(poseMat, transformMat);
      transformMat.invert();
      if (!this._scene.useRightHandedSystem) {
        transformMat.toggleModelMatrixHandInPlace();
      }
      transformMat.decompose(undefined, this._referenceQuaternion, this._referencedPosition);
      const transform = new XRRigidTransform({
        x: this._referencedPosition.x / this._xrSessionManager.worldScalingFactor,
        y: this._referencedPosition.y / this._xrSessionManager.worldScalingFactor,
        z: this._referencedPosition.z / this._xrSessionManager.worldScalingFactor
      }, {
        x: this._referenceQuaternion.x,
        y: this._referenceQuaternion.y,
        z: this._referenceQuaternion.z,
        w: this._referenceQuaternion.w
      });
      this._xrSessionManager.referenceSpace = this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(transform);
    }
  }
}
WebXRCamera._ScaleReadOnly = Vector3.One();

// node_modules/@babylonjs/core/XR/webXRExperienceHelper.js
init_logger();
init_math_vector();
init_abstractEngine();

class WebXRExperienceHelper {
  constructor(_scene) {
    this._scene = _scene;
    this._nonVRCamera = null;
    this._attachedToElement = false;
    this._spectatorCamera = null;
    this._originalSceneAutoClear = true;
    this._supported = false;
    this._spectatorMode = false;
    this._lastTimestamp = 0;
    this.onInitialXRPoseSetObservable = new Observable;
    this.onStateChangedObservable = new Observable;
    this.state = 3;
    this.sessionManager = new WebXRSessionManager(_scene);
    this.camera = new WebXRCamera("webxr", _scene, this.sessionManager);
    this.featuresManager = new WebXRFeaturesManager(this.sessionManager);
    _scene.onDisposeObservable.addOnce(() => {
      this.dispose();
    });
  }
  static CreateAsync(scene) {
    const helper = new WebXRExperienceHelper(scene);
    return helper.sessionManager.initializeAsync().then(() => {
      helper._supported = true;
      return helper;
    }).catch((e) => {
      helper._setState(3);
      helper.dispose();
      throw e;
    });
  }
  dispose() {
    this.exitXRAsync();
    this.camera.dispose();
    this.onStateChangedObservable.clear();
    this.onInitialXRPoseSetObservable.clear();
    this.sessionManager.dispose();
    this._spectatorCamera?.dispose();
    if (this._nonVRCamera) {
      this._scene.activeCamera = this._nonVRCamera;
    }
  }
  async enterXRAsync(sessionMode, referenceSpaceType, renderTarget = this.sessionManager.getWebXRRenderTarget(), sessionCreationOptions = {}) {
    if (!this._supported) {
      throw "WebXR not supported in this browser or environment";
    }
    this._setState(0);
    if (referenceSpaceType !== "viewer" && referenceSpaceType !== "local") {
      sessionCreationOptions.optionalFeatures = sessionCreationOptions.optionalFeatures || [];
      sessionCreationOptions.optionalFeatures.push(referenceSpaceType);
    }
    sessionCreationOptions = await this.featuresManager._extendXRSessionInitObject(sessionCreationOptions);
    if (sessionMode === "immersive-ar" && referenceSpaceType !== "unbounded") {
      Logger.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");
    }
    try {
      await this.sessionManager.initializeSessionAsync(sessionMode, sessionCreationOptions);
      await this.sessionManager.setReferenceSpaceTypeAsync(referenceSpaceType);
      const xrRenderState = {
        depthFar: this.camera.maxZ || 1e4,
        depthNear: this.camera.minZ
      };
      if (!this.featuresManager.getEnabledFeature(WebXRFeatureName.LAYERS)) {
        const baseLayer = await renderTarget.initializeXRLayerAsync(this.sessionManager.session);
        xrRenderState.baseLayer = baseLayer;
      }
      this.sessionManager.updateRenderState(xrRenderState);
      this.sessionManager.runXRRenderLoop();
      this._originalSceneAutoClear = this._scene.autoClear;
      this._nonVRCamera = this._scene.activeCamera;
      this._attachedToElement = !!this._nonVRCamera?.inputs?.attachedToElement;
      this._nonVRCamera?.detachControl();
      this._scene.activeCamera = this.camera;
      if (sessionMode !== "immersive-ar") {
        this._nonXRToXRCamera();
      } else {
        this._scene.autoClear = false;
        this.camera.compensateOnFirstFrame = false;
        this.camera.position.set(0, 0, 0);
        this.camera.rotationQuaternion.set(0, 0, 0, 1);
        this.onInitialXRPoseSetObservable.notifyObservers(this.camera);
      }
      AbstractEngine.audioEngine?._resumeAudioContextOnStateChange();
      this.sessionManager.onXRSessionEnded.addOnce(() => {
        if (this.state !== 1) {
          this._setState(1);
        }
        this.camera.rigCameras.forEach((c) => {
          c.outputRenderTarget = null;
        });
        this._scene.autoClear = this._originalSceneAutoClear;
        this._scene.activeCamera = this._nonVRCamera;
        if (this._attachedToElement && this._nonVRCamera) {
          this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault);
        }
        if (sessionMode !== "immersive-ar" && this.camera.compensateOnFirstFrame) {
          if (this._nonVRCamera.setPosition) {
            this._nonVRCamera.setPosition(this.camera.position);
          } else {
            this._nonVRCamera.position.copyFrom(this.camera.position);
          }
        }
        this._setState(3);
      });
      this.sessionManager.onXRFrameObservable.addOnce(() => {
        this._setState(2);
      });
      return this.sessionManager;
    } catch (e) {
      Logger.Log(e);
      Logger.Log(e.message);
      this._setState(3);
      throw e;
    }
  }
  exitXRAsync() {
    if (this.state !== 2) {
      return Promise.resolve();
    }
    this._setState(1);
    return this.sessionManager.exitXRAsync();
  }
  enableSpectatorMode(options) {
    if (!this._spectatorMode) {
      this._spectatorMode = true;
      this._switchSpectatorMode(options);
    }
  }
  disableSpecatatorMode() {
    if (this._spectatorMode) {
      this._spectatorMode = false;
      this._switchSpectatorMode();
    }
  }
  _switchSpectatorMode(options) {
    const fps = options?.fps ? options.fps : 1000;
    const refreshRate = 1 / fps * 1000;
    const cameraIndex = options?.preferredCameraIndex ? options?.preferredCameraIndex : 0;
    const updateSpectatorCamera = () => {
      if (this._spectatorCamera) {
        const delta = this.sessionManager.currentTimestamp - this._lastTimestamp;
        if (delta >= refreshRate) {
          this._lastTimestamp = this.sessionManager.currentTimestamp;
          this._spectatorCamera.position.copyFrom(this.camera.rigCameras[cameraIndex].globalPosition);
          this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[cameraIndex].absoluteRotation);
        }
      }
    };
    if (this._spectatorMode) {
      if (cameraIndex >= this.camera.rigCameras.length) {
        throw new Error("the preferred camera index is beyond the length of rig camera array.");
      }
      const onStateChanged = () => {
        if (this.state === 2) {
          this._spectatorCamera = new UniversalCamera("webxr-spectator", Vector3.Zero(), this._scene);
          this._spectatorCamera.rotationQuaternion = new Quaternion;
          this._scene.activeCameras = [this.camera, this._spectatorCamera];
          this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera);
          this._scene.onAfterRenderCameraObservable.add((camera2) => {
            if (camera2 === this.camera) {
              this._scene.getEngine().framebufferDimensionsObject = null;
            }
          });
        } else if (this.state === 1) {
          this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);
          this._scene.activeCameras = null;
        }
      };
      this.onStateChangedObservable.add(onStateChanged);
      onStateChanged();
    } else {
      this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);
      this._scene.activeCameras = [this.camera];
    }
  }
  _nonXRToXRCamera() {
    this.camera.setTransformationFromNonVRCamera(this._nonVRCamera);
    this.onInitialXRPoseSetObservable.notifyObservers(this.camera);
  }
  _setState(val) {
    if (this.state === val) {
      return;
    }
    this.state = val;
    this.onStateChangedObservable.notifyObservers(this.state);
  }
}

// node_modules/@babylonjs/core/XR/webXRInput.js
init_observable();

// node_modules/@babylonjs/core/XR/webXRInputSource.js
init_observable();
init_math_vector();

// node_modules/@babylonjs/core/XR/motionController/webXRControllerComponent.js
init_observable();

class WebXRControllerComponent {
  constructor(id, type, _buttonIndex = -1, _axesIndices = []) {
    this.id = id;
    this.type = type;
    this._buttonIndex = _buttonIndex;
    this._axesIndices = _axesIndices;
    this._axes = {
      x: 0,
      y: 0
    };
    this._changes = {};
    this._currentValue = 0;
    this._hasChanges = false;
    this._pressed = false;
    this._touched = false;
    this.onAxisValueChangedObservable = new Observable;
    this.onButtonStateChangedObservable = new Observable;
  }
  get axes() {
    return this._axes;
  }
  get changes() {
    return this._changes;
  }
  get hasChanges() {
    return this._hasChanges;
  }
  get pressed() {
    return this._pressed;
  }
  get touched() {
    return this._touched;
  }
  get value() {
    return this._currentValue;
  }
  dispose() {
    this.onAxisValueChangedObservable.clear();
    this.onButtonStateChangedObservable.clear();
  }
  isAxes() {
    return this._axesIndices.length !== 0;
  }
  isButton() {
    return this._buttonIndex !== -1;
  }
  update(nativeController) {
    let buttonUpdated = false;
    let axesUpdate = false;
    this._hasChanges = false;
    this._changes = {};
    if (this.isButton()) {
      const button = nativeController.buttons[this._buttonIndex];
      if (!button) {
        return;
      }
      if (this._currentValue !== button.value) {
        this.changes.value = {
          current: button.value,
          previous: this._currentValue
        };
        buttonUpdated = true;
        this._currentValue = button.value;
      }
      if (this._touched !== button.touched) {
        this.changes.touched = {
          current: button.touched,
          previous: this._touched
        };
        buttonUpdated = true;
        this._touched = button.touched;
      }
      if (this._pressed !== button.pressed) {
        this.changes.pressed = {
          current: button.pressed,
          previous: this._pressed
        };
        buttonUpdated = true;
        this._pressed = button.pressed;
      }
    }
    if (this.isAxes()) {
      if (this._axes.x !== nativeController.axes[this._axesIndices[0]]) {
        this.changes.axes = {
          current: {
            x: nativeController.axes[this._axesIndices[0]],
            y: this._axes.y
          },
          previous: {
            x: this._axes.x,
            y: this._axes.y
          }
        };
        this._axes.x = nativeController.axes[this._axesIndices[0]];
        axesUpdate = true;
      }
      if (this._axes.y !== nativeController.axes[this._axesIndices[1]]) {
        if (this.changes.axes) {
          this.changes.axes.current.y = nativeController.axes[this._axesIndices[1]];
        } else {
          this.changes.axes = {
            current: {
              x: this._axes.x,
              y: nativeController.axes[this._axesIndices[1]]
            },
            previous: {
              x: this._axes.x,
              y: this._axes.y
            }
          };
        }
        this._axes.y = nativeController.axes[this._axesIndices[1]];
        axesUpdate = true;
      }
    }
    if (buttonUpdated) {
      this._hasChanges = true;
      this.onButtonStateChangedObservable.notifyObservers(this);
    }
    if (axesUpdate) {
      this._hasChanges = true;
      this.onAxisValueChangedObservable.notifyObservers(this._axes);
    }
  }
}
WebXRControllerComponent.BUTTON_TYPE = "button";
WebXRControllerComponent.SQUEEZE_TYPE = "squeeze";
WebXRControllerComponent.THUMBSTICK_TYPE = "thumbstick";
WebXRControllerComponent.TOUCHPAD_TYPE = "touchpad";
WebXRControllerComponent.TRIGGER_TYPE = "trigger";

// node_modules/@babylonjs/core/XR/motionController/webXRAbstractMotionController.js
init_observable();
init_logger();

// node_modules/@babylonjs/core/Loading/sceneLoader.js
init_tools();
init_observable();
init_scene();
init_engineStore();
init_logger();
init_fileTools();
init_error();
init_guid();
init_abstractEngine();

// node_modules/@babylonjs/core/Misc/webRequest.fetch.js
init_webRequest();
function _FetchAsync(url, options) {
  const method = options.method || "GET";
  return new Promise((resolve3, reject) => {
    const request = new WebRequest;
    request.addEventListener("readystatechange", () => {
      if (request.readyState == 4) {
        if (request.status == 200) {
          const headerValues = {};
          if (options.responseHeaders) {
            for (const header of options.responseHeaders) {
              headerValues[header] = request.getResponseHeader(header) || "";
            }
          }
          resolve3({ response: request.response, headerValues });
        } else {
          reject(`Unable to fetch data from ${url}. Error code: ${request.status}`);
        }
      }
    });
    request.open(method, url);
    request.send();
  });
}

// node_modules/@babylonjs/core/Loading/sceneLoader.js
var SceneLoaderAnimationGroupLoadingMode;
(function(SceneLoaderAnimationGroupLoadingMode2) {
  SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Clean"] = 0] = "Clean";
  SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Stop"] = 1] = "Stop";
  SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Sync"] = 2] = "Sync";
  SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["NoSync"] = 3] = "NoSync";
})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));
function isFactory(pluginOrFactory) {
  return !!pluginOrFactory.createPlugin;
}
function isFile(value) {
  return !!value.name;
}
var onPluginActivatedObservable = new Observable;
var registeredPlugins = {};
var showingLoadingScreen = false;
function getDefaultPlugin() {
  return registeredPlugins[".babylon"];
}
function getPluginForMimeType(mimeType) {
  for (const registeredPluginKey in registeredPlugins) {
    const registeredPlugin = registeredPlugins[registeredPluginKey];
    if (registeredPlugin.mimeType === mimeType) {
      return registeredPlugin;
    }
  }
  return;
}
function getPluginForExtension(extension, returnDefault) {
  const registeredPlugin = registeredPlugins[extension];
  if (registeredPlugin) {
    return registeredPlugin;
  }
  Logger.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes");
  return returnDefault ? getDefaultPlugin() : undefined;
}
function isPluginForExtensionAvailable(extension) {
  return !!registeredPlugins[extension];
}
function getPluginForDirectLoad(data) {
  for (const extension in registeredPlugins) {
    const plugin = registeredPlugins[extension].plugin;
    if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
      return registeredPlugins[extension];
    }
  }
  return getDefaultPlugin();
}
function getFilenameExtension(sceneFilename) {
  const queryStringPosition = sceneFilename.indexOf("?");
  if (queryStringPosition !== -1) {
    sceneFilename = sceneFilename.substring(0, queryStringPosition);
  }
  const dotPosition = sceneFilename.lastIndexOf(".");
  return sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
}
function getDirectLoad(sceneFilename) {
  if (sceneFilename.substring(0, 5) === "data:") {
    return sceneFilename.substring(5);
  }
  return null;
}
function formatErrorMessage(fileInfo, message, exception) {
  const fromLoad = fileInfo.rawData ? "binary data" : fileInfo.url;
  let errorMessage = "Unable to load from " + fromLoad;
  if (message) {
    errorMessage += `: ${message}`;
  } else if (exception) {
    errorMessage += `: ${exception}`;
  }
  return errorMessage;
}
async function loadDataAsync(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name325, pluginOptions) {
  const directLoad = getDirectLoad(fileInfo.url);
  if (fileInfo.rawData && !pluginExtension) {
    throw "When using ArrayBufferView to load data the file extension must be provided.";
  }
  const fileExtension = !directLoad && !pluginExtension ? getFilenameExtension(fileInfo.url) : "";
  let registeredPlugin = pluginExtension ? getPluginForExtension(pluginExtension, true) : directLoad ? getPluginForDirectLoad(fileInfo.url) : getPluginForExtension(fileExtension, false);
  if (!registeredPlugin && fileExtension) {
    if (fileInfo.url && !fileInfo.url.startsWith("blob:")) {
      const response = await _FetchAsync(fileInfo.url, { method: "HEAD", responseHeaders: ["Content-Type"] });
      const mimeType = response.headerValues ? response.headerValues["Content-Type"] : "";
      if (mimeType) {
        registeredPlugin = getPluginForMimeType(mimeType);
      }
    }
    if (!registeredPlugin) {
      registeredPlugin = getDefaultPlugin();
    }
  }
  if (!registeredPlugin) {
    throw new Error(`No plugin or fallback for ${pluginExtension ?? fileInfo.url}`);
  }
  if (pluginOptions?.[registeredPlugin.plugin.name]?.enabled === false) {
    throw new Error(`The '${registeredPlugin.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);
  }
  if (fileInfo.rawData && !registeredPlugin.isBinary) {
    throw "Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";
  }
  const getPluginInstance = (callback) => {
    if (isFactory(registeredPlugin.plugin)) {
      const pluginFactory = registeredPlugin.plugin;
      const partialPlugin = pluginFactory.createPlugin(pluginOptions ?? {});
      if (partialPlugin instanceof Promise) {
        partialPlugin.then(callback).catch((error) => {
          onError("Error instantiating plugin.", error);
        });
        return null;
      } else {
        callback(partialPlugin);
        return partialPlugin;
      }
    } else {
      callback(registeredPlugin.plugin);
      return registeredPlugin.plugin;
    }
  };
  return getPluginInstance((plugin) => {
    if (!plugin) {
      throw `The loader plugin corresponding to the '${pluginExtension}' file type has not been found. If using es6, please import the plugin you wish to use before.`;
    }
    onPluginActivatedObservable.notifyObservers(plugin);
    if (directLoad && (plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url) || !IsBase64DataUrl(fileInfo.url))) {
      if (plugin.directLoad) {
        const result = plugin.directLoad(scene, directLoad);
        if (result instanceof Promise) {
          result.then((data) => {
            onSuccess(plugin, data);
          }).catch((error) => {
            onError("Error in directLoad of _loadData: " + error, error);
          });
        } else {
          onSuccess(plugin, result);
        }
      } else {
        onSuccess(plugin, directLoad);
      }
      return;
    }
    const useArrayBuffer = registeredPlugin.isBinary;
    const dataCallback = (data, responseURL) => {
      if (scene.isDisposed) {
        onError("Scene has been disposed");
        return;
      }
      onSuccess(plugin, data, responseURL);
    };
    let request = null;
    let pluginDisposed = false;
    plugin.onDisposeObservable?.add(() => {
      pluginDisposed = true;
      if (request) {
        request.abort();
        request = null;
      }
      onDispose();
    });
    const manifestChecked = () => {
      if (pluginDisposed) {
        return;
      }
      const errorCallback = (request2, exception) => {
        onError(request2?.statusText, exception);
      };
      if (!plugin.loadFile && fileInfo.rawData) {
        throw "Plugin does not support loading ArrayBufferView.";
      }
      request = plugin.loadFile ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name325) : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback);
    };
    const engine2 = scene.getEngine();
    let canUseOfflineSupport = engine2.enableOfflineSupport;
    if (canUseOfflineSupport) {
      let exceptionFound = false;
      for (const regex of scene.disableOfflineSupportExceptionRules) {
        if (regex.test(fileInfo.url)) {
          exceptionFound = true;
          break;
        }
      }
      canUseOfflineSupport = !exceptionFound;
    }
    if (canUseOfflineSupport && AbstractEngine.OfflineProviderFactory) {
      scene.offlineProvider = AbstractEngine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine2.disableManifestCheck);
    } else {
      manifestChecked();
    }
  });
}
function _getFileInfo(rootUrl, sceneSource) {
  let url;
  let name325;
  let file = null;
  let rawData = null;
  if (!sceneSource) {
    url = rootUrl;
    name325 = Tools.GetFilename(rootUrl);
    rootUrl = Tools.GetFolderPath(rootUrl);
  } else if (isFile(sceneSource)) {
    url = `file:${sceneSource.name}`;
    name325 = sceneSource.name;
    file = sceneSource;
  } else if (ArrayBuffer.isView(sceneSource)) {
    url = "";
    name325 = RandomGUID();
    rawData = sceneSource;
  } else if (sceneSource.startsWith("data:")) {
    url = sceneSource;
    name325 = "";
  } else if (rootUrl) {
    const filename = sceneSource;
    if (filename.substring(0, 1) === "/") {
      Tools.Error("Wrong sceneFilename parameter");
      return null;
    }
    url = rootUrl + filename;
    name325 = filename;
  } else {
    url = sceneSource;
    name325 = Tools.GetFilename(sceneSource);
    rootUrl = Tools.GetFolderPath(sceneSource);
  }
  return {
    url,
    rootUrl,
    name: name325,
    file,
    rawData
  };
}
function RegisterSceneLoaderPlugin(plugin) {
  if (typeof plugin.extensions === "string") {
    const extension = plugin.extensions;
    registeredPlugins[extension.toLowerCase()] = {
      plugin,
      isBinary: false
    };
  } else {
    const extensions = plugin.extensions;
    Object.keys(extensions).forEach((extension) => {
      registeredPlugins[extension.toLowerCase()] = {
        plugin,
        isBinary: extensions[extension].isBinary,
        mimeType: extensions[extension].mimeType
      };
    });
  }
}
async function importMeshAsync(meshNames, rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name325 = "", pluginOptions = {}) {
  if (!scene) {
    Logger.Error("No scene available to import mesh to");
    return null;
  }
  const fileInfo = _getFileInfo(rootUrl, sceneFilename);
  if (!fileInfo) {
    return null;
  }
  const loadingToken = {};
  scene.addPendingData(loadingToken);
  const disposeHandler = () => {
    scene.removePendingData(loadingToken);
  };
  const errorHandler = (message, exception) => {
    const errorMessage = formatErrorMessage(fileInfo, message, exception);
    if (onError) {
      onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
    } else {
      Logger.Error(errorMessage);
    }
    disposeHandler();
  };
  const progressHandler = onProgress ? (event) => {
    try {
      onProgress(event);
    } catch (e) {
      errorHandler("Error in onProgress callback: " + e, e);
    }
  } : undefined;
  const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => {
    scene.importedMeshesFiles.push(fileInfo.url);
    if (onSuccess) {
      try {
        onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers);
      } catch (e) {
        errorHandler("Error in onSuccess callback: " + e, e);
      }
    }
    scene.removePendingData(loadingToken);
  };
  return await loadDataAsync(fileInfo, scene, (plugin, data, responseURL) => {
    if (plugin.rewriteRootURL) {
      fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
    }
    if (plugin.importMesh) {
      const syncedPlugin = plugin;
      const meshes = [];
      const particleSystems = [];
      const skeletons = [];
      if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
        return;
      }
      scene.loadingPluginName = plugin.name;
      successHandler(meshes, particleSystems, skeletons, [], [], [], [], []);
    } else {
      const asyncedPlugin = plugin;
      asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((result) => {
        scene.loadingPluginName = plugin.name;
        successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights, result.spriteManagers);
      }).catch((error) => {
        errorHandler(error.message, error);
      });
    }
  }, progressHandler, errorHandler, disposeHandler, pluginExtension, name325, pluginOptions);
}
function importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325, pluginOptions) {
  return new Promise((resolve3, reject) => {
    try {
      importMeshAsync(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => {
        resolve3({
          meshes,
          particleSystems,
          skeletons,
          animationGroups,
          transformNodes,
          geometries,
          lights,
          spriteManagers
        });
      }, onProgress, (scene2, message, exception) => {
        reject(exception || new Error(message));
      }, pluginExtension, name325, pluginOptions).catch(reject);
    } catch (error) {
      reject(error);
    }
  });
}
async function loadSceneImplAsync(rootUrl, sceneFilename = "", engine2 = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name325 = "", pluginOptions = {}) {
  if (!engine2) {
    Tools.Error("No engine available");
    return;
  }
  await appendSceneImplAsync(rootUrl, sceneFilename, new Scene(engine2), onSuccess, onProgress, onError, pluginExtension, name325, pluginOptions);
}
function loadSceneSharedAsync(rootUrl, sceneFilename, engine2, onProgress, pluginExtension, name325, pluginOptions) {
  return new Promise((resolve3, reject) => {
    loadSceneImplAsync(rootUrl, sceneFilename, engine2, (scene) => {
      resolve3(scene);
    }, onProgress, (scene, message, exception) => {
      reject(exception || new Error(message));
    }, pluginExtension, name325, pluginOptions);
  });
}
async function appendSceneImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name325 = "", pluginOptions = {}) {
  if (!scene) {
    Logger.Error("No scene available to append to");
    return null;
  }
  const fileInfo = _getFileInfo(rootUrl, sceneFilename);
  if (!fileInfo) {
    return null;
  }
  const loadingToken = {};
  scene.addPendingData(loadingToken);
  const disposeHandler = () => {
    scene.removePendingData(loadingToken);
  };
  if (SceneLoaderFlags.ShowLoadingScreen && !showingLoadingScreen) {
    showingLoadingScreen = true;
    scene.getEngine().displayLoadingUI();
    scene.executeWhenReady(() => {
      scene.getEngine().hideLoadingUI();
      showingLoadingScreen = false;
    });
  }
  const errorHandler = (message, exception) => {
    const errorMessage = formatErrorMessage(fileInfo, message, exception);
    if (onError) {
      onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
    } else {
      Logger.Error(errorMessage);
    }
    disposeHandler();
  };
  const progressHandler = onProgress ? (event) => {
    try {
      onProgress(event);
    } catch (e) {
      errorHandler("Error in onProgress callback", e);
    }
  } : undefined;
  const successHandler = () => {
    if (onSuccess) {
      try {
        onSuccess(scene);
      } catch (e) {
        errorHandler("Error in onSuccess callback", e);
      }
    }
    scene.removePendingData(loadingToken);
  };
  return await loadDataAsync(fileInfo, scene, (plugin, data) => {
    if (plugin.load) {
      const syncedPlugin = plugin;
      if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
        return;
      }
      scene.loadingPluginName = plugin.name;
      successHandler();
    } else {
      const asyncedPlugin = plugin;
      asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(() => {
        scene.loadingPluginName = plugin.name;
        successHandler();
      }).catch((error) => {
        errorHandler(error.message, error);
      });
    }
  }, progressHandler, errorHandler, disposeHandler, pluginExtension, name325, pluginOptions);
}
function appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325, pluginOptions) {
  return new Promise((resolve3, reject) => {
    try {
      appendSceneImplAsync(rootUrl, sceneFilename, scene, (scene2) => {
        resolve3(scene2);
      }, onProgress, (scene2, message, exception) => {
        reject(exception || new Error(message));
      }, pluginExtension, name325, pluginOptions).catch(reject);
    } catch (error) {
      reject(error);
    }
  });
}
async function loadAssetContainerImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name325 = "", pluginOptions = {}) {
  if (!scene) {
    Logger.Error("No scene available to load asset container to");
    return null;
  }
  const fileInfo = _getFileInfo(rootUrl, sceneFilename);
  if (!fileInfo) {
    return null;
  }
  const loadingToken = {};
  scene.addPendingData(loadingToken);
  const disposeHandler = () => {
    scene.removePendingData(loadingToken);
  };
  const errorHandler = (message, exception) => {
    const errorMessage = formatErrorMessage(fileInfo, message, exception);
    if (onError) {
      onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));
    } else {
      Logger.Error(errorMessage);
    }
    disposeHandler();
  };
  const progressHandler = onProgress ? (event) => {
    try {
      onProgress(event);
    } catch (e) {
      errorHandler("Error in onProgress callback", e);
    }
  } : undefined;
  const successHandler = (assets) => {
    if (onSuccess) {
      try {
        onSuccess(assets);
      } catch (e) {
        errorHandler("Error in onSuccess callback", e);
      }
    }
    scene.removePendingData(loadingToken);
  };
  return await loadDataAsync(fileInfo, scene, (plugin, data) => {
    if (plugin.loadAssetContainer) {
      const syncedPlugin = plugin;
      const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
      if (!assetContainer) {
        return;
      }
      assetContainer.populateRootNodes();
      scene.loadingPluginName = plugin.name;
      successHandler(assetContainer);
    } else if (plugin.loadAssetContainerAsync) {
      const asyncedPlugin = plugin;
      asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((assetContainer) => {
        assetContainer.populateRootNodes();
        scene.loadingPluginName = plugin.name;
        successHandler(assetContainer);
      }).catch((error) => {
        errorHandler(error.message, error);
      });
    } else {
      errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
    }
  }, progressHandler, errorHandler, disposeHandler, pluginExtension, name325, pluginOptions);
}
function loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325, pluginOptions) {
  return new Promise((resolve3, reject) => {
    try {
      loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, (assets) => {
        resolve3(assets);
      }, onProgress, (scene2, message, exception) => {
        reject(exception || new Error(message));
      }, pluginExtension, name325, pluginOptions).catch(reject);
    } catch (error) {
      reject(error);
    }
  });
}
async function importAnimationsImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = 0, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name325 = "", pluginOptions = {}) {
  if (!scene) {
    Logger.Error("No scene available to load animations to");
    return;
  }
  if (overwriteAnimations) {
    for (const animatable2 of scene.animatables) {
      animatable2.reset();
    }
    scene.stopAllAnimations();
    scene.animationGroups.slice().forEach((animationGroup2) => {
      animationGroup2.dispose();
    });
    const nodes = scene.getNodes();
    nodes.forEach((node) => {
      if (node.animations) {
        node.animations = [];
      }
    });
  } else {
    switch (animationGroupLoadingMode) {
      case 0:
        scene.animationGroups.slice().forEach((animationGroup2) => {
          animationGroup2.dispose();
        });
        break;
      case 1:
        scene.animationGroups.forEach((animationGroup2) => {
          animationGroup2.stop();
        });
        break;
      case 2:
        scene.animationGroups.forEach((animationGroup2) => {
          animationGroup2.reset();
          animationGroup2.restart();
        });
        break;
      case 3:
        break;
      default:
        Logger.Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'");
        return;
    }
  }
  const startingIndexForNewAnimatables = scene.animatables.length;
  const onAssetContainerLoaded = (container) => {
    container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter);
    container.dispose();
    scene.onAnimationFileImportedObservable.notifyObservers(scene);
    if (onSuccess) {
      onSuccess(scene);
    }
  };
  await loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension, name325, pluginOptions);
}
function importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name325, pluginOptions) {
  return new Promise((resolve3, reject) => {
    try {
      importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (scene2) => {
        resolve3(scene2);
      }, onProgress, (scene2, message, exception) => {
        reject(exception || new Error(message));
      }, pluginExtension, name325, pluginOptions).catch(reject);
    } catch (error) {
      reject(error);
    }
  });
}

class SceneLoader {
  static get ForceFullSceneLoadingForIncremental() {
    return SceneLoaderFlags.ForceFullSceneLoadingForIncremental;
  }
  static set ForceFullSceneLoadingForIncremental(value) {
    SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value;
  }
  static get ShowLoadingScreen() {
    return SceneLoaderFlags.ShowLoadingScreen;
  }
  static set ShowLoadingScreen(value) {
    SceneLoaderFlags.ShowLoadingScreen = value;
  }
  static get loggingLevel() {
    return SceneLoaderFlags.loggingLevel;
  }
  static set loggingLevel(value) {
    SceneLoaderFlags.loggingLevel = value;
  }
  static get CleanBoneMatrixWeights() {
    return SceneLoaderFlags.CleanBoneMatrixWeights;
  }
  static set CleanBoneMatrixWeights(value) {
    SceneLoaderFlags.CleanBoneMatrixWeights = value;
  }
  static GetDefaultPlugin() {
    return getDefaultPlugin();
  }
  static GetPluginForExtension(extension) {
    return getPluginForExtension(extension, true)?.plugin;
  }
  static IsPluginForExtensionAvailable(extension) {
    return isPluginForExtensionAvailable(extension);
  }
  static RegisterPlugin(plugin) {
    RegisterSceneLoaderPlugin(plugin);
  }
  static ImportMesh(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325) {
    importMeshAsync(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error));
  }
  static ImportMeshAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325) {
    return importMeshAsyncCore(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325);
  }
  static Load(rootUrl, sceneFilename, engine2, onSuccess, onProgress, onError, pluginExtension, name325) {
    loadSceneImplAsync(rootUrl, sceneFilename, engine2, onSuccess, onProgress, onError, pluginExtension, name325).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error));
  }
  static LoadAsync(rootUrl, sceneFilename, engine2, onProgress, pluginExtension, name325) {
    return loadSceneSharedAsync(rootUrl, sceneFilename, engine2, onProgress, pluginExtension, name325);
  }
  static Append(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325) {
    appendSceneImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error));
  }
  static AppendAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325) {
    return appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325);
  }
  static LoadAssetContainer(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325) {
    loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name325).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error));
  }
  static LoadAssetContainerAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325) {
    return loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name325);
  }
  static ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name325) {
    importAnimationsImplAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name325).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error));
  }
  static ImportAnimationsAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name325) {
    return importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name325);
  }
}
SceneLoader.NO_LOGGING = 0;
SceneLoader.MINIMAL_LOGGING = 1;
SceneLoader.SUMMARY_LOGGING = 2;
SceneLoader.DETAILED_LOGGING = 3;
SceneLoader.OnPluginActivatedObservable = onPluginActivatedObservable;

// node_modules/@babylonjs/core/XR/motionController/webXRAbstractMotionController.js
init_math_vector();
class WebXRAbstractMotionController {
  constructor(scene, layout, gamepadObject, handedness, _doNotLoadControllerMesh = false, _controllerCache) {
    this.scene = scene;
    this.layout = layout;
    this.gamepadObject = gamepadObject;
    this.handedness = handedness;
    this._doNotLoadControllerMesh = _doNotLoadControllerMesh;
    this._controllerCache = _controllerCache;
    this._initComponent = (id) => {
      if (!id) {
        return;
      }
      const componentDef = this.layout.components[id];
      const type = componentDef.type;
      const buttonIndex = componentDef.gamepadIndices.button;
      const axes = [];
      if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) {
        axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis);
      }
      this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes);
    };
    this._modelReady = false;
    this.components = {};
    this.disableAnimation = false;
    this.onModelLoadedObservable = new Observable;
    if (layout.components) {
      Object.keys(layout.components).forEach(this._initComponent);
    }
  }
  dispose() {
    this.getComponentIds().forEach((id) => this.getComponent(id).dispose());
    if (this.rootMesh) {
      this.rootMesh.getChildren(undefined, true).forEach((node) => {
        node.setEnabled(false);
      });
      this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache);
    }
    this.onModelLoadedObservable.clear();
  }
  getAllComponentsOfType(type) {
    return this.getComponentIds().map((id) => this.components[id]).filter((component) => component.type === type);
  }
  getComponent(id) {
    return this.components[id];
  }
  getComponentIds() {
    return Object.keys(this.components);
  }
  getComponentOfType(type) {
    return this.getAllComponentsOfType(type)[0] || null;
  }
  getMainComponent() {
    return this.getComponent(this.layout.selectComponentId);
  }
  async loadModel() {
    const useGeneric = !this._getModelLoadingConstraints();
    let loadingParams = this._getGenericFilenameAndPath();
    if (useGeneric) {
      Logger.Warn("Falling back to generic models");
    } else {
      loadingParams = this._getFilenameAndPath();
    }
    return new Promise((resolve3, reject) => {
      const meshesLoaded = (meshes) => {
        if (useGeneric) {
          this._getGenericParentMesh(meshes);
        } else {
          this._setRootMesh(meshes);
        }
        this._processLoadedModel(meshes);
        this._modelReady = true;
        this.onModelLoadedObservable.notifyObservers(this);
        resolve3(true);
      };
      if (this._controllerCache) {
        const found = this._controllerCache.filter((c) => {
          return c.filename === loadingParams.filename && c.path === loadingParams.path;
        });
        if (found[0]) {
          found[0].meshes.forEach((mesh) => mesh.setEnabled(true));
          meshesLoaded(found[0].meshes);
          return;
        }
      }
      SceneLoader.ImportMesh("", loadingParams.path, loadingParams.filename, this.scene, (meshes) => {
        if (this._controllerCache) {
          this._controllerCache.push({
            ...loadingParams,
            meshes
          });
        }
        meshesLoaded(meshes);
      }, null, (_scene, message) => {
        Logger.Log(message);
        Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`);
        reject(message);
      });
    });
  }
  updateFromXRFrame(xrFrame) {
    this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject));
    this.updateModel(xrFrame);
  }
  get handness() {
    return this.handedness;
  }
  pulse(value, duration, hapticActuatorIndex = 0) {
    if (this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[hapticActuatorIndex]) {
      return this.gamepadObject.hapticActuators[hapticActuatorIndex].pulse(value, duration);
    } else {
      return Promise.resolve(false);
    }
  }
  _getChildByName(node, name325) {
    return node.getChildren((n) => n.name === name325, false)[0];
  }
  _getImmediateChildByName(node, name325) {
    return node.getChildren((n) => n.name == name325, true)[0];
  }
  _lerpTransform(axisMap, axisValue, fixValueCoordinates) {
    if (!axisMap.minMesh || !axisMap.maxMesh || !axisMap.valueMesh) {
      return;
    }
    if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) {
      return;
    }
    const lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue;
    Quaternion.SlerpToRef(axisMap.minMesh.rotationQuaternion, axisMap.maxMesh.rotationQuaternion, lerpValue, axisMap.valueMesh.rotationQuaternion);
    Vector3.LerpToRef(axisMap.minMesh.position, axisMap.maxMesh.position, lerpValue, axisMap.valueMesh.position);
  }
  updateModel(xrFrame) {
    if (!this._modelReady) {
      return;
    }
    this._updateModel(xrFrame);
  }
  _getGenericFilenameAndPath() {
    return {
      filename: "generic.babylon",
      path: "https://controllers.babylonjs.com/generic/"
    };
  }
  _getGenericParentMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene);
    meshes.forEach((mesh) => {
      if (!mesh.parent) {
        mesh.isPickable = false;
        mesh.setParent(this.rootMesh);
      }
    });
    this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
  }
}

// node_modules/@babylonjs/core/XR/motionController/webXRGenericMotionController.js
init_math_vector();

class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController {
  constructor(scene, gamepadObject, handedness) {
    super(scene, GenericTriggerLayout[handedness], gamepadObject, handedness);
    this.profileId = WebXRGenericTriggerMotionController.ProfileId;
  }
  _getFilenameAndPath() {
    return {
      filename: "generic.babylon",
      path: "https://controllers.babylonjs.com/generic/"
    };
  }
  _getModelLoadingConstraints() {
    return true;
  }
  _processLoadedModel(meshes) {}
  _setRootMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene);
    meshes.forEach((mesh) => {
      mesh.isPickable = false;
      if (!mesh.parent) {
        mesh.setParent(this.rootMesh);
      }
    });
    this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
  }
  _updateModel() {}
}
WebXRGenericTriggerMotionController.ProfileId = "generic-trigger";
var GenericTriggerLayout = {
  left: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-trigger-left",
    assetPath: "left.glb"
  },
  right: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-trigger-right",
    assetPath: "right.glb"
  },
  none: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-trigger-none",
    assetPath: "none.glb"
  }
};

// node_modules/@babylonjs/core/XR/motionController/webXRMotionControllerManager.js
init_tools();

// node_modules/@babylonjs/core/XR/motionController/webXRProfiledMotionController.js
init_math_axis();
init_math_color();
init_logger();

class WebXRProfiledMotionController extends WebXRAbstractMotionController {
  constructor(scene, xrInput, _profile, _repositoryUrl, controllerCache) {
    super(scene, _profile.layouts[xrInput.handedness || "none"], xrInput.gamepad, xrInput.handedness, undefined, controllerCache);
    this._repositoryUrl = _repositoryUrl;
    this.controllerCache = controllerCache;
    this._buttonMeshMapping = {};
    this._touchDots = {};
    this.profileId = _profile.profileId;
  }
  dispose() {
    super.dispose();
    if (!this.controllerCache) {
      Object.keys(this._touchDots).forEach((visResKey) => {
        this._touchDots[visResKey].dispose();
      });
    }
  }
  _getFilenameAndPath() {
    return {
      filename: this.layout.assetPath,
      path: `${this._repositoryUrl}/profiles/${this.profileId}/`
    };
  }
  _getModelLoadingConstraints() {
    const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(".glb");
    if (!glbLoaded) {
      Logger.Warn("glTF / glb loader was not registered, using generic controller instead");
    }
    return glbLoaded;
  }
  _processLoadedModel(_meshes) {
    this.getComponentIds().forEach((type) => {
      const componentInLayout = this.layout.components[type];
      this._buttonMeshMapping[type] = {
        mainMesh: this._getChildByName(this.rootMesh, componentInLayout.rootNodeName),
        states: {}
      };
      Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {
        const visResponse = componentInLayout.visualResponses[visualResponseKey];
        if (visResponse.valueNodeProperty === "transform") {
          this._buttonMeshMapping[type].states[visualResponseKey] = {
            valueMesh: this._getChildByName(this.rootMesh, visResponse.valueNodeName),
            minMesh: this._getChildByName(this.rootMesh, visResponse.minNodeName),
            maxMesh: this._getChildByName(this.rootMesh, visResponse.maxNodeName)
          };
        } else {
          const nameOfMesh = componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && componentInLayout.touchPointNodeName ? componentInLayout.touchPointNodeName : visResponse.valueNodeName;
          this._buttonMeshMapping[type].states[visualResponseKey] = {
            valueMesh: this._getChildByName(this.rootMesh, nameOfMesh)
          };
          if (componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && !this._touchDots[visualResponseKey]) {
            const dot = CreateSphere(visualResponseKey + "dot", {
              diameter: 0.0015,
              segments: 8
            }, this.scene);
            dot.material = new StandardMaterial(visualResponseKey + "mat", this.scene);
            dot.material.diffuseColor = Color3.Red();
            dot.parent = this._buttonMeshMapping[type].states[visualResponseKey].valueMesh || null;
            dot.isVisible = false;
            this._touchDots[visualResponseKey] = dot;
          }
        }
      });
    });
  }
  _setRootMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + "-" + this.handedness, this.scene);
    this.rootMesh.isPickable = false;
    let rootMesh;
    for (let i = 0;i < meshes.length; i++) {
      const mesh = meshes[i];
      mesh.isPickable = false;
      if (!mesh.parent) {
        rootMesh = mesh;
      }
    }
    if (rootMesh) {
      rootMesh.setParent(this.rootMesh);
    }
    if (!this.scene.useRightHandedSystem) {
      this.rootMesh.rotate(Axis.Y, Math.PI, 1);
    }
  }
  _updateModel(_xrFrame) {
    if (this.disableAnimation) {
      return;
    }
    this.getComponentIds().forEach((id) => {
      const component = this.getComponent(id);
      if (!component.hasChanges) {
        return;
      }
      const meshes = this._buttonMeshMapping[id];
      const componentInLayout = this.layout.components[id];
      Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {
        const visResponse = componentInLayout.visualResponses[visualResponseKey];
        let value = component.value;
        if (visResponse.componentProperty === "xAxis") {
          value = component.axes.x;
        } else if (visResponse.componentProperty === "yAxis") {
          value = component.axes.y;
        }
        if (visResponse.valueNodeProperty === "transform") {
          this._lerpTransform(meshes.states[visualResponseKey], value, visResponse.componentProperty !== "button");
        } else {
          const valueMesh = meshes.states[visualResponseKey].valueMesh;
          if (valueMesh) {
            valueMesh.isVisible = component.touched || component.pressed;
          }
          if (this._touchDots[visualResponseKey]) {
            this._touchDots[visualResponseKey].isVisible = component.touched || component.pressed;
          }
        }
      });
    });
  }
}

// node_modules/@babylonjs/core/XR/motionController/webXRMotionControllerManager.js
var controllerCache = [];

class WebXRMotionControllerManager {
  static ClearProfilesCache() {
    this._ProfilesList = null;
    this._ProfileLoadingPromises = {};
  }
  static DefaultFallbacks() {
    this.RegisterFallbacksForProfileId("google-daydream", ["generic-touchpad"]);
    this.RegisterFallbacksForProfileId("htc-vive-focus", ["generic-trigger-touchpad"]);
    this.RegisterFallbacksForProfileId("htc-vive", ["generic-trigger-squeeze-touchpad"]);
    this.RegisterFallbacksForProfileId("magicleap-one", ["generic-trigger-squeeze-touchpad"]);
    this.RegisterFallbacksForProfileId("windows-mixed-reality", ["generic-trigger-squeeze-touchpad-thumbstick"]);
    this.RegisterFallbacksForProfileId("microsoft-mixed-reality", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
    this.RegisterFallbacksForProfileId("oculus-go", ["generic-trigger-touchpad"]);
    this.RegisterFallbacksForProfileId("oculus-touch-v2", ["oculus-touch", "generic-trigger-squeeze-thumbstick"]);
    this.RegisterFallbacksForProfileId("oculus-touch", ["generic-trigger-squeeze-thumbstick"]);
    this.RegisterFallbacksForProfileId("samsung-gearvr", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
    this.RegisterFallbacksForProfileId("samsung-odyssey", ["generic-touchpad"]);
    this.RegisterFallbacksForProfileId("valve-index", ["generic-trigger-squeeze-touchpad-thumbstick"]);
    this.RegisterFallbacksForProfileId("generic-hand-select", ["generic-trigger"]);
  }
  static FindFallbackWithProfileId(profileId) {
    const returnArray = this._Fallbacks[profileId] || [];
    returnArray.unshift(profileId);
    return returnArray;
  }
  static GetMotionControllerWithXRInput(xrInput, scene, forceProfile) {
    const profileArray = [];
    if (forceProfile) {
      profileArray.push(forceProfile);
    }
    profileArray.push(...xrInput.profiles || []);
    if (profileArray.length && !profileArray[0]) {
      profileArray.pop();
    }
    if (xrInput.gamepad && xrInput.gamepad.id) {
      switch (xrInput.gamepad.id) {
        case (xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined):
          profileArray.push("oculus-touch-v2");
          break;
      }
    }
    const windowsMRIdx = profileArray.indexOf("windows-mixed-reality");
    if (windowsMRIdx !== -1) {
      profileArray.splice(windowsMRIdx, 0, "microsoft-mixed-reality");
    }
    if (!profileArray.length) {
      profileArray.push("generic-trigger");
    }
    if (this.UseOnlineRepository) {
      const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers;
      const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;
      return firstFunction.call(this, profileArray, xrInput, scene).catch(() => {
        return secondFunction.call(this, profileArray, xrInput, scene);
      });
    } else {
      return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene);
    }
  }
  static RegisterController(type, constructFunction) {
    this._AvailableControllers[type] = constructFunction;
  }
  static RegisterFallbacksForProfileId(profileId, fallbacks) {
    if (this._Fallbacks[profileId]) {
      this._Fallbacks[profileId].push(...fallbacks);
    } else {
      this._Fallbacks[profileId] = fallbacks;
    }
  }
  static UpdateProfilesList() {
    this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + "/profiles/profilesList.json", false).then((data) => {
      return JSON.parse(data);
    });
    return this._ProfilesList;
  }
  static ClearControllerCache() {
    controllerCache.forEach((cacheItem) => {
      cacheItem.meshes.forEach((mesh) => {
        mesh.dispose(false, true);
      });
    });
    controllerCache.length = 0;
  }
  static _LoadProfileFromRepository(profileArray, xrInput, scene) {
    return Promise.resolve().then(() => {
      if (!this._ProfilesList) {
        return this.UpdateProfilesList();
      } else {
        return this._ProfilesList;
      }
    }).then((profilesList) => {
      for (let i = 0;i < profileArray.length; ++i) {
        if (!profileArray[i]) {
          continue;
        }
        if (profilesList[profileArray[i]]) {
          return profileArray[i];
        }
      }
      throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`);
    }).then((profileToLoad) => {
      if (!this._ProfileLoadingPromises[profileToLoad]) {
        this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => JSON.parse(data));
      }
      return this._ProfileLoadingPromises[profileToLoad];
    }).then((profile) => {
      return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl, this.DisableControllerCache ? undefined : controllerCache);
    });
  }
  static _LoadProfilesFromAvailableControllers(profileArray, xrInput, scene) {
    for (let i = 0;i < profileArray.length; ++i) {
      if (!profileArray[i]) {
        continue;
      }
      const fallbacks = this.FindFallbackWithProfileId(profileArray[i]);
      for (let j = 0;j < fallbacks.length; ++j) {
        const constructionFunction = this._AvailableControllers[fallbacks[j]];
        if (constructionFunction) {
          return Promise.resolve(constructionFunction(xrInput, scene));
        }
      }
    }
    throw new Error(`no controller requested was found in the available controllers list`);
  }
}
WebXRMotionControllerManager._AvailableControllers = {};
WebXRMotionControllerManager._Fallbacks = {};
WebXRMotionControllerManager._ProfileLoadingPromises = {};
WebXRMotionControllerManager.BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist";
WebXRMotionControllerManager.PrioritizeOnlineRepository = true;
WebXRMotionControllerManager.UseOnlineRepository = true;
WebXRMotionControllerManager.DisableControllerCache = true;
WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput, scene) => {
  return new WebXRGenericTriggerMotionController(scene, xrInput.gamepad, xrInput.handedness);
});
WebXRMotionControllerManager.DefaultFallbacks();

// node_modules/@babylonjs/core/XR/webXRInputSource.js
init_tools();
var idCount = 0;

class WebXRInputSource {
  constructor(_scene, inputSource, _options = {}) {
    this._scene = _scene;
    this.inputSource = inputSource;
    this._options = _options;
    this._tmpVector = new Vector3;
    this._disposed = false;
    this.onDisposeObservable = new Observable;
    this.onMeshLoadedObservable = new Observable;
    this.onMotionControllerInitObservable = new Observable;
    this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`;
    this.pointer = new Mesh(`${this._uniqueId}-pointer`, _scene);
    this.pointer.rotationQuaternion = new Quaternion;
    if (this.inputSource.gripSpace) {
      this.grip = new Mesh(`${this._uniqueId}-grip`, this._scene);
      this.grip.rotationQuaternion = new Quaternion;
    }
    this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
    if (this.inputSource.gamepad && this.inputSource.targetRayMode === "tracked-pointer") {
      WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => {
        this.motionController = motionController;
        this.onMotionControllerInitObservable.notifyObservers(motionController);
        if (!this._options.doNotLoadControllerMesh && !this.motionController._doNotLoadControllerMesh) {
          this.motionController.loadModel().then((success) => {
            if (success && this.motionController && this.motionController.rootMesh) {
              if (this._options.renderingGroupId) {
                this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId;
                this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => mesh.renderingGroupId = this._options.renderingGroupId);
              }
              this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh);
              this.motionController.rootMesh.parent = this.grip || this.pointer;
              this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation;
            }
            if (this._disposed) {
              this.motionController?.dispose();
            }
          });
        }
      }, () => {
        Tools.Warn(`Could not find a matching motion controller for the registered input source`);
      });
    }
  }
  get uniqueId() {
    return this._uniqueId;
  }
  dispose() {
    if (this.grip) {
      this.grip.dispose(true);
    }
    if (this.motionController) {
      this.motionController.dispose();
    }
    this.pointer.dispose(true);
    this.onMotionControllerInitObservable.clear();
    this.onMeshLoadedObservable.clear();
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    this._disposed = true;
  }
  getWorldPointerRayToRef(result, gripIfAvailable = false) {
    const object = gripIfAvailable && this.grip ? this.grip : this.pointer;
    Vector3.TransformNormalToRef(this._tmpVector, object.getWorldMatrix(), result.direction);
    result.direction.normalize();
    result.origin.copyFrom(object.absolutePosition);
    result.length = 1000;
  }
  updateFromXRFrame(xrFrame, referenceSpace, xrCamera, xrSessionManager) {
    const pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace);
    this._lastXRPose = pose;
    if (pose) {
      const pos = pose.transform.position;
      this.pointer.position.set(pos.x, pos.y, pos.z).scaleInPlace(xrSessionManager.worldScalingFactor);
      const orientation = pose.transform.orientation;
      this.pointer.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
      if (!this._scene.useRightHandedSystem) {
        this.pointer.position.z *= -1;
        this.pointer.rotationQuaternion.z *= -1;
        this.pointer.rotationQuaternion.w *= -1;
      }
      this.pointer.parent = xrCamera.parent;
      this.pointer.scaling.setAll(xrSessionManager.worldScalingFactor);
    }
    if (this.inputSource.gripSpace && this.grip) {
      const pose2 = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace);
      if (pose2) {
        const pos = pose2.transform.position;
        const orientation = pose2.transform.orientation;
        this.grip.position.set(pos.x, pos.y, pos.z).scaleInPlace(xrSessionManager.worldScalingFactor);
        this.grip.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);
        if (!this._scene.useRightHandedSystem) {
          this.grip.position.z *= -1;
          this.grip.rotationQuaternion.z *= -1;
          this.grip.rotationQuaternion.w *= -1;
        }
      }
      this.grip.parent = xrCamera.parent;
      this.grip.scaling.setAll(xrSessionManager.worldScalingFactor);
    }
    if (this.motionController) {
      this.motionController.updateFromXRFrame(xrFrame);
    }
  }
}

// node_modules/@babylonjs/core/XR/webXRInput.js
class WebXRInput {
  constructor(xrSessionManager, xrCamera, _options = {}) {
    this.xrSessionManager = xrSessionManager;
    this.xrCamera = xrCamera;
    this._options = _options;
    this.controllers = [];
    this.onControllerAddedObservable = new Observable;
    this.onControllerRemovedObservable = new Observable;
    this._onInputSourcesChange = (event) => {
      this._addAndRemoveControllers(event.added, event.removed);
    };
    this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(() => {
      this._addAndRemoveControllers([], this.controllers.map((c) => {
        return c.inputSource;
      }));
    });
    this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add((session) => {
      session.addEventListener("inputsourceschange", this._onInputSourcesChange);
    });
    this._frameObserver = this.xrSessionManager.onXRFrameObservable.add((frame) => {
      this.controllers.forEach((controller) => {
        controller.updateFromXRFrame(frame, this.xrSessionManager.referenceSpace, this.xrCamera, this.xrSessionManager);
      });
    });
    if (this._options.customControllersRepositoryURL) {
      WebXRMotionControllerManager.BaseRepositoryUrl = this._options.customControllersRepositoryURL;
    }
    WebXRMotionControllerManager.UseOnlineRepository = !this._options.disableOnlineControllerRepository;
    if (WebXRMotionControllerManager.UseOnlineRepository) {
      try {
        WebXRMotionControllerManager.UpdateProfilesList().catch(() => {
          WebXRMotionControllerManager.UseOnlineRepository = false;
        });
      } catch (e) {
        WebXRMotionControllerManager.UseOnlineRepository = false;
      }
    }
  }
  _addAndRemoveControllers(addInputs, removeInputs) {
    const sources = this.controllers.map((c) => {
      return c.inputSource;
    });
    for (const input of addInputs) {
      if (sources.indexOf(input) === -1) {
        const controller = new WebXRInputSource(this.xrSessionManager.scene, input, {
          ...this._options.controllerOptions || {},
          forceControllerProfile: this._options.forceInputProfile,
          doNotLoadControllerMesh: this._options.doNotLoadControllerMeshes,
          disableMotionControllerAnimation: this._options.disableControllerAnimation
        });
        this.controllers.push(controller);
        this.onControllerAddedObservable.notifyObservers(controller);
      }
    }
    const keepControllers = [];
    const removedControllers = [];
    this.controllers.forEach((c) => {
      if (removeInputs.indexOf(c.inputSource) === -1) {
        keepControllers.push(c);
      } else {
        removedControllers.push(c);
      }
    });
    this.controllers = keepControllers;
    removedControllers.forEach((c) => {
      this.onControllerRemovedObservable.notifyObservers(c);
      c.dispose();
    });
  }
  dispose() {
    this.controllers.forEach((c) => {
      c.dispose();
    });
    this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver);
    this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver);
    this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver);
    this.onControllerAddedObservable.clear();
    this.onControllerRemovedObservable.clear();
    WebXRMotionControllerManager.ClearControllerCache();
  }
}

// node_modules/@babylonjs/core/XR/features/WebXRControllerPointerSelection.js
init_math_vector();
init_math_color();
init_math_axis();
init_pickingInfo();

// node_modules/@babylonjs/core/XR/features/WebXRAbstractFeature.js
init_observable();
init_logger();

class WebXRAbstractFeature {
  get xrNativeFeatureName() {
    return this._xrNativeFeatureName;
  }
  set xrNativeFeatureName(name325) {
    if (!this._xrSessionManager.isNative && name325 && this._xrSessionManager.inXRSession && this._xrSessionManager.enabledFeatures?.indexOf(name325) === -1) {
      Logger.Warn(`The feature ${name325} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`);
    }
    this._xrNativeFeatureName = name325;
  }
  constructor(_xrSessionManager) {
    this._xrSessionManager = _xrSessionManager;
    this._attached = false;
    this._removeOnDetach = [];
    this.isDisposed = false;
    this.disableAutoAttach = false;
    this._xrNativeFeatureName = "";
    this.onFeatureAttachObservable = new Observable;
    this.onFeatureDetachObservable = new Observable;
  }
  get attached() {
    return this._attached;
  }
  attach(force) {
    if (this.isDisposed) {
      return false;
    }
    if (!force) {
      if (this.attached) {
        return false;
      }
    } else {
      if (this.attached) {
        this.detach();
      }
    }
    if (!this._xrSessionManager.enabledFeatures) {
      Logger.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");
    } else if (!this._xrSessionManager.isNative && this.xrNativeFeatureName && this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName) === -1) {
      return false;
    }
    this._attached = true;
    this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame));
    this.onFeatureAttachObservable.notifyObservers(this);
    return true;
  }
  detach() {
    if (!this._attached) {
      this.disableAutoAttach = true;
      return false;
    }
    this._attached = false;
    this._removeOnDetach.forEach((toRemove) => {
      toRemove.observable.remove(toRemove.observer);
    });
    this.onFeatureDetachObservable.notifyObservers(this);
    return true;
  }
  dispose() {
    this.detach();
    this.isDisposed = true;
    this.onFeatureAttachObservable.clear();
    this.onFeatureDetachObservable.clear();
  }
  isCompatible() {
    return true;
  }
  _addNewAttachObserver(observable, callback, insertFirst) {
    this._removeOnDetach.push({
      observable,
      observer: observable.add(callback, undefined, insertFirst)
    });
  }
}

// node_modules/@babylonjs/core/XR/features/WebXRControllerPointerSelection.js
init_tools();

class WebXRControllerPointerSelection extends WebXRAbstractFeature {
  constructor(_xrSessionManager, _options) {
    super(_xrSessionManager);
    this._options = _options;
    this._attachController = (xrController) => {
      if (this._controllers[xrController.uniqueId]) {
        return;
      }
      const { laserPointer, selectionMesh } = this._generateNewMeshPair(this._options.forceGripIfAvailable && xrController.grip ? xrController.grip : xrController.pointer);
      this._controllers[xrController.uniqueId] = {
        xrController,
        laserPointer,
        selectionMesh,
        meshUnderPointer: null,
        pick: null,
        tmpRay: new Ray(new Vector3, new Vector3),
        disabledByNearInteraction: false,
        id: WebXRControllerPointerSelection._IdCounter++
      };
      if (this._attachedController) {
        if (!this._options.enablePointerSelectionOnAllControllers && this._options.preferredHandedness && xrController.inputSource.handedness === this._options.preferredHandedness) {
          this._attachedController = xrController.uniqueId;
        }
      } else {
        if (!this._options.enablePointerSelectionOnAllControllers) {
          this._attachedController = xrController.uniqueId;
        }
      }
      switch (xrController.inputSource.targetRayMode) {
        case "tracked-pointer":
          return this._attachTrackedPointerRayMode(xrController);
        case "gaze":
          return this._attachGazeMode(xrController);
        case "screen":
        case "transient-pointer":
          return this._attachScreenRayMode(xrController);
      }
    };
    this._controllers = {};
    this._tmpVectorForPickCompare = new Vector3;
    this.disablePointerLighting = true;
    this.disableSelectionMeshLighting = true;
    this.displayLaserPointer = true;
    this.displaySelectionMesh = true;
    this.laserPointerPickedColor = new Color3(0.9, 0.9, 0.9);
    this.laserPointerDefaultColor = new Color3(0.7, 0.7, 0.7);
    this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);
    this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1);
    this._identityMatrix = Matrix.Identity();
    this._screenCoordinatesRef = Vector3.Zero();
    this._viewportRef = new Viewport(0, 0, 0, 0);
    this._scene = this._xrSessionManager.scene;
    if (this._options.lookAndPickMode === undefined && (this._scene.getEngine()._badDesktopOS || this._scene.getEngine()._badOS)) {
      this._options.lookAndPickMode = true;
    }
    if (this._options.lookAndPickMode) {
      this._options.enablePointerSelectionOnAllControllers = true;
      this.displayLaserPointer = false;
    }
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    this._options.xrInput.controllers.forEach(this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController, true);
    this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
      this._detachController(controller.uniqueId);
    }, true);
    this._scene.constantlyUpdateMeshUnderPointer = true;
    if (this._options.gazeCamera) {
      const webXRCamera = this._options.gazeCamera;
      const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera);
      this._controllers["camera"] = {
        webXRCamera,
        laserPointer,
        selectionMesh,
        meshUnderPointer: null,
        pick: null,
        tmpRay: new Ray(new Vector3, new Vector3),
        disabledByNearInteraction: false,
        id: WebXRControllerPointerSelection._IdCounter++
      };
      this._attachGazeMode();
    }
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      this._detachController(controllerId);
    });
    return true;
  }
  getMeshUnderPointer(controllerId) {
    if (this._controllers[controllerId]) {
      return this._controllers[controllerId].meshUnderPointer;
    } else {
      return null;
    }
  }
  getXRControllerByPointerId(id) {
    const keys = Object.keys(this._controllers);
    for (let i = 0;i < keys.length; ++i) {
      if (this._controllers[keys[i]].id === id) {
        return this._controllers[keys[i]].xrController || null;
      }
    }
    return null;
  }
  _getPointerSelectionDisabledByPointerId(id) {
    const keys = Object.keys(this._controllers);
    for (let i = 0;i < keys.length; ++i) {
      if (this._controllers[keys[i]].id === id) {
        return this._controllers[keys[i]].disabledByNearInteraction;
      }
    }
    return true;
  }
  _setPointerSelectionDisabledByPointerId(id, state) {
    const keys = Object.keys(this._controllers);
    for (let i = 0;i < keys.length; ++i) {
      if (this._controllers[keys[i]].id === id) {
        this._controllers[keys[i]].disabledByNearInteraction = state;
        return;
      }
    }
  }
  _onXRFrame(_xrFrame) {
    Object.keys(this._controllers).forEach((id) => {
      const controllerData = this._controllers[id];
      if (this._options.lookAndPickMode && controllerData.xrController?.inputSource.targetRayMode !== "transient-pointer") {
        return;
      }
      if (!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController || controllerData.disabledByNearInteraction) {
        controllerData.selectionMesh.isVisible = false;
        controllerData.laserPointer.isVisible = false;
        controllerData.pick = null;
        return;
      }
      controllerData.laserPointer.isVisible = this.displayLaserPointer;
      let controllerGlobalPosition;
      if (controllerData.xrController) {
        controllerGlobalPosition = this._options.forceGripIfAvailable && controllerData.xrController.grip ? controllerData.xrController.grip.position : controllerData.xrController.pointer.position;
        controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay, this._options.forceGripIfAvailable);
      } else if (controllerData.webXRCamera) {
        controllerGlobalPosition = controllerData.webXRCamera.position;
        controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay);
      } else {
        return;
      }
      if (this._options.maxPointerDistance) {
        controllerData.tmpRay.length = this._options.maxPointerDistance;
      }
      if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) {
        const scene = this._xrSessionManager.scene;
        const camera2 = this._options.xrInput.xrCamera;
        if (camera2) {
          camera2.viewport.toGlobalToRef(scene.getEngine().getRenderWidth() / camera2.rigCameras.length, scene.getEngine().getRenderHeight(), this._viewportRef);
          Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, camera2.getTransformationMatrix(), this._viewportRef, this._screenCoordinatesRef);
          if (typeof this._screenCoordinatesRef.x === "number" && typeof this._screenCoordinatesRef.y === "number" && !isNaN(this._screenCoordinatesRef.x) && !isNaN(this._screenCoordinatesRef.y) && this._screenCoordinatesRef.x !== Infinity && this._screenCoordinatesRef.y !== Infinity) {
            scene.pointerX = this._screenCoordinatesRef.x;
            scene.pointerY = this._screenCoordinatesRef.y;
            controllerData.screenCoordinates = {
              x: this._screenCoordinatesRef.x,
              y: this._screenCoordinatesRef.y
            };
          }
        }
      }
      let utilityScenePick = null;
      if (this._utilityLayerScene) {
        utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate);
      }
      const originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate);
      if (!utilityScenePick || !utilityScenePick.hit) {
        controllerData.pick = originalScenePick;
      } else if (!originalScenePick || !originalScenePick.hit) {
        controllerData.pick = utilityScenePick;
      } else if (utilityScenePick.distance < originalScenePick.distance) {
        controllerData.pick = utilityScenePick;
      } else {
        controllerData.pick = originalScenePick;
      }
      if (controllerData.pick && controllerData.xrController) {
        controllerData.pick.aimTransform = controllerData.xrController.pointer;
        controllerData.pick.gripTransform = controllerData.xrController.grip || null;
        controllerData.pick.originMesh = controllerData.xrController.pointer;
        controllerData.tmpRay.length = controllerData.pick.distance;
      }
      const pick = controllerData.pick;
      if (pick && pick.pickedPoint && pick.hit) {
        this._updatePointerDistance(controllerData.laserPointer, pick.distance);
        controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
        controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
        controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
        controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
        const pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);
        const deltaFighting = 0.001;
        controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
        if (pickNormal) {
          const axis1 = Vector3.Cross(Axis.Y, pickNormal);
          const axis2 = Vector3.Cross(pickNormal, axis1);
          Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
          controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
        }
        controllerData.selectionMesh.isVisible = this.displaySelectionMesh;
        controllerData.meshUnderPointer = pick.pickedMesh;
      } else {
        controllerData.selectionMesh.isVisible = false;
        this._updatePointerDistance(controllerData.laserPointer, 1);
        controllerData.meshUnderPointer = null;
      }
    });
  }
  get _utilityLayerScene() {
    return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;
  }
  _attachGazeMode(xrController) {
    const controllerData = this._controllers[xrController && xrController.uniqueId || "camera"];
    const timeToSelect = this._options.timeToSelect || 3000;
    const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene;
    let oldPick = new PickingInfo;
    const discMesh = CreateTorus("selection", {
      diameter: 0.0035 * 15,
      thickness: 0.0025 * 6,
      tessellation: 20
    }, sceneToRenderTo);
    discMesh.isVisible = false;
    discMesh.isPickable = false;
    discMesh.parent = controllerData.selectionMesh;
    let timer = 0;
    let downTriggered = false;
    const pointerEventInit = {
      pointerId: controllerData.id,
      pointerType: "xr"
    };
    controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
      if (!controllerData.pick) {
        return;
      }
      this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
      controllerData.laserPointer.material.alpha = 0;
      discMesh.isVisible = false;
      if (controllerData.pick.hit) {
        if (!this._pickingMoved(oldPick, controllerData.pick)) {
          if (timer > timeToSelect / 10) {
            discMesh.isVisible = true;
          }
          timer += this._scene.getEngine().getDeltaTime();
          if (timer >= timeToSelect) {
            this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
            downTriggered = true;
            if (this._options.disablePointerUpOnTouchOut) {
              this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
            }
            discMesh.isVisible = false;
          } else {
            const scaleFactor = 1 - timer / timeToSelect;
            discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
          }
        } else {
          if (downTriggered) {
            if (!this._options.disablePointerUpOnTouchOut) {
              this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
            }
          }
          downTriggered = false;
          timer = 0;
        }
      } else {
        downTriggered = false;
        timer = 0;
      }
      this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
      oldPick = controllerData.pick;
    });
    if (this._options.renderingGroupId !== undefined) {
      discMesh.renderingGroupId = this._options.renderingGroupId;
    }
    if (xrController) {
      xrController.onDisposeObservable.addOnce(() => {
        if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
          this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
          controllerData.finalPointerUpTriggered = true;
        }
        discMesh.dispose();
      });
    }
  }
  _attachScreenRayMode(xrController) {
    const controllerData = this._controllers[xrController.uniqueId];
    let downTriggered = false;
    const pointerEventInit = {
      pointerId: controllerData.id,
      pointerType: "xr"
    };
    controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
      this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
      if (!controllerData.pick || this._options.disablePointerUpOnTouchOut && downTriggered) {
        return;
      }
      if (!downTriggered) {
        this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
        controllerData.pointerDownTriggered = true;
        downTriggered = true;
        if (this._options.disablePointerUpOnTouchOut) {
          this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
        }
      } else {
        this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
      }
    });
    xrController.onDisposeObservable.addOnce(() => {
      this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
      this._xrSessionManager.runInXRFrame(() => {
        if (controllerData.pick && !controllerData.finalPointerUpTriggered && downTriggered && !this._options.disablePointerUpOnTouchOut) {
          this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
          controllerData.finalPointerUpTriggered = true;
        }
      });
    });
  }
  _attachTrackedPointerRayMode(xrController) {
    const controllerData = this._controllers[xrController.uniqueId];
    if (this._options.forceGazeMode) {
      return this._attachGazeMode(xrController);
    }
    const pointerEventInit = {
      pointerId: controllerData.id,
      pointerType: "xr"
    };
    controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
      controllerData.laserPointer.material.disableLighting = this.disablePointerLighting;
      controllerData.selectionMesh.material.disableLighting = this.disableSelectionMeshLighting;
      if (controllerData.pick) {
        this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
        this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
      }
    });
    if (xrController.inputSource.gamepad) {
      const init = (motionController) => {
        if (this._options.overrideButtonId) {
          controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);
        }
        if (!controllerData.selectionComponent) {
          controllerData.selectionComponent = motionController.getMainComponent();
        }
        controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
          if (component.changes.pressed) {
            const pressed = component.changes.pressed.current;
            if (controllerData.pick) {
              if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) {
                this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
                if (pressed) {
                  this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
                  controllerData.pointerDownTriggered = true;
                  controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;
                  controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;
                } else {
                  this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
                  controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;
                  controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;
                }
              }
            } else {
              if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) {
                const prevController = this._controllers[this._attachedController];
                if (prevController && prevController.pointerDownTriggered && !prevController.finalPointerUpTriggered) {
                  this._augmentPointerInit(pointerEventInit, prevController.id, prevController.screenCoordinates);
                  this._scene.simulatePointerUp(new PickingInfo, {
                    pointerId: prevController.id,
                    pointerType: "xr"
                  });
                  prevController.finalPointerUpTriggered = true;
                }
                this._attachedController = xrController.uniqueId;
              }
            }
          }
        });
      };
      if (xrController.motionController) {
        init(xrController.motionController);
      } else {
        xrController.onMotionControllerInitObservable.add(init);
      }
    } else {
      const selectStartListener = (event) => {
        this._xrSessionManager.onXRFrameObservable.addOnce(() => {
          this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
          if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {
            this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
            controllerData.pointerDownTriggered = true;
            controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;
            controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;
          }
        });
      };
      const selectEndListener = (event) => {
        this._xrSessionManager.onXRFrameObservable.addOnce(() => {
          this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
          if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {
            this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
            controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;
            controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;
          }
        });
      };
      controllerData.eventListeners = {
        selectend: selectEndListener,
        selectstart: selectStartListener
      };
      this._xrSessionManager.session.addEventListener("selectstart", selectStartListener);
      this._xrSessionManager.session.addEventListener("selectend", selectEndListener);
    }
  }
  _convertNormalToDirectionOfRay(normal, ray2) {
    if (normal) {
      const angle = Math.acos(Vector3.Dot(normal, ray2.direction));
      if (angle < Math.PI / 2) {
        normal.scaleInPlace(-1);
      }
    }
    return normal;
  }
  _detachController(xrControllerUniqueId) {
    const controllerData = this._controllers[xrControllerUniqueId];
    if (!controllerData) {
      return;
    }
    if (controllerData.selectionComponent) {
      if (controllerData.onButtonChangedObserver) {
        controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
      }
    }
    if (controllerData.onFrameObserver) {
      this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
    }
    if (controllerData.eventListeners) {
      Object.keys(controllerData.eventListeners).forEach((eventName) => {
        const func = controllerData.eventListeners && controllerData.eventListeners[eventName];
        if (func) {
          this._xrSessionManager.session.removeEventListener(eventName, func);
        }
      });
    }
    if (!controllerData.finalPointerUpTriggered && controllerData.pointerDownTriggered) {
      const pointerEventInit = {
        pointerId: controllerData.id,
        pointerType: "xr"
      };
      this._xrSessionManager.runInXRFrame(() => {
        this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);
        this._scene.simulatePointerUp(controllerData.pick || new PickingInfo, pointerEventInit);
        controllerData.finalPointerUpTriggered = true;
      });
    }
    this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => {
      try {
        controllerData.selectionMesh.dispose();
        controllerData.laserPointer.dispose();
        delete this._controllers[xrControllerUniqueId];
        if (this._attachedController === xrControllerUniqueId) {
          const keys = Object.keys(this._controllers);
          if (keys.length) {
            this._attachedController = keys[0];
          } else {
            this._attachedController = "";
          }
        }
      } catch (e) {
        Tools.Warn("controller already detached.");
      }
    });
  }
  _generateNewMeshPair(meshParent) {
    const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;
    const laserPointer = this._options.customLasterPointerMeshGenerator ? this._options.customLasterPointerMeshGenerator() : CreateCylinder("laserPointer", {
      height: 1,
      diameterTop: 0.0002,
      diameterBottom: 0.004,
      tessellation: 20,
      subdivisions: 1
    }, sceneToRenderTo);
    laserPointer.parent = meshParent;
    const laserPointerMaterial = new StandardMaterial("laserPointerMat", sceneToRenderTo);
    laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor;
    laserPointerMaterial.alpha = 0.7;
    laserPointer.material = laserPointerMaterial;
    laserPointer.rotation.x = Math.PI / 2;
    this._updatePointerDistance(laserPointer, 1);
    laserPointer.isPickable = false;
    laserPointer.isVisible = false;
    const selectionMesh = this._options.customSelectionMeshGenerator ? this._options.customSelectionMeshGenerator() : CreateTorus("gazeTracker", {
      diameter: 0.0035 * 3,
      thickness: 0.0025 * 3,
      tessellation: 20
    }, sceneToRenderTo);
    selectionMesh.bakeCurrentTransformIntoVertices();
    selectionMesh.isPickable = false;
    selectionMesh.isVisible = false;
    const targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
    targetMat.specularColor = Color3.Black();
    targetMat.emissiveColor = this.selectionMeshDefaultColor;
    targetMat.backFaceCulling = false;
    selectionMesh.material = targetMat;
    if (this._options.renderingGroupId !== undefined) {
      laserPointer.renderingGroupId = this._options.renderingGroupId;
      selectionMesh.renderingGroupId = this._options.renderingGroupId;
    }
    return {
      laserPointer,
      selectionMesh
    };
  }
  _pickingMoved(oldPick, newPick) {
    if (!oldPick.hit || !newPick.hit) {
      return true;
    }
    if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) {
      return true;
    }
    if (oldPick.pickedMesh !== newPick.pickedMesh) {
      return true;
    }
    oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
    this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
    const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance;
    const length = this._tmpVectorForPickCompare.length();
    if (length > delta) {
      return true;
    }
    return false;
  }
  _updatePointerDistance(_laserPointer, distance = 100) {
    _laserPointer.scaling.y = distance;
    if (this._scene.useRightHandedSystem) {
      distance *= -1;
    }
    _laserPointer.position.z = distance / 2 + 0.05;
  }
  _augmentPointerInit(pointerEventInit, id, screenCoordinates) {
    pointerEventInit.pointerId = id;
    pointerEventInit.pointerType = "xr";
    if (screenCoordinates) {
      pointerEventInit.screenX = screenCoordinates.x;
      pointerEventInit.screenY = screenCoordinates.y;
    }
  }
  get lasterPointerDefaultColor() {
    return this.laserPointerDefaultColor;
  }
}
WebXRControllerPointerSelection._IdCounter = 200;
WebXRControllerPointerSelection.Name = WebXRFeatureName.POINTER_SELECTION;
WebXRControllerPointerSelection.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  return () => new WebXRControllerPointerSelection(xrSessionManager, options);
}, WebXRControllerPointerSelection.Version, true);

// node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js
init_math_vector();
init_pickingInfo();
init_math_color();

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_tslib_es6();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.js
var NodeMaterialBlockConnectionPointTypes;
(function(NodeMaterialBlockConnectionPointTypes2) {
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Float"] = 1] = "Float";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Int"] = 2] = "Int";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Vector2"] = 4] = "Vector2";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Vector3"] = 8] = "Vector3";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Vector4"] = 16] = "Vector4";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Color3"] = 32] = "Color3";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Color4"] = 64] = "Color4";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Matrix"] = 128] = "Matrix";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["Object"] = 256] = "Object";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["AutoDetect"] = 1024] = "AutoDetect";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["BasedOnInput"] = 2048] = "BasedOnInput";
  NodeMaterialBlockConnectionPointTypes2[NodeMaterialBlockConnectionPointTypes2["All"] = 4095] = "All";
})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));

// node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockTargets.js
var NodeMaterialBlockTargets;
(function(NodeMaterialBlockTargets2) {
  NodeMaterialBlockTargets2[NodeMaterialBlockTargets2["Vertex"] = 1] = "Vertex";
  NodeMaterialBlockTargets2[NodeMaterialBlockTargets2["Fragment"] = 2] = "Fragment";
  NodeMaterialBlockTargets2[NodeMaterialBlockTargets2["Neutral"] = 4] = "Neutral";
  NodeMaterialBlockTargets2[NodeMaterialBlockTargets2["VertexAndFragment"] = 3] = "VertexAndFragment";
})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));

// node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildState.js
init_shaderStore();

class NodeMaterialBuildState {
  constructor() {
    this.supportUniformBuffers = false;
    this.attributes = [];
    this.uniforms = [];
    this.constants = [];
    this.samplers = [];
    this.functions = {};
    this.extensions = {};
    this.prePassOutput = {};
    this.counters = {};
    this._terminalBlocks = new Set;
    this._attributeDeclaration = "";
    this._uniformDeclaration = "";
    this._constantDeclaration = "";
    this._samplerDeclaration = "";
    this._varyingTransfer = "";
    this._injectAtEnd = "";
    this._repeatableContentAnchorIndex = 0;
    this._builtCompilationString = "";
    this.compilationString = "";
  }
  get shaderLanguage() {
    return this.sharedData.nodeMaterial.shaderLanguage;
  }
  get fSuffix() {
    return this.shaderLanguage === 1 ? "f" : "";
  }
  finalize(state) {
    const emitComments = state.sharedData.emitComments;
    const isFragmentMode = this.target === NodeMaterialBlockTargets.Fragment;
    if (this.shaderLanguage === 1) {
      if (isFragmentMode) {
        this.compilationString = `
${emitComments ? `//Entry point
` : ""}@fragment
fn main(input: FragmentInputs) -> FragmentOutputs {
${this.sharedData.varyingInitializationsFragment}${this.compilationString}`;
      } else {
        this.compilationString = `
${emitComments ? `//Entry point
` : ""}@vertex
fn main(input: VertexInputs) -> FragmentInputs{
${this.compilationString}`;
      }
    } else {
      this.compilationString = `
${emitComments ? `//Entry point
` : ""}void main(void) {
${this.compilationString}`;
    }
    if (this._constantDeclaration) {
      this.compilationString = `
${emitComments ? `//Constants
` : ""}${this._constantDeclaration}
${this.compilationString}`;
    }
    let functionCode = "";
    for (const functionName in this.functions) {
      functionCode += this.functions[functionName] + `
`;
    }
    this.compilationString = `
${functionCode}
${this.compilationString}`;
    if (!isFragmentMode && this._varyingTransfer) {
      this.compilationString = `${this.compilationString}
${this._varyingTransfer}`;
    }
    if (this._injectAtEnd) {
      this.compilationString = `${this.compilationString}
${this._injectAtEnd}`;
    }
    this.compilationString = `${this.compilationString}
}`;
    if (this.sharedData.varyingDeclaration) {
      this.compilationString = `
${emitComments ? `//Varyings
` : ""}${isFragmentMode ? this.sharedData.varyingDeclarationFragment : this.sharedData.varyingDeclaration}
${this.compilationString}`;
    }
    if (this._samplerDeclaration) {
      this.compilationString = `
${emitComments ? `//Samplers
` : ""}${this._samplerDeclaration}
${this.compilationString}`;
    }
    if (this._uniformDeclaration) {
      this.compilationString = `
${emitComments ? `//Uniforms
` : ""}${this._uniformDeclaration}
${this.compilationString}`;
    }
    if (this._attributeDeclaration && !isFragmentMode) {
      this.compilationString = `
${emitComments ? `//Attributes
` : ""}${this._attributeDeclaration}
${this.compilationString}`;
    }
    if (this.shaderLanguage !== 1) {
      this.compilationString = `precision highp float;
` + this.compilationString;
      this.compilationString = `#if defined(WEBGL2) || defined(WEBGPU)
precision highp sampler2DArray;
#endif
` + this.compilationString;
      if (isFragmentMode) {
        this.compilationString = `#if defined(PREPASS)\r
#extension GL_EXT_draw_buffers : require\r
layout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r
highp vec4 gl_FragColor;\r
#endif\r
` + this.compilationString;
      }
      for (const extensionName in this.extensions) {
        const extension = this.extensions[extensionName];
        this.compilationString = `
${extension}
${this.compilationString}`;
      }
    }
    this._builtCompilationString = this.compilationString;
  }
  get _repeatableContentAnchor() {
    return `###___ANCHOR${this._repeatableContentAnchorIndex++}___###`;
  }
  _getFreeVariableName(prefix) {
    prefix = prefix.replace(/[^a-zA-Z_]+/g, "");
    if (this.sharedData.variableNames[prefix] === undefined) {
      this.sharedData.variableNames[prefix] = 0;
      if (prefix === "output" || prefix === "texture") {
        return prefix + this.sharedData.variableNames[prefix];
      }
      return prefix;
    } else {
      this.sharedData.variableNames[prefix]++;
    }
    return prefix + this.sharedData.variableNames[prefix];
  }
  _getFreeDefineName(prefix) {
    if (this.sharedData.defineNames[prefix] === undefined) {
      this.sharedData.defineNames[prefix] = 0;
    } else {
      this.sharedData.defineNames[prefix]++;
    }
    return prefix + this.sharedData.defineNames[prefix];
  }
  _excludeVariableName(name325) {
    this.sharedData.variableNames[name325] = 0;
  }
  _emit2DSampler(name325, define = "", force = false) {
    if (this.samplers.indexOf(name325) < 0 || force) {
      if (define) {
        this._samplerDeclaration += `#if ${define}
`;
      }
      if (this.shaderLanguage === 1) {
        this._samplerDeclaration += `var ${name325 + `Sampler`}: sampler;
`;
        this._samplerDeclaration += `var ${name325}: texture_2d<f32>;
`;
      } else {
        this._samplerDeclaration += `uniform sampler2D ${name325};
`;
      }
      if (define) {
        this._samplerDeclaration += `#endif
`;
      }
      if (!force) {
        this.samplers.push(name325);
      }
    }
  }
  _emitCubeSampler(name325, define = "", force = false) {
    if (this.samplers.indexOf(name325) < 0 || force) {
      if (define) {
        this._samplerDeclaration += `#if ${define}
`;
      }
      if (this.shaderLanguage === 1) {
        this._samplerDeclaration += `var ${name325 + `Sampler`}: sampler;
`;
        this._samplerDeclaration += `var ${name325}: texture_cube<f32>;
`;
      } else {
        this._samplerDeclaration += `uniform samplerCube ${name325};
`;
      }
      if (define) {
        this._samplerDeclaration += `#endif
`;
      }
      if (!force) {
        this.samplers.push(name325);
      }
    }
  }
  _emit2DArraySampler(name325) {
    if (this.samplers.indexOf(name325) < 0) {
      this._samplerDeclaration += `uniform sampler2DArray ${name325};
`;
      this.samplers.push(name325);
    }
  }
  _getGLType(type) {
    switch (type) {
      case NodeMaterialBlockConnectionPointTypes.Float:
        return "float";
      case NodeMaterialBlockConnectionPointTypes.Int:
        return "int";
      case NodeMaterialBlockConnectionPointTypes.Vector2:
        return "vec2";
      case NodeMaterialBlockConnectionPointTypes.Color3:
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        return "vec3";
      case NodeMaterialBlockConnectionPointTypes.Color4:
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        return "vec4";
      case NodeMaterialBlockConnectionPointTypes.Matrix:
        return "mat4";
    }
    return "";
  }
  _getShaderType(type) {
    const isWGSL = this.shaderLanguage === 1;
    switch (type) {
      case NodeMaterialBlockConnectionPointTypes.Float:
        return isWGSL ? "f32" : "float";
      case NodeMaterialBlockConnectionPointTypes.Int:
        return isWGSL ? "i32" : "int";
      case NodeMaterialBlockConnectionPointTypes.Vector2:
        return isWGSL ? "vec2f" : "vec2";
      case NodeMaterialBlockConnectionPointTypes.Color3:
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        return isWGSL ? "vec3f" : "vec3";
      case NodeMaterialBlockConnectionPointTypes.Color4:
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        return isWGSL ? "vec4f" : "vec4";
      case NodeMaterialBlockConnectionPointTypes.Matrix:
        return isWGSL ? "mat4x4f" : "mat4";
    }
    return "";
  }
  _emitExtension(name325, extension, define = "") {
    if (this.extensions[name325]) {
      return;
    }
    if (define) {
      extension = `#if ${define}
${extension}
#endif`;
    }
    this.extensions[name325] = extension;
  }
  _emitFunction(name325, code, comments) {
    if (this.functions[name325]) {
      return;
    }
    if (this.sharedData.emitComments) {
      code = comments + `
` + code;
    }
    this.functions[name325] = code;
  }
  _emitCodeFromInclude(includeName, comments, options) {
    const store = ShaderStore.GetIncludesShadersStore(this.shaderLanguage);
    if (options && options.repeatKey) {
      return `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]
`;
    }
    let code = store[includeName] + `
`;
    if (this.sharedData.emitComments) {
      code = comments + `
` + code;
    }
    if (!options) {
      return code;
    }
    if (options.replaceStrings) {
      for (let index = 0;index < options.replaceStrings.length; index++) {
        const replaceString = options.replaceStrings[index];
        code = code.replace(replaceString.search, replaceString.replace);
      }
    }
    return code;
  }
  _emitFunctionFromInclude(includeName, comments, options, storeKey = "") {
    const key = includeName + storeKey;
    if (this.functions[key]) {
      return;
    }
    const store = ShaderStore.GetIncludesShadersStore(this.shaderLanguage);
    if (!options || !options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings) {
      if (options && options.repeatKey) {
        this.functions[key] = `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]
`;
      } else {
        this.functions[key] = `#include<${includeName}>${options?.substitutionVars ? "(" + options?.substitutionVars + ")" : ""}
`;
      }
      if (this.sharedData.emitComments) {
        this.functions[key] = comments + `
` + this.functions[key];
      }
      return;
    }
    this.functions[key] = store[includeName];
    if (this.sharedData.emitComments) {
      this.functions[key] = comments + `
` + this.functions[key];
    }
    if (options.removeIfDef) {
      this.functions[key] = this.functions[key].replace(/^\s*?#ifdef.+$/gm, "");
      this.functions[key] = this.functions[key].replace(/^\s*?#endif.*$/gm, "");
      this.functions[key] = this.functions[key].replace(/^\s*?#else.*$/gm, "");
      this.functions[key] = this.functions[key].replace(/^\s*?#elif.*$/gm, "");
    }
    if (options.removeAttributes) {
      this.functions[key] = this.functions[key].replace(/\s*?attribute .+?;/g, `
`);
    }
    if (options.removeUniforms) {
      this.functions[key] = this.functions[key].replace(/\s*?uniform .*?;/g, `
`);
    }
    if (options.removeVaryings) {
      this.functions[key] = this.functions[key].replace(/\s*?(varying|in) .+?;/g, `
`);
    }
    if (options.replaceStrings) {
      for (let index = 0;index < options.replaceStrings.length; index++) {
        const replaceString = options.replaceStrings[index];
        this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace);
      }
    }
  }
  _registerTempVariable(name325) {
    if (this.sharedData.temps.indexOf(name325) !== -1) {
      return false;
    }
    this.sharedData.temps.push(name325);
    return true;
  }
  _emitVaryingFromString(name325, type, define = "", notDefine = false) {
    if (this.sharedData.varyings.indexOf(name325) !== -1) {
      return false;
    }
    this.sharedData.varyings.push(name325);
    const shaderType = this._getShaderType(type);
    const emitCode = (forFragment = false) => {
      let code = "";
      if (define) {
        if (define.startsWith("defined(")) {
          code += `#if ${define}
`;
        } else {
          code += `${notDefine ? "#ifndef" : "#ifdef"} ${define}
`;
        }
      }
      if (this.shaderLanguage === 1) {
        switch (shaderType) {
          case "mat4x4f":
            code += `varying ${name325}_r0: vec4f;
`;
            code += `varying ${name325}_r1: vec4f;
`;
            code += `varying ${name325}_r2: vec4f;
`;
            code += `varying ${name325}_r3: vec4f;
`;
            if (forFragment) {
              code += `var<private> ${name325}: mat4x4f;
`;
              this.sharedData.varyingInitializationsFragment += `${name325} = mat4x4f(fragmentInputs.${name325}_r0, fragmentInputs.${name325}_r1, fragmentInputs.${name325}_r2, fragmentInputs.${name325}_r3);
`;
            }
            break;
          default:
            code += `varying ${name325}: ${shaderType};
`;
            break;
        }
      } else {
        code += `varying ${shaderType} ${name325};
`;
      }
      if (define) {
        code += `#endif
`;
      }
      return code;
    };
    if (this.shaderLanguage === 1) {
      this.sharedData.varyingDeclaration += emitCode(false);
      this.sharedData.varyingDeclarationFragment += emitCode(true);
    } else {
      const code = emitCode();
      this.sharedData.varyingDeclaration += code;
      this.sharedData.varyingDeclarationFragment += code;
    }
    return true;
  }
  _getVaryingName(name325) {
    if (this.shaderLanguage === 1) {
      return (this.target !== NodeMaterialBlockTargets.Fragment ? "vertexOutputs." : "fragmentInputs.") + name325;
    }
    return name325;
  }
  _emitUniformFromString(name325, type, define = "", notDefine = false) {
    if (this.uniforms.indexOf(name325) !== -1) {
      return;
    }
    this.uniforms.push(name325);
    if (define) {
      if (define.startsWith("defined(")) {
        this._uniformDeclaration += `#if ${define}
`;
      } else {
        this._uniformDeclaration += `${notDefine ? "#ifndef" : "#ifdef"} ${define}
`;
      }
    }
    const shaderType = this._getShaderType(type);
    if (this.shaderLanguage === 1) {
      this._uniformDeclaration += `uniform ${name325}: ${shaderType};
`;
    } else {
      this._uniformDeclaration += `uniform ${shaderType} ${name325};
`;
    }
    if (define) {
      this._uniformDeclaration += `#endif
`;
    }
  }
  _generateTernary(trueStatement, falseStatement, condition2) {
    if (this.shaderLanguage === 1) {
      return `select(${falseStatement}, ${trueStatement}, ${condition2})`;
    }
    return `(${condition2}) ? ${trueStatement} : ${falseStatement}`;
  }
  _emitFloat(value) {
    if (value.toString() === value.toFixed(0)) {
      return `${value}.0`;
    }
    return value.toString();
  }
  _declareOutput(output, isConst) {
    return this._declareLocalVar(output.associatedVariableName, output.type, isConst);
  }
  _declareLocalVar(name325, type, isConst) {
    if (this.shaderLanguage === 1) {
      return `${isConst ? "const" : "var"} ${name325}: ${this._getShaderType(type)}`;
    } else {
      return `${this._getShaderType(type)} ${name325}`;
    }
  }
  _samplerCubeFunc() {
    if (this.shaderLanguage === 1) {
      return "textureSample";
    }
    return "textureCube";
  }
  _samplerFunc() {
    if (this.shaderLanguage === 1) {
      return "textureSample";
    }
    return "texture2D";
  }
  _samplerLODFunc() {
    if (this.shaderLanguage === 1) {
      return "textureSampleLevel";
    }
    return "texture2DLodEXT";
  }
  _toLinearSpace(output) {
    if (this.shaderLanguage === 1) {
      if (output.type === NodeMaterialBlockConnectionPointTypes.Color3 || output.type === NodeMaterialBlockConnectionPointTypes.Vector3) {
        return `toLinearSpaceVec3(${output.associatedVariableName})`;
      }
      return `toLinearSpace(${output.associatedVariableName})`;
    }
    return `toLinearSpace(${output.associatedVariableName})`;
  }
  _generateTextureSample(uv, samplerName) {
    if (this.shaderLanguage === 1) {
      return `${this._samplerFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv})`;
    }
    return `${this._samplerFunc()}(${samplerName}, ${uv})`;
  }
  _generateTextureSampleLOD(uv, samplerName, lod) {
    if (this.shaderLanguage === 1) {
      return `${this._samplerLODFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv}, ${lod})`;
    }
    return `${this._samplerLODFunc()}(${samplerName}, ${uv}, ${lod})`;
  }
  _generateTextureSampleCube(uv, samplerName) {
    if (this.shaderLanguage === 1) {
      return `${this._samplerCubeFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv})`;
    }
    return `${this._samplerCubeFunc()}(${samplerName}, ${uv})`;
  }
  _generateTextureSampleCubeLOD(uv, samplerName, lod) {
    if (this.shaderLanguage === 1) {
      return `${this._samplerCubeFunc()}(${samplerName},${samplerName + `Sampler`}, ${uv}, ${lod})`;
    }
    return `${this._samplerCubeFunc()}(${samplerName}, ${uv}, ${lod})`;
  }
  _convertVariableDeclarationToWGSL(type, dest, source) {
    return source.replace(new RegExp(`(${type})\\s+(\\w+)`, "g"), `var $2: ${dest}`);
  }
  _convertVariableConstructorsToWGSL(type, dest, source) {
    return source.replace(new RegExp(`(${type})\\(`, "g"), ` ${dest}(`);
  }
  _convertOutParametersToWGSL(source) {
    return source.replace(new RegExp(`out\\s+var\\s+(\\w+)\\s*:\\s*(\\w+)`, "g"), `$1: ptr<function, $2>`);
  }
  _convertTernaryOperandsToWGSL(source) {
    return source.replace(new RegExp(`\\[(.*?)\\?(.*?):(.*)\\]`, "g"), (match, condition2, trueCase, falseCase) => `select(${falseCase}, ${trueCase}, ${condition2})`);
  }
  _convertModOperatorsToWGSL(source) {
    return source.replace(new RegExp(`mod\\((.+?),\\s*(.+?)\\)`, "g"), (match, left, right) => `((${left})%(${right}))`);
  }
  _convertConstToWGSL(source) {
    return source.replace(new RegExp(`const var`, "g"), `const`);
  }
  _convertInnerFunctionsToWGSL(source) {
    return source.replace(new RegExp(`inversesqrt`, "g"), `inverseSqrt`);
  }
  _convertFunctionsToWGSL(source) {
    const regex = /var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;
    let match;
    while ((match = regex.exec(source)) !== null) {
      const funcName = match[1];
      const funcType = match[2];
      const params = match[3];
      const formattedParams = params.replace(/var\s/g, "");
      source = source.replace(match[0], `fn ${funcName}(${formattedParams}) -> ${funcType}`);
    }
    return source;
  }
  _babylonSLtoWGSL(code) {
    code = this._convertVariableDeclarationToWGSL("void", "voidnull", code);
    code = this._convertVariableDeclarationToWGSL("bool", "bool", code);
    code = this._convertVariableDeclarationToWGSL("int", "i32", code);
    code = this._convertVariableDeclarationToWGSL("uint", "u32", code);
    code = this._convertVariableDeclarationToWGSL("float", "f32", code);
    code = this._convertVariableDeclarationToWGSL("vec2", "vec2f", code);
    code = this._convertVariableDeclarationToWGSL("vec3", "vec3f", code);
    code = this._convertVariableDeclarationToWGSL("vec4", "vec4f", code);
    code = this._convertVariableDeclarationToWGSL("mat2", "mat2x2f", code);
    code = this._convertVariableDeclarationToWGSL("mat3", "mat3x3f", code);
    code = this._convertVariableDeclarationToWGSL("mat4", "mat4x4f", code);
    code = this._convertVariableConstructorsToWGSL("float", "f32", code);
    code = this._convertVariableConstructorsToWGSL("vec2", "vec2f", code);
    code = this._convertVariableConstructorsToWGSL("vec3", "vec3f", code);
    code = this._convertVariableConstructorsToWGSL("vec4", "vec4f", code);
    code = this._convertVariableConstructorsToWGSL("mat2", "mat2x2f", code);
    code = this._convertVariableConstructorsToWGSL("mat3", "mat3x3f", code);
    code = this._convertVariableConstructorsToWGSL("mat4", "mat4x4f", code);
    code = this._convertTernaryOperandsToWGSL(code);
    code = this._convertModOperatorsToWGSL(code);
    code = this._convertConstToWGSL(code);
    code = this._convertInnerFunctionsToWGSL(code);
    code = this._convertOutParametersToWGSL(code);
    code = code.replace(/\[\*\]/g, "*");
    code = this._convertFunctionsToWGSL(code);
    code = code.replace(/\s->\svoidnull/g, "");
    code = code.replace(/dFdx/g, "dpdx");
    code = code.replace(/dFdy/g, "dpdy");
    return code;
  }
  _convertTernaryOperandsToGLSL(source) {
    return source.replace(new RegExp(`\\[(.+?)\\?(.+?):(.+)\\]`, "g"), (match, condition2, trueCase, falseCase) => `${condition2} ? ${trueCase} : ${falseCase}`);
  }
  _babylonSLtoGLSL(code) {
    code = code.replace(/\[\*\]/g, "");
    code = this._convertTernaryOperandsToGLSL(code);
    return code;
  }
}

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_effect();
init_observable();

// node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildStateSharedData.js
init_logger();

class NodeMaterialBuildStateSharedData {
  constructor() {
    this.temps = [];
    this.varyings = [];
    this.varyingDeclaration = "";
    this.varyingDeclarationFragment = "";
    this.varyingInitializationsFragment = "";
    this.inputBlocks = [];
    this.textureBlocks = [];
    this.bindableBlocks = [];
    this.forcedBindableBlocks = [];
    this.blocksWithFallbacks = [];
    this.blocksWithDefines = [];
    this.repeatableContentBlocks = [];
    this.dynamicUniformBlocks = [];
    this.blockingBlocks = [];
    this.animatedInputs = [];
    this.variableNames = {};
    this.defineNames = {};
    this.hints = {
      needWorldViewMatrix: false,
      needWorldViewProjectionMatrix: false,
      needAlphaBlending: false,
      needAlphaTesting: false
    };
    this.checks = {
      emitVertex: false,
      emitFragment: false,
      notConnectedNonOptionalInputs: new Array
    };
    this.allowEmptyVertexProgram = false;
    this.variableNames["position"] = 0;
    this.variableNames["normal"] = 0;
    this.variableNames["tangent"] = 0;
    this.variableNames["uv"] = 0;
    this.variableNames["uv2"] = 0;
    this.variableNames["uv3"] = 0;
    this.variableNames["uv4"] = 0;
    this.variableNames["uv5"] = 0;
    this.variableNames["uv6"] = 0;
    this.variableNames["color"] = 0;
    this.variableNames["matricesIndices"] = 0;
    this.variableNames["matricesWeights"] = 0;
    this.variableNames["matricesIndicesExtra"] = 0;
    this.variableNames["matricesWeightsExtra"] = 0;
    this.variableNames["diffuseBase"] = 0;
    this.variableNames["specularBase"] = 0;
    this.variableNames["worldPos"] = 0;
    this.variableNames["shadow"] = 0;
    this.variableNames["view"] = 0;
    this.variableNames["vTBN"] = 0;
    this.defineNames["MAINUV0"] = 0;
    this.defineNames["MAINUV1"] = 0;
    this.defineNames["MAINUV2"] = 0;
    this.defineNames["MAINUV3"] = 0;
    this.defineNames["MAINUV4"] = 0;
    this.defineNames["MAINUV5"] = 0;
    this.defineNames["MAINUV6"] = 0;
    this.defineNames["MAINUV7"] = 0;
  }
  emitErrors(errorObservable = null) {
    let errorMessage = "";
    if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) {
      errorMessage += `NodeMaterial does not have a vertex output. You need to at least add a block that generates a position value.
`;
    }
    if (!this.checks.emitFragment) {
      errorMessage += `NodeMaterial does not have a fragment output. You need to at least add a block that generates a color value.
`;
    }
    for (const notConnectedInput of this.checks.notConnectedNonOptionalInputs) {
      errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.
`;
    }
    if (errorMessage) {
      if (errorObservable) {
        errorObservable.notifyObservers(errorMessage);
      }
      Logger.Error(`Build of NodeMaterial failed:
` + errorMessage);
      return false;
    }
    return true;
  }
}

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_buffer();
init_tools();

// node_modules/@babylonjs/core/Materials/Node/Blocks/transformBlock.js
init_tslib_es6();

// node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlockConnectionPoint.js
init_observable();
var NodeMaterialConnectionPointCompatibilityStates;
(function(NodeMaterialConnectionPointCompatibilityStates2) {
  NodeMaterialConnectionPointCompatibilityStates2[NodeMaterialConnectionPointCompatibilityStates2["Compatible"] = 0] = "Compatible";
  NodeMaterialConnectionPointCompatibilityStates2[NodeMaterialConnectionPointCompatibilityStates2["TypeIncompatible"] = 1] = "TypeIncompatible";
  NodeMaterialConnectionPointCompatibilityStates2[NodeMaterialConnectionPointCompatibilityStates2["TargetIncompatible"] = 2] = "TargetIncompatible";
  NodeMaterialConnectionPointCompatibilityStates2[NodeMaterialConnectionPointCompatibilityStates2["HierarchyIssue"] = 3] = "HierarchyIssue";
})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));
var NodeMaterialConnectionPointDirection;
(function(NodeMaterialConnectionPointDirection2) {
  NodeMaterialConnectionPointDirection2[NodeMaterialConnectionPointDirection2["Input"] = 0] = "Input";
  NodeMaterialConnectionPointDirection2[NodeMaterialConnectionPointDirection2["Output"] = 1] = "Output";
})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));

class NodeMaterialConnectionPoint {
  static AreEquivalentTypes(type1, type2) {
    switch (type1) {
      case NodeMaterialBlockConnectionPointTypes.Vector3: {
        if (type2 === NodeMaterialBlockConnectionPointTypes.Color3) {
          return true;
        }
        break;
      }
      case NodeMaterialBlockConnectionPointTypes.Vector4: {
        if (type2 === NodeMaterialBlockConnectionPointTypes.Color4) {
          return true;
        }
        break;
      }
      case NodeMaterialBlockConnectionPointTypes.Color3: {
        if (type2 === NodeMaterialBlockConnectionPointTypes.Vector3) {
          return true;
        }
        break;
      }
      case NodeMaterialBlockConnectionPointTypes.Color4: {
        if (type2 === NodeMaterialBlockConnectionPointTypes.Vector4) {
          return true;
        }
        break;
      }
    }
    return false;
  }
  get _connectedPoint() {
    return this._connectedPointBackingField;
  }
  set _connectedPoint(value) {
    if (this._connectedPointBackingField === value) {
      return;
    }
    this._connectedPointTypeChangedObserver?.remove();
    this._updateTypeDependentState(() => this._connectedPointBackingField = value);
    if (this._connectedPointBackingField) {
      this._connectedPointTypeChangedObserver = this._connectedPointBackingField.onTypeChangedObservable.add(() => {
        this._notifyTypeChanged();
      });
    }
  }
  get _typeConnectionSource() {
    return this._typeConnectionSourceBackingField;
  }
  set _typeConnectionSource(value) {
    if (this._typeConnectionSourceBackingField === value) {
      return;
    }
    this._typeConnectionSourceTypeChangedObserver?.remove();
    this._updateTypeDependentState(() => this._typeConnectionSourceBackingField = value);
    if (this._typeConnectionSourceBackingField) {
      this._typeConnectionSourceTypeChangedObserver = this._typeConnectionSourceBackingField.onTypeChangedObservable.add(() => {
        this._notifyTypeChanged();
      });
    }
  }
  get _defaultConnectionPointType() {
    return this._defaultConnectionPointTypeBackingField;
  }
  set _defaultConnectionPointType(value) {
    this._updateTypeDependentState(() => this._defaultConnectionPointTypeBackingField = value);
  }
  get _linkedConnectionSource() {
    return this._linkedConnectionSourceBackingField;
  }
  set _linkedConnectionSource(value) {
    if (this._linkedConnectionSourceBackingField === value) {
      return;
    }
    this._linkedConnectionSourceTypeChangedObserver?.remove();
    this._updateTypeDependentState(() => this._linkedConnectionSourceBackingField = value);
    this._isMainLinkSource = false;
    if (this._linkedConnectionSourceBackingField) {
      this._linkedConnectionSourceTypeChangedObserver = this._linkedConnectionSourceBackingField.onTypeChangedObservable.add(() => {
        this._notifyTypeChanged();
      });
    }
  }
  get direction() {
    return this._direction;
  }
  get declarationVariableName() {
    if (this._ownerBlock.isInput) {
      return this._ownerBlock.declarationVariableName;
    }
    if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) {
      return this._connectedPoint.declarationVariableName;
    }
    return this._associatedVariableName;
  }
  get associatedVariableName() {
    if (this._ownerBlock.isInput) {
      return this._ownerBlock.associatedVariableName;
    }
    if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) {
      return this._connectedPoint.associatedVariableName;
    }
    return this._associatedVariableName;
  }
  set associatedVariableName(value) {
    this._associatedVariableName = value;
  }
  get innerType() {
    if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) {
      return this.type;
    }
    return this._type;
  }
  get type() {
    if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {
      if (this._ownerBlock.isInput) {
        return this._ownerBlock.type;
      }
      if (this._connectedPoint) {
        return this._connectedPoint.type;
      }
      if (this._linkedConnectionSource) {
        if (this._linkedConnectionSource.isConnected) {
          if (this._linkedConnectionSource.connectedPoint._redirectedSource && this._linkedConnectionSource.connectedPoint._redirectedSource.isConnected) {
            return this._linkedConnectionSource.connectedPoint._redirectedSource.type;
          }
          return this._linkedConnectionSource.type;
        }
        if (this._linkedConnectionSource._defaultConnectionPointType) {
          return this._linkedConnectionSource._defaultConnectionPointType;
        }
      }
      if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) {
      if (this._typeConnectionSource) {
        if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) {
          return this._defaultConnectionPointType;
        }
        return this._typeConnectionSource.type;
      } else if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    return this._type;
  }
  set type(value) {
    this._updateTypeDependentState(() => this._type = value);
  }
  get target() {
    if (!this._prioritizeVertex || !this._ownerBlock) {
      return this._target;
    }
    if (this._target !== NodeMaterialBlockTargets.VertexAndFragment) {
      return this._target;
    }
    if (this._ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      return NodeMaterialBlockTargets.Fragment;
    }
    return NodeMaterialBlockTargets.Vertex;
  }
  set target(value) {
    this._target = value;
  }
  get isConnected() {
    return this.connectedPoint !== null || this.hasEndpoints;
  }
  get isConnectedToInputBlock() {
    return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput;
  }
  get connectInputBlock() {
    if (!this.isConnectedToInputBlock) {
      return null;
    }
    return this.connectedPoint.ownerBlock;
  }
  get connectedPoint() {
    return this._connectedPoint;
  }
  get ownerBlock() {
    return this._ownerBlock;
  }
  get sourceBlock() {
    if (!this._connectedPoint) {
      return null;
    }
    return this._connectedPoint.ownerBlock;
  }
  get connectedBlocks() {
    if (this._endpoints.length === 0) {
      return [];
    }
    return this._endpoints.map((e) => e.ownerBlock);
  }
  get endpoints() {
    return this._endpoints;
  }
  get hasEndpoints() {
    return this._endpoints && this._endpoints.length > 0;
  }
  get isDirectlyConnectedToVertexOutput() {
    if (!this.hasEndpoints) {
      return false;
    }
    for (const endpoint of this._endpoints) {
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {
        return true;
      }
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {
        if (endpoint.ownerBlock.outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {
          return true;
        }
      }
    }
    return false;
  }
  get isConnectedInVertexShader() {
    if (this.target === NodeMaterialBlockTargets.Vertex) {
      return true;
    }
    if (!this.hasEndpoints) {
      return false;
    }
    for (const endpoint of this._endpoints) {
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {
        return true;
      }
      if (endpoint.target === NodeMaterialBlockTargets.Vertex) {
        return true;
      }
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {
        if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInVertexShader)) {
          return true;
        }
      }
    }
    return false;
  }
  get isConnectedInFragmentShader() {
    if (this.target === NodeMaterialBlockTargets.Fragment) {
      return true;
    }
    if (!this.hasEndpoints) {
      return false;
    }
    for (const endpoint of this._endpoints) {
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
        return true;
      }
      if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {
        if (endpoint.ownerBlock.isConnectedInFragmentShader()) {
          return true;
        }
      }
    }
    return false;
  }
  createCustomInputBlock() {
    return null;
  }
  constructor(name325, ownerBlock, direction) {
    this._preventBubbleUp = false;
    this._connectedPointBackingField = null;
    this._endpoints = new Array;
    this._redirectedSource = null;
    this._typeConnectionSourceBackingField = null;
    this._defaultConnectionPointTypeBackingField = null;
    this._isMainLinkSource = false;
    this._linkedConnectionSourceBackingField = null;
    this._acceptedConnectionPointType = null;
    this._type = NodeMaterialBlockConnectionPointTypes.Float;
    this._enforceAssociatedVariableName = false;
    this._forPostBuild = false;
    this.needDualDirectionValidation = false;
    this.acceptedConnectionPointTypes = [];
    this.excludedConnectionPointTypes = [];
    this.onConnectionObservable = new Observable;
    this.onDisconnectionObservable = new Observable;
    this.onTypeChangedObservable = new Observable;
    this._isTypeChangeObservableNotifying = false;
    this.isExposedOnFrame = false;
    this.exposedPortPosition = -1;
    this._prioritizeVertex = false;
    this._target = NodeMaterialBlockTargets.VertexAndFragment;
    this._ownerBlock = ownerBlock;
    this.name = name325;
    this._direction = direction;
  }
  getClassName() {
    return "NodeMaterialConnectionPoint";
  }
  canConnectTo(connectionPoint) {
    return this.checkCompatibilityState(connectionPoint) === 0;
  }
  checkCompatibilityState(connectionPoint) {
    const ownerBlock = this._ownerBlock;
    const otherBlock = connectionPoint.ownerBlock;
    if (ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      if (otherBlock.target === NodeMaterialBlockTargets.Vertex) {
        return 2;
      }
      for (const output of otherBlock.outputs) {
        if (output.ownerBlock.target != NodeMaterialBlockTargets.Neutral && output.isConnectedInVertexShader) {
          return 2;
        }
      }
    }
    if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect) {
      if (NodeMaterialConnectionPoint.AreEquivalentTypes(this.type, connectionPoint.type)) {
        return 0;
      }
      if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1 || connectionPoint._acceptedConnectionPointType && NodeMaterialConnectionPoint.AreEquivalentTypes(connectionPoint._acceptedConnectionPointType.type, this.type)) {
        return 0;
      } else {
        return 1;
      }
    }
    if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) {
      return 1;
    }
    let targetBlock = otherBlock;
    let sourceBlock = ownerBlock;
    if (this.direction === 0) {
      targetBlock = ownerBlock;
      sourceBlock = otherBlock;
    }
    if (targetBlock.isAnAncestorOf(sourceBlock)) {
      return 3;
    }
    return 0;
  }
  connectTo(connectionPoint, ignoreConstraints = false) {
    if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {
      throw "Cannot connect these two connectors.";
    }
    this._endpoints.push(connectionPoint);
    connectionPoint._connectedPoint = this;
    this._enforceAssociatedVariableName = false;
    this.onConnectionObservable.notifyObservers(connectionPoint);
    connectionPoint.onConnectionObservable.notifyObservers(this);
    return this;
  }
  disconnectFrom(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index === -1) {
      return this;
    }
    this._endpoints.splice(index, 1);
    endpoint._connectedPoint = null;
    this._enforceAssociatedVariableName = false;
    endpoint._enforceAssociatedVariableName = false;
    this.onDisconnectionObservable.notifyObservers(endpoint);
    endpoint.onDisconnectionObservable.notifyObservers(this);
    return this;
  }
  addExcludedConnectionPointFromAllowedTypes(mask) {
    let bitmask = 1;
    while (bitmask < NodeMaterialBlockConnectionPointTypes.All) {
      if (!(mask & bitmask)) {
        this.excludedConnectionPointTypes.push(bitmask);
      }
      bitmask = bitmask << 1;
    }
  }
  serialize(isInput = true) {
    const serializationObject = {};
    serializationObject.name = this.name;
    if (this.displayName) {
      serializationObject.displayName = this.displayName;
    }
    if (isInput && this.connectedPoint) {
      serializationObject.inputName = this.name;
      serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;
      serializationObject.targetConnectionName = this.connectedPoint.name;
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    if (this.isExposedOnFrame || this.exposedPortPosition >= 0) {
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    return serializationObject;
  }
  dispose() {
    this.onConnectionObservable.clear();
    this.onDisconnectionObservable.clear();
    this.onTypeChangedObservable.clear();
    this._connectedPoint = null;
    this._typeConnectionSource = null;
    this._linkedConnectionSource = null;
  }
  _updateTypeDependentState(update) {
    const previousType = this.type;
    update();
    if (this.type !== previousType) {
      this._notifyTypeChanged();
    }
  }
  _notifyTypeChanged() {
    if (this._isTypeChangeObservableNotifying) {
      return;
    }
    this._isTypeChangeObservableNotifying = true;
    this.onTypeChangedObservable.notifyObservers(this.type);
    this._isTypeChangeObservableNotifying = false;
  }
}

// node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlock.js
init_uniqueIdGenerator();
init_typeStore();
init_logger();
init_observable();

class NodeMaterialBlock {
  get _isFinalOutputAndActive() {
    return this._isFinalOutput;
  }
  get _hasPrecedence() {
    return false;
  }
  get name() {
    return this._name;
  }
  get codeIsReady() {
    return this._codeIsReady;
  }
  set name(newName) {
    if (!this.validateBlockName(newName)) {
      return;
    }
    this._name = newName;
  }
  get isUnique() {
    return this._isUnique;
  }
  get isFinalMerger() {
    return this._isFinalMerger;
  }
  get isInput() {
    return this._isInput;
  }
  get isTeleportOut() {
    return this._isTeleportOut;
  }
  get isTeleportIn() {
    return this._isTeleportIn;
  }
  get isLoop() {
    return this._isLoop;
  }
  get buildId() {
    return this._buildId;
  }
  set buildId(value) {
    this._buildId = value;
  }
  get target() {
    return this._target;
  }
  set target(value) {
    if ((this._target & value) !== 0) {
      return;
    }
    this._target = value;
  }
  get inputs() {
    return this._inputs;
  }
  get outputs() {
    return this._outputs;
  }
  getInputByName(name325) {
    const filter = this._inputs.filter((e) => e.name === name325);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  getOutputByName(name325) {
    const filter = this._outputs.filter((e) => e.name === name325);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  constructor(name325, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isFinalOutput = false) {
    this._isFinalMerger = false;
    this._isInput = false;
    this._isLoop = false;
    this._isTeleportOut = false;
    this._isTeleportIn = false;
    this._name = "";
    this._isUnique = false;
    this._codeIsReady = true;
    this._isFinalOutput = false;
    this.onCodeIsReadyObservable = new Observable;
    this.inputsAreExclusive = false;
    this._codeVariableName = "";
    this._inputs = new Array;
    this._outputs = new Array;
    this.comments = "";
    this.visibleInInspector = false;
    this.visibleOnFrame = false;
    this._target = target;
    this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;
    this._isFinalMerger = isFinalMerger;
    this._isFinalOutput = isFinalOutput;
    switch (this.getClassName()) {
      case "InputBlock":
        this._isInput = true;
        break;
      case "NodeMaterialTeleportOutBlock":
        this._isTeleportOut = true;
        break;
      case "NodeMaterialTeleportInBlock":
        this._isTeleportIn = true;
        break;
      case "LoopBlock":
        this._isLoop = true;
        break;
    }
    this._name = name325;
    this.uniqueId = UniqueIdGenerator.UniqueId;
  }
  _setInitialTarget(target) {
    this._target = target;
    this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;
  }
  initialize(state) {}
  bind(effect, nodeMaterial, mesh, subMesh) {}
  _writeVariable(currentPoint) {
    const connectionPoint = currentPoint.connectedPoint;
    if (connectionPoint) {
      return `${currentPoint.associatedVariableName}`;
    }
    return `0.`;
  }
  _writeFloat(value) {
    let stringVersion = value.toString();
    if (stringVersion.indexOf(".") === -1) {
      stringVersion += ".0";
    }
    return `${stringVersion}`;
  }
  getClassName() {
    return "NodeMaterialBlock";
  }
  isConnectedInFragmentShader() {
    return this.outputs.some((o) => o.isConnectedInFragmentShader);
  }
  registerInput(name325, type, isOptional = false, target, point) {
    point = point ?? new NodeMaterialConnectionPoint(name325, this, 0);
    point.type = type;
    point.isOptional = isOptional;
    if (target) {
      point.target = target;
    }
    this._inputs.push(point);
    return this;
  }
  registerOutput(name325, type, target, point) {
    point = point ?? new NodeMaterialConnectionPoint(name325, this, 1);
    point.type = type;
    if (target) {
      point.target = target;
    }
    this._outputs.push(point);
    return this;
  }
  getFirstAvailableInput(forOutput = null) {
    for (const input of this._inputs) {
      if (!input.connectedPoint) {
        if (!forOutput || forOutput.type === input.type || input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect || input.acceptedConnectionPointTypes.indexOf(forOutput.type) !== -1) {
          return input;
        }
      }
    }
    return null;
  }
  getFirstAvailableOutput(forBlock = null) {
    for (const output of this._outputs) {
      if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {
        return output;
      }
    }
    return null;
  }
  getSiblingOutput(current) {
    const index = this._outputs.indexOf(current);
    if (index === -1 || index >= this._outputs.length) {
      return null;
    }
    return this._outputs[index + 1];
  }
  isAnAncestorOf(block) {
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        if (endpoint.ownerBlock === block) {
          return true;
        }
        if (endpoint.ownerBlock.isAnAncestorOf(block)) {
          return true;
        }
      }
    }
    return false;
  }
  connectTo(other, options) {
    if (this._outputs.length === 0) {
      return;
    }
    let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
    let notFound = true;
    while (notFound) {
      const input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
      if (output && input && output.canConnectTo(input)) {
        output.connectTo(input);
        notFound = false;
      } else if (!output) {
        throw "Unable to find a compatible match";
      } else {
        output = this.getSiblingOutput(output);
      }
    }
    return this;
  }
  _buildBlock(state) {}
  _postBuildBlock(state) {}
  updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {}
  provideFallbacks(mesh, fallbacks) {}
  initializeDefines(mesh, nodeMaterial, defines, useInstances = false) {}
  prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {}
  autoConfigure(material, additionalFilteringInfo = () => true) {}
  replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {}
  get willBeGeneratedIntoVertexShaderFromFragmentShader() {
    if (this.isInput || this.isFinalMerger) {
      return false;
    }
    if (this._outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {
      return false;
    }
    if (this.target === NodeMaterialBlockTargets.Vertex) {
      return false;
    }
    if (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) {
      if (this._outputs.some((o) => o.isConnectedInVertexShader)) {
        return true;
      }
    }
    return false;
  }
  isReady(mesh, nodeMaterial, defines, useInstances = false) {
    return true;
  }
  _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) {
    if (looseCoupling) {
      this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0];
    } else {
      this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
      this._inputs[inputIndex0]._isMainLinkSource = true;
    }
    this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
  }
  _processBuild(block, state, input, activeBlocks) {
    block.build(state, activeBlocks);
    const localBlockIsFragment = state._vertexState != null;
    const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment;
    if (localBlockIsFragment && ((block.target & block._buildTarget) === 0 || (block.target & input.target) === 0 || this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader)) {
      if (!block.isInput && state.target !== block._buildTarget || block.isInput && block.isAttribute && !block._noContextSwitch) {
        const connectedPoint = input.connectedPoint;
        if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.declarationVariableName, connectedPoint.type)) {
          const prefix2 = state.shaderLanguage === 1 ? "vertexOutputs." : "";
          if (state.shaderLanguage === 1 && connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Matrix) {
            state._vertexState.compilationString += `${prefix2}${"v_" + connectedPoint.declarationVariableName}_r0 = ${connectedPoint.associatedVariableName}[0];
`;
            state._vertexState.compilationString += `${prefix2}${"v_" + connectedPoint.declarationVariableName}_r1 = ${connectedPoint.associatedVariableName}[1];
`;
            state._vertexState.compilationString += `${prefix2}${"v_" + connectedPoint.declarationVariableName}_r2 = ${connectedPoint.associatedVariableName}[2];
`;
            state._vertexState.compilationString += `${prefix2}${"v_" + connectedPoint.declarationVariableName}_r3 = ${connectedPoint.associatedVariableName}[3];
`;
          } else {
            state._vertexState.compilationString += `${prefix2}${"v_" + connectedPoint.declarationVariableName} = ${connectedPoint.associatedVariableName};
`;
          }
        }
        const prefix = state.shaderLanguage === 1 && connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Matrix ? "fragmentInputs." : "";
        input.associatedVariableName = prefix + "v_" + connectedPoint.declarationVariableName;
        input._enforceAssociatedVariableName = true;
      }
    }
  }
  validateBlockName(newName) {
    const reservedNames = [
      "position",
      "normal",
      "tangent",
      "particle_positionw",
      "uv",
      "uv2",
      "uv3",
      "uv4",
      "uv5",
      "uv6",
      "position2d",
      "particle_uv",
      "matricesIndices",
      "matricesWeights",
      "world0",
      "world1",
      "world2",
      "world3",
      "particle_color",
      "particle_texturemask"
    ];
    for (const reservedName of reservedNames) {
      if (newName === reservedName) {
        return false;
      }
    }
    return true;
  }
  _customBuildStep(state, activeBlocks) {}
  build(state, activeBlocks) {
    if (this._buildId === state.sharedData.buildId) {
      return true;
    }
    if (!this.isInput) {
      for (const output of this._outputs) {
        if (!output.associatedVariableName) {
          output.associatedVariableName = state._getFreeVariableName(output.name);
        }
      }
    }
    for (const input of this._inputs) {
      if (!input.connectedPoint) {
        if (!input.isOptional) {
          state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
        }
        continue;
      }
      if (this.target !== NodeMaterialBlockTargets.Neutral) {
        if ((input.target & this.target) === 0) {
          continue;
        }
        if ((input.target & state.target) === 0) {
          continue;
        }
      }
      const block = input.connectedPoint.ownerBlock;
      if (block && block !== this) {
        this._processBuild(block, state, input, activeBlocks);
      }
    }
    this._customBuildStep(state, activeBlocks);
    if (this._buildId === state.sharedData.buildId) {
      return true;
    }
    if (state.sharedData.verbose) {
      Logger.Log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`);
    }
    if (this.isFinalMerger) {
      switch (state.target) {
        case NodeMaterialBlockTargets.Vertex:
          state.sharedData.checks.emitVertex = true;
          break;
        case NodeMaterialBlockTargets.Fragment:
          state.sharedData.checks.emitFragment = true;
          break;
      }
    }
    if (!this.isInput && state.sharedData.emitComments) {
      state.compilationString += `
//${this.name}
`;
    }
    this._buildBlock(state);
    this._buildId = state.sharedData.buildId;
    this._buildTarget = state.target;
    for (const output of this._outputs) {
      if (output._forPostBuild) {
        continue;
      }
      if ((output.target & state.target) === 0) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const block = endpoint.ownerBlock;
        if (block) {
          if ((block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1 || state._terminalBlocks.has(block)) {
            this._processBuild(block, state, endpoint, activeBlocks);
          }
        }
      }
    }
    this._postBuildBlock(state);
    for (const output of this._outputs) {
      if (!output._forPostBuild) {
        continue;
      }
      if ((output.target & state.target) === 0) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const block = endpoint.ownerBlock;
        if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {
          this._processBuild(block, state, endpoint, activeBlocks);
        }
      }
    }
    return false;
  }
  _inputRename(name325) {
    return name325;
  }
  _outputRename(name325) {
    return name325;
  }
  _dumpPropertiesCode() {
    const variableName = this._codeVariableName;
    return `${variableName}.visibleInInspector = ${this.visibleInInspector};
${variableName}.visibleOnFrame = ${this.visibleOnFrame};
${variableName}.target = ${this.target};
`;
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    alreadyDumped.push(this);
    const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
    this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;
    if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
      let index = 0;
      do {
        index++;
        this._codeVariableName = nameAsVariableName + index;
      } while (uniqueNames.indexOf(this._codeVariableName) !== -1);
    }
    uniqueNames.push(this._codeVariableName);
    let codeString = `
// ${this.getClassName()}
`;
    if (this.comments) {
      codeString += `// ${this.comments}
`;
    }
    codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");
`;
    codeString += this._dumpPropertiesCode();
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      if (alreadyDumped.indexOf(connectedBlock) === -1) {
        codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    for (const output of this.outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const connectedBlock = endpoint.ownerBlock;
        if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
          codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
        }
      }
    }
    return codeString;
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = "";
    if (alreadyDumped.indexOf(this) !== -1) {
      return codeString;
    }
    alreadyDumped.push(this);
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
      codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});
`;
    }
    return codeString;
  }
  clone(scene, rootUrl = "") {
    const serializationObject = this.serialize();
    const blockType = GetClass(serializationObject.customType);
    if (blockType) {
      const block = new blockType;
      block._deserialize(serializationObject, scene, rootUrl);
      return block;
    }
    return null;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.customType = "BABYLON." + this.getClassName();
    serializationObject.id = this.uniqueId;
    serializationObject.name = this.name;
    serializationObject.comments = this.comments;
    serializationObject.visibleInInspector = this.visibleInInspector;
    serializationObject.visibleOnFrame = this.visibleOnFrame;
    serializationObject.target = this.target;
    serializationObject.inputs = [];
    serializationObject.outputs = [];
    for (const input of this.inputs) {
      serializationObject.inputs.push(input.serialize());
    }
    for (const output of this.outputs) {
      serializationObject.outputs.push(output.serialize(false));
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl, urlRewriter) {
    this.name = serializationObject.name;
    this.comments = serializationObject.comments;
    this.visibleInInspector = !!serializationObject.visibleInInspector;
    this.visibleOnFrame = !!serializationObject.visibleOnFrame;
    this._target = serializationObject.target ?? this.target;
    this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);
  }
  _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) {
    const serializedInputs = serializationObject.inputs;
    const serializedOutputs = serializationObject.outputs;
    if (serializedInputs) {
      serializedInputs.forEach((port, i) => {
        if (port.displayName) {
          this.inputs[i].displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          this.inputs[i].isExposedOnFrame = port.isExposedOnFrame;
          this.inputs[i].exposedPortPosition = port.exposedPortPosition;
        }
      });
    }
    if (serializedOutputs) {
      serializedOutputs.forEach((port, i) => {
        if (port.displayName) {
          this.outputs[i].displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;
          this.outputs[i].exposedPortPosition = port.exposedPortPosition;
        }
      });
    }
  }
  dispose() {
    this.onCodeIsReadyObservable.clear();
    for (const input of this.inputs) {
      input.dispose();
    }
    for (const output of this.outputs) {
      output.dispose();
    }
  }
}

// node_modules/@babylonjs/core/Materials/Node/Blocks/transformBlock.js
init_typeStore();
class TransformBlock extends NodeMaterialBlock {
  get transformAsDirection() {
    return this.complementW === 0;
  }
  set transformAsDirection(value) {
    this.complementW = value ? 0 : 1;
  }
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Neutral);
    this.complementW = 1;
    this.complementZ = 0;
    this.target = NodeMaterialBlockTargets.Vertex;
    this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("transform", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._inputs[0].onConnectionObservable.add((other) => {
      if (other.ownerBlock.isInput) {
        const otherAsInput = other.ownerBlock;
        if (otherAsInput.name === "normal" || otherAsInput.name === "tangent") {
          this.complementW = 0;
        }
      }
    });
  }
  getClassName() {
    return "TransformBlock";
  }
  get vector() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  get xyz() {
    return this._outputs[1];
  }
  get transform() {
    return this._inputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const vector = this.vector;
    const transform = this.transform;
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    if (vector.connectedPoint) {
      if (this.complementW === 0 || this.transformAsDirection) {
        const comments = `//${this.name}`;
        state._emitFunctionFromInclude("helperFunctions", comments);
        state.sharedData.blocksWithDefines.push(this);
        const transformName = state._getFreeVariableName(`${transform.associatedVariableName}_NUS`);
        if (state.shaderLanguage === 1) {
          state.compilationString += `var ${transformName}: mat3x3f = mat3x3f(${transform.associatedVariableName}[0].xyz, ${transform.associatedVariableName}[1].xyz, ${transform.associatedVariableName}[2].xyz);
`;
        } else {
          state.compilationString += `mat3 ${transformName} = mat3(${transform.associatedVariableName});
`;
        }
        state.compilationString += `#ifdef NONUNIFORMSCALING
`;
        state.compilationString += `${transformName} = transposeMat3(inverseMat3(${transformName}));
`;
        state.compilationString += `#endif
`;
        switch (vector.connectedPoint.type) {
          case NodeMaterialBlockConnectionPointTypes.Vector2:
            state.compilationString += state._declareOutput(this.output) + ` = ${vec4}(${transformName} * ${vec3}(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});
`;
            break;
          case NodeMaterialBlockConnectionPointTypes.Vector3:
          case NodeMaterialBlockConnectionPointTypes.Color3:
            state.compilationString += state._declareOutput(this.output) + ` = ${vec4}(${transformName} * ${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});
`;
            break;
          default:
            state.compilationString += state._declareOutput(this.output) + ` = ${vec4}(${transformName} * ${vector.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});
`;
            break;
        }
      } else {
        const transformName = transform.associatedVariableName;
        switch (vector.connectedPoint.type) {
          case NodeMaterialBlockConnectionPointTypes.Vector2:
            state.compilationString += state._declareOutput(this.output) + ` = ${transformName} * ${vec4}(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});
`;
            break;
          case NodeMaterialBlockConnectionPointTypes.Vector3:
          case NodeMaterialBlockConnectionPointTypes.Color3:
            state.compilationString += state._declareOutput(this.output) + ` = ${transformName} * ${vec4}(${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});
`;
            break;
          default:
            state.compilationString += state._declareOutput(this.output) + ` = ${transformName} * ${vector.associatedVariableName};
`;
            break;
        }
      }
      if (this.xyz.hasEndpoints) {
        state.compilationString += state._declareOutput(this.xyz) + ` = ${this.output.associatedVariableName}.xyz;
`;
      }
    }
    return this;
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (mesh.nonUniformScaling) {
      defines.setValue("NONUNIFORMSCALING", true);
    }
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.complementZ = this.complementZ;
    serializationObject.complementW = this.complementW;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0;
    this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.complementZ = ${this.complementZ};
`;
    codeString += `${this._codeVariableName}.complementW = ${this.complementW};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Transform as direction", 0, undefined, { embedded: true })
], TransformBlock.prototype, "transformAsDirection", null);
RegisterClass("BABYLON.TransformBlock", TransformBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/vertexOutputBlock.js
init_typeStore();

class VertexOutputBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Vertex, true);
    this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "VertexOutputBlock";
  }
  get vector() {
    return this._inputs[0];
  }
  _isLogarithmicDepthEnabled(nodeList, useLogarithmicDepth) {
    if (useLogarithmicDepth) {
      return true;
    }
    for (const node of nodeList) {
      if (node.useLogarithmicDepth) {
        return true;
      }
    }
    return false;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const input = this.vector;
    const isWebGPU = state.shaderLanguage === 1;
    if (state.shaderLanguage === 1) {
      state.compilationString += `vertexOutputs.position = ${input.associatedVariableName};
`;
    } else {
      state.compilationString += `gl_Position = ${input.associatedVariableName};
`;
    }
    if (this._isLogarithmicDepthEnabled(state.sharedData.fragmentOutputNodes, state.sharedData.nodeMaterial.useLogarithmicDepth)) {
      state._emitUniformFromString("logarithmicDepthConstant", NodeMaterialBlockConnectionPointTypes.Float);
      state._emitVaryingFromString("vFragmentDepth", NodeMaterialBlockConnectionPointTypes.Float);
      const fragDepth = isWebGPU ? "vertexOutputs.vFragmentDepth" : "vFragmentDepth";
      const uniformP = isWebGPU ? "uniforms." : "";
      const position = isWebGPU ? "vertexOutputs.position" : "gl_Position";
      state.compilationString += `${fragDepth} = 1.0 + ${position}.w;
`;
      state.compilationString += `${position}.z = log2(max(0.000001, ${fragDepth})) * ${uniformP}logarithmicDepthConstant;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.VertexOutputBlock", VertexOutputBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragmentOutputBlock.js
init_tslib_es6();
init_typeStore();
init_materialHelper_functions();
var FragmentOutputBlockColorSpace;
(function(FragmentOutputBlockColorSpace2) {
  FragmentOutputBlockColorSpace2[FragmentOutputBlockColorSpace2["NoColorSpace"] = 0] = "NoColorSpace";
  FragmentOutputBlockColorSpace2[FragmentOutputBlockColorSpace2["Gamma"] = 1] = "Gamma";
  FragmentOutputBlockColorSpace2[FragmentOutputBlockColorSpace2["Linear"] = 2] = "Linear";
})(FragmentOutputBlockColorSpace || (FragmentOutputBlockColorSpace = {}));

class FragmentOutputBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Fragment, true, true);
    this.convertToGammaSpace = false;
    this.convertToLinearSpace = false;
    this.useLogarithmicDepth = false;
    this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true);
    this.registerInput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("glow", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
    this.rgb.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this.additionalColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
    this.additionalColor.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
  }
  get colorSpace() {
    if (this.convertToGammaSpace) {
      return FragmentOutputBlockColorSpace.Gamma;
    }
    if (this.convertToLinearSpace) {
      return FragmentOutputBlockColorSpace.Linear;
    }
    return FragmentOutputBlockColorSpace.NoColorSpace;
  }
  set colorSpace(value) {
    this.convertToGammaSpace = value === FragmentOutputBlockColorSpace.Gamma;
    this.convertToLinearSpace = value === FragmentOutputBlockColorSpace.Linear;
  }
  getClassName() {
    return "FragmentOutputBlock";
  }
  initialize(state) {
    state._excludeVariableName("logarithmicDepthConstant");
    state._excludeVariableName("vFragmentDepth");
  }
  get rgba() {
    return this._inputs[0];
  }
  get rgb() {
    return this._inputs[1];
  }
  get a() {
    return this._inputs[2];
  }
  get additionalColor() {
    return this._inputs[3];
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    defines.setValue(this._linearDefineName, this.convertToLinearSpace, true);
    defines.setValue(this._gammaDefineName, this.convertToGammaSpace, true);
    defines.setValue(this._additionalColorDefineName, this.additionalColor.connectedPoint && nodeMaterial._useAdditionalColor, true);
  }
  bind(effect, nodeMaterial, mesh) {
    if ((this.useLogarithmicDepth || nodeMaterial.useLogarithmicDepth) && mesh) {
      BindLogDepth(undefined, effect, mesh.getScene());
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const rgba = this.rgba;
    const rgb = this.rgb;
    const a = this.a;
    const additionalColor = this.additionalColor;
    const isWebGPU = state.shaderLanguage === 1;
    state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected;
    state.sharedData.blocksWithDefines.push(this);
    if (this.useLogarithmicDepth || state.sharedData.nodeMaterial.useLogarithmicDepth) {
      state._emitUniformFromString("logarithmicDepthConstant", NodeMaterialBlockConnectionPointTypes.Float);
      state._emitVaryingFromString("vFragmentDepth", NodeMaterialBlockConnectionPointTypes.Float);
      state.sharedData.bindableBlocks.push(this);
    }
    if (additionalColor.connectedPoint) {
      state._excludeVariableName("useAdditionalColor");
      state._emitUniformFromString("useAdditionalColor", NodeMaterialBlockConnectionPointTypes.Float);
      this._additionalColorDefineName = state._getFreeDefineName("USEADDITIONALCOLOR");
    }
    this._linearDefineName = state._getFreeDefineName("CONVERTTOLINEAR");
    this._gammaDefineName = state._getFreeDefineName("CONVERTTOGAMMA");
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    let outputString = "gl_FragColor";
    if (state.shaderLanguage === 1) {
      state.compilationString += `var fragmentOutputsColor : vec4<f32>;\r
`;
      outputString = "fragmentOutputsColor";
    }
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    if (additionalColor.connectedPoint) {
      let aValue = "1.0";
      if (a.connectedPoint) {
        aValue = a.associatedVariableName;
      }
      state.compilationString += `#ifdef ${this._additionalColorDefineName}
`;
      if (additionalColor.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) {
        state.compilationString += `${outputString}  = ${vec4}(${additionalColor.associatedVariableName}, ${additionalColor.associatedVariableName}, ${additionalColor.associatedVariableName}, ${aValue});
`;
      } else {
        state.compilationString += `${outputString}  = ${vec4}(${additionalColor.associatedVariableName}, ${aValue});
`;
      }
      state.compilationString += `#else
`;
    }
    if (rgba.connectedPoint) {
      if (a.isConnected) {
        state.compilationString += `${outputString} = ${vec4}(${rgba.associatedVariableName}.rgb, ${a.associatedVariableName});
`;
      } else {
        state.compilationString += `${outputString}  = ${rgba.associatedVariableName};
`;
      }
    } else if (rgb.connectedPoint) {
      let aValue = "1.0";
      if (a.connectedPoint) {
        aValue = a.associatedVariableName;
      }
      if (rgb.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) {
        state.compilationString += `${outputString}  = ${vec4}(${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${aValue});
`;
      } else {
        state.compilationString += `${outputString}  = ${vec4}(${rgb.associatedVariableName}, ${aValue});
`;
      }
    } else {
      state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba);
    }
    if (additionalColor.connectedPoint) {
      state.compilationString += `#endif
`;
    }
    state.compilationString += `#ifdef ${this._linearDefineName}
`;
    state.compilationString += `${outputString}  = toLinearSpace(${outputString});
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef ${this._gammaDefineName}
`;
    state.compilationString += `${outputString}  = toGammaSpace(${outputString});
`;
    state.compilationString += `#endif
`;
    if (state.shaderLanguage === 1) {
      state.compilationString += `#if !defined(PREPASS)\r
`;
      state.compilationString += `fragmentOutputs.color = fragmentOutputsColor;\r
`;
      state.compilationString += `#endif\r
`;
    }
    if (this.useLogarithmicDepth || state.sharedData.nodeMaterial.useLogarithmicDepth) {
      const fragDepth = isWebGPU ? "input.vFragmentDepth" : "vFragmentDepth";
      const uniformP = isWebGPU ? "uniforms." : "";
      const output = isWebGPU ? "fragmentOutputs.fragDepth" : "gl_FragDepthEXT";
      state.compilationString += `${output} = log2(${fragDepth}) * ${uniformP}logarithmicDepthConstant * 0.5;
`;
    }
    state.compilationString += `#if defined(PREPASS)\r
`;
    state.compilationString += `${isWebGPU ? "fragmentOutputs.fragData0" : "gl_FragData[0]"} = ${outputString};\r
`;
    state.compilationString += `#endif\r
`;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`;
    codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`;
    codeString += `${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    serializationObject.useLogarithmicDepth = this.useLogarithmicDepth;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertToGammaSpace = !!serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    this.useLogarithmicDepth = serializationObject.useLogarithmicDepth ?? false;
  }
}
__decorate([
  editableInPropertyPage("Use logarithmic depth", 0, "PROPERTIES", { embedded: true })
], FragmentOutputBlock.prototype, "useLogarithmicDepth", undefined);
__decorate([
  editableInPropertyPage("Color space", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "No color space", value: FragmentOutputBlockColorSpace.NoColorSpace },
      { label: "Gamma", value: FragmentOutputBlockColorSpace.Gamma },
      { label: "Linear", value: FragmentOutputBlockColorSpace.Linear }
    ]
  })
], FragmentOutputBlock.prototype, "colorSpace", null);
RegisterClass("BABYLON.FragmentOutputBlock", FragmentOutputBlock);

// node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialSystemValues.js
var NodeMaterialSystemValues;
(function(NodeMaterialSystemValues2) {
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["World"] = 1] = "World";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["View"] = 2] = "View";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["Projection"] = 3] = "Projection";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["ViewProjection"] = 4] = "ViewProjection";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["WorldView"] = 5] = "WorldView";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["WorldViewProjection"] = 6] = "WorldViewProjection";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["CameraPosition"] = 7] = "CameraPosition";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["FogColor"] = 8] = "FogColor";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["DeltaTime"] = 9] = "DeltaTime";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["CameraParameters"] = 10] = "CameraParameters";
  NodeMaterialSystemValues2[NodeMaterialSystemValues2["MaterialAlpha"] = 11] = "MaterialAlpha";
})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));

// node_modules/@babylonjs/core/Materials/Node/Blocks/Input/inputBlock.js
init_math_vector();
init_typeStore();
init_math();

// node_modules/@babylonjs/core/Materials/Node/Blocks/Input/animatedInputBlockTypes.js
var AnimatedInputBlockTypes;
(function(AnimatedInputBlockTypes2) {
  AnimatedInputBlockTypes2[AnimatedInputBlockTypes2["None"] = 0] = "None";
  AnimatedInputBlockTypes2[AnimatedInputBlockTypes2["Time"] = 1] = "Time";
  AnimatedInputBlockTypes2[AnimatedInputBlockTypes2["RealTime"] = 2] = "RealTime";
  AnimatedInputBlockTypes2[AnimatedInputBlockTypes2["MouseInfo"] = 3] = "MouseInfo";
})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {}));

// node_modules/@babylonjs/core/Materials/Node/Blocks/Input/inputBlock.js
init_observable();
init_precisionDate();
var remapAttributeName = {
  position2d: "position",
  particle_uv: "vUV",
  particle_color: "vColor",
  particle_texturemask: "textureMask",
  particle_positionw: "vPositionW"
};
var attributeInFragmentOnly = {
  particle_uv: true,
  particle_color: true,
  particle_texturemask: true,
  particle_positionw: true
};
var attributeAsUniform = {
  particle_texturemask: true
};
var attributeDefine = {
  normal: "NORMAL",
  tangent: "TANGENT",
  uv: "UV1",
  uv2: "UV2",
  uv3: "UV3",
  uv4: "UV4",
  uv5: "UV5",
  uv6: "UV6",
  uv7: "UV7",
  uv8: "UV8"
};

class InputBlock extends NodeMaterialBlock {
  get type() {
    if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {
      if (this.isUniform && this.value != null) {
        if (!isNaN(this.value)) {
          this._type = NodeMaterialBlockConnectionPointTypes.Float;
          return this._type;
        }
        switch (this.value.getClassName()) {
          case "Vector2":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector2;
            return this._type;
          case "Vector3":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector3;
            return this._type;
          case "Vector4":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector4;
            return this._type;
          case "Color3":
            this._type = NodeMaterialBlockConnectionPointTypes.Color3;
            return this._type;
          case "Color4":
            this._type = NodeMaterialBlockConnectionPointTypes.Color4;
            return this._type;
          case "Matrix":
            this._type = NodeMaterialBlockConnectionPointTypes.Matrix;
            return this._type;
        }
      }
      if (this.isAttribute) {
        switch (this.name) {
          case "splatIndex":
            this._type = NodeMaterialBlockConnectionPointTypes.Float;
            return this._type;
          case "position":
          case "normal":
          case "particle_positionw":
          case "splatPosition":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector3;
            return this._type;
          case "uv":
          case "uv2":
          case "uv3":
          case "uv4":
          case "uv5":
          case "uv6":
          case "position2d":
          case "particle_uv":
          case "splatScale":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector2;
            return this._type;
          case "matricesIndices":
          case "matricesWeights":
          case "matricesIndicesExtra":
          case "matricesWeightsExtra":
          case "world0":
          case "world1":
          case "world2":
          case "world3":
          case "tangent":
            this._type = NodeMaterialBlockConnectionPointTypes.Vector4;
            return this._type;
          case "color":
          case "instanceColor":
          case "particle_color":
          case "particle_texturemask":
          case "splatColor":
            this._type = NodeMaterialBlockConnectionPointTypes.Color4;
            return this._type;
        }
      }
      if (this.isSystemValue) {
        switch (this._systemValue) {
          case NodeMaterialSystemValues.World:
          case NodeMaterialSystemValues.WorldView:
          case NodeMaterialSystemValues.WorldViewProjection:
          case NodeMaterialSystemValues.View:
          case NodeMaterialSystemValues.ViewProjection:
          case NodeMaterialSystemValues.Projection:
            this._type = NodeMaterialBlockConnectionPointTypes.Matrix;
            return this._type;
          case NodeMaterialSystemValues.CameraPosition:
            this._type = NodeMaterialBlockConnectionPointTypes.Vector3;
            return this._type;
          case NodeMaterialSystemValues.FogColor:
            this._type = NodeMaterialBlockConnectionPointTypes.Color3;
            return this._type;
          case NodeMaterialSystemValues.DeltaTime:
          case NodeMaterialSystemValues.MaterialAlpha:
            this._type = NodeMaterialBlockConnectionPointTypes.Float;
            return this._type;
          case NodeMaterialSystemValues.CameraParameters:
            this._type = NodeMaterialBlockConnectionPointTypes.Vector4;
            return this._type;
        }
      }
    }
    return this._type;
  }
  constructor(name325, target = NodeMaterialBlockTargets.Vertex, type = NodeMaterialBlockConnectionPointTypes.AutoDetect) {
    super(name325, target, false);
    this._mode = 3;
    this._animationType = AnimatedInputBlockTypes.None;
    this._prefix = "";
    this.min = 0;
    this.max = 0;
    this.isBoolean = false;
    this.matrixMode = 0;
    this._systemValue = null;
    this.isConstant = false;
    this.groupInInspector = "";
    this.onValueChangedObservable = new Observable;
    this.convertToGammaSpace = false;
    this.convertToLinearSpace = false;
    this._type = type;
    this.setDefaultValue();
    this.registerOutput("output", type);
  }
  validateBlockName(newName) {
    if (!this.isAttribute) {
      return super.validateBlockName(newName);
    }
    return true;
  }
  get output() {
    return this._outputs[0];
  }
  setAsAttribute(attributeName) {
    this._mode = 1;
    if (attributeName) {
      this.name = attributeName;
    }
    return this;
  }
  setAsSystemValue(value) {
    this.systemValue = value;
    return this;
  }
  get value() {
    return this._storedValue;
  }
  set value(value) {
    if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {
      if (this.isBoolean) {
        value = value ? 1 : 0;
      } else if (this.min !== this.max) {
        value = Math.max(this.min, value);
        value = Math.min(this.max, value);
      }
    }
    this._storedValue = value;
    this._mode = 0;
    this.onValueChangedObservable.notifyObservers(this);
  }
  get valueCallback() {
    return this._valueCallback;
  }
  set valueCallback(value) {
    this._valueCallback = value;
    this._mode = 0;
  }
  get declarationVariableName() {
    return this._associatedVariableName;
  }
  get associatedVariableName() {
    return this._prefix + this._associatedVariableName;
  }
  set associatedVariableName(value) {
    this._associatedVariableName = value;
  }
  get animationType() {
    return this._animationType;
  }
  set animationType(value) {
    this._animationType = value;
  }
  get isUndefined() {
    return this._mode === 3;
  }
  get isUniform() {
    return this._mode === 0;
  }
  set isUniform(value) {
    this._mode = value ? 0 : 3;
    this.associatedVariableName = "";
  }
  get isAttribute() {
    return this._mode === 1;
  }
  set isAttribute(value) {
    this._mode = value ? 1 : 3;
    this.associatedVariableName = "";
  }
  get isVarying() {
    return this._mode === 2;
  }
  set isVarying(value) {
    this._mode = value ? 2 : 3;
    this.associatedVariableName = "";
  }
  get isSystemValue() {
    return this._systemValue != null;
  }
  get systemValue() {
    return this._systemValue;
  }
  set systemValue(value) {
    this._mode = 0;
    this.associatedVariableName = "";
    this._systemValue = value;
  }
  getClassName() {
    return "InputBlock";
  }
  animate(scene) {
    switch (this._animationType) {
      case AnimatedInputBlockTypes.Time: {
        if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {
          this.value += scene.getAnimationRatio() * 0.01;
        }
        break;
      }
      case AnimatedInputBlockTypes.RealTime: {
        if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {
          this.value = (PrecisionDate.Now - scene.getEngine().startTime) / 1000;
        }
        break;
      }
      case AnimatedInputBlockTypes.MouseInfo: {
        if (this.type === NodeMaterialBlockConnectionPointTypes.Vector4) {
          const event = scene._inputManager._originMouseEvent;
          if (event) {
            const x = event.offsetX;
            const y = event.offsetY;
            const z = (event.buttons & 1) != 0 ? 1 : 0;
            const w = (event.buttons & 2) != 0 ? 1 : 0;
            this.value = new Vector4(x, y, z, w);
          } else {
            this.value = new Vector4(0, 0, 0, 0);
          }
        }
        break;
      }
    }
  }
  _emitDefine(define) {
    if (define[0] === "!") {
      return `#ifndef ${define.substring(1)}
`;
    }
    return `#ifdef ${define}
`;
  }
  initialize() {
    this.associatedVariableName = "";
  }
  setDefaultValue() {
    switch (this.type) {
      case NodeMaterialBlockConnectionPointTypes.Float:
        this.value = 0;
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector2:
        this.value = Vector2.Zero();
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        this.value = Vector3.Zero();
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        this.value = Vector4.Zero();
        break;
      case NodeMaterialBlockConnectionPointTypes.Color3:
        this.value = Color3.White();
        break;
      case NodeMaterialBlockConnectionPointTypes.Color4:
        this.value = new Color4(1, 1, 1, 1);
        break;
      case NodeMaterialBlockConnectionPointTypes.Matrix:
        this.value = Matrix.Identity();
        break;
    }
  }
  _emitConstant(state) {
    switch (this.type) {
      case NodeMaterialBlockConnectionPointTypes.Float:
        return `${state._emitFloat(this.value)}`;
      case NodeMaterialBlockConnectionPointTypes.Vector2:
        return `vec2(${this.value.x}, ${this.value.y})`;
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        return `vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        return `vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;
      case NodeMaterialBlockConnectionPointTypes.Color3:
        TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);
        if (this.convertToGammaSpace) {
          TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);
        }
        if (this.convertToLinearSpace) {
          TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);
        }
        return `vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`;
      case NodeMaterialBlockConnectionPointTypes.Color4:
        TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);
        if (this.convertToGammaSpace) {
          TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);
        }
        if (this.convertToLinearSpace) {
          TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);
        }
        return `vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`;
    }
    return "";
  }
  get _noContextSwitch() {
    return attributeInFragmentOnly[this.name];
  }
  _emit(state, define) {
    if (this.isUniform) {
      if (!this._associatedVariableName) {
        this._associatedVariableName = state._getFreeVariableName("u_" + this.name);
      }
      if (this.isConstant) {
        if (state.constants.indexOf(this.associatedVariableName) !== -1) {
          return;
        }
        state.constants.push(this.associatedVariableName);
        state._constantDeclaration += state._declareOutput(this.output, true) + ` = ${this._emitConstant(state)};
`;
        return;
      }
      if (state.uniforms.indexOf(this.associatedVariableName) !== -1) {
        return;
      }
      state.uniforms.push(this.associatedVariableName);
      if (define) {
        state._uniformDeclaration += this._emitDefine(define);
      }
      const shaderType = state._getShaderType(this.type);
      if (state.shaderLanguage === 1) {
        state._uniformDeclaration += `uniform ${this._associatedVariableName}: ${shaderType};
`;
        this._prefix = "uniforms.";
      } else {
        state._uniformDeclaration += `uniform ${shaderType} ${this.associatedVariableName};
`;
      }
      if (define) {
        state._uniformDeclaration += `#endif
`;
      }
      const hints = state.sharedData.hints;
      if (this._systemValue !== null && this._systemValue !== undefined) {
        switch (this._systemValue) {
          case NodeMaterialSystemValues.WorldView:
            hints.needWorldViewMatrix = true;
            break;
          case NodeMaterialSystemValues.WorldViewProjection:
            hints.needWorldViewProjectionMatrix = true;
            break;
        }
      } else {
        if (this._animationType !== AnimatedInputBlockTypes.None) {
          state.sharedData.animatedInputs.push(this);
        }
      }
      return;
    }
    if (this.isAttribute) {
      this.associatedVariableName = remapAttributeName[this.name] ?? this.name;
      if (this.target === NodeMaterialBlockTargets.Vertex && state._vertexState) {
        if (attributeInFragmentOnly[this.name]) {
          if (attributeAsUniform[this.name]) {
            state._emitUniformFromString(this.declarationVariableName, this.type, define);
            if (state.shaderLanguage === 1) {
              this._prefix = `vertexInputs.`;
            }
          } else {
            state._emitVaryingFromString(this.declarationVariableName, this.type, define);
          }
        } else {
          this._emit(state._vertexState, define);
        }
        return;
      }
      const alreadyDeclared = state.attributes.indexOf(this.declarationVariableName) !== -1;
      if (!alreadyDeclared) {
        state.attributes.push(this.declarationVariableName);
      }
      if (attributeInFragmentOnly[this.name]) {
        if (attributeAsUniform[this.name]) {
          if (!alreadyDeclared) {
            state._emitUniformFromString(this.declarationVariableName, this.type, define);
          }
          if (state.shaderLanguage === 1) {
            this._prefix = `uniforms.`;
          }
        } else {
          if (!alreadyDeclared) {
            state._emitVaryingFromString(this.declarationVariableName, this.type, define);
          }
          if (state.shaderLanguage === 1) {
            this._prefix = `fragmentInputs.`;
          }
        }
      } else {
        if (define && !alreadyDeclared) {
          state._attributeDeclaration += this._emitDefine(define);
        }
        if (state.shaderLanguage === 1) {
          if (!alreadyDeclared) {
            const defineName = attributeDefine[this.name];
            if (defineName) {
              state._attributeDeclaration += `#ifdef ${defineName}
`;
              state._attributeDeclaration += `attribute ${this.declarationVariableName}: ${state._getShaderType(this.type)};
`;
              state._attributeDeclaration += `#else
`;
              state._attributeDeclaration += `var<private> ${this.declarationVariableName}: ${state._getShaderType(this.type)} = ${state._getShaderType(this.type)}(0.);
`;
              state._attributeDeclaration += `#endif
`;
            } else {
              state._attributeDeclaration += `attribute ${this.declarationVariableName}: ${state._getShaderType(this.type)};
`;
            }
          }
          this._prefix = `vertexInputs.`;
        } else {
          if (!alreadyDeclared) {
            const defineName = attributeDefine[this.name];
            if (defineName) {
              state._attributeDeclaration += `#ifdef ${defineName}
`;
              state._attributeDeclaration += `attribute ${state._getShaderType(this.type)} ${this.declarationVariableName};
`;
              state._attributeDeclaration += `#else
`;
              state._attributeDeclaration += `${state._getShaderType(this.type)} ${this.declarationVariableName} = ${state._getShaderType(this.type)}(0.);
`;
              state._attributeDeclaration += `#endif
`;
            } else {
              state._attributeDeclaration += `attribute ${state._getShaderType(this.type)} ${this.declarationVariableName};
`;
            }
          }
        }
        if (define && !alreadyDeclared) {
          state._attributeDeclaration += `#endif
`;
        }
      }
    }
  }
  _transmitWorld(effect, world, worldView, worldViewProjection) {
    if (!this._systemValue) {
      return;
    }
    const variableName = this._associatedVariableName;
    switch (this._systemValue) {
      case NodeMaterialSystemValues.World:
        effect.setMatrix(variableName, world);
        break;
      case NodeMaterialSystemValues.WorldView:
        effect.setMatrix(variableName, worldView);
        break;
      case NodeMaterialSystemValues.WorldViewProjection:
        effect.setMatrix(variableName, worldViewProjection);
        break;
    }
  }
  _transmit(effect, scene, material) {
    if (this.isAttribute) {
      return;
    }
    const variableName = this._associatedVariableName;
    if (this._systemValue) {
      switch (this._systemValue) {
        case NodeMaterialSystemValues.World:
        case NodeMaterialSystemValues.WorldView:
        case NodeMaterialSystemValues.WorldViewProjection:
          return;
        case NodeMaterialSystemValues.View:
          effect.setMatrix(variableName, scene.getViewMatrix());
          break;
        case NodeMaterialSystemValues.Projection:
          effect.setMatrix(variableName, scene.getProjectionMatrix());
          break;
        case NodeMaterialSystemValues.ViewProjection:
          effect.setMatrix(variableName, scene.getTransformMatrix());
          break;
        case NodeMaterialSystemValues.CameraPosition:
          scene.bindEyePosition(effect, variableName, true);
          break;
        case NodeMaterialSystemValues.FogColor:
          effect.setColor3(variableName, scene.fogColor);
          break;
        case NodeMaterialSystemValues.DeltaTime:
          effect.setFloat(variableName, scene.deltaTime / 1000);
          break;
        case NodeMaterialSystemValues.CameraParameters:
          if (scene.activeCamera) {
            effect.setFloat4(variableName, scene.getEngine().hasOriginBottomLeft ? -1 : 1, scene.activeCamera.minZ, scene.activeCamera.maxZ, 1 / scene.activeCamera.maxZ);
          }
          break;
        case NodeMaterialSystemValues.MaterialAlpha:
          effect.setFloat(variableName, material.alpha);
          break;
      }
      return;
    }
    const value = this._valueCallback ? this._valueCallback() : this._storedValue;
    if (value === null) {
      return;
    }
    switch (this.type) {
      case NodeMaterialBlockConnectionPointTypes.Float:
        effect.setFloat(variableName, value);
        break;
      case NodeMaterialBlockConnectionPointTypes.Int:
        effect.setInt(variableName, value);
        break;
      case NodeMaterialBlockConnectionPointTypes.Color3:
        TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);
        if (this.convertToGammaSpace) {
          TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);
        }
        if (this.convertToLinearSpace) {
          TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);
        }
        effect.setColor3(variableName, TmpColors.Color3[0]);
        break;
      case NodeMaterialBlockConnectionPointTypes.Color4:
        TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);
        if (this.convertToGammaSpace) {
          TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);
        }
        if (this.convertToLinearSpace) {
          TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);
        }
        effect.setDirectColor4(variableName, TmpColors.Color4[0]);
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector2:
        effect.setVector2(variableName, value);
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        effect.setVector3(variableName, value);
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        effect.setVector4(variableName, value);
        break;
      case NodeMaterialBlockConnectionPointTypes.Matrix:
        effect.setMatrix(variableName, value);
        break;
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.isUniform || this.isSystemValue) {
      state.sharedData.inputBlocks.push(this);
    }
    this._emit(state);
  }
  _dumpPropertiesCode() {
    const variableName = this._codeVariableName;
    if (this.isAttribute) {
      return super._dumpPropertiesCode() + `${variableName}.setAsAttribute("${this.name}");
`;
    }
    if (this.isSystemValue) {
      return super._dumpPropertiesCode() + `${variableName}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${NodeMaterialSystemValues[this._systemValue]});
`;
    }
    if (this.isUniform) {
      const codes = [];
      let valueString = "";
      switch (this.type) {
        case NodeMaterialBlockConnectionPointTypes.Float:
          valueString = `${this.value}`;
          break;
        case NodeMaterialBlockConnectionPointTypes.Vector2:
          valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;
          break;
        case NodeMaterialBlockConnectionPointTypes.Vector3:
          valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;
          break;
        case NodeMaterialBlockConnectionPointTypes.Vector4:
          valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;
          break;
        case NodeMaterialBlockConnectionPointTypes.Color3:
          valueString = `new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`;
          if (this.convertToGammaSpace) {
            valueString += ".toGammaSpace()";
          }
          if (this.convertToLinearSpace) {
            valueString += ".toLinearSpace()";
          }
          break;
        case NodeMaterialBlockConnectionPointTypes.Color4:
          valueString = `new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`;
          if (this.convertToGammaSpace) {
            valueString += ".toGammaSpace()";
          }
          if (this.convertToLinearSpace) {
            valueString += ".toLinearSpace()";
          }
          break;
        case NodeMaterialBlockConnectionPointTypes.Matrix:
          valueString = `BABYLON.Matrix.FromArray([${this.value.m}])`;
          break;
      }
      codes.push(`${variableName}.value = ${valueString}`);
      if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {
        codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`, `${variableName}.isBoolean = ${this.isBoolean}`, `${variableName}.matrixMode = ${this.matrixMode}`, `${variableName}.animationType = BABYLON.AnimatedInputBlockTypes.${AnimatedInputBlockTypes[this.animationType]}`);
      }
      codes.push(`${variableName}.isConstant = ${this.isConstant}`);
      codes.push("");
      return super._dumpPropertiesCode() + codes.join(`;
`);
    }
    return super._dumpPropertiesCode();
  }
  dispose() {
    this.onValueChangedObservable.clear();
    super.dispose();
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.type = this.type;
    serializationObject.mode = this._mode;
    serializationObject.systemValue = this._systemValue;
    serializationObject.animationType = this._animationType;
    serializationObject.min = this.min;
    serializationObject.max = this.max;
    serializationObject.isBoolean = this.isBoolean;
    serializationObject.matrixMode = this.matrixMode;
    serializationObject.isConstant = this.isConstant;
    serializationObject.groupInInspector = this.groupInInspector;
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    if (this._storedValue != null && this._mode === 0) {
      if (this._storedValue.asArray) {
        serializationObject.valueType = "BABYLON." + this._storedValue.getClassName();
        serializationObject.value = this._storedValue.asArray();
      } else {
        serializationObject.valueType = "number";
        serializationObject.value = this._storedValue;
      }
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    this._mode = serializationObject.mode;
    super._deserialize(serializationObject, scene, rootUrl);
    this._type = serializationObject.type;
    this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue;
    this._animationType = serializationObject.animationType;
    this.min = serializationObject.min || 0;
    this.max = serializationObject.max || 0;
    this.isBoolean = !!serializationObject.isBoolean;
    this.matrixMode = serializationObject.matrixMode || 0;
    this.isConstant = !!serializationObject.isConstant;
    this.groupInInspector = serializationObject.groupInInspector || "";
    this.convertToGammaSpace = !!serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    if (serializationObject.name === "tangent" && serializationObject.mode === 1 && serializationObject.type === NodeMaterialBlockConnectionPointTypes.Vector3) {
      this._type = NodeMaterialBlockConnectionPointTypes.Vector4;
    }
    if (!serializationObject.valueType) {
      return;
    }
    if (serializationObject.valueType === "number") {
      this._storedValue = serializationObject.value;
    } else {
      const valueType = GetClass(serializationObject.valueType);
      if (valueType) {
        this._storedValue = valueType.FromArray(serializationObject.value);
      }
    }
  }
}
RegisterClass("BABYLON.InputBlock", InputBlock);

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_typeStore();
init_decorators();
init_decorators_serialization();

// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/currentScreenBlock.js
init_typeStore();
init_texture();

class CurrentScreenBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.VertexAndFragment);
    this._samplerName = "textureSampler";
    this.convertToGammaSpace = false;
    this.convertToLinearSpace = false;
    this._isUnique = false;
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this._inputs[0]._prioritizeVertex = false;
  }
  getClassName() {
    return "CurrentScreenBlock";
  }
  get uv() {
    return this._inputs[0];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  initialize(state) {
    state._excludeVariableName(this._samplerName);
  }
  get target() {
    if (!this.uv.isConnected) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    if (this.uv.sourceBlock.isInput) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    return NodeMaterialBlockTargets.Fragment;
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);
    defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);
  }
  isReady() {
    if (this.texture && !this.texture.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  _injectVertexCode(state) {
    const uvInput = this.uv;
    if (uvInput.connectedPoint.ownerBlock.isInput) {
      const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;
      if (!uvInputOwnerBlock.isAttribute) {
        state._emitUniformFromString(uvInput.associatedVariableName, NodeMaterialBlockConnectionPointTypes.Vector2);
      }
    }
    this._mainUVName = "vMain" + uvInput.associatedVariableName;
    state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2);
    state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;
`;
    if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
      return;
    }
    this._writeTextureRead(state, true);
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        this._writeOutput(state, output, output.name, true);
      }
    }
  }
  _writeTextureRead(state, vertexMode = false) {
    const uvInput = this.uv;
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      const textureReadFunc2 = state.shaderLanguage === 0 ? `texture2D(${this._samplerName},` : `textureSampleLevel(${this._samplerName}, ${this._samplerName + `Sampler`},`;
      const complement = state.shaderLanguage === 0 ? "" : ", 0";
      state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc2} ${uvInput.associatedVariableName}${complement});
`;
      return;
    }
    const textureReadFunc = state.shaderLanguage === 0 ? `texture2D(${this._samplerName},` : `textureSample(${this._samplerName}, ${this._samplerName + `Sampler`},`;
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${uvInput.associatedVariableName});
`;
      return;
    }
    state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${this._mainUVName});
`;
  }
  _writeOutput(state, output, swizzle, vertexMode = false) {
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      return;
    }
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      return;
    }
    state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
    state.compilationString += `#ifdef ${this._linearDefineName}
`;
    state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef ${this._gammaDefineName}
`;
    state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});
`;
    state.compilationString += `#endif
`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
    if (state.sharedData.blockingBlocks.indexOf(this) < 0) {
      state.sharedData.blockingBlocks.push(this);
    }
    if (state.sharedData.textureBlocks.indexOf(this) < 0) {
      state.sharedData.textureBlocks.push(this);
    }
    if (state.sharedData.blocksWithDefines.indexOf(this) < 0) {
      state.sharedData.blocksWithDefines.push(this);
    }
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      state._emit2DSampler(this._samplerName);
      this._injectVertexCode(state);
      return;
    }
    if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {
      return;
    }
    state._emit2DSampler(this._samplerName);
    this._linearDefineName = state._getFreeDefineName("ISLINEAR");
    this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    this._writeTextureRead(state);
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        this._writeOutput(state, output, output.name);
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    if (this.texture && !this.texture.isRenderTarget) {
      serializationObject.texture = this.texture.serialize();
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertToGammaSpace = serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    if (serializationObject.texture) {
      rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
      this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
    }
  }
}
RegisterClass("BABYLON.CurrentScreenBlock", CurrentScreenBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleTextureBlock.js
init_typeStore();
init_texture();

class ParticleTextureBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Fragment);
    this._samplerName = "diffuseSampler";
    this.convertToGammaSpace = false;
    this.convertToLinearSpace = false;
    this._isUnique = false;
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ParticleTextureBlock";
  }
  get uv() {
    return this._inputs[0];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  initialize(state) {
    state._excludeVariableName("diffuseSampler");
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.uv.isConnected) {
      let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "particle_uv" && additionalFilteringInfo(b));
      if (!uvInput) {
        uvInput = new InputBlock("uv");
        uvInput.setAsAttribute("particle_uv");
      }
      uvInput.output.connectTo(this.uv);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);
    defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);
  }
  isReady() {
    if (this.texture && !this.texture.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  _writeOutput(state, output, swizzle) {
    state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
    state.compilationString += `#ifdef ${this._linearDefineName}
`;
    state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef ${this._gammaDefineName}
`;
    state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});
`;
    state.compilationString += `#endif
`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      return;
    }
    this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
    state._emit2DSampler(this._samplerName);
    state.sharedData.blockingBlocks.push(this);
    state.sharedData.textureBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    this._linearDefineName = state._getFreeDefineName("ISLINEAR");
    this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${state._generateTextureSample(this.uv.associatedVariableName, this._samplerName)};
`;
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        this._writeOutput(state, output, output.name);
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    if (this.texture && !this.texture.isRenderTarget) {
      serializationObject.texture = this.texture.serialize();
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertToGammaSpace = serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    if (serializationObject.texture) {
      rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
      this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
    }
  }
}
RegisterClass("BABYLON.ParticleTextureBlock", ParticleTextureBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleRampGradientBlock.js
init_typeStore();

class ParticleRampGradientBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Fragment);
    this._isUnique = true;
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("rampColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "ParticleRampGradientBlock";
  }
  get color() {
    return this._inputs[0];
  }
  get rampColor() {
    return this._outputs[0];
  }
  initialize(state) {
    state._excludeVariableName("remapRanges");
    state._excludeVariableName("rampSampler");
    state._excludeVariableName("baseColor");
    state._excludeVariableName("alpha");
    state._excludeVariableName("remappedColorIndex");
    state._excludeVariableName("rampColor");
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      return;
    }
    state._emit2DSampler("rampSampler", "RAMPGRADIENT");
    state._emitVaryingFromString("remapRanges", NodeMaterialBlockConnectionPointTypes.Vector4, "RAMPGRADIENT");
    const varyingString = state.shaderLanguage === 0 ? "" : "fragmentInputs.";
    state.compilationString += `
            #ifdef RAMPGRADIENT
                ${state._declareLocalVar("baseColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.color.associatedVariableName};
                ${state._declareLocalVar("alpha", NodeMaterialBlockConnectionPointTypes.Float)} = ${this.color.associatedVariableName}.a;

                ${state._declareLocalVar("remappedColorIndex", NodeMaterialBlockConnectionPointTypes.Float)} = clamp((alpha - ${varyingString}remapRanges.x) / ${varyingString}remapRanges.y, 0.0, 1.0);

                ${state._declareLocalVar("rampColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${state._generateTextureSample("vec2(1.0 - remappedColorIndex, 0.)", "rampSampler")};

                // Remapped alpha
                ${state._declareOutput(this.rampColor)} = vec4${state.fSuffix}(baseColor.rgb * rampColor.rgb, clamp((alpha * rampColor.a - ${varyingString}remapRanges.z) / ${varyingString}remapRanges.w, 0.0, 1.0));
            #else
                ${state._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};
            #endif
        `;
    return this;
  }
}
RegisterClass("BABYLON.ParticleRampGradientBlock", ParticleRampGradientBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.js
init_typeStore();

class ParticleBlendMultiplyBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Fragment);
    this._isUnique = true;
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("alphaTexture", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("alphaColor", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("blendColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "ParticleBlendMultiplyBlock";
  }
  get color() {
    return this._inputs[0];
  }
  get alphaTexture() {
    return this._inputs[1];
  }
  get alphaColor() {
    return this._inputs[2];
  }
  get blendColor() {
    return this._outputs[0];
  }
  initialize(state) {
    state._excludeVariableName("sourceAlpha");
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      return;
    }
    state.compilationString += `
            #ifdef BLENDMULTIPLYMODE
                ${state._declareOutput(this.blendColor)};
                ${state._declareLocalVar("sourceAlpha", NodeMaterialBlockConnectionPointTypes.Float)}  = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};
                ${this.blendColor.associatedVariableName} = vec4${state.fSuffix}(${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha), ${this.color.associatedVariableName}.a);
            #else
                ${state._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};
            #endif
        `;
    return this;
  }
}
RegisterClass("BABYLON.ParticleBlendMultiplyBlock", ParticleBlendMultiplyBlock);

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_webRequest();
init_postProcess();

// node_modules/@babylonjs/core/Materials/Node/Blocks/vectorMergerBlock.js
init_typeStore();

class VectorMergerBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Neutral);
    this.xSwizzle = "x";
    this.ySwizzle = "y";
    this.zSwizzle = "z";
    this.wSwizzle = "w";
    this.registerInput("xyzw ", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true);
    this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true);
    this.registerInput("zw ", NodeMaterialBlockConnectionPointTypes.Vector2, true);
    this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("z", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("w", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "VectorMergerBlock";
  }
  get xyzwIn() {
    return this._inputs[0];
  }
  get xyzIn() {
    return this._inputs[1];
  }
  get xyIn() {
    return this._inputs[2];
  }
  get zwIn() {
    return this._inputs[3];
  }
  get x() {
    return this._inputs[4];
  }
  get y() {
    return this._inputs[5];
  }
  get z() {
    return this._inputs[6];
  }
  get w() {
    return this._inputs[7];
  }
  get xyzw() {
    return this._outputs[0];
  }
  get xyzOut() {
    return this._outputs[1];
  }
  get xyOut() {
    return this._outputs[2];
  }
  get zwOut() {
    return this._outputs[3];
  }
  get xy() {
    return this.xyOut;
  }
  get xyz() {
    return this.xyzOut;
  }
  _inputRename(name325) {
    if (name325 === "xyzw ") {
      return "xyzwIn";
    }
    if (name325 === "xyz ") {
      return "xyzIn";
    }
    if (name325 === "xy ") {
      return "xyIn";
    }
    if (name325 === "zw ") {
      return "zwIn";
    }
    return name325;
  }
  _buildSwizzle(len) {
    const swizzle = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle;
    return "." + swizzle.substring(0, len);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const xInput = this.x;
    const yInput = this.y;
    const zInput = this.z;
    const wInput = this.w;
    const xyInput = this.xyIn;
    const zwInput = this.zwIn;
    const xyzInput = this.xyzIn;
    const xyzwInput = this.xyzwIn;
    const v4Output = this._outputs[0];
    const v3Output = this._outputs[1];
    const v2Output = this._outputs[2];
    const v2CompOutput = this._outputs[3];
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    const vec2 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector2);
    if (xyzwInput.isConnected) {
      if (v4Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v4Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(4)};
`;
      }
      if (v3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v3Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(3)};
`;
      }
      if (v2Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v2Output) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(2)};
`;
      }
    } else if (xyzInput.isConnected) {
      if (v4Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v4Output) + ` = ${vec4}(${xyzInput.associatedVariableName}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};
`;
      }
      if (v3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v3Output) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(3)};
`;
      }
      if (v2Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v2Output) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(2)};
`;
      }
    } else if (xyInput.isConnected) {
      if (v4Output.hasEndpoints) {
        if (zwInput.isConnected) {
          state.compilationString += state._declareOutput(v4Output) + ` = ${vec4}(${xyInput.associatedVariableName}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};
`;
        } else {
          state.compilationString += state._declareOutput(v4Output) + ` = ${vec4}(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};
`;
        }
      }
      if (v3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v3Output) + ` = ${vec3}(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"})${this._buildSwizzle(3)};
`;
      }
      if (v2Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v2Output) + ` = ${xyInput.associatedVariableName}${this._buildSwizzle(2)};
`;
      }
      if (v2CompOutput.hasEndpoints) {
        if (zwInput.isConnected) {
          state.compilationString += state._declareOutput(v2CompOutput) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};
`;
        } else {
          state.compilationString += state._declareOutput(v2CompOutput) + ` = ${vec2}(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};
`;
        }
      }
    } else {
      if (v4Output.hasEndpoints) {
        if (zwInput.isConnected) {
          state.compilationString += state._declareOutput(v4Output) + ` = ${vec4}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};
`;
        } else {
          state.compilationString += state._declareOutput(v4Output) + ` = ${vec4}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};
`;
        }
      }
      if (v3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v3Output) + ` = ${vec3}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"})${this._buildSwizzle(3)};
`;
      }
      if (v2Output.hasEndpoints) {
        state.compilationString += state._declareOutput(v2Output) + ` = ${vec2}(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"})${this._buildSwizzle(2)};
`;
      }
      if (v2CompOutput.hasEndpoints) {
        if (zwInput.isConnected) {
          state.compilationString += state._declareOutput(v2CompOutput) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};
`;
        } else {
          state.compilationString += state._declareOutput(v2CompOutput) + ` = ${vec2}(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};
`;
        }
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.xSwizzle = this.xSwizzle;
    serializationObject.ySwizzle = this.ySwizzle;
    serializationObject.zSwizzle = this.zSwizzle;
    serializationObject.wSwizzle = this.wSwizzle;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.xSwizzle = serializationObject.xSwizzle ?? "x";
    this.ySwizzle = serializationObject.ySwizzle ?? "y";
    this.zSwizzle = serializationObject.zSwizzle ?? "z";
    this.wSwizzle = serializationObject.wSwizzle ?? "w";
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";
`;
    codeString += `${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";
`;
    codeString += `${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";
`;
    codeString += `${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";
`;
    return codeString;
  }
}
RegisterClass("BABYLON.VectorMergerBlock", VectorMergerBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/remapBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
class RemapBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Neutral);
    this.sourceRange = new Vector2(-1, 1);
    this.targetRange = new Vector2(0, 1);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("sourceMin", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("sourceMax", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("targetMin", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("targetMax", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "RemapBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get sourceMin() {
    return this._inputs[1];
  }
  get sourceMax() {
    return this._inputs[2];
  }
  get targetMin() {
    return this._inputs[3];
  }
  get targetMax() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x);
    const sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y);
    const targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x);
    const targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);
    state.compilationString += state._declareOutput(output) + ` = ${targetMin} + (${this._inputs[0].associatedVariableName} - ${sourceMin}) * (${targetMax} - ${targetMin}) / (${sourceMax} - ${sourceMin});
`;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});
`;
    codeString += `${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.sourceRange = this.sourceRange.asArray();
    serializationObject.targetRange = this.targetRange.asArray();
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.sourceRange = Vector2.FromArray(serializationObject.sourceRange);
    this.targetRange = Vector2.FromArray(serializationObject.targetRange);
  }
}
__decorate([
  editableInPropertyPage("From", 3)
], RemapBlock.prototype, "sourceRange", undefined);
__decorate([
  editableInPropertyPage("To", 3)
], RemapBlock.prototype, "targetRange", undefined);
RegisterClass("BABYLON.RemapBlock", RemapBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/multiplyBlock.js
init_typeStore();

// node_modules/@babylonjs/core/Materials/Node/Blocks/baseMathBlock.js
class BaseMathBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this.output._typeConnectionSource = this.left;
    this._linkConnectionTypes(0, 1, true);
    this.left.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this.right.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._connectionObservers = [
      this.left.onTypeChangedObservable.add(() => this._updateInputOutputTypes()),
      this.right.onTypeChangedObservable.add(() => this._updateInputOutputTypes())
    ];
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _updateInputOutputTypes() {
    this.output._typeConnectionSource = this.left;
    if (this.left.isConnected && this.right.isConnected) {
      if (this.left.type === NodeMaterialBlockConnectionPointTypes.Int || this.left.type === NodeMaterialBlockConnectionPointTypes.Float && this.right.type !== NodeMaterialBlockConnectionPointTypes.Int) {
        this.output._typeConnectionSource = this.right;
      }
    } else if (this.left.isConnected !== this.right.isConnected) {
      this.output._typeConnectionSource = this.left.isConnected ? this.left : this.right;
    }
    if (this.left.isConnected || this.right.isConnected) {
      for (const [first, second] of [
        [this.left, this.right],
        [this.right, this.left]
      ]) {
        first.acceptedConnectionPointTypes = [NodeMaterialBlockConnectionPointTypes.Int, NodeMaterialBlockConnectionPointTypes.Float];
        if (second.isConnected) {
          first.acceptedConnectionPointTypes.push(second.type);
          if (second.type === NodeMaterialBlockConnectionPointTypes.Int || second.type === NodeMaterialBlockConnectionPointTypes.Float) {
            first.acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockConnectionPointTypes.Matrix);
          }
        }
      }
    }
  }
  dispose() {
    super.dispose();
    this._connectionObservers.forEach((observer2) => observer2.remove());
    this._connectionObservers.length = 0;
  }
}

// node_modules/@babylonjs/core/Materials/Node/Blocks/multiplyBlock.js
class MultiplyBlock extends BaseMathBlock {
  constructor(name325) {
    super(name325);
  }
  getClassName() {
    return "MultiplyBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.MultiplyBlock", MultiplyBlock);

// node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialModes.js
var NodeMaterialModes;
(function(NodeMaterialModes2) {
  NodeMaterialModes2[NodeMaterialModes2["Material"] = 0] = "Material";
  NodeMaterialModes2[NodeMaterialModes2["PostProcess"] = 1] = "PostProcess";
  NodeMaterialModes2[NodeMaterialModes2["Particle"] = 2] = "Particle";
  NodeMaterialModes2[NodeMaterialModes2["ProceduralTexture"] = 3] = "ProceduralTexture";
  NodeMaterialModes2[NodeMaterialModes2["GaussianSplatting"] = 4] = "GaussianSplatting";
})(NodeMaterialModes || (NodeMaterialModes = {}));

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_texture();

// node_modules/@babylonjs/core/Particles/baseParticleSystem.js
init_math_vector();

// node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.defines.js
class ImageProcessingConfigurationDefines extends MaterialDefines {
  constructor() {
    super();
    this.IMAGEPROCESSING = false;
    this.VIGNETTE = false;
    this.VIGNETTEBLENDMODEMULTIPLY = false;
    this.VIGNETTEBLENDMODEOPAQUE = false;
    this.TONEMAPPING = 0;
    this.CONTRAST = false;
    this.COLORCURVES = false;
    this.COLORGRADING = false;
    this.COLORGRADING3D = false;
    this.SAMPLER3DGREENDEPTH = false;
    this.SAMPLER3DBGRMAP = false;
    this.DITHER = false;
    this.IMAGEPROCESSINGPOSTPROCESS = false;
    this.EXPOSURE = false;
    this.SKIPFINALCOLORCLAMP = false;
    this.rebuild();
  }
}

// node_modules/@babylonjs/core/Particles/baseParticleSystem.js
init_math_color();
init_engine_dynamicBuffer();
init_typeStore();

class BaseParticleSystem {
  get noiseTexture() {
    return this._noiseTexture;
  }
  set noiseTexture(value) {
    if (this._noiseTexture === value) {
      return;
    }
    this._noiseTexture = value;
    this._reset();
  }
  get isAnimationSheetEnabled() {
    return this._isAnimationSheetEnabled;
  }
  set isAnimationSheetEnabled(value) {
    if (this._isAnimationSheetEnabled == value) {
      return;
    }
    this._isAnimationSheetEnabled = value;
    this._reset();
  }
  get useLogarithmicDepth() {
    return this._useLogarithmicDepth;
  }
  set useLogarithmicDepth(value) {
    this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  }
  getScene() {
    return this._scene;
  }
  _hasTargetStopDurationDependantGradient() {
    return this._startSizeGradients && this._startSizeGradients.length > 0 || this._emitRateGradients && this._emitRateGradients.length > 0 || this._lifeTimeGradients && this._lifeTimeGradients.length > 0;
  }
  getDragGradients() {
    return this._dragGradients;
  }
  getLimitVelocityGradients() {
    return this._limitVelocityGradients;
  }
  getColorGradients() {
    return this._colorGradients;
  }
  getSizeGradients() {
    return this._sizeGradients;
  }
  getColorRemapGradients() {
    return this._colorRemapGradients;
  }
  getAlphaRemapGradients() {
    return this._alphaRemapGradients;
  }
  getLifeTimeGradients() {
    return this._lifeTimeGradients;
  }
  getAngularSpeedGradients() {
    return this._angularSpeedGradients;
  }
  getVelocityGradients() {
    return this._velocityGradients;
  }
  getStartSizeGradients() {
    return this._startSizeGradients;
  }
  getEmitRateGradients() {
    return this._emitRateGradients;
  }
  get direction1() {
    if (this.particleEmitterType.direction1) {
      return this.particleEmitterType.direction1;
    }
    return Vector3.Zero();
  }
  set direction1(value) {
    if (this.particleEmitterType.direction1) {
      this.particleEmitterType.direction1 = value;
    }
  }
  get direction2() {
    if (this.particleEmitterType.direction2) {
      return this.particleEmitterType.direction2;
    }
    return Vector3.Zero();
  }
  set direction2(value) {
    if (this.particleEmitterType.direction2) {
      this.particleEmitterType.direction2 = value;
    }
  }
  get minEmitBox() {
    if (this.particleEmitterType.minEmitBox) {
      return this.particleEmitterType.minEmitBox;
    }
    return Vector3.Zero();
  }
  set minEmitBox(value) {
    if (this.particleEmitterType.minEmitBox) {
      this.particleEmitterType.minEmitBox = value;
    }
  }
  get maxEmitBox() {
    if (this.particleEmitterType.maxEmitBox) {
      return this.particleEmitterType.maxEmitBox;
    }
    return Vector3.Zero();
  }
  set maxEmitBox(value) {
    if (this.particleEmitterType.maxEmitBox) {
      this.particleEmitterType.maxEmitBox = value;
    }
  }
  get billboardMode() {
    return this._billboardMode;
  }
  set billboardMode(value) {
    if (this._billboardMode === value) {
      return;
    }
    this._billboardMode = value;
    this._reset();
  }
  get isBillboardBased() {
    return this._isBillboardBased;
  }
  set isBillboardBased(value) {
    if (this._isBillboardBased === value) {
      return;
    }
    this._isBillboardBased = value;
    this._reset();
  }
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    this._attachImageProcessingConfiguration(value);
  }
  _attachImageProcessingConfiguration(configuration) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (!configuration && this._scene) {
      this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
    } else {
      this._imageProcessingConfiguration = configuration;
    }
  }
  _reset() {}
  _removeGradientAndTexture(gradient, gradients, texture) {
    if (!gradients) {
      return this;
    }
    let index = 0;
    for (const valueGradient of gradients) {
      if (valueGradient.gradient === gradient) {
        gradients.splice(index, 1);
        break;
      }
      index++;
    }
    if (texture) {
      texture.dispose();
    }
    return this;
  }
  constructor(name325) {
    this.animations = [];
    this.renderingGroupId = 0;
    this.emitter = Vector3.Zero();
    this.emitRate = 10;
    this.manualEmitCount = -1;
    this.updateSpeed = 0.01;
    this.targetStopDuration = 0;
    this.disposeOnStop = false;
    this.minEmitPower = 1;
    this.maxEmitPower = 1;
    this.minLifeTime = 1;
    this.maxLifeTime = 1;
    this.minSize = 1;
    this.maxSize = 1;
    this.minScaleX = 1;
    this.maxScaleX = 1;
    this.minScaleY = 1;
    this.maxScaleY = 1;
    this.minInitialRotation = 0;
    this.maxInitialRotation = 0;
    this.minAngularSpeed = 0;
    this.maxAngularSpeed = 0;
    this.layerMask = 268435455;
    this.customShader = null;
    this.preventAutoStart = false;
    this.applyFog = false;
    this._wasDispatched = false;
    this._rootUrl = "";
    this.noiseStrength = new Vector3(10, 10, 10);
    this.onAnimationEnd = null;
    this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE;
    this.forceDepthWrite = false;
    this.preWarmCycles = 0;
    this.preWarmStepOffset = 1;
    this.spriteCellChangeSpeed = 1;
    this.startSpriteCellID = 0;
    this.endSpriteCellID = 0;
    this.spriteCellWidth = 0;
    this.spriteCellHeight = 0;
    this.spriteCellLoop = true;
    this.spriteRandomStartCell = false;
    this.translationPivot = new Vector2(0, 0);
    this.beginAnimationOnStart = false;
    this.beginAnimationFrom = 0;
    this.beginAnimationTo = 60;
    this.beginAnimationLoop = false;
    this.worldOffset = new Vector3(0, 0, 0);
    this._useLogarithmicDepth = false;
    this.gravity = Vector3.Zero();
    this._colorGradients = null;
    this._sizeGradients = null;
    this._lifeTimeGradients = null;
    this._angularSpeedGradients = null;
    this._velocityGradients = null;
    this._limitVelocityGradients = null;
    this._dragGradients = null;
    this._emitRateGradients = null;
    this._startSizeGradients = null;
    this._rampGradients = null;
    this._colorRemapGradients = null;
    this._alphaRemapGradients = null;
    this.startDelay = 0;
    this.limitVelocityDamping = 0.4;
    this.color1 = new Color4(1, 1, 1, 1);
    this.color2 = new Color4(1, 1, 1, 1);
    this.colorDead = new Color4(0, 0, 0, 1);
    this.textureMask = new Color4(1, 1, 1, 1);
    this._isSubEmitter = false;
    this._billboardMode = 7;
    this._isBillboardBased = true;
    this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines;
    this.id = name325;
    this.name = name325;
  }
  createPointEmitter(direction1, direction2) {
    throw new Error("Method not implemented.");
  }
  createHemisphericEmitter(radius = 1, radiusRange = 1) {
    throw new Error("Method not implemented.");
  }
  createSphereEmitter(radius = 1, radiusRange = 1) {
    throw new Error("Method not implemented.");
  }
  createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    throw new Error("Method not implemented.");
  }
  createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
    throw new Error("Method not implemented.");
  }
  createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    throw new Error("Method not implemented.");
  }
  createConeEmitter(radius = 1, angle = Math.PI / 4) {
    throw new Error("Method not implemented.");
  }
  createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    throw new Error("Method not implemented.");
  }
  createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {
    throw new Error("Method not implemented.");
  }
}
BaseParticleSystem.BLENDMODE_ONEONE = 0;
BaseParticleSystem.BLENDMODE_STANDARD = 1;
BaseParticleSystem.BLENDMODE_ADD = 2;
BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
RegisterClass("BABYLON.BaseParticleSystem", BaseParticleSystem);

// node_modules/@babylonjs/core/Materials/Node/Blocks/colorSplitterBlock.js
init_typeStore();

class ColorSplitterBlock extends NodeMaterialBlock {
  constructor(name325) {
    super(name325, NodeMaterialBlockTargets.Neutral);
    this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true);
    this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float);
    this.inputsAreExclusive = true;
  }
  getClassName() {
    return "ColorSplitterBlock";
  }
  get rgba() {
    return this._inputs[0];
  }
  get rgbIn() {
    return this._inputs[1];
  }
  get rgbOut() {
    return this._outputs[0];
  }
  get r() {
    return this._outputs[1];
  }
  get g() {
    return this._outputs[2];
  }
  get b() {
    return this._outputs[3];
  }
  get a() {
    return this._outputs[4];
  }
  _inputRename(name325) {
    if (name325 === "rgb ") {
      return "rgbIn";
    }
    return name325;
  }
  _outputRename(name325) {
    if (name325 === "rgb") {
      return "rgbOut";
    }
    return name325;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const input = this.rgba.isConnected ? this.rgba : this.rgbIn;
    if (!input.isConnected) {
      return;
    }
    const rgbOutput = this._outputs[0];
    const rOutput = this._outputs[1];
    const gOutput = this._outputs[2];
    const bOutput = this._outputs[3];
    const aOutput = this._outputs[4];
    if (rgbOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(rgbOutput) + ` = ${input.associatedVariableName}.rgb;
`;
    }
    if (rOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(rOutput) + ` = ${input.associatedVariableName}.r;
`;
    }
    if (gOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(gOutput) + ` = ${input.associatedVariableName}.g;
`;
    }
    if (bOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(bOutput) + ` = ${input.associatedVariableName}.b;
`;
    }
    if (aOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(aOutput) + ` = ${input.associatedVariableName}.a;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.ColorSplitterBlock", ColorSplitterBlock);

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_timingTools();

// node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.js
init_tslib_es6();
init_decorators();
init_observable();
init_buffer();
init_sceneComponent();
init_texture();
init_renderTargetTexture();

// node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTextureSceneComponent.js
init_tools();
init_sceneComponent();

class ProceduralTextureSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE;
    this.scene = scene;
  }
  register() {
    this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  }
  rebuild() {}
  dispose() {}
  _beforeClear() {
    if (this.scene.proceduralTexturesEnabled) {
      Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
      for (let proceduralIndex = 0;proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
        const proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
        if (proceduralTexture._shouldRender()) {
          proceduralTexture.render();
        }
      }
      Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
    }
  }
}

// node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.js
init_typeStore();
init_engineStore();
init_drawWrapper();

class ProceduralTexture extends Texture {
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(name327, size, fragment, scene, fallbackTexture = null, generateMipMaps = true, isCube = false, textureType = 0) {
    super(null, scene, !generateMipMaps);
    this.isEnabled = true;
    this.autoClear = true;
    this.onGeneratedObservable = new Observable;
    this.onBeforeGenerationObservable = new Observable;
    this.nodeMaterialSource = null;
    this.defines = "";
    this._textures = {};
    this._currentRefreshId = -1;
    this._frameId = -1;
    this._refreshRate = 1;
    this._vertexBuffers = {};
    this._uniforms = new Array;
    this._samplers = new Array;
    this._floats = {};
    this._ints = {};
    this._floatsArrays = {};
    this._colors3 = {};
    this._colors4 = {};
    this._vectors2 = {};
    this._vectors3 = {};
    this._vectors4 = {};
    this._matrices = {};
    this._fallbackTextureUsed = false;
    this._cachedDefines = null;
    this._contentUpdateId = -1;
    this._rtWrapper = null;
    if (fallbackTexture !== null && !(fallbackTexture instanceof Texture)) {
      this._options = fallbackTexture;
      this._fallbackTexture = fallbackTexture.fallbackTexture ?? null;
    } else {
      this._options = {};
      this._fallbackTexture = fallbackTexture;
    }
    this._shaderLanguage = this._options.shaderLanguage ?? 0;
    scene = this.getScene() || EngineStore.LastCreatedScene;
    let component = scene._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);
    if (!component) {
      component = new ProceduralTextureSceneComponent(scene);
      scene._addComponent(component);
    }
    scene.proceduralTextures.push(this);
    this._fullEngine = scene.getEngine();
    this.name = name327;
    this.isRenderTarget = true;
    this._size = size;
    this._textureType = textureType;
    this._generateMipMaps = generateMipMaps;
    this._drawWrapper = new DrawWrapper(this._fullEngine);
    this.setFragment(fragment);
    const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, textureType);
    this._texture = rtWrapper.texture;
    const vertices = [];
    vertices.push(1, 1);
    vertices.push(-1, 1);
    vertices.push(-1, -1);
    vertices.push(1, -1);
    this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._fullEngine, vertices, VertexBuffer.PositionKind, false, false, 2);
    this._createIndexBuffer();
  }
  _createRtWrapper(isCube, size, generateMipMaps, textureType) {
    if (isCube) {
      this._rtWrapper = this._fullEngine.createRenderTargetCubeTexture(size, {
        generateMipMaps,
        generateDepthBuffer: false,
        generateStencilBuffer: false,
        type: textureType,
        ...this._options
      });
      this.setFloat("face", 0);
    } else {
      this._rtWrapper = this._fullEngine.createRenderTargetTexture(size, {
        generateMipMaps,
        generateDepthBuffer: false,
        generateStencilBuffer: false,
        type: textureType,
        ...this._options
      });
      if (this._rtWrapper.is3D) {
        this.setFloat("layer", 0);
        this.setInt("layerNum", 0);
      }
    }
    return this._rtWrapper;
  }
  getEffect() {
    return this._drawWrapper.effect;
  }
  _setEffect(effect) {
    this._drawWrapper.effect = effect;
  }
  getContent() {
    if (this._contentData && this._frameId === this._contentUpdateId) {
      return this._contentData;
    }
    if (this._contentData) {
      this._contentData.then((buffer2) => {
        this._contentData = this.readPixels(0, 0, buffer2);
        this._contentUpdateId = this._frameId;
      });
    } else {
      this._contentData = this.readPixels(0, 0);
      this._contentUpdateId = this._frameId;
    }
    return this._contentData;
  }
  _createIndexBuffer() {
    const engine2 = this._fullEngine;
    const indices = [];
    indices.push(0);
    indices.push(1);
    indices.push(2);
    indices.push(0);
    indices.push(2);
    indices.push(3);
    this._indexBuffer = engine2.createIndexBuffer(indices);
  }
  _rebuild() {
    const vb = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vb) {
      vb._rebuild();
    }
    this._createIndexBuffer();
    if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
      this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
    }
  }
  reset() {
    this._drawWrapper.effect?.dispose();
    this._drawWrapper.effect = null;
    this._cachedDefines = null;
  }
  _getDefines() {
    return this.defines;
  }
  executeWhenReady(func) {
    if (this.isReady()) {
      func(this);
      return;
    }
    const effect = this.getEffect();
    if (effect) {
      effect.executeWhenCompiled(() => {
        func(this);
      });
    }
  }
  isReady() {
    const engine2 = this._fullEngine;
    if (this.nodeMaterialSource) {
      return this._drawWrapper.effect.isReady();
    }
    if (!this._fragment) {
      return false;
    }
    if (this._fallbackTextureUsed) {
      return true;
    }
    if (!this._texture) {
      return false;
    }
    const defines = this._getDefines();
    if (this._drawWrapper.effect && defines === this._cachedDefines && this._drawWrapper.effect.isReady()) {
      return true;
    }
    const shaders = {
      vertex: "procedural",
      fragmentElement: this._fragment.fragmentElement,
      fragmentSource: this._fragment.fragmentSource,
      fragment: typeof this._fragment === "string" ? this._fragment : undefined
    };
    if (this._cachedDefines !== defines) {
      this._cachedDefines = defines;
      this._drawWrapper.effect = engine2.createEffect(shaders, [VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, () => {
        this._rtWrapper?.dispose();
        this._rtWrapper = this._texture = null;
        if (this._fallbackTexture) {
          this._texture = this._fallbackTexture._texture;
          if (this._texture) {
            this._texture.incrementReferences();
          }
        }
        this._fallbackTextureUsed = true;
      }, undefined, this._shaderLanguage, async () => {
        if (this._options.extraInitializationsAsync) {
          if (this.shaderLanguage === 1) {
            await Promise.all([Promise.resolve().then(() => (init_procedural_vertex(), exports_procedural_vertex)), this._options.extraInitializationsAsync()]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_procedural_vertex2(), exports_procedural_vertex2)), this._options.extraInitializationsAsync()]);
          }
        } else {
          if (this.shaderLanguage === 1) {
            await Promise.resolve().then(() => (init_procedural_vertex(), exports_procedural_vertex));
          } else {
            await Promise.resolve().then(() => (init_procedural_vertex2(), exports_procedural_vertex2));
          }
        }
      });
    }
    return this._drawWrapper.effect.isReady();
  }
  resetRefreshCounter() {
    this._currentRefreshId = -1;
  }
  setFragment(fragment) {
    this._fragment = fragment;
  }
  get refreshRate() {
    return this._refreshRate;
  }
  set refreshRate(value) {
    this._refreshRate = value;
    this.resetRefreshCounter();
  }
  _shouldRender() {
    if (!this.isEnabled || !this.isReady() || !this._texture) {
      if (this._texture) {
        this._texture.isReady = false;
      }
      return false;
    }
    if (this._fallbackTextureUsed) {
      return false;
    }
    if (this._currentRefreshId === -1) {
      this._currentRefreshId = 1;
      this._frameId++;
      return true;
    }
    if (this.refreshRate === this._currentRefreshId) {
      this._currentRefreshId = 1;
      this._frameId++;
      return true;
    }
    this._currentRefreshId++;
    return false;
  }
  getRenderSize() {
    return this._size;
  }
  resize(size, generateMipMaps) {
    if (this._fallbackTextureUsed || !this._rtWrapper || !this._texture) {
      return;
    }
    const isCube = this._texture.isCube;
    this._rtWrapper.dispose();
    const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, this._textureType);
    this._texture = rtWrapper.texture;
    this._size = size;
    this._generateMipMaps = generateMipMaps;
  }
  _checkUniform(uniformName) {
    if (this._uniforms.indexOf(uniformName) === -1) {
      this._uniforms.push(uniformName);
    }
  }
  setTexture(name327, texture) {
    if (this._samplers.indexOf(name327) === -1) {
      this._samplers.push(name327);
    }
    this._textures[name327] = texture;
    return this;
  }
  setFloat(name327, value) {
    this._checkUniform(name327);
    this._floats[name327] = value;
    return this;
  }
  setInt(name327, value) {
    this._checkUniform(name327);
    this._ints[name327] = value;
    return this;
  }
  setFloats(name327, value) {
    this._checkUniform(name327);
    this._floatsArrays[name327] = value;
    return this;
  }
  setColor3(name327, value) {
    this._checkUniform(name327);
    this._colors3[name327] = value;
    return this;
  }
  setColor4(name327, value) {
    this._checkUniform(name327);
    this._colors4[name327] = value;
    return this;
  }
  setVector2(name327, value) {
    this._checkUniform(name327);
    this._vectors2[name327] = value;
    return this;
  }
  setVector3(name327, value) {
    this._checkUniform(name327);
    this._vectors3[name327] = value;
    return this;
  }
  setVector4(name327, value) {
    this._checkUniform(name327);
    this._vectors4[name327] = value;
    return this;
  }
  setMatrix(name327, value) {
    this._checkUniform(name327);
    this._matrices[name327] = value;
    return this;
  }
  render(useCameraPostProcess) {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    const engine2 = this._fullEngine;
    engine2.enableEffect(this._drawWrapper);
    this.onBeforeGenerationObservable.notifyObservers(this);
    engine2.setState(false);
    if (!this.nodeMaterialSource) {
      for (const name327 in this._textures) {
        this._drawWrapper.effect.setTexture(name327, this._textures[name327]);
      }
      for (const name327 in this._ints) {
        this._drawWrapper.effect.setInt(name327, this._ints[name327]);
      }
      for (const name327 in this._floats) {
        this._drawWrapper.effect.setFloat(name327, this._floats[name327]);
      }
      for (const name327 in this._floatsArrays) {
        this._drawWrapper.effect.setArray(name327, this._floatsArrays[name327]);
      }
      for (const name327 in this._colors3) {
        this._drawWrapper.effect.setColor3(name327, this._colors3[name327]);
      }
      for (const name327 in this._colors4) {
        const color = this._colors4[name327];
        this._drawWrapper.effect.setFloat4(name327, color.r, color.g, color.b, color.a);
      }
      for (const name327 in this._vectors2) {
        this._drawWrapper.effect.setVector2(name327, this._vectors2[name327]);
      }
      for (const name327 in this._vectors3) {
        this._drawWrapper.effect.setVector3(name327, this._vectors3[name327]);
      }
      for (const name327 in this._vectors4) {
        this._drawWrapper.effect.setVector4(name327, this._vectors4[name327]);
      }
      for (const name327 in this._matrices) {
        this._drawWrapper.effect.setMatrix(name327, this._matrices[name327]);
      }
    }
    if (!this._texture || !this._rtWrapper) {
      return;
    }
    engine2._debugPushGroup?.(`procedural texture generation for ${this.name}`, 1);
    const viewPort = engine2.currentViewport;
    if (this.isCube) {
      for (let face = 0;face < 6; face++) {
        engine2.bindFramebuffer(this._rtWrapper, face, undefined, undefined, true);
        engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);
        this._drawWrapper.effect.setFloat("face", face);
        if (this.autoClear) {
          engine2.clear(scene.clearColor, true, false, false);
        }
        engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
        engine2.unBindFramebuffer(this._rtWrapper, true);
      }
    } else {
      let numLayers = 1;
      if (this._rtWrapper.is3D) {
        numLayers = this._rtWrapper.depth;
      } else if (this._rtWrapper.is2DArray) {
        numLayers = this._rtWrapper.layers;
      }
      for (let layer = 0;layer < numLayers; layer++) {
        engine2.bindFramebuffer(this._rtWrapper, 0, undefined, undefined, true, 0, layer);
        engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);
        if (this._rtWrapper.is3D || this._rtWrapper.is2DArray) {
          this._drawWrapper.effect?.setFloat("layer", numLayers !== 1 ? layer / (numLayers - 1) : 0);
          this._drawWrapper.effect?.setInt("layerNum", layer);
          for (const name327 in this._textures) {
            this._drawWrapper.effect.setTexture(name327, this._textures[name327]);
          }
        }
        if (this.autoClear) {
          engine2.clear(scene.clearColor, true, false, false);
        }
        engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
        engine2.unBindFramebuffer(this._rtWrapper, !this._generateMipMaps);
      }
    }
    if (viewPort) {
      engine2.setViewport(viewPort);
    }
    if (this.isCube) {
      engine2.generateMipMapsForCubemap(this._texture, true);
    }
    engine2._debugPopGroup?.(1);
    if (this.onGenerated) {
      this.onGenerated();
    }
    this.onGeneratedObservable.notifyObservers(this);
  }
  clone() {
    const textureSize = this.getSize();
    const newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
    newTexture.hasAlpha = this.hasAlpha;
    newTexture.level = this.level;
    newTexture.coordinatesMode = this.coordinatesMode;
    return newTexture;
  }
  dispose() {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    const index = scene.proceduralTextures.indexOf(this);
    if (index >= 0) {
      scene.proceduralTextures.splice(index, 1);
    }
    const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vertexBuffer) {
      vertexBuffer.dispose();
      this._vertexBuffers[VertexBuffer.PositionKind] = null;
    }
    if (this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer)) {
      this._indexBuffer = null;
    }
    this.onGeneratedObservable.clear();
    this.onBeforeGenerationObservable.clear();
    super.dispose();
  }
}
__decorate([
  serialize()
], ProceduralTexture.prototype, "isEnabled", undefined);
__decorate([
  serialize()
], ProceduralTexture.prototype, "autoClear", undefined);
__decorate([
  serialize()
], ProceduralTexture.prototype, "_generateMipMaps", undefined);
__decorate([
  serialize()
], ProceduralTexture.prototype, "_size", undefined);
__decorate([
  serialize()
], ProceduralTexture.prototype, "refreshRate", null);
RegisterClass("BABYLON.ProceduralTexture", ProceduralTexture);

// node_modules/@babylonjs/core/Materials/Node/Blocks/trigonometryBlock.js
init_tslib_es6();
init_typeStore();
var TrigonometryBlockOperations;
(function(TrigonometryBlockOperations2) {
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Cos"] = 0] = "Cos";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Sin"] = 1] = "Sin";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Abs"] = 2] = "Abs";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Exp"] = 3] = "Exp";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Exp2"] = 4] = "Exp2";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Round"] = 5] = "Round";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Floor"] = 6] = "Floor";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Ceiling"] = 7] = "Ceiling";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Sqrt"] = 8] = "Sqrt";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Log"] = 9] = "Log";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Tan"] = 10] = "Tan";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["ArcTan"] = 11] = "ArcTan";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["ArcCos"] = 12] = "ArcCos";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["ArcSin"] = 13] = "ArcSin";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Fract"] = 14] = "Fract";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Sign"] = 15] = "Sign";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Radians"] = 16] = "Radians";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Degrees"] = 17] = "Degrees";
  TrigonometryBlockOperations2[TrigonometryBlockOperations2["Set"] = 18] = "Set";
})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));

class TrigonometryBlock extends NodeMaterialBlock {
  constructor(name327) {
    super(name327, NodeMaterialBlockTargets.Neutral);
    this.operation = TrigonometryBlockOperations.Cos;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "TrigonometryBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    let operation = "";
    switch (this.operation) {
      case TrigonometryBlockOperations.Cos: {
        operation = "cos";
        break;
      }
      case TrigonometryBlockOperations.Sin: {
        operation = "sin";
        break;
      }
      case TrigonometryBlockOperations.Abs: {
        operation = "abs";
        break;
      }
      case TrigonometryBlockOperations.Exp: {
        operation = "exp";
        break;
      }
      case TrigonometryBlockOperations.Exp2: {
        operation = "exp2";
        break;
      }
      case TrigonometryBlockOperations.Round: {
        operation = "round";
        break;
      }
      case TrigonometryBlockOperations.Floor: {
        operation = "floor";
        break;
      }
      case TrigonometryBlockOperations.Ceiling: {
        operation = "ceil";
        break;
      }
      case TrigonometryBlockOperations.Sqrt: {
        operation = "sqrt";
        break;
      }
      case TrigonometryBlockOperations.Log: {
        operation = "log";
        break;
      }
      case TrigonometryBlockOperations.Tan: {
        operation = "tan";
        break;
      }
      case TrigonometryBlockOperations.ArcTan: {
        operation = "atan";
        break;
      }
      case TrigonometryBlockOperations.ArcCos: {
        operation = "acos";
        break;
      }
      case TrigonometryBlockOperations.ArcSin: {
        operation = "asin";
        break;
      }
      case TrigonometryBlockOperations.Fract: {
        operation = "fract";
        break;
      }
      case TrigonometryBlockOperations.Sign: {
        operation = "sign";
        break;
      }
      case TrigonometryBlockOperations.Radians: {
        operation = "radians";
        break;
      }
      case TrigonometryBlockOperations.Degrees: {
        operation = "degrees";
        break;
      }
      case TrigonometryBlockOperations.Set: {
        operation = "";
        break;
      }
    }
    state.compilationString += state._declareOutput(output) + ` = ${operation}(${this.input.associatedVariableName});
`;
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.operation = this.operation;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.operation = serializationObject.operation;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${TrigonometryBlockOperations[this.operation]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Operation", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Cos", value: TrigonometryBlockOperations.Cos },
      { label: "Sin", value: TrigonometryBlockOperations.Sin },
      { label: "Abs", value: TrigonometryBlockOperations.Abs },
      { label: "Exp", value: TrigonometryBlockOperations.Exp },
      { label: "Exp2", value: TrigonometryBlockOperations.Exp2 },
      { label: "Round", value: TrigonometryBlockOperations.Round },
      { label: "Floor", value: TrigonometryBlockOperations.Floor },
      { label: "Ceiling", value: TrigonometryBlockOperations.Ceiling },
      { label: "Sqrt", value: TrigonometryBlockOperations.Sqrt },
      { label: "Log", value: TrigonometryBlockOperations.Log },
      { label: "Tan", value: TrigonometryBlockOperations.Tan },
      { label: "ArcTan", value: TrigonometryBlockOperations.ArcTan },
      { label: "ArcCos", value: TrigonometryBlockOperations.ArcCos },
      { label: "ArcSin", value: TrigonometryBlockOperations.ArcSin },
      { label: "Fract", value: TrigonometryBlockOperations.Fract },
      { label: "Sign", value: TrigonometryBlockOperations.Sign },
      { label: "Radians", value: TrigonometryBlockOperations.Radians },
      { label: "Degrees", value: TrigonometryBlockOperations.Degrees },
      { label: "Set", value: TrigonometryBlockOperations.Set }
    ]
  })
], TrigonometryBlock.prototype, "operation", undefined);
RegisterClass("BABYLON.TrigonometryBlock", TrigonometryBlock);

// node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js
init_engineStore();
init_logger();
init_materialHelper_functions();
init_abstractEngine();
var onCreatedEffectParameters4 = { effect: null, subMesh: null };

class NodeMaterialDefines extends MaterialDefines {
  constructor() {
    super();
    this.NORMAL = false;
    this.TANGENT = false;
    this.VERTEXCOLOR_NME = false;
    this.UV1 = false;
    this.UV2 = false;
    this.UV3 = false;
    this.UV4 = false;
    this.UV5 = false;
    this.UV6 = false;
    this.PREPASS = false;
    this.PREPASS_NORMAL = false;
    this.PREPASS_NORMAL_INDEX = -1;
    this.PREPASS_WORLD_NORMAL = false;
    this.PREPASS_WORLD_NORMAL_INDEX = -1;
    this.PREPASS_POSITION = false;
    this.PREPASS_POSITION_INDEX = -1;
    this.PREPASS_LOCAL_POSITION = false;
    this.PREPASS_LOCAL_POSITION_INDEX = -1;
    this.PREPASS_DEPTH = false;
    this.PREPASS_DEPTH_INDEX = -1;
    this.PREPASS_SCREENSPACE_DEPTH = false;
    this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1;
    this.SCENE_MRT_COUNT = 0;
    this.NUM_BONE_INFLUENCERS = 0;
    this.BonesPerMesh = 0;
    this.BONETEXTURE = false;
    this.MORPHTARGETS = false;
    this.MORPHTARGETS_POSITION = false;
    this.MORPHTARGETS_NORMAL = false;
    this.MORPHTARGETS_TANGENT = false;
    this.MORPHTARGETS_UV = false;
    this.MORPHTARGETS_UV2 = false;
    this.MORPHTARGETS_COLOR = false;
    this.MORPHTARGETTEXTURE_HASPOSITIONS = false;
    this.MORPHTARGETTEXTURE_HASNORMALS = false;
    this.MORPHTARGETTEXTURE_HASTANGENTS = false;
    this.MORPHTARGETTEXTURE_HASUVS = false;
    this.MORPHTARGETTEXTURE_HASUV2S = false;
    this.MORPHTARGETTEXTURE_HASCOLORS = false;
    this.NUM_MORPH_INFLUENCERS = 0;
    this.MORPHTARGETS_TEXTURE = false;
    this.IMAGEPROCESSING = false;
    this.VIGNETTE = false;
    this.VIGNETTEBLENDMODEMULTIPLY = false;
    this.VIGNETTEBLENDMODEOPAQUE = false;
    this.TONEMAPPING = 0;
    this.CONTRAST = false;
    this.EXPOSURE = false;
    this.COLORCURVES = false;
    this.COLORGRADING = false;
    this.COLORGRADING3D = false;
    this.SAMPLER3DGREENDEPTH = false;
    this.SAMPLER3DBGRMAP = false;
    this.DITHER = false;
    this.IMAGEPROCESSINGPOSTPROCESS = false;
    this.SKIPFINALCOLORCLAMP = false;
    this.BUMPDIRECTUV = 0;
    this.CAMERA_ORTHOGRAPHIC = false;
    this.CAMERA_PERSPECTIVE = false;
    this.AREALIGHTSUPPORTED = true;
    this.AREALIGHTNOROUGHTNESS = true;
    this.rebuild();
  }
  setValue(name327, value, markAsUnprocessedIfDirty = false) {
    if (this[name327] === undefined) {
      this._keys.push(name327);
    }
    if (markAsUnprocessedIfDirty && this[name327] !== value) {
      this.markAsUnprocessed();
    }
    this[name327] = value;
  }
}

class NodeMaterial extends PushMaterial {
  static _BlockIsTextureBlock(block) {
    return block.getClassName() === "TextureBlock" || block.getClassName() === "ReflectionTextureBaseBlock" || block.getClassName() === "ReflectionTextureBlock" || block.getClassName() === "ReflectionBlock" || block.getClassName() === "RefractionBlock" || block.getClassName() === "CurrentScreenBlock" || block.getClassName() === "ParticleTextureBlock" || block.getClassName() === "ImageSourceBlock" || block.getClassName() === "TriPlanarBlock" || block.getClassName() === "BiPlanarBlock" || block.getClassName() === "PrePassTextureBlock";
  }
  set _glowModeEnabled(value) {
    this._useAdditionalColor = value;
  }
  _getGlobalNodeMaterialEditor() {
    if (typeof NODEEDITOR !== "undefined") {
      return NODEEDITOR;
    }
    if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeEditor !== "undefined") {
      return BABYLON;
    }
    return;
  }
  get shaderLanguage() {
    return this._options?.shaderLanguage || NodeMaterial.DefaultShaderLanguage;
  }
  set shaderLanguage(value) {
    this._options.shaderLanguage = value;
  }
  get options() {
    return this._options;
  }
  set options(options) {
    this._options = options;
  }
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    this._attachImageProcessingConfiguration(value);
    this._markAllSubMeshesAsTexturesDirty();
  }
  get mode() {
    return this._mode;
  }
  set mode(value) {
    this._mode = value;
  }
  get buildId() {
    return this._buildId;
  }
  set buildId(value) {
    this._buildId = value;
  }
  constructor(name327, scene, options = {}) {
    super(name327, scene || EngineStore.LastCreatedScene);
    this._buildId = NodeMaterial._BuildIdGenerator++;
    this._buildWasSuccessful = false;
    this._cachedWorldViewMatrix = new Matrix;
    this._cachedWorldViewProjectionMatrix = new Matrix;
    this._optimizers = new Array;
    this._animationFrame = -1;
    this._buildIsInProgress = false;
    this.BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();
    this._useAdditionalColor = false;
    this.editorData = null;
    this.ignoreAlpha = false;
    this.maxSimultaneousLights = 4;
    this.onBuildObservable = new Observable;
    this.onBuildErrorObservable = new Observable;
    this._vertexOutputNodes = new Array;
    this._fragmentOutputNodes = new Array;
    this.attachedBlocks = [];
    this._mode = NodeMaterialModes.Material;
    this.forceAlphaBlending = false;
    if (!NodeMaterial.UseNativeShaderLanguageOfEngine && options && options.shaderLanguage === 1 && !this.getScene().getEngine().isWebGPU) {
      throw new Error("WebGPU shader language is only supported with WebGPU engine");
    }
    this._options = {
      emitComments: false,
      shaderLanguage: NodeMaterial.DefaultShaderLanguage,
      ...options
    };
    if (NodeMaterial.UseNativeShaderLanguageOfEngine) {
      this._options.shaderLanguage = this.getScene().getEngine().isWebGPU ? 1 : 0;
    }
    this._attachImageProcessingConfiguration(null);
  }
  getClassName() {
    return "NodeMaterial";
  }
  _attachImageProcessingConfiguration(configuration) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (!configuration) {
      this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
    } else {
      this._imageProcessingConfiguration = configuration;
    }
    if (this._imageProcessingConfiguration) {
      this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
        this._markAllSubMeshesAsImageProcessingDirty();
      });
    }
  }
  getBlockByName(name327) {
    let result = null;
    for (const block of this.attachedBlocks) {
      if (block.name === name327) {
        if (!result) {
          result = block;
        } else {
          Tools.Warn("More than one block was found with the name `" + name327 + "`");
          return result;
        }
      }
    }
    return result;
  }
  getBlockByPredicate(predicate) {
    for (const block of this.attachedBlocks) {
      if (predicate(block)) {
        return block;
      }
    }
    return null;
  }
  getInputBlockByPredicate(predicate) {
    for (const block of this.attachedBlocks) {
      if (block.isInput && predicate(block)) {
        return block;
      }
    }
    return null;
  }
  getInputBlocks() {
    const blocks = [];
    for (const block of this.attachedBlocks) {
      if (block.isInput) {
        blocks.push(block);
      }
    }
    return blocks;
  }
  registerOptimizer(optimizer) {
    const index = this._optimizers.indexOf(optimizer);
    if (index > -1) {
      return;
    }
    this._optimizers.push(optimizer);
    return this;
  }
  unregisterOptimizer(optimizer) {
    const index = this._optimizers.indexOf(optimizer);
    if (index === -1) {
      return;
    }
    this._optimizers.splice(index, 1);
    return this;
  }
  addOutputNode(node) {
    if (node.target === null) {
      throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
    }
    if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
      this._addVertexOutputNode(node);
    }
    if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
      this._addFragmentOutputNode(node);
    }
    return this;
  }
  removeOutputNode(node) {
    if (node.target === null) {
      return this;
    }
    if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {
      this._removeVertexOutputNode(node);
    }
    if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {
      this._removeFragmentOutputNode(node);
    }
    return this;
  }
  _addVertexOutputNode(node) {
    if (this._vertexOutputNodes.indexOf(node) !== -1) {
      return;
    }
    node.target = NodeMaterialBlockTargets.Vertex;
    this._vertexOutputNodes.push(node);
    return this;
  }
  _removeVertexOutputNode(node) {
    const index = this._vertexOutputNodes.indexOf(node);
    if (index === -1) {
      return;
    }
    this._vertexOutputNodes.splice(index, 1);
    return this;
  }
  _addFragmentOutputNode(node) {
    if (this._fragmentOutputNodes.indexOf(node) !== -1) {
      return;
    }
    node.target = NodeMaterialBlockTargets.Fragment;
    this._fragmentOutputNodes.push(node);
    return this;
  }
  _removeFragmentOutputNode(node) {
    const index = this._fragmentOutputNodes.indexOf(node);
    if (index === -1) {
      return;
    }
    this._fragmentOutputNodes.splice(index, 1);
    return this;
  }
  get _supportGlowLayer() {
    if (this._fragmentOutputNodes.length === 0) {
      return false;
    }
    if (this._fragmentOutputNodes.some((f) => f.additionalColor && f.additionalColor.isConnected)) {
      return true;
    }
    return false;
  }
  needAlphaBlending() {
    if (this.ignoreAlpha) {
      return false;
    }
    return this.forceAlphaBlending || this.alpha < 1 || this._sharedData && this._sharedData.hints.needAlphaBlending;
  }
  needAlphaTesting() {
    return this._sharedData && this._sharedData.hints.needAlphaTesting;
  }
  _processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure = true) {
    if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {
      nodesToProcessForOtherBuildState.push(block);
    } else if (state.target === NodeMaterialBlockTargets.Fragment && block.target === NodeMaterialBlockTargets.Vertex && block._preparationId !== this._buildId) {
      nodesToProcessForOtherBuildState.push(block);
    }
    this._initializeBlock(block, state, nodesToProcessForOtherBuildState, autoConfigure);
  }
  _attachBlock(node) {
    if (this.attachedBlocks.indexOf(node) === -1) {
      if (node.isUnique) {
        const className = node.getClassName();
        for (const other of this.attachedBlocks) {
          if (other.getClassName() === className) {
            throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`;
          }
        }
      }
      this.attachedBlocks.push(node);
    }
  }
  _initializeBlock(node, state, nodesToProcessForOtherBuildState, autoConfigure = true) {
    node.initialize(state);
    if (autoConfigure) {
      node.autoConfigure(this);
    }
    node._preparationId = this._buildId;
    this._attachBlock(node);
    for (const input of node.inputs) {
      input.associatedVariableName = "";
      const connectedPoint = input.connectedPoint;
      if (connectedPoint && !connectedPoint._preventBubbleUp) {
        const block = connectedPoint.ownerBlock;
        if (block !== node) {
          this._processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure);
        }
      }
    }
    if (node.isLoop) {
      const loopBlock = node;
      if (loopBlock.loopID.hasEndpoints) {
        for (const endpoint of loopBlock.loopID.endpoints) {
          const block = endpoint.ownerBlock;
          if (block.outputs.length !== 0) {
            continue;
          }
          state._terminalBlocks.add(block);
          this._processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure);
        }
      }
    } else if (node.isTeleportOut) {
      const teleport = node;
      if (teleport.entryPoint) {
        this._processInitializeOnLink(teleport.entryPoint, state, nodesToProcessForOtherBuildState, autoConfigure);
      }
    }
    for (const output of node.outputs) {
      output.associatedVariableName = "";
    }
  }
  _resetDualBlocks(node, id) {
    if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {
      node.buildId = id;
    }
    for (const input of node.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint && !connectedPoint._preventBubbleUp) {
        const block = connectedPoint.ownerBlock;
        if (block !== node) {
          this._resetDualBlocks(block, id);
        }
      }
    }
    if (node.isTeleportOut) {
      const teleportOut = node;
      if (teleportOut.entryPoint) {
        this._resetDualBlocks(teleportOut.entryPoint, id);
      }
    } else if (node.isLoop) {
      const loopBlock = node;
      if (loopBlock.loopID.hasEndpoints) {
        for (const endpoint of loopBlock.loopID.endpoints) {
          const block = endpoint.ownerBlock;
          if (block.outputs.length !== 0) {
            continue;
          }
          this._resetDualBlocks(block, id);
        }
      }
    }
  }
  removeBlock(block) {
    const attachedBlockIndex = this.attachedBlocks.indexOf(block);
    if (attachedBlockIndex > -1) {
      this.attachedBlocks.splice(attachedBlockIndex, 1);
    }
    if (block.isFinalMerger) {
      this.removeOutputNode(block);
    }
  }
  build(verbose = false, updateBuildId = true, autoConfigure = false) {
    if (this._buildIsInProgress) {
      Logger.Warn("Build is already in progress, You can use NodeMaterial.onBuildObservable to determine when the build is completed.");
      return;
    }
    this._buildIsInProgress = true;
    if (!this._vertexCompilationState && !autoConfigure) {
      autoConfigure = true;
    }
    this._buildWasSuccessful = false;
    const engine2 = this.getScene().getEngine();
    const allowEmptyVertexProgram = this._mode === NodeMaterialModes.Particle;
    if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) {
      throw "You must define at least one vertexOutputNode";
    }
    if (this._fragmentOutputNodes.length === 0) {
      throw "You must define at least one fragmentOutputNode";
    }
    this._vertexCompilationState = new NodeMaterialBuildState;
    this._vertexCompilationState.supportUniformBuffers = engine2.supportsUniformBuffers;
    this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;
    this._fragmentCompilationState = new NodeMaterialBuildState;
    this._fragmentCompilationState.supportUniformBuffers = engine2.supportsUniformBuffers;
    this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;
    const needToPurgeList = this._fragmentOutputNodes.filter((n) => n._isFinalOutputAndActive).length > 1;
    let fragmentOutputNodes = this._fragmentOutputNodes;
    if (needToPurgeList) {
      fragmentOutputNodes = this._fragmentOutputNodes.filter((n) => !n._isFinalOutputAndActive);
      fragmentOutputNodes.push(this._fragmentOutputNodes.filter((n) => n._isFinalOutputAndActive && n._hasPrecedence)[0]);
    }
    this._sharedData = new NodeMaterialBuildStateSharedData;
    this._sharedData.nodeMaterial = this;
    this._sharedData.fragmentOutputNodes = fragmentOutputNodes;
    this._vertexCompilationState.sharedData = this._sharedData;
    this._fragmentCompilationState.sharedData = this._sharedData;
    this._sharedData.buildId = this._buildId;
    this._sharedData.emitComments = this._options.emitComments;
    this._sharedData.verbose = verbose;
    this._sharedData.scene = this.getScene();
    this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram;
    const vertexNodes = [];
    const fragmentNodes = [];
    for (const vertexOutputNode of this._vertexOutputNodes) {
      vertexNodes.push(vertexOutputNode);
      this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes, autoConfigure);
    }
    for (const fragmentOutputNode of fragmentOutputNodes) {
      fragmentNodes.push(fragmentOutputNode);
      this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes, autoConfigure);
    }
    let waitingNodeCount = 0;
    for (const node of this.attachedBlocks) {
      if (!node.codeIsReady) {
        waitingNodeCount++;
        node.onCodeIsReadyObservable.addOnce(() => {
          waitingNodeCount--;
          if (waitingNodeCount === 0) {
            this._finishBuildProcess(verbose, updateBuildId, vertexNodes, fragmentNodes);
          }
        });
      }
    }
    if (waitingNodeCount !== 0) {
      return;
    }
    this._finishBuildProcess(verbose, updateBuildId, vertexNodes, fragmentNodes);
  }
  _finishBuildProcess(verbose = false, updateBuildId = true, vertexNodes, fragmentNodes) {
    this.optimize();
    for (const vertexOutputNode of vertexNodes) {
      vertexOutputNode.build(this._vertexCompilationState, vertexNodes);
    }
    this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);
    this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;
    this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;
    this._fragmentCompilationState._vertexState = this._vertexCompilationState;
    for (const fragmentOutputNode of fragmentNodes) {
      this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);
    }
    for (const fragmentOutputNode of fragmentNodes) {
      fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);
    }
    this._vertexCompilationState.finalize(this._vertexCompilationState);
    this._fragmentCompilationState.finalize(this._fragmentCompilationState);
    if (updateBuildId) {
      this._buildId = NodeMaterial._BuildIdGenerator++;
    }
    const noError = this._sharedData.emitErrors(this.onBuildErrorObservable);
    if (verbose) {
      Logger.Log("Vertex shader:");
      Logger.Log(this._vertexCompilationState.compilationString);
      Logger.Log("Fragment shader:");
      Logger.Log(this._fragmentCompilationState.compilationString);
    }
    this._buildIsInProgress = false;
    this._buildWasSuccessful = true;
    if (noError) {
      this.onBuildObservable.notifyObservers(this);
    }
    const meshes = this.getScene().meshes;
    for (const mesh of meshes) {
      if (!mesh.subMeshes) {
        continue;
      }
      for (const subMesh of mesh.subMeshes) {
        if (subMesh.getMaterial() !== this) {
          continue;
        }
        if (!subMesh.materialDefines) {
          continue;
        }
        const defines = subMesh.materialDefines;
        defines.markAllAsDirty();
        defines.reset();
      }
    }
    if (this.prePassTextureInputs.length) {
      this.getScene().enablePrePassRenderer();
    }
    const prePassRenderer = this.getScene().prePassRenderer;
    if (prePassRenderer) {
      prePassRenderer.markAsDirty();
    }
  }
  optimize() {
    for (const optimizer of this._optimizers) {
      optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);
    }
  }
  _prepareDefinesForAttributes(mesh, defines) {
    const oldNormal = defines["NORMAL"];
    const oldTangent = defines["TANGENT"];
    const oldColor = defines["VERTEXCOLOR_NME"];
    defines["NORMAL"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);
    defines["TANGENT"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);
    const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);
    defines["VERTEXCOLOR_NME"] = hasVertexColors;
    let uvChanged = false;
    for (let i = 1;i <= 6; ++i) {
      const oldUV = defines["UV" + i];
      defines["UV" + i] = mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`);
      uvChanged = uvChanged || defines["UV" + i] !== oldUV;
    }
    const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;
    PrepareDefinesForPrePass(this.getScene(), defines, !oit);
    MaterialHelperGeometryRendering.PrepareDefines(this.getScene().getEngine().currentRenderPassId, mesh, defines);
    if (oldNormal !== defines["NORMAL"] || oldTangent !== defines["TANGENT"] || oldColor !== defines["VERTEXCOLOR_NME"] || uvChanged) {
      defines.markAsAttributesDirty();
    }
  }
  get isPrePassCapable() {
    return true;
  }
  get prePassTextureOutputs() {
    const prePassOutputBlock = this.getBlockByPredicate((block) => block.getClassName() === "PrePassOutputBlock");
    const result = [4];
    if (!prePassOutputBlock) {
      return result;
    }
    if (this.prePassTextureInputs.length) {
      return result;
    }
    if (prePassOutputBlock.viewDepth.isConnected) {
      result.push(5);
    }
    if (prePassOutputBlock.screenDepth.isConnected) {
      result.push(10);
    }
    if (prePassOutputBlock.viewNormal.isConnected) {
      result.push(6);
    }
    if (prePassOutputBlock.worldNormal.isConnected) {
      result.push(8);
    }
    if (prePassOutputBlock.worldPosition.isConnected) {
      result.push(1);
    }
    if (prePassOutputBlock.localPosition.isConnected) {
      result.push(9);
    }
    if (prePassOutputBlock.reflectivity.isConnected) {
      result.push(3);
    }
    if (prePassOutputBlock.velocity.isConnected) {
      result.push(2);
    }
    if (prePassOutputBlock.velocityLinear.isConnected) {
      result.push(11);
    }
    return result;
  }
  get prePassTextureInputs() {
    const prePassTextureBlocks = this.getAllTextureBlocks().filter((block) => block.getClassName() === "PrePassTextureBlock");
    const result = [];
    for (const block of prePassTextureBlocks) {
      if (block.position.isConnected && !result.includes(1)) {
        result.push(1);
      }
      if (block.localPosition.isConnected && !result.includes(9)) {
        result.push(9);
      }
      if (block.depth.isConnected && !result.includes(5)) {
        result.push(5);
      }
      if (block.screenDepth.isConnected && !result.includes(10)) {
        result.push(10);
      }
      if (block.normal.isConnected && !result.includes(6)) {
        result.push(6);
      }
      if (block.worldNormal.isConnected && !result.includes(8)) {
        result.push(8);
      }
    }
    return result;
  }
  setPrePassRenderer(prePassRenderer) {
    const prePassTexturesRequired = this.prePassTextureInputs.concat(this.prePassTextureOutputs);
    if (prePassRenderer && prePassTexturesRequired.length > 1) {
      let cfg = prePassRenderer.getEffectConfiguration("nodeMaterial");
      if (!cfg) {
        cfg = prePassRenderer.addEffectConfiguration({
          enabled: true,
          needsImageProcessing: false,
          name: "nodeMaterial",
          texturesRequired: []
        });
      }
      for (const prePassTexture of prePassTexturesRequired) {
        if (!cfg.texturesRequired.includes(prePassTexture)) {
          cfg.texturesRequired.push(prePassTexture);
        }
      }
      cfg.enabled = true;
    }
    return prePassTexturesRequired.length > 1;
  }
  createPostProcess(camera2, options = 1, samplingMode = 1, engine2, reusable, textureType = 0, textureFormat = 5) {
    if (this.mode !== NodeMaterialModes.PostProcess) {
      Logger.Log("Incompatible material mode");
      return null;
    }
    return this._createEffectForPostProcess(null, camera2, options, samplingMode, engine2, reusable, textureType, textureFormat);
  }
  createEffectForPostProcess(postProcess) {
    this._createEffectForPostProcess(postProcess);
  }
  _createEffectForPostProcess(postProcess, camera2, options = 1, samplingMode = 1, engine2, reusable, textureType = 0, textureFormat = 5) {
    let tempName = this.name + this._buildId;
    const defines = new NodeMaterialDefines;
    const dummyMesh = new Mesh(tempName + "PostProcess", this.getScene());
    let buildId = this._buildId;
    this._processDefines(dummyMesh, defines);
    Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage);
    if (!postProcess) {
      postProcess = new PostProcess(this.name + "PostProcess", tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, options, camera2, samplingMode, engine2, reusable, defines.toString(), textureType, tempName, { maxSimultaneousLights: this.maxSimultaneousLights }, false, textureFormat, this.shaderLanguage);
    } else {
      postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName);
    }
    postProcess.nodeMaterialSource = this;
    postProcess.onDisposeObservable.add(() => {
      dummyMesh.dispose();
    });
    postProcess.onApplyObservable.add((effect) => {
      if (buildId !== this._buildId) {
        delete Effect.ShadersStore[tempName + "VertexShader"];
        delete Effect.ShadersStore[tempName + "PixelShader"];
        tempName = this.name + this._buildId;
        defines.markAllAsDirty();
        buildId = this._buildId;
      }
      const result = this._processDefines(dummyMesh, defines);
      if (result) {
        Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);
        TimingTools.SetImmediate(() => postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName));
      }
      this._checkInternals(effect);
    });
    return postProcess;
  }
  createProceduralTexture(size, scene) {
    if (this.mode !== NodeMaterialModes.ProceduralTexture) {
      Logger.Log("Incompatible material mode");
      return null;
    }
    let tempName = this.name + this._buildId;
    const proceduralTexture = new ProceduralTexture(tempName, size, null, scene);
    const dummyMesh = new Mesh(tempName + "Procedural", this.getScene());
    dummyMesh.reservedDataStore = {
      hidden: true
    };
    const defines = new NodeMaterialDefines;
    const result = this._processDefines(dummyMesh, defines);
    Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage);
    let effect = this.getScene().getEngine().createEffect({
      vertexElement: tempName,
      fragmentElement: tempName
    }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result?.fallbacks, undefined, undefined, undefined, this.shaderLanguage);
    proceduralTexture.nodeMaterialSource = this;
    proceduralTexture._setEffect(effect);
    let buildId = this._buildId;
    const refreshEffect = () => {
      if (buildId !== this._buildId) {
        delete Effect.ShadersStore[tempName + "VertexShader"];
        delete Effect.ShadersStore[tempName + "PixelShader"];
        tempName = this.name + this._buildId;
        defines.markAllAsDirty();
        buildId = this._buildId;
      }
      const result2 = this._processDefines(dummyMesh, defines);
      if (result2) {
        Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString, this.shaderLanguage);
        TimingTools.SetImmediate(() => {
          effect = this.getScene().getEngine().createEffect({
            vertexElement: tempName,
            fragmentElement: tempName
          }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result2?.fallbacks, undefined);
          proceduralTexture._setEffect(effect);
        });
      }
      this._checkInternals(effect);
    };
    proceduralTexture.onBeforeGenerationObservable.add(() => {
      refreshEffect();
    });
    this.onBuildObservable.add(() => {
      refreshEffect();
    });
    return proceduralTexture;
  }
  _createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined = "") {
    let tempName = this.name + this._buildId + "_" + blendMode;
    if (!defines) {
      defines = new NodeMaterialDefines;
    }
    if (!dummyMesh) {
      dummyMesh = this.getScene().getMeshByName(this.name + "Particle");
      if (!dummyMesh) {
        dummyMesh = new Mesh(this.name + "Particle", this.getScene());
        dummyMesh.reservedDataStore = {
          hidden: true
        };
      }
    }
    let buildId = this._buildId;
    const particleSystemDefines = [];
    let join6 = particleSystemDefinesJoined;
    if (!effect) {
      const result = this._processDefines(dummyMesh, defines);
      Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, undefined, this.shaderLanguage);
      particleSystem.fillDefines(particleSystemDefines, blendMode, false);
      join6 = particleSystemDefines.join(`
`);
      effect = this.getScene().getEngine().createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + `
` + join6, result?.fallbacks, onCompiled, onError, particleSystem, this.shaderLanguage);
      particleSystem.setCustomEffect(effect, blendMode);
    }
    effect.onBindObservable.add((effect2) => {
      if (buildId !== this._buildId) {
        delete Effect.ShadersStore[tempName + "PixelShader"];
        tempName = this.name + this._buildId + "_" + blendMode;
        defines.markAllAsDirty();
        buildId = this._buildId;
      }
      particleSystemDefines.length = 0;
      particleSystem.fillDefines(particleSystemDefines, blendMode, false);
      const particleSystemDefinesJoinedCurrent = particleSystemDefines.join(`
`);
      if (particleSystemDefinesJoinedCurrent !== join6) {
        defines.markAllAsDirty();
        join6 = particleSystemDefinesJoinedCurrent;
      }
      const result = this._processDefines(dummyMesh, defines);
      if (result) {
        Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, undefined, this.shaderLanguage);
        effect2 = this.getScene().getEngine().createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + `
` + join6, result?.fallbacks, onCompiled, onError, particleSystem);
        particleSystem.setCustomEffect(effect2, blendMode);
        this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect2, defines, dummyMesh, particleSystemDefinesJoined);
        return;
      }
      this._checkInternals(effect2);
    });
  }
  _checkInternals(effect) {
    if (this._sharedData.animatedInputs) {
      const scene = this.getScene();
      const frameId = scene.getFrameId();
      if (this._animationFrame !== frameId) {
        for (const input of this._sharedData.animatedInputs) {
          input.animate(scene);
        }
        this._animationFrame = frameId;
      }
    }
    for (const block of this._sharedData.bindableBlocks) {
      block.bind(effect, this);
    }
    for (const inputBlock2 of this._sharedData.inputBlocks) {
      inputBlock2._transmit(effect, this.getScene(), this);
    }
  }
  createEffectForParticles(particleSystem, onCompiled, onError) {
    if (this.mode !== NodeMaterialModes.Particle) {
      Logger.Log("Incompatible material mode");
      return;
    }
    this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_ONEONE, onCompiled, onError);
    this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_MULTIPLY, onCompiled, onError);
  }
  createAsShadowDepthWrapper(targetMaterial) {
    if (this.mode !== NodeMaterialModes.Material) {
      Logger.Log("Incompatible material mode");
      return;
    }
    targetMaterial.shadowDepthWrapper = new BABYLON.ShadowDepthWrapper(this, this.getScene());
  }
  _processDefines(mesh, defines, useInstances = false, subMesh) {
    let result = null;
    const scene = this.getScene();
    if (PrepareDefinesForCamera(scene, defines)) {
      defines.markAsMiscDirty();
    }
    this._sharedData.blocksWithDefines.forEach((b) => {
      b.initializeDefines(mesh, this, defines, useInstances);
    });
    this._sharedData.blocksWithDefines.forEach((b) => {
      b.prepareDefines(mesh, this, defines, useInstances, subMesh);
    });
    if (defines.isDirty) {
      const lightDisposed = defines._areLightsDisposed;
      defines.markAsProcessed();
      this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
      this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
      this._sharedData.repeatableContentBlocks.forEach((b) => {
        b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);
      });
      const uniformBuffers = [];
      this._sharedData.dynamicUniformBlocks.forEach((b) => {
        b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);
      });
      const mergedUniforms = this._vertexCompilationState.uniforms;
      this._fragmentCompilationState.uniforms.forEach((u) => {
        const index = mergedUniforms.indexOf(u);
        if (index === -1) {
          mergedUniforms.push(u);
        }
      });
      const mergedSamplers = this._vertexCompilationState.samplers;
      this._fragmentCompilationState.samplers.forEach((s) => {
        const index = mergedSamplers.indexOf(s);
        if (index === -1) {
          mergedSamplers.push(s);
        }
      });
      const fallbacks = new EffectFallbacks;
      this._sharedData.blocksWithFallbacks.forEach((b) => {
        b.provideFallbacks(mesh, fallbacks);
      });
      result = {
        lightDisposed,
        uniformBuffers,
        mergedUniforms,
        mergedSamplers,
        fallbacks
      };
    }
    return result;
  }
  isReadyForSubMesh(mesh, subMesh, useInstances = false) {
    if (!this._buildWasSuccessful) {
      return false;
    }
    const scene = this.getScene();
    if (this._sharedData.animatedInputs) {
      const frameId = scene.getFrameId();
      if (this._animationFrame !== frameId) {
        for (const input of this._sharedData.animatedInputs) {
          input.animate(scene);
        }
        this._animationFrame = frameId;
      }
    }
    const drawWrapper = subMesh._drawWrapper;
    if (drawWrapper.effect && this.isFrozen) {
      if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    if (!subMesh.materialDefines || typeof subMesh.materialDefines === "string") {
      subMesh.materialDefines = new NodeMaterialDefines;
    }
    const defines = subMesh.materialDefines;
    if (this._isReadyForSubMesh(subMesh)) {
      return true;
    }
    const engine2 = scene.getEngine();
    this._prepareDefinesForAttributes(mesh, defines);
    if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {
      return false;
    }
    const result = this._processDefines(mesh, defines, useInstances, subMesh);
    if (result) {
      const previousEffect = subMesh.effect;
      const join6 = defines.toString();
      let effect = engine2.createEffect({
        vertex: "nodeMaterial" + this._buildId,
        fragment: "nodeMaterial" + this._buildId,
        vertexSource: this._vertexCompilationState.compilationString,
        fragmentSource: this._fragmentCompilationState.compilationString
      }, {
        attributes: this._vertexCompilationState.attributes,
        uniformsNames: result.mergedUniforms,
        uniformBuffersNames: result.uniformBuffers,
        samplers: result.mergedSamplers,
        defines: join6,
        fallbacks: result.fallbacks,
        onCompiled: this.onCompiled,
        onError: this.onError,
        multiTarget: defines.PREPASS,
        indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },
        shaderLanguage: this.shaderLanguage
      }, engine2);
      if (effect) {
        if (this._onEffectCreatedObservable) {
          onCreatedEffectParameters4.effect = effect;
          onCreatedEffectParameters4.subMesh = subMesh;
          this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters4);
        }
        if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
          effect = previousEffect;
          defines.markAsUnprocessed();
          if (result.lightDisposed) {
            defines._areLightsDisposed = true;
            return false;
          }
        } else {
          scene.resetCachedMaterial();
          subMesh.setEffect(effect, defines, this._materialContext);
        }
      }
    }
    if (defines["AREALIGHTUSED"]) {
      for (let index = 0;index < mesh.lightSources.length; index++) {
        if (!mesh.lightSources[index]._isReady()) {
          return false;
        }
      }
    }
    if (!subMesh.effect || !subMesh.effect.isReady()) {
      return false;
    }
    defines._renderId = scene.getRenderId();
    drawWrapper._wasPreviouslyReady = true;
    drawWrapper._wasPreviouslyUsingInstances = useInstances;
    this._checkScenePerformancePriority();
    return true;
  }
  get compiledShaders() {
    if (!this._buildWasSuccessful) {
      this.build();
    }
    return `// Vertex shader
${this._vertexCompilationState.compilationString}

// Fragment shader
${this._fragmentCompilationState.compilationString}`;
  }
  bindOnlyWorldMatrix(world) {
    const scene = this.getScene();
    if (!this._activeEffect) {
      return;
    }
    const hints = this._sharedData.hints;
    if (hints.needWorldViewMatrix) {
      world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
    }
    if (hints.needWorldViewProjectionMatrix) {
      world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
    }
    for (const inputBlock2 of this._sharedData.inputBlocks) {
      inputBlock2._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
    }
  }
  bindForSubMesh(world, mesh, subMesh) {
    const scene = this.getScene();
    const effect = subMesh.effect;
    if (!effect) {
      return;
    }
    this._activeEffect = effect;
    this.bindOnlyWorldMatrix(world);
    const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
    const sharedData = this._sharedData;
    if (mustRebind) {
      for (const block of sharedData.bindableBlocks) {
        block.bind(effect, this, mesh, subMesh);
      }
      for (const block of sharedData.forcedBindableBlocks) {
        block.bind(effect, this, mesh, subMesh);
      }
      for (const inputBlock2 of sharedData.inputBlocks) {
        inputBlock2._transmit(effect, scene, this);
      }
    } else if (!this.isFrozen) {
      for (const block of sharedData.forcedBindableBlocks) {
        block.bind(effect, this, mesh, subMesh);
      }
    }
    this._afterBind(mesh, this._activeEffect, subMesh);
  }
  getActiveTextures() {
    const activeTextures = super.getActiveTextures();
    if (this._sharedData) {
      activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture));
    }
    return activeTextures;
  }
  getTextureBlocks() {
    if (!this._sharedData) {
      return [];
    }
    return this._sharedData.textureBlocks;
  }
  getAllTextureBlocks() {
    const textureBlocks = [];
    for (const block of this.attachedBlocks) {
      if (NodeMaterial._BlockIsTextureBlock(block)) {
        textureBlocks.push(block);
      }
    }
    return textureBlocks;
  }
  hasTexture(texture) {
    if (super.hasTexture(texture)) {
      return true;
    }
    if (!this._sharedData) {
      return false;
    }
    for (const t of this._sharedData.textureBlocks) {
      if (t.texture === texture) {
        return true;
      }
    }
    return false;
  }
  dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
    if (forceDisposeTextures) {
      for (const texture of this.getTextureBlocks().filter((tb) => tb.texture).map((tb) => tb.texture)) {
        texture.dispose();
      }
    }
    for (const block of this.attachedBlocks) {
      block.dispose();
    }
    this.attachedBlocks.length = 0;
    this._sharedData = null;
    this._vertexCompilationState = null;
    this._fragmentCompilationState = null;
    this.onBuildObservable.clear();
    this.onBuildErrorObservable.clear();
    if (this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
      this._imageProcessingObserver = null;
    }
    super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  }
  _createNodeEditor(additionalConfig) {
    const nodeEditorConfig = {
      nodeMaterial: this,
      ...additionalConfig
    };
    this.BJSNODEMATERIALEDITOR.NodeEditor.Show(nodeEditorConfig);
  }
  edit(config) {
    return new Promise((resolve3) => {
      this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
      if (typeof this.BJSNODEMATERIALEDITOR == "undefined") {
        const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
        Tools.LoadBabylonScript(editorUrl, () => {
          this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
          this._createNodeEditor(config?.nodeEditorConfig);
          resolve3();
        });
      } else {
        this._createNodeEditor(config?.nodeEditorConfig);
        resolve3();
      }
    });
  }
  clear() {
    this._vertexOutputNodes.length = 0;
    this._fragmentOutputNodes.length = 0;
    this.attachedBlocks.length = 0;
    this._buildIsInProgress = false;
  }
  setToDefault() {
    this.clear();
    this.editorData = null;
    const positionInput = new InputBlock("Position");
    positionInput.setAsAttribute("position");
    const worldInput = new InputBlock("World");
    worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
    const worldPos = new TransformBlock("WorldPos");
    positionInput.connectTo(worldPos);
    worldInput.connectTo(worldPos);
    const viewProjectionInput = new InputBlock("ViewProjection");
    viewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);
    const worldPosdMultipliedByViewProjection = new TransformBlock("WorldPos * ViewProjectionTransform");
    worldPos.connectTo(worldPosdMultipliedByViewProjection);
    viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
    const vertexOutput = new VertexOutputBlock("VertexOutput");
    worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
    const pixelColor = new InputBlock("color");
    pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);
    const fragmentOutput = new FragmentOutputBlock("FragmentOutput");
    pixelColor.connectTo(fragmentOutput);
    this.addOutputNode(vertexOutput);
    this.addOutputNode(fragmentOutput);
    this._mode = NodeMaterialModes.Material;
  }
  setToDefaultPostProcess() {
    this.clear();
    this.editorData = null;
    const position = new InputBlock("Position");
    position.setAsAttribute("position2d");
    const const1 = new InputBlock("Constant1");
    const1.isConstant = true;
    const1.value = 1;
    const vmerger = new VectorMergerBlock("Position3D");
    position.connectTo(vmerger);
    const1.connectTo(vmerger, { input: "w" });
    const vertexOutput = new VertexOutputBlock("VertexOutput");
    vmerger.connectTo(vertexOutput);
    const scale = new InputBlock("Scale");
    scale.visibleInInspector = true;
    scale.value = new Vector2(1, 1);
    const uv0 = new RemapBlock("uv0");
    position.connectTo(uv0);
    const uv = new MultiplyBlock("UV scale");
    uv0.connectTo(uv);
    scale.connectTo(uv);
    const currentScreen = new CurrentScreenBlock("CurrentScreen");
    uv.connectTo(currentScreen);
    const textureUrl = Tools.GetAssetUrl("https://assets.babylonjs.com/core/nme/currentScreenPostProcess.png");
    currentScreen.texture = new Texture(textureUrl, this.getScene());
    const fragmentOutput = new FragmentOutputBlock("FragmentOutput");
    currentScreen.connectTo(fragmentOutput, { output: "rgba" });
    this.addOutputNode(vertexOutput);
    this.addOutputNode(fragmentOutput);
    this._mode = NodeMaterialModes.PostProcess;
  }
  setToDefaultProceduralTexture() {
    this.clear();
    this.editorData = null;
    const position = new InputBlock("Position");
    position.setAsAttribute("position2d");
    const const1 = new InputBlock("Constant1");
    const1.isConstant = true;
    const1.value = 1;
    const vmerger = new VectorMergerBlock("Position3D");
    position.connectTo(vmerger);
    const1.connectTo(vmerger, { input: "w" });
    const vertexOutput = new VertexOutputBlock("VertexOutput");
    vmerger.connectTo(vertexOutput);
    const time = new InputBlock("Time");
    time.value = 0;
    time.min = 0;
    time.max = 0;
    time.isBoolean = false;
    time.matrixMode = 0;
    time.animationType = AnimatedInputBlockTypes.Time;
    time.isConstant = false;
    const color = new InputBlock("Color3");
    color.value = new Color3(1, 1, 1);
    color.isConstant = false;
    const fragmentOutput = new FragmentOutputBlock("FragmentOutput");
    const vectorMerger = new VectorMergerBlock("VectorMerger");
    vectorMerger.visibleInInspector = false;
    const cos = new TrigonometryBlock("Cos");
    cos.operation = TrigonometryBlockOperations.Cos;
    position.connectTo(vectorMerger);
    time.output.connectTo(cos.input);
    cos.output.connectTo(vectorMerger.z);
    vectorMerger.xyzOut.connectTo(fragmentOutput.rgb);
    this.addOutputNode(vertexOutput);
    this.addOutputNode(fragmentOutput);
    this._mode = NodeMaterialModes.ProceduralTexture;
  }
  setToDefaultParticle() {
    this.clear();
    this.editorData = null;
    const uv = new InputBlock("uv");
    uv.setAsAttribute("particle_uv");
    const texture = new ParticleTextureBlock("ParticleTexture");
    uv.connectTo(texture);
    const color = new InputBlock("Color");
    color.setAsAttribute("particle_color");
    const multiply = new MultiplyBlock("Texture * Color");
    texture.connectTo(multiply);
    color.connectTo(multiply);
    const rampGradient = new ParticleRampGradientBlock("ParticleRampGradient");
    multiply.connectTo(rampGradient);
    const cSplitter = new ColorSplitterBlock("ColorSplitter");
    color.connectTo(cSplitter);
    const blendMultiply = new ParticleBlendMultiplyBlock("ParticleBlendMultiply");
    rampGradient.connectTo(blendMultiply);
    texture.connectTo(blendMultiply, { output: "a" });
    cSplitter.connectTo(blendMultiply, { output: "a" });
    const fragmentOutput = new FragmentOutputBlock("FragmentOutput");
    blendMultiply.connectTo(fragmentOutput);
    this.addOutputNode(fragmentOutput);
    this._mode = NodeMaterialModes.Particle;
  }
  async loadAsync(url, rootUrl = "") {
    return NodeMaterial.ParseFromFileAsync("", url, this.getScene(), rootUrl, true, this);
  }
  _gatherBlocks(rootNode, list) {
    if (list.indexOf(rootNode) !== -1) {
      return;
    }
    list.push(rootNode);
    for (const input of rootNode.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint) {
        const block = connectedPoint.ownerBlock;
        if (block !== rootNode) {
          this._gatherBlocks(block, list);
        }
      }
    }
    if (rootNode.isTeleportOut) {
      const block = rootNode;
      if (block.entryPoint) {
        this._gatherBlocks(block.entryPoint, list);
      }
    }
  }
  generateCode() {
    let alreadyDumped = [];
    const vertexBlocks = [];
    const uniqueNames = ["const", "var", "let"];
    for (const outputNode of this._vertexOutputNodes) {
      this._gatherBlocks(outputNode, vertexBlocks);
    }
    const fragmentBlocks = [];
    for (const outputNode of this._fragmentOutputNodes) {
      this._gatherBlocks(outputNode, fragmentBlocks);
    }
    let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");
`;
    codeString += `nodeMaterial.mode = BABYLON.NodeMaterialModes.${NodeMaterialModes[this.mode]};
`;
    for (const node of vertexBlocks) {
      if (node.isInput && alreadyDumped.indexOf(node) === -1) {
        codeString += node._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    for (const node of fragmentBlocks) {
      if (node.isInput && alreadyDumped.indexOf(node) === -1) {
        codeString += node._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    alreadyDumped = [];
    codeString += `
// Connections
`;
    for (const node of this._vertexOutputNodes) {
      codeString += node._dumpCodeForOutputConnections(alreadyDumped);
    }
    for (const node of this._fragmentOutputNodes) {
      codeString += node._dumpCodeForOutputConnections(alreadyDumped);
    }
    codeString += `
// Output nodes
`;
    for (const node of this._vertexOutputNodes) {
      codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});
`;
    }
    for (const node of this._fragmentOutputNodes) {
      codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});
`;
    }
    codeString += `nodeMaterial.build();
`;
    return codeString;
  }
  serialize(selectedBlocks) {
    const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
    serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData));
    let blocks = [];
    if (selectedBlocks) {
      blocks = selectedBlocks;
    } else {
      serializationObject.customType = "BABYLON.NodeMaterial";
      serializationObject.outputNodes = [];
      for (const outputNode of this._vertexOutputNodes) {
        this._gatherBlocks(outputNode, blocks);
        serializationObject.outputNodes.push(outputNode.uniqueId);
      }
      for (const outputNode of this._fragmentOutputNodes) {
        this._gatherBlocks(outputNode, blocks);
        if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {
          serializationObject.outputNodes.push(outputNode.uniqueId);
        }
      }
    }
    serializationObject.blocks = [];
    for (const block of blocks) {
      serializationObject.blocks.push(block.serialize());
    }
    if (!selectedBlocks) {
      for (const block of this.attachedBlocks) {
        if (blocks.indexOf(block) !== -1) {
          continue;
        }
        serializationObject.blocks.push(block.serialize());
      }
    }
    serializationObject.uniqueId = this.uniqueId;
    return serializationObject;
  }
  _restoreConnections(block, source, map) {
    for (const outputPoint of block.outputs) {
      for (const candidate of source.blocks) {
        const target = map[candidate.id];
        if (!target) {
          continue;
        }
        for (const input of candidate.inputs) {
          if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
            const inputPoint = target.getInputByName(input.inputName);
            if (!inputPoint || inputPoint.isConnected) {
              continue;
            }
            outputPoint.connectTo(inputPoint, true);
            this._restoreConnections(target, source, map);
            continue;
          }
        }
      }
    }
  }
  parseSerializedObject(source, rootUrl = "", merge = false, urlRewriter) {
    if (!merge) {
      this.clear();
    }
    const map = {};
    for (const parsedBlock of source.blocks) {
      const blockType = GetClass(parsedBlock.customType);
      if (blockType) {
        const block = new blockType;
        block._deserialize(parsedBlock, this.getScene(), rootUrl, urlRewriter);
        map[parsedBlock.id] = block;
        this.attachedBlocks.push(block);
      }
    }
    for (const block of this.attachedBlocks) {
      if (block.isTeleportOut) {
        const teleportOut = block;
        const id = teleportOut._tempEntryPointUniqueId;
        if (id) {
          const source2 = map[id];
          source2.attachToEndpoint(teleportOut);
        }
      }
    }
    for (let blockIndex = 0;blockIndex < source.blocks.length; blockIndex++) {
      const parsedBlock = source.blocks[blockIndex];
      const block = map[parsedBlock.id];
      if (!block) {
        continue;
      }
      if (block.inputs.length && !merge) {
        continue;
      }
      this._restoreConnections(block, source, map);
    }
    if (source.outputNodes) {
      for (const outputNodeId of source.outputNodes) {
        this.addOutputNode(map[outputNodeId]);
      }
    }
    if (source.locations || source.editorData && source.editorData.locations) {
      const locations = source.locations || source.editorData.locations;
      for (const location2 of locations) {
        if (map[location2.blockId]) {
          location2.blockId = map[location2.blockId].uniqueId;
        }
      }
      if (merge && this.editorData && this.editorData.locations) {
        locations.concat(this.editorData.locations);
      }
      if (source.locations) {
        this.editorData = {
          locations
        };
      } else {
        this.editorData = source.editorData;
        this.editorData.locations = locations;
      }
      const blockMap = [];
      for (const key in map) {
        blockMap[key] = map[key].uniqueId;
      }
      this.editorData.map = blockMap;
    }
    this.comment = source.comment;
    if (source.forceAlphaBlending !== undefined) {
      this.forceAlphaBlending = source.forceAlphaBlending;
    }
    if (source.alphaMode !== undefined) {
      this.alphaMode = source.alphaMode;
    }
    if (!merge) {
      this._mode = source.mode ?? NodeMaterialModes.Material;
    }
  }
  loadFromSerialization(source, rootUrl = "", merge = false) {
    this.parseSerializedObject(source, rootUrl, merge);
  }
  clone(name327, shareEffect = false) {
    const serializationObject = this.serialize();
    const clone = SerializationHelper.Clone(() => new NodeMaterial(name327, this.getScene(), this.options), this);
    clone.id = name327;
    clone.name = name327;
    clone.parseSerializedObject(serializationObject);
    clone._buildId = this._buildId;
    clone.build(false, !shareEffect);
    return clone;
  }
  whenTexturesReadyAsync() {
    const textureReadyPromises = [];
    this.getActiveTextures().forEach((texture) => {
      const internalTexture = texture.getInternalTexture();
      if (internalTexture && !internalTexture.isReady) {
        textureReadyPromises.push(new Promise((textureResolve, textureReject) => {
          internalTexture.onLoadedObservable.addOnce(() => {
            textureResolve();
          });
          internalTexture.onErrorObservable.addOnce((e) => {
            textureReject(e);
          });
        }));
      }
    });
    return Promise.all(textureReadyPromises);
  }
  static Parse(source, scene, rootUrl = "", shaderLanguage = 0) {
    const nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene, { shaderLanguage }), source, scene, rootUrl);
    nodeMaterial.parseSerializedObject(source, rootUrl);
    nodeMaterial.build();
    return nodeMaterial;
  }
  static async ParseFromFileAsync(name327, url, scene, rootUrl = "", skipBuild = false, targetMaterial, urlRewriter, options) {
    const material = targetMaterial ?? new NodeMaterial(name327, scene, options);
    const data = await scene._loadFileAsync(url);
    const serializationObject = JSON.parse(data);
    material.parseSerializedObject(serializationObject, rootUrl, undefined, urlRewriter);
    if (!skipBuild) {
      material.build();
    }
    return material;
  }
  static ParseFromSnippetAsync(snippetId, scene = EngineStore.LastCreatedScene, rootUrl = "", nodeMaterial, skipBuild = false, waitForTextureReadyness = false, urlRewriter, options) {
    if (snippetId === "_BLANK") {
      return Promise.resolve(NodeMaterial.CreateDefault("blank", scene));
    }
    return new Promise((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);
            const serializationObject = JSON.parse(snippet.nodeMaterial);
            if (!nodeMaterial) {
              nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene, options), serializationObject, scene, rootUrl);
              nodeMaterial.uniqueId = scene.getUniqueId();
            }
            nodeMaterial.parseSerializedObject(serializationObject, undefined, undefined, urlRewriter);
            nodeMaterial.snippetId = snippetId;
            nodeMaterial.sideOrientation = null;
            try {
              if (!skipBuild) {
                nodeMaterial.build();
              }
            } catch (err) {
              reject(err);
            }
            if (waitForTextureReadyness) {
              nodeMaterial.whenTexturesReadyAsync().then(() => {
                resolve3(nodeMaterial);
              }).catch((err) => {
                reject(err);
              });
            } else {
              resolve3(nodeMaterial);
            }
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
  static CreateDefault(name327, scene) {
    const newMaterial = new NodeMaterial(name327, scene);
    newMaterial.setToDefault();
    newMaterial.build();
    return newMaterial;
  }
}
NodeMaterial._BuildIdGenerator = 0;
NodeMaterial.EditorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/nodeEditor/babylon.nodeEditor.js`;
NodeMaterial.SnippetUrl = `https://snippet.babylonjs.com`;
NodeMaterial.IgnoreTexturesAtLoadTime = false;
NodeMaterial.DefaultShaderLanguage = 0;
NodeMaterial.UseNativeShaderLanguageOfEngine = false;
__decorate([
  serialize()
], NodeMaterial.prototype, "ignoreAlpha", undefined);
__decorate([
  serialize()
], NodeMaterial.prototype, "maxSimultaneousLights", undefined);
__decorate([
  serialize("mode")
], NodeMaterial.prototype, "_mode", undefined);
__decorate([
  serialize("comment")
], NodeMaterial.prototype, "comment", undefined);
__decorate([
  serialize()
], NodeMaterial.prototype, "forceAlphaBlending", undefined);
RegisterClass("BABYLON.NodeMaterial", NodeMaterial);

// node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js
init_animation();
init_easing();

// node_modules/@babylonjs/core/Meshes/subMesh.project.js
init_math_vector();
SubMesh.prototype._projectOnTrianglesToRef = function(vector, positions, indices, step, checkStopper, ref) {
  const proj = TmpVectors.Vector3[0];
  const tmp = TmpVectors.Vector3[1];
  let distance = Infinity;
  for (let index = this.indexStart;index < this.indexStart + this.indexCount - (3 - step); index += step) {
    const indexA = indices[index];
    const indexB = indices[index + 1];
    const indexC = indices[index + 2];
    if (checkStopper && indexC === 4294967295) {
      index += 2;
      continue;
    }
    const p0 = positions[indexA];
    const p1 = positions[indexB];
    const p2 = positions[indexC];
    if (!p0 || !p1 || !p2) {
      continue;
    }
    const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);
    if (tmpDist < distance) {
      proj.copyFrom(tmp);
      distance = tmpDist;
    }
  }
  ref.copyFrom(proj);
  return distance;
};
SubMesh.prototype._projectOnUnIndexedTrianglesToRef = function(vector, positions, indices, ref) {
  const proj = TmpVectors.Vector3[0];
  const tmp = TmpVectors.Vector3[1];
  let distance = Infinity;
  for (let index = this.verticesStart;index < this.verticesStart + this.verticesCount; index += 3) {
    const p0 = positions[index];
    const p1 = positions[index + 1];
    const p2 = positions[index + 2];
    const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);
    if (tmpDist < distance) {
      proj.copyFrom(tmp);
      distance = tmpDist;
    }
  }
  ref.copyFrom(proj);
  return distance;
};
SubMesh.prototype.projectToRef = function(vector, positions, indices, ref) {
  const material = this.getMaterial();
  if (!material) {
    return -1;
  }
  let step = 3;
  let checkStopper = false;
  switch (material.fillMode) {
    case 3:
    case 5:
    case 6:
    case 8:
      return -1;
    case 7:
      step = 1;
      checkStopper = true;
      break;
    default:
      break;
  }
  if (material.fillMode === 4) {
    return -1;
  } else {
    if (!indices.length && this._mesh._unIndexed) {
      return this._projectOnUnIndexedTrianglesToRef(vector, positions, indices, ref);
    }
    return this._projectOnTrianglesToRef(vector, positions, indices, step, checkStopper, ref);
  }
};

// node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js
init_logger();
var ControllerOrbAnimationState;
(function(ControllerOrbAnimationState2) {
  ControllerOrbAnimationState2[ControllerOrbAnimationState2["DEHYDRATED"] = 0] = "DEHYDRATED";
  ControllerOrbAnimationState2[ControllerOrbAnimationState2["HOVER"] = 1] = "HOVER";
  ControllerOrbAnimationState2[ControllerOrbAnimationState2["TOUCH"] = 2] = "TOUCH";
})(ControllerOrbAnimationState || (ControllerOrbAnimationState = {}));
var WebXRNearControllerMode;
(function(WebXRNearControllerMode2) {
  WebXRNearControllerMode2[WebXRNearControllerMode2["DISABLED"] = 0] = "DISABLED";
  WebXRNearControllerMode2[WebXRNearControllerMode2["CENTERED_ON_CONTROLLER"] = 1] = "CENTERED_ON_CONTROLLER";
  WebXRNearControllerMode2[WebXRNearControllerMode2["CENTERED_IN_FRONT"] = 2] = "CENTERED_IN_FRONT";
})(WebXRNearControllerMode || (WebXRNearControllerMode = {}));
var _tmpVectors = [new Vector3, new Vector3, new Vector3, new Vector3];

class WebXRNearInteraction extends WebXRAbstractFeature {
  constructor(_xrSessionManager, _options) {
    super(_xrSessionManager);
    this._options = _options;
    this._tmpRay = new Ray(new Vector3, new Vector3);
    this._attachController = (xrController) => {
      if (this._controllers[xrController.uniqueId]) {
        return;
      }
      const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh();
      const selectionMesh = this._generateVisualCue();
      this._controllers[xrController.uniqueId] = {
        xrController,
        meshUnderPointer: null,
        nearInteractionTargetMesh: null,
        pick: null,
        stalePick: null,
        touchCollisionMesh,
        touchCollisionMeshFunction,
        hydrateCollisionMeshFunction,
        currentAnimationState: ControllerOrbAnimationState.DEHYDRATED,
        grabRay: new Ray(new Vector3, new Vector3),
        hoverInteraction: false,
        nearInteraction: false,
        grabInteraction: false,
        downTriggered: false,
        id: WebXRNearInteraction._IdCounter++,
        pickedPointVisualCue: selectionMesh
      };
      this._controllers[xrController.uniqueId]._worldScaleObserver = this._controllers[xrController.uniqueId]._worldScaleObserver || this._xrSessionManager.onWorldScaleFactorChangedObservable.add((values) => {
        if (values.newScaleFactor !== values.previousScaleFactor) {
          this._controllers[xrController.uniqueId].touchCollisionMesh.dispose();
          this._controllers[xrController.uniqueId].pickedPointVisualCue.dispose();
          const { touchCollisionMesh: touchCollisionMesh2, touchCollisionMeshFunction: touchCollisionMeshFunction2, hydrateCollisionMeshFunction: hydrateCollisionMeshFunction2 } = this._generateNewTouchPointMesh();
          this._controllers[xrController.uniqueId].touchCollisionMesh = touchCollisionMesh2;
          this._controllers[xrController.uniqueId].touchCollisionMeshFunction = touchCollisionMeshFunction2;
          this._controllers[xrController.uniqueId].hydrateCollisionMeshFunction = hydrateCollisionMeshFunction2;
          this._controllers[xrController.uniqueId].pickedPointVisualCue = this._generateVisualCue();
        }
      });
      if (this._attachedController) {
        if (!this._options.enableNearInteractionOnAllControllers && this._options.preferredHandedness && xrController.inputSource.handedness === this._options.preferredHandedness) {
          this._attachedController = xrController.uniqueId;
        }
      } else {
        if (!this._options.enableNearInteractionOnAllControllers) {
          this._attachedController = xrController.uniqueId;
        }
      }
      switch (xrController.inputSource.targetRayMode) {
        case "tracked-pointer":
          return this._attachNearInteractionMode(xrController);
        case "gaze":
          return null;
        case "screen":
          return null;
      }
    };
    this._controllers = {};
    this._farInteractionFeature = null;
    this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);
    this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1);
    this.alwaysHideSelectionMesh = false;
    this._hoverRadius = 0.1;
    this._pickRadius = 0.02;
    this._controllerPickRadius = 0.03;
    this._nearGrabLengthScale = 5;
    this._scene = this._xrSessionManager.scene;
    if (this._options.nearInteractionControllerMode === undefined) {
      this._options.nearInteractionControllerMode = 2;
    }
    if (this._options.farInteractionFeature) {
      this._farInteractionFeature = this._options.farInteractionFeature;
    }
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    this._options.xrInput.controllers.forEach(this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
      this._detachController(controller.uniqueId);
    });
    this._scene.constantlyUpdateMeshUnderPointer = true;
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      this._detachController(controllerId);
    });
    return true;
  }
  getMeshUnderPointer(controllerId) {
    if (this._controllers[controllerId]) {
      return this._controllers[controllerId].meshUnderPointer;
    } else {
      return null;
    }
  }
  getXRControllerByPointerId(id) {
    const keys = Object.keys(this._controllers);
    for (let i = 0;i < keys.length; ++i) {
      if (this._controllers[keys[i]].id === id) {
        return this._controllers[keys[i]].xrController || null;
      }
    }
    return null;
  }
  setFarInteractionFeature(farInteractionFeature) {
    this._farInteractionFeature = farInteractionFeature;
  }
  _nearPickPredicate(mesh) {
    return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable;
  }
  _nearGrabPredicate(mesh) {
    return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable;
  }
  _nearInteractionPredicate(mesh) {
    return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable);
  }
  _controllerAvailablePredicate(mesh, controllerId) {
    let parent = mesh;
    while (parent) {
      if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) {
        return false;
      }
      parent = parent.parent;
    }
    return true;
  }
  _handleTransitionAnimation(controllerData, newState) {
    if (controllerData.currentAnimationState === newState || this._options.nearInteractionControllerMode !== 2 || !!controllerData.xrController?.inputSource.hand) {
      return;
    }
    if (newState > controllerData.currentAnimationState) {
      switch (controllerData.currentAnimationState) {
        case ControllerOrbAnimationState.DEHYDRATED: {
          controllerData.hydrateCollisionMeshFunction(true);
          if (newState === ControllerOrbAnimationState.HOVER) {
            break;
          }
        }
        case ControllerOrbAnimationState.HOVER: {
          controllerData.touchCollisionMeshFunction(true);
          if (newState === ControllerOrbAnimationState.TOUCH) {
            break;
          }
        }
      }
    } else {
      switch (controllerData.currentAnimationState) {
        case ControllerOrbAnimationState.TOUCH: {
          controllerData.touchCollisionMeshFunction(false);
          if (newState === ControllerOrbAnimationState.HOVER) {
            break;
          }
        }
        case ControllerOrbAnimationState.HOVER: {
          controllerData.hydrateCollisionMeshFunction(false);
          if (newState === ControllerOrbAnimationState.DEHYDRATED) {
            break;
          }
        }
      }
    }
    controllerData.currentAnimationState = newState;
  }
  _processTouchPoint(id, position, orientation) {
    const controllerData = this._controllers[id];
    controllerData.grabRay.origin.copyFrom(position);
    orientation.toEulerAnglesToRef(TmpVectors.Vector3[0]);
    controllerData.grabRay.direction.copyFrom(TmpVectors.Vector3[0]);
    if (this._options.nearInteractionControllerMode === 2 && !controllerData.xrController?.inputSource.hand) {
      controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);
      controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05));
    }
    controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius * this._xrSessionManager.worldScalingFactor;
    controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor);
  }
  _onXRFrame(_xrFrame) {
    Object.keys(this._controllers).forEach((id) => {
      const controllerData = this._controllers[id];
      const handData = controllerData.xrController?.inputSource.hand;
      if (!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController || !controllerData.xrController || !handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad)) {
        controllerData.pick = null;
        return;
      }
      controllerData.hoverInteraction = false;
      controllerData.nearInteraction = false;
      if (controllerData.xrController) {
        if (handData) {
          const xrIndexTip = handData.get("index-finger-tip");
          if (xrIndexTip) {
            const indexTipPose = _xrFrame.getJointPose(xrIndexTip, this._xrSessionManager.referenceSpace);
            if (indexTipPose && indexTipPose.transform) {
              const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1;
              TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier);
              TmpVectors.Quaternion[0].set(indexTipPose.transform.orientation.x, indexTipPose.transform.orientation.y, indexTipPose.transform.orientation.z * axisRHSMultiplier, indexTipPose.transform.orientation.w * axisRHSMultiplier);
              this._processTouchPoint(id, TmpVectors.Vector3[0], TmpVectors.Quaternion[0]);
            }
          }
        } else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== 0) {
          let controllerPose = controllerData.xrController.pointer;
          if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === 1) {
            controllerPose = controllerData.xrController.grip;
          }
          this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion);
        }
      } else {
        return;
      }
      const accuratePickInfo = (originalScenePick, utilityScenePick) => {
        let pick = null;
        if (!utilityScenePick || !utilityScenePick.hit) {
          pick = originalScenePick;
        } else if (!originalScenePick || !originalScenePick.hit) {
          pick = utilityScenePick;
        } else if (utilityScenePick.distance < originalScenePick.distance) {
          pick = utilityScenePick;
        } else {
          pick = originalScenePick;
        }
        return pick;
      };
      const populateNearInteractionInfo = (nearInteractionInfo) => {
        let result = new PickingInfo;
        let nearInteractionAtOrigin = false;
        const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit;
        if (nearInteractionInfo?.pickedPoint) {
          nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0;
        }
        if (nearInteraction && !nearInteractionAtOrigin) {
          result = nearInteractionInfo;
        }
        return result;
      };
      if (!controllerData.grabInteraction) {
        let pick = null;
        let utilitySceneHoverPick = null;
        if (this._options.useUtilityLayer && this._utilityLayerScene) {
          utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius * this._xrSessionManager.worldScalingFactor, this._utilityLayerScene, (mesh) => this._nearInteractionPredicate(mesh));
        }
        const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius * this._xrSessionManager.worldScalingFactor, this._scene, (mesh) => this._nearInteractionPredicate(mesh));
        const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick);
        if (hoverPickInfo && hoverPickInfo.hit) {
          pick = populateNearInteractionInfo(hoverPickInfo);
          if (pick.hit) {
            controllerData.hoverInteraction = true;
          }
        }
        if (controllerData.hoverInteraction) {
          let utilitySceneNearPick = null;
          const radius = (handData ? this._pickRadius : this._controllerPickRadius) * this._xrSessionManager.worldScalingFactor;
          if (this._options.useUtilityLayer && this._utilityLayerScene) {
            utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh) => this._nearPickPredicate(mesh));
          }
          const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh) => this._nearPickPredicate(mesh));
          const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick);
          const nearPick = populateNearInteractionInfo(pickInfo);
          if (nearPick.hit) {
            pick = nearPick;
            controllerData.nearInteraction = true;
          }
        }
        controllerData.stalePick = controllerData.pick;
        controllerData.pick = pick;
        if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) {
          controllerData.meshUnderPointer = controllerData.pick.pickedMesh;
          controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint);
          controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh;
          if (this._farInteractionFeature && this._farInteractionFeature.attached) {
            this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true);
          }
        } else {
          controllerData.meshUnderPointer = null;
          controllerData.pickedPointVisualCue.isVisible = false;
          if (this._farInteractionFeature && this._farInteractionFeature.attached) {
            this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false);
          }
        }
      }
      let state = ControllerOrbAnimationState.DEHYDRATED;
      if (controllerData.grabInteraction || controllerData.nearInteraction) {
        state = ControllerOrbAnimationState.TOUCH;
      } else if (controllerData.hoverInteraction) {
        state = ControllerOrbAnimationState.HOVER;
      }
      this._handleTransitionAnimation(controllerData, state);
    });
  }
  get _utilityLayerScene() {
    return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;
  }
  _generateVisualCue() {
    const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;
    const selectionMesh = CreateSphere("nearInteraction", {
      diameter: 0.0035 * 3 * this._xrSessionManager.worldScalingFactor
    }, sceneToRenderTo);
    selectionMesh.bakeCurrentTransformIntoVertices();
    selectionMesh.isPickable = false;
    selectionMesh.isVisible = false;
    selectionMesh.rotationQuaternion = Quaternion.Identity();
    const targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
    targetMat.specularColor = Color3.Black();
    targetMat.emissiveColor = this.selectionMeshDefaultColor;
    targetMat.backFaceCulling = false;
    selectionMesh.material = targetMat;
    return selectionMesh;
  }
  _isControllerReadyForNearInteraction(id) {
    if (this._farInteractionFeature) {
      return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id);
    }
    return true;
  }
  _attachNearInteractionMode(xrController) {
    const controllerData = this._controllers[xrController.uniqueId];
    const pointerEventInit = {
      pointerId: controllerData.id,
      pointerType: "xr-near"
    };
    controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
      if (!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController || !controllerData.xrController || !controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad)) {
        return;
      }
      if (controllerData.pick) {
        controllerData.pick.ray = controllerData.grabRay;
      }
      if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) {
        this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
      }
      if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) {
        if (!controllerData.nearInteractionTargetMesh) {
          this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
          controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer;
          controllerData.downTriggered = true;
        }
      } else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) {
        this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit);
        controllerData.downTriggered = false;
        controllerData.nearInteractionTargetMesh = null;
      }
    });
    const grabCheck = (pressed) => {
      if (this._options.enableNearInteractionOnAllControllers || xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id)) {
        if (controllerData.pick) {
          controllerData.pick.ray = controllerData.grabRay;
        }
        if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) {
          controllerData.grabInteraction = true;
          controllerData.pickedPointVisualCue.isVisible = false;
          this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
          controllerData.downTriggered = true;
        } else if (!pressed && controllerData.pick && controllerData.grabInteraction) {
          this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
          controllerData.downTriggered = false;
          controllerData.grabInteraction = false;
          controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh;
        }
      } else {
        if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) {
          this._attachedController = xrController.uniqueId;
        }
      }
    };
    if (xrController.inputSource.gamepad) {
      const init = (motionController) => {
        controllerData.squeezeComponent = motionController.getComponent("grasp");
        if (controllerData.squeezeComponent) {
          controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => {
            if (component.changes.pressed) {
              const pressed = component.changes.pressed.current;
              grabCheck(pressed);
            }
          });
        } else {
          controllerData.selectionComponent = motionController.getMainComponent();
          controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
            if (component.changes.pressed) {
              const pressed = component.changes.pressed.current;
              grabCheck(pressed);
            }
          });
        }
      };
      if (xrController.motionController) {
        init(xrController.motionController);
      } else {
        xrController.onMotionControllerInitObservable.add(init);
      }
    } else {
      const selectStartListener = (event) => {
        if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id) && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) {
          controllerData.grabInteraction = true;
          controllerData.pickedPointVisualCue.isVisible = false;
          this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
          controllerData.downTriggered = true;
        }
      };
      const selectEndListener = (event) => {
        if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) {
          this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
          controllerData.grabInteraction = false;
          controllerData.pickedPointVisualCue.isVisible = !this.alwaysHideSelectionMesh;
          controllerData.downTriggered = false;
        }
      };
      controllerData.eventListeners = {
        selectend: selectEndListener,
        selectstart: selectStartListener
      };
      this._xrSessionManager.session.addEventListener("selectstart", selectStartListener);
      this._xrSessionManager.session.addEventListener("selectend", selectEndListener);
    }
  }
  _detachController(xrControllerUniqueId) {
    const controllerData = this._controllers[xrControllerUniqueId];
    if (!controllerData) {
      return;
    }
    if (controllerData.squeezeComponent) {
      if (controllerData.onSqueezeButtonChangedObserver) {
        controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver);
      }
    }
    if (controllerData.selectionComponent) {
      if (controllerData.onButtonChangedObserver) {
        controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
      }
    }
    if (controllerData.onFrameObserver) {
      this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
    }
    if (controllerData.eventListeners) {
      Object.keys(controllerData.eventListeners).forEach((eventName) => {
        const func = controllerData.eventListeners && controllerData.eventListeners[eventName];
        if (func) {
          this._xrSessionManager.session.removeEventListener(eventName, func);
        }
      });
    }
    controllerData.touchCollisionMesh.dispose();
    controllerData.pickedPointVisualCue.dispose();
    this._xrSessionManager.runInXRFrame(() => {
      if (!controllerData.downTriggered) {
        return;
      }
      const pointerEventInit = {
        pointerId: controllerData.id,
        pointerType: "xr-near"
      };
      this._scene.simulatePointerUp(new PickingInfo, pointerEventInit);
    });
    if (controllerData._worldScaleObserver) {
      this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(controllerData._worldScaleObserver);
    }
    delete this._controllers[xrControllerUniqueId];
    if (this._attachedController === xrControllerUniqueId) {
      const keys = Object.keys(this._controllers);
      if (keys.length) {
        this._attachedController = keys[0];
      } else {
        this._attachedController = "";
      }
    }
  }
  _generateNewTouchPointMesh() {
    const worldScale = this._xrSessionManager.worldScalingFactor;
    const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;
    const touchCollisionMesh = CreateSphere("PickSphere", { diameter: 1 * worldScale }, meshCreationScene);
    touchCollisionMesh.isVisible = false;
    if (this._options.motionControllerOrbMaterial) {
      touchCollisionMesh.material = this._options.motionControllerOrbMaterial;
    } else {
      let parsePromise;
      if (this._options.motionControllerTouchMaterialSnippetUrl) {
        parsePromise = NodeMaterial.ParseFromFileAsync("motionControllerTouchMaterial", this._options.motionControllerTouchMaterialSnippetUrl, meshCreationScene);
      } else {
        parsePromise = NodeMaterial.ParseFromSnippetAsync("8RUNKL#3", meshCreationScene);
      }
      parsePromise.then((mat) => {
        touchCollisionMesh.material = mat;
      }).catch((err) => {
        Logger.Warn(`Error creating touch material in WebXRNearInteraction: ${err}`);
      });
    }
    const easingFunction = new QuadraticEase;
    easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
    const hoverSizeVec = new Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius).scaleInPlace(worldScale);
    const touchSize = this._controllerPickRadius * (4 / 3);
    const touchSizeVec = new Vector3(touchSize, touchSize, touchSize).scaleInPlace(worldScale);
    const hydrateTransitionSize = this._controllerPickRadius * (7 / 6);
    const hydrateTransitionSizeVec = new Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize).scaleInPlace(worldScale);
    const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5);
    const touchHoverTransitionSizeVec = new Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize).scaleInPlace(worldScale);
    const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2);
    const hoverTouchTransitionSizeVec = new Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize).scaleInPlace(worldScale);
    const touchKeys = [
      { frame: 0, value: hoverSizeVec },
      { frame: 10, value: hoverTouchTransitionSizeVec },
      { frame: 18, value: touchSizeVec }
    ];
    const releaseKeys = [
      { frame: 0, value: touchSizeVec },
      { frame: 10, value: touchHoverTransitionSizeVec },
      { frame: 18, value: hoverSizeVec }
    ];
    const hydrateKeys = [
      { frame: 0, value: Vector3.ZeroReadOnly },
      { frame: 12, value: hydrateTransitionSizeVec },
      { frame: 15, value: hoverSizeVec }
    ];
    const dehydrateKeys = [
      { frame: 0, value: hoverSizeVec },
      { frame: 10, value: Vector3.ZeroReadOnly },
      { frame: 15, value: Vector3.ZeroReadOnly }
    ];
    const touchAction = new Animation("touch", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const releaseAction = new Animation("release", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const hydrateAction = new Animation("hydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
    const dehydrateAction = new Animation("dehydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
    touchAction.setEasingFunction(easingFunction);
    releaseAction.setEasingFunction(easingFunction);
    hydrateAction.setEasingFunction(easingFunction);
    dehydrateAction.setEasingFunction(easingFunction);
    touchAction.setKeys(touchKeys);
    releaseAction.setKeys(releaseKeys);
    hydrateAction.setKeys(hydrateKeys);
    dehydrateAction.setKeys(dehydrateKeys);
    const touchCollisionMeshFunction = (isTouch) => {
      const action2 = isTouch ? touchAction : releaseAction;
      meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action2], 0, 18, false, 1);
    };
    const hydrateCollisionMeshFunction = (isHydration) => {
      const action2 = isHydration ? hydrateAction : dehydrateAction;
      if (isHydration) {
        touchCollisionMesh.isVisible = true;
      }
      meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action2], 0, 15, false, 1, () => {
        if (!isHydration) {
          touchCollisionMesh.isVisible = false;
        }
      });
    };
    return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction };
  }
  _pickWithSphere(controllerData, radius, sceneToUse, predicate) {
    const pickingInfo2 = new PickingInfo;
    pickingInfo2.distance = Infinity;
    if (controllerData.touchCollisionMesh && controllerData.xrController) {
      const position = controllerData.touchCollisionMesh.position;
      const sphere = BoundingSphere.CreateFromCenterAndRadius(position, radius);
      for (let meshIndex = 0;meshIndex < sceneToUse.meshes.length; meshIndex++) {
        const mesh = sceneToUse.meshes[meshIndex];
        if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) {
          continue;
        }
        const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere);
        if (result && result.hit && result.distance < pickingInfo2.distance) {
          pickingInfo2.hit = result.hit;
          pickingInfo2.pickedMesh = mesh;
          pickingInfo2.pickedPoint = result.pickedPoint;
          pickingInfo2.aimTransform = controllerData.xrController.pointer;
          pickingInfo2.gripTransform = controllerData.xrController.grip || null;
          pickingInfo2.originMesh = controllerData.touchCollisionMesh;
          pickingInfo2.distance = result.distance;
          pickingInfo2.bu = result.bu;
          pickingInfo2.bv = result.bv;
          pickingInfo2.faceId = result.faceId;
          pickingInfo2.subMeshId = result.subMeshId;
        }
      }
    }
    return pickingInfo2;
  }
  static PickMeshWithSphere(mesh, sphere, skipBoundingInfo = false) {
    const subMeshes = mesh.subMeshes;
    const pi = new PickingInfo;
    const boundingInfo2 = mesh.getBoundingInfo();
    if (!mesh._generatePointsArray()) {
      return pi;
    }
    if (!mesh.subMeshes || !boundingInfo2) {
      return pi;
    }
    if (!skipBoundingInfo && !BoundingSphere.Intersects(boundingInfo2.boundingSphere, sphere)) {
      return pi;
    }
    const result = _tmpVectors[0];
    const tmpVec = _tmpVectors[1];
    _tmpVectors[2].setAll(0);
    _tmpVectors[3].setAll(0);
    const tmpRay = new Ray(_tmpVectors[2], _tmpVectors[3], 1);
    let distance = Infinity;
    let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter, intersectionInfo2;
    const center = TmpVectors.Vector3[2];
    const worldToMesh = TmpVectors.Matrix[0];
    worldToMesh.copyFrom(mesh.getWorldMatrix());
    worldToMesh.invert();
    Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center);
    for (let index = 0;index < subMeshes.length; index++) {
      const subMesh = subMeshes[index];
      subMesh.projectToRef(center, mesh._positions, mesh.getIndices(), tmpVec);
      Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec);
      tmp = Vector3.Distance(tmpVec, sphere.center);
      tmpDistanceSurfaceToCenter = Vector3.DistanceSquared(tmpVec, mesh.getAbsolutePosition());
      tmpDistanceSphereToCenter = Vector3.DistanceSquared(sphere.center, mesh.getAbsolutePosition());
      if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) {
        tmp = 0;
        tmpVec.copyFrom(sphere.center);
      }
      if (tmp !== -1 && tmp < distance) {
        distance = tmp;
        Ray.CreateFromToToRef(sphere.center, tmpVec, tmpRay);
        tmpRay.length = distance * 2;
        intersectionInfo2 = tmpRay.intersectsMesh(mesh);
        result.copyFrom(tmpVec);
      }
    }
    if (distance < sphere.radius) {
      pi.hit = true;
      pi.distance = distance;
      pi.pickedMesh = mesh;
      pi.pickedPoint = result.clone();
      if (intersectionInfo2 && intersectionInfo2.bu !== null && intersectionInfo2.bv !== null) {
        pi.faceId = intersectionInfo2.faceId;
        pi.subMeshId = intersectionInfo2.subMeshId;
        pi.bu = intersectionInfo2.bu;
        pi.bv = intersectionInfo2.bv;
      }
    }
    return pi;
  }
}
WebXRNearInteraction._IdCounter = 200;
WebXRNearInteraction.Name = WebXRFeatureName.NEAR_INTERACTION;
WebXRNearInteraction.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, (xrSessionManager, options) => {
  return () => new WebXRNearInteraction(xrSessionManager, options);
}, WebXRNearInteraction.Version, true);

// node_modules/@babylonjs/core/XR/webXREnterExitUI.js
init_observable();
init_tools();

class WebXREnterExitUIButton {
  constructor(element, sessionMode, referenceSpaceType) {
    this.element = element;
    this.sessionMode = sessionMode;
    this.referenceSpaceType = referenceSpaceType;
  }
  update(activeButton) {}
}
class WebXREnterExitUI {
  constructor(_scene, options) {
    this._scene = _scene;
    this.options = options;
    this._activeButton = null;
    this._buttons = [];
    this.activeButtonChangedObservable = new Observable;
    this._onSessionGranted = (evt) => {
      if (this._helper) {
        this._enterXRWithButtonIndex(0);
      }
    };
    this.overlay = document.createElement("div");
    this.overlay.classList.add("xr-button-overlay");
    if (!options.ignoreSessionGrantedEvent && navigator.xr) {
      navigator.xr.addEventListener("sessiongranted", this._onSessionGranted);
    }
    if (typeof window !== "undefined") {
      if (window.location && window.location.protocol === "http:" && window.location.hostname !== "localhost") {
        Tools.Warn("WebXR can only be served over HTTPS");
        throw new Error("WebXR can only be served over HTTPS");
      }
    }
    if (options.customButtons) {
      this._buttons = options.customButtons;
    } else {
      this.overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
      const sessionMode = options.sessionMode || "immersive-vr";
      const referenceSpaceType = options.referenceSpaceType || "local-floor";
      const url = typeof SVGSVGElement === "undefined" ? "https://cdn.babylonjs.com/Assets/vrButton.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A";
      let css = ".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + url + "); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
      css += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';
      const style = document.createElement("style");
      style.appendChild(document.createTextNode(css));
      document.getElementsByTagName("head")[0].appendChild(style);
      const hmdBtn = document.createElement("button");
      hmdBtn.className = "babylonVRicon";
      hmdBtn.title = `${sessionMode} - ${referenceSpaceType}`;
      this._buttons.push(new WebXREnterExitUIButton(hmdBtn, sessionMode, referenceSpaceType));
      this._buttons[this._buttons.length - 1].update = function(activeButton) {
        this.element.style.display = activeButton === null || activeButton === this ? "" : "none";
        hmdBtn.className = "babylonVRicon" + (activeButton === this ? " vrdisplaypresenting" : "");
      };
      this._updateButtons(null);
    }
    const renderCanvas = _scene.getEngine().getInputElement();
    if (renderCanvas && renderCanvas.parentNode) {
      renderCanvas.parentNode.appendChild(this.overlay);
      _scene.onDisposeObservable.addOnce(() => {
        this.dispose();
      });
    }
  }
  async setHelperAsync(helper, renderTarget) {
    this._helper = helper;
    this._renderTarget = renderTarget;
    const supportedPromises = this._buttons.map((btn) => {
      return helper.sessionManager.isSessionSupportedAsync(btn.sessionMode);
    });
    helper.onStateChangedObservable.add((state) => {
      if (state == 3) {
        this._updateButtons(null);
      }
    });
    const results = await Promise.all(supportedPromises);
    results.forEach((supported, i) => {
      if (supported) {
        this.overlay.appendChild(this._buttons[i].element);
        this._buttons[i].element.onclick = this._enterXRWithButtonIndex.bind(this, i);
      } else {
        Tools.Warn(`Session mode "${this._buttons[i].sessionMode}" not supported in browser`);
      }
    });
  }
  static async CreateAsync(scene, helper, options) {
    const ui = new WebXREnterExitUI(scene, options);
    await ui.setHelperAsync(helper, options.renderTarget || undefined);
    return ui;
  }
  async _enterXRWithButtonIndex(idx = 0) {
    if (this._helper.state == 2) {
      await this._helper.exitXRAsync();
      this._updateButtons(null);
    } else if (this._helper.state == 3) {
      try {
        await this._helper.enterXRAsync(this._buttons[idx].sessionMode, this._buttons[idx].referenceSpaceType, this._renderTarget, {
          optionalFeatures: this.options.optionalFeatures,
          requiredFeatures: this.options.requiredFeatures
        });
        this._updateButtons(this._buttons[idx]);
      } catch (e) {
        this._updateButtons(null);
        const element = this._buttons[idx].element;
        const prevTitle = element.title;
        element.title = "Error entering XR session : " + prevTitle;
        element.classList.add("xr-error");
        if (this.options.onError) {
          this.options.onError(e);
        }
      }
    }
  }
  dispose() {
    const renderCanvas = this._scene.getEngine().getInputElement();
    if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this.overlay)) {
      renderCanvas.parentNode.removeChild(this.overlay);
    }
    this.activeButtonChangedObservable.clear();
    navigator.xr.removeEventListener("sessiongranted", this._onSessionGranted);
  }
  _updateButtons(activeButton) {
    this._activeButton = activeButton;
    this._buttons.forEach((b) => {
      b.update(this._activeButton);
    });
    this.activeButtonChangedObservable.notifyObservers(this._activeButton);
  }
}

// node_modules/@babylonjs/core/XR/features/WebXRHandTracking.js
init_math_vector();
init_observable();
init_math_color();
init_math_axis();
init_engineStore();
init_tools();
var HandPart;
(function(HandPart2) {
  HandPart2["WRIST"] = "wrist";
  HandPart2["THUMB"] = "thumb";
  HandPart2["INDEX"] = "index";
  HandPart2["MIDDLE"] = "middle";
  HandPart2["RING"] = "ring";
  HandPart2["LITTLE"] = "little";
})(HandPart || (HandPart = {}));
var WebXRHandJoint;
(function(WebXRHandJoint2) {
  WebXRHandJoint2["WRIST"] = "wrist";
  WebXRHandJoint2["THUMB_METACARPAL"] = "thumb-metacarpal";
  WebXRHandJoint2["THUMB_PHALANX_PROXIMAL"] = "thumb-phalanx-proximal";
  WebXRHandJoint2["THUMB_PHALANX_DISTAL"] = "thumb-phalanx-distal";
  WebXRHandJoint2["THUMB_TIP"] = "thumb-tip";
  WebXRHandJoint2["INDEX_FINGER_METACARPAL"] = "index-finger-metacarpal";
  WebXRHandJoint2["INDEX_FINGER_PHALANX_PROXIMAL"] = "index-finger-phalanx-proximal";
  WebXRHandJoint2["INDEX_FINGER_PHALANX_INTERMEDIATE"] = "index-finger-phalanx-intermediate";
  WebXRHandJoint2["INDEX_FINGER_PHALANX_DISTAL"] = "index-finger-phalanx-distal";
  WebXRHandJoint2["INDEX_FINGER_TIP"] = "index-finger-tip";
  WebXRHandJoint2["MIDDLE_FINGER_METACARPAL"] = "middle-finger-metacarpal";
  WebXRHandJoint2["MIDDLE_FINGER_PHALANX_PROXIMAL"] = "middle-finger-phalanx-proximal";
  WebXRHandJoint2["MIDDLE_FINGER_PHALANX_INTERMEDIATE"] = "middle-finger-phalanx-intermediate";
  WebXRHandJoint2["MIDDLE_FINGER_PHALANX_DISTAL"] = "middle-finger-phalanx-distal";
  WebXRHandJoint2["MIDDLE_FINGER_TIP"] = "middle-finger-tip";
  WebXRHandJoint2["RING_FINGER_METACARPAL"] = "ring-finger-metacarpal";
  WebXRHandJoint2["RING_FINGER_PHALANX_PROXIMAL"] = "ring-finger-phalanx-proximal";
  WebXRHandJoint2["RING_FINGER_PHALANX_INTERMEDIATE"] = "ring-finger-phalanx-intermediate";
  WebXRHandJoint2["RING_FINGER_PHALANX_DISTAL"] = "ring-finger-phalanx-distal";
  WebXRHandJoint2["RING_FINGER_TIP"] = "ring-finger-tip";
  WebXRHandJoint2["PINKY_FINGER_METACARPAL"] = "pinky-finger-metacarpal";
  WebXRHandJoint2["PINKY_FINGER_PHALANX_PROXIMAL"] = "pinky-finger-phalanx-proximal";
  WebXRHandJoint2["PINKY_FINGER_PHALANX_INTERMEDIATE"] = "pinky-finger-phalanx-intermediate";
  WebXRHandJoint2["PINKY_FINGER_PHALANX_DISTAL"] = "pinky-finger-phalanx-distal";
  WebXRHandJoint2["PINKY_FINGER_TIP"] = "pinky-finger-tip";
})(WebXRHandJoint || (WebXRHandJoint = {}));
var handJointReferenceArray = [
  "wrist",
  "thumb-metacarpal",
  "thumb-phalanx-proximal",
  "thumb-phalanx-distal",
  "thumb-tip",
  "index-finger-metacarpal",
  "index-finger-phalanx-proximal",
  "index-finger-phalanx-intermediate",
  "index-finger-phalanx-distal",
  "index-finger-tip",
  "middle-finger-metacarpal",
  "middle-finger-phalanx-proximal",
  "middle-finger-phalanx-intermediate",
  "middle-finger-phalanx-distal",
  "middle-finger-tip",
  "ring-finger-metacarpal",
  "ring-finger-phalanx-proximal",
  "ring-finger-phalanx-intermediate",
  "ring-finger-phalanx-distal",
  "ring-finger-tip",
  "pinky-finger-metacarpal",
  "pinky-finger-phalanx-proximal",
  "pinky-finger-phalanx-intermediate",
  "pinky-finger-phalanx-distal",
  "pinky-finger-tip"
];
var handPartsDefinition = {
  ["wrist"]: ["wrist"],
  ["thumb"]: ["thumb-metacarpal", "thumb-phalanx-proximal", "thumb-phalanx-distal", "thumb-tip"],
  ["index"]: [
    "index-finger-metacarpal",
    "index-finger-phalanx-proximal",
    "index-finger-phalanx-intermediate",
    "index-finger-phalanx-distal",
    "index-finger-tip"
  ],
  ["middle"]: [
    "middle-finger-metacarpal",
    "middle-finger-phalanx-proximal",
    "middle-finger-phalanx-intermediate",
    "middle-finger-phalanx-distal",
    "middle-finger-tip"
  ],
  ["ring"]: [
    "ring-finger-metacarpal",
    "ring-finger-phalanx-proximal",
    "ring-finger-phalanx-intermediate",
    "ring-finger-phalanx-distal",
    "ring-finger-tip"
  ],
  ["little"]: [
    "pinky-finger-metacarpal",
    "pinky-finger-phalanx-proximal",
    "pinky-finger-phalanx-intermediate",
    "pinky-finger-phalanx-distal",
    "pinky-finger-tip"
  ]
};

class WebXRHand {
  get handMesh() {
    return this._handMesh;
  }
  getHandPartMeshes(part) {
    return handPartsDefinition[part].map((name327) => this._jointMeshes[handJointReferenceArray.indexOf(name327)]);
  }
  getJointMesh(jointName) {
    return this._jointMeshes[handJointReferenceArray.indexOf(jointName)];
  }
  constructor(xrController, _jointMeshes, _handMesh, rigMapping, _leftHandedMeshes = false, _jointsInvisible = false, _jointScaleFactor = 1) {
    this.xrController = xrController;
    this._jointMeshes = _jointMeshes;
    this._handMesh = _handMesh;
    this.rigMapping = rigMapping;
    this._leftHandedMeshes = _leftHandedMeshes;
    this._jointsInvisible = _jointsInvisible;
    this._jointScaleFactor = _jointScaleFactor;
    this.onHandMeshSetObservable = new Observable;
    this._jointTransforms = new Array(handJointReferenceArray.length);
    this._jointTransformMatrices = new Float32Array(handJointReferenceArray.length * 16);
    this._tempJointMatrix = new Matrix;
    this._jointRadii = new Float32Array(handJointReferenceArray.length);
    this._scene = _jointMeshes[0].getScene();
    for (let jointIdx = 0;jointIdx < this._jointTransforms.length; jointIdx++) {
      this._jointTransforms[jointIdx] = new TransformNode(handJointReferenceArray[jointIdx], this._scene);
      this._jointTransforms[jointIdx].rotationQuaternion = new Quaternion;
      if (_jointMeshes[jointIdx].rotationQuaternion) {
        _jointMeshes[jointIdx].rotationQuaternion = new Quaternion;
      } else {
        _jointMeshes[jointIdx].rotationQuaternion?.set(0, 0, 0, 1);
      }
    }
    if (_handMesh) {
      this.setHandMesh(_handMesh, rigMapping);
    }
    if (this.xrController.motionController) {
      if (this.xrController.motionController.rootMesh) {
        this.xrController.motionController.rootMesh.dispose(false, true);
      }
    }
    this.xrController.onMotionControllerInitObservable.add((motionController) => {
      motionController._doNotLoadControllerMesh = true;
    });
  }
  setHandMesh(handMesh, rigMapping, _xrSessionManager) {
    this._handMesh = handMesh;
    handMesh.alwaysSelectAsActiveMesh = true;
    handMesh.getChildMeshes().forEach((mesh) => {
      mesh.alwaysSelectAsActiveMesh = true;
    });
    if (this._handMesh.skeleton) {
      const handMeshSkeleton = this._handMesh.skeleton;
      handJointReferenceArray.forEach((jointName, jointIdx) => {
        const jointBoneIdx = handMeshSkeleton.getBoneIndexByName(rigMapping ? rigMapping[jointName] : jointName);
        if (jointBoneIdx !== -1) {
          handMeshSkeleton.bones[jointBoneIdx].linkTransformNode(this._jointTransforms[jointIdx]);
        }
      });
    }
    this.onHandMeshSetObservable.notifyObservers(this);
  }
  updateFromXRFrame(xrFrame, referenceSpace) {
    const hand = this.xrController.inputSource.hand;
    if (!hand) {
      return;
    }
    const anyHand = hand;
    const jointSpaces = handJointReferenceArray.map((jointName) => anyHand[jointName] || hand.get(jointName));
    let trackingSuccessful = false;
    if (xrFrame.fillPoses && xrFrame.fillJointRadii) {
      trackingSuccessful = xrFrame.fillPoses(jointSpaces, referenceSpace, this._jointTransformMatrices) && xrFrame.fillJointRadii(jointSpaces, this._jointRadii);
    } else if (xrFrame.getJointPose) {
      trackingSuccessful = true;
      for (let jointIdx = 0;jointIdx < jointSpaces.length; jointIdx++) {
        const jointPose = xrFrame.getJointPose(jointSpaces[jointIdx], referenceSpace);
        if (jointPose) {
          this._jointTransformMatrices.set(jointPose.transform.matrix, jointIdx * 16);
          this._jointRadii[jointIdx] = jointPose.radius || 0.008;
        } else {
          trackingSuccessful = false;
          break;
        }
      }
    }
    if (!trackingSuccessful) {
      return;
    }
    handJointReferenceArray.forEach((_jointName, jointIdx) => {
      const jointTransform = this._jointTransforms[jointIdx];
      Matrix.FromArrayToRef(this._jointTransformMatrices, jointIdx * 16, this._tempJointMatrix);
      this._tempJointMatrix.decompose(undefined, jointTransform.rotationQuaternion, jointTransform.position);
      const scaledJointRadius = this._jointRadii[jointIdx] * this._jointScaleFactor;
      const jointMesh = this._jointMeshes[jointIdx];
      jointMesh.isVisible = !this._handMesh && !this._jointsInvisible;
      jointMesh.position.copyFrom(jointTransform.position);
      jointMesh.rotationQuaternion.copyFrom(jointTransform.rotationQuaternion);
      jointMesh.scaling.setAll(scaledJointRadius);
      if (!this._scene.useRightHandedSystem) {
        jointMesh.position.z *= -1;
        jointMesh.rotationQuaternion.z *= -1;
        jointMesh.rotationQuaternion.w *= -1;
        if (this._leftHandedMeshes && this._handMesh) {
          jointTransform.position.z *= -1;
          jointTransform.rotationQuaternion.z *= -1;
          jointTransform.rotationQuaternion.w *= -1;
        }
      }
    });
    if (this._handMesh) {
      this._handMesh.isVisible = true;
    }
  }
  dispose(disposeMeshes = false) {
    if (this._handMesh) {
      if (disposeMeshes) {
        this._handMesh.skeleton?.dispose();
        this._handMesh.dispose(false, true);
      } else {
        this._handMesh.isVisible = false;
      }
    }
    this._jointTransforms.forEach((transform) => transform.dispose());
    this._jointTransforms.length = 0;
    this.onHandMeshSetObservable.clear();
  }
}

class WebXRHandTracking extends WebXRAbstractFeature {
  static _GenerateTrackedJointMeshes(featureOptions, originalMesh = CreateIcoSphere("jointParent", WebXRHandTracking._ICOSPHERE_PARAMS)) {
    const meshes = {};
    ["left", "right"].map((handedness) => {
      const trackedMeshes = [];
      originalMesh.isVisible = !!featureOptions.jointMeshes?.keepOriginalVisible;
      for (let i = 0;i < handJointReferenceArray.length; ++i) {
        let newInstance = originalMesh.createInstance(`${handedness}-handJoint-${i}`);
        if (featureOptions.jointMeshes?.onHandJointMeshGenerated) {
          const returnedMesh = featureOptions.jointMeshes.onHandJointMeshGenerated(newInstance, i, handedness);
          if (returnedMesh) {
            if (returnedMesh !== newInstance) {
              newInstance.dispose();
              newInstance = returnedMesh;
            }
          }
        }
        newInstance.isPickable = false;
        if (featureOptions.jointMeshes?.enablePhysics) {
          const props = featureOptions.jointMeshes?.physicsProps || {};
          newInstance.scaling.setAll(0.02);
          const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;
          newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, { mass: 0, ...props });
        }
        newInstance.rotationQuaternion = new Quaternion;
        newInstance.isVisible = false;
        trackedMeshes.push(newInstance);
      }
      meshes[handedness] = trackedMeshes;
    });
    return { left: meshes.left, right: meshes.right };
  }
  static _GenerateDefaultHandMeshesAsync(scene, xrSessionManager, options) {
    return new Promise(async (resolve3) => {
      const riggedMeshes = {};
      if (WebXRHandTracking._RightHandGLB?.meshes[1]?.isDisposed()) {
        WebXRHandTracking._RightHandGLB = null;
      }
      if (WebXRHandTracking._LeftHandGLB?.meshes[1]?.isDisposed()) {
        WebXRHandTracking._LeftHandGLB = null;
      }
      const handsDefined = !!(WebXRHandTracking._RightHandGLB && WebXRHandTracking._LeftHandGLB);
      const defaulrHandGLBUrl = Tools.GetAssetUrl(WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL);
      const handGLBs = await Promise.all([
        WebXRHandTracking._RightHandGLB || SceneLoader.ImportMeshAsync("", defaulrHandGLBUrl, WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME, scene),
        WebXRHandTracking._LeftHandGLB || SceneLoader.ImportMeshAsync("", defaulrHandGLBUrl, WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME, scene)
      ]);
      WebXRHandTracking._RightHandGLB = handGLBs[0];
      WebXRHandTracking._LeftHandGLB = handGLBs[1];
      const shaderUrl = Tools.GetAssetUrl(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL);
      const handShader = await NodeMaterial.ParseFromFileAsync("handShader", shaderUrl, scene, undefined, true);
      handShader.needDepthPrePass = true;
      handShader.transparencyMode = Material.MATERIAL_ALPHABLEND;
      handShader.alphaMode = 2;
      handShader.build(false);
      const handColors = {
        base: Color3.FromInts(116, 63, 203),
        fresnel: Color3.FromInts(149, 102, 229),
        fingerColor: Color3.FromInts(177, 130, 255),
        tipFresnel: Color3.FromInts(220, 200, 255),
        ...options?.handMeshes?.customColors
      };
      const handNodes = {
        base: handShader.getBlockByName("baseColor"),
        fresnel: handShader.getBlockByName("fresnelColor"),
        fingerColor: handShader.getBlockByName("fingerColor"),
        tipFresnel: handShader.getBlockByName("tipFresnelColor")
      };
      handNodes.base.value = handColors.base;
      handNodes.fresnel.value = handColors.fresnel;
      handNodes.fingerColor.value = handColors.fingerColor;
      handNodes.tipFresnel.value = handColors.tipFresnel;
      const isMultiview = xrSessionManager._getBaseLayerWrapper()?.isMultiview;
      ["left", "right"].forEach((handedness) => {
        const handGLB = handedness == "left" ? WebXRHandTracking._LeftHandGLB : WebXRHandTracking._RightHandGLB;
        if (!handGLB) {
          throw new Error("Could not load hand model");
        }
        const handMesh = handGLB.meshes[1];
        handMesh._internalAbstractMeshDataInfo._computeBonesUsingShaders = true;
        if (!isMultiview && !options?.handMeshes?.disableHandShader) {
          handMesh.material = handShader.clone(`${handedness}HandShaderClone`, true);
        }
        handMesh.isVisible = false;
        riggedMeshes[handedness] = handMesh;
        if (!handsDefined && !scene.useRightHandedSystem) {
          handGLB.meshes[1].rotate(Axis.Y, Math.PI);
        }
      });
      handShader.dispose();
      resolve3({ left: riggedMeshes.left, right: riggedMeshes.right });
    });
  }
  static _GenerateDefaultHandMeshRigMapping(handedness) {
    const H = handedness == "right" ? "R" : "L";
    return {
      ["wrist"]: `wrist_${H}`,
      ["thumb-metacarpal"]: `thumb_metacarpal_${H}`,
      ["thumb-phalanx-proximal"]: `thumb_proxPhalanx_${H}`,
      ["thumb-phalanx-distal"]: `thumb_distPhalanx_${H}`,
      ["thumb-tip"]: `thumb_tip_${H}`,
      ["index-finger-metacarpal"]: `index_metacarpal_${H}`,
      ["index-finger-phalanx-proximal"]: `index_proxPhalanx_${H}`,
      ["index-finger-phalanx-intermediate"]: `index_intPhalanx_${H}`,
      ["index-finger-phalanx-distal"]: `index_distPhalanx_${H}`,
      ["index-finger-tip"]: `index_tip_${H}`,
      ["middle-finger-metacarpal"]: `middle_metacarpal_${H}`,
      ["middle-finger-phalanx-proximal"]: `middle_proxPhalanx_${H}`,
      ["middle-finger-phalanx-intermediate"]: `middle_intPhalanx_${H}`,
      ["middle-finger-phalanx-distal"]: `middle_distPhalanx_${H}`,
      ["middle-finger-tip"]: `middle_tip_${H}`,
      ["ring-finger-metacarpal"]: `ring_metacarpal_${H}`,
      ["ring-finger-phalanx-proximal"]: `ring_proxPhalanx_${H}`,
      ["ring-finger-phalanx-intermediate"]: `ring_intPhalanx_${H}`,
      ["ring-finger-phalanx-distal"]: `ring_distPhalanx_${H}`,
      ["ring-finger-tip"]: `ring_tip_${H}`,
      ["pinky-finger-metacarpal"]: `little_metacarpal_${H}`,
      ["pinky-finger-phalanx-proximal"]: `little_proxPhalanx_${H}`,
      ["pinky-finger-phalanx-intermediate"]: `little_intPhalanx_${H}`,
      ["pinky-finger-phalanx-distal"]: `little_distPhalanx_${H}`,
      ["pinky-finger-tip"]: `little_tip_${H}`
    };
  }
  isCompatible() {
    return typeof XRHand !== "undefined";
  }
  getHandByControllerId(controllerId) {
    return this._attachedHands[controllerId];
  }
  getHandByHandedness(handedness) {
    if (handedness == "none") {
      return null;
    }
    return this._trackingHands[handedness];
  }
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this.options = options;
    this._attachedHands = {};
    this._trackingHands = { left: null, right: null };
    this._handResources = { jointMeshes: null, handMeshes: null, rigMappings: null };
    this._worldScaleObserver = null;
    this.onHandAddedObservable = new Observable;
    this.onHandRemovedObservable = new Observable;
    this._attachHand = (xrController) => {
      if (!xrController.inputSource.hand || xrController.inputSource.handedness == "none" || !this._handResources.jointMeshes) {
        return;
      }
      const handedness = xrController.inputSource.handedness;
      const webxrHand = new WebXRHand(xrController, this._handResources.jointMeshes[handedness], this._handResources.handMeshes && this._handResources.handMeshes[handedness], this._handResources.rigMappings && this._handResources.rigMappings[handedness], this.options.handMeshes?.meshesUseLeftHandedCoordinates, this.options.jointMeshes?.invisible, this.options.jointMeshes?.scaleFactor);
      this._attachedHands[xrController.uniqueId] = webxrHand;
      this._trackingHands[handedness] = webxrHand;
      this.onHandAddedObservable.notifyObservers(webxrHand);
    };
    this._detachHand = (xrController) => {
      this._detachHandById(xrController.uniqueId);
    };
    this.xrNativeFeatureName = "hand-tracking";
    const anyOptions = options;
    const anyJointMeshOptions = anyOptions.jointMeshes;
    if (anyJointMeshOptions) {
      if (typeof anyJointMeshOptions.disableDefaultHandMesh !== "undefined") {
        options.handMeshes = options.handMeshes || {};
        options.handMeshes.disableDefaultMeshes = anyJointMeshOptions.disableDefaultHandMesh;
      }
      if (typeof anyJointMeshOptions.handMeshes !== "undefined") {
        options.handMeshes = options.handMeshes || {};
        options.handMeshes.customMeshes = anyJointMeshOptions.handMeshes;
      }
      if (typeof anyJointMeshOptions.leftHandedSystemMeshes !== "undefined") {
        options.handMeshes = options.handMeshes || {};
        options.handMeshes.meshesUseLeftHandedCoordinates = anyJointMeshOptions.leftHandedSystemMeshes;
      }
      if (typeof anyJointMeshOptions.rigMapping !== "undefined") {
        options.handMeshes = options.handMeshes || {};
        const leftRigMapping = {};
        const rightRigMapping = {};
        [
          [anyJointMeshOptions.rigMapping.left, leftRigMapping],
          [anyJointMeshOptions.rigMapping.right, rightRigMapping]
        ].forEach((rigMappingTuple) => {
          const legacyRigMapping = rigMappingTuple[0];
          const rigMapping = rigMappingTuple[1];
          legacyRigMapping.forEach((modelJointName, index) => {
            rigMapping[handJointReferenceArray[index]] = modelJointName;
          });
        });
        options.handMeshes.customRigMappings = {
          left: leftRigMapping,
          right: rightRigMapping
        };
      }
    }
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    if (!this._handResources.jointMeshes) {
      this._originalMesh = this._originalMesh || this.options.jointMeshes?.sourceMesh || CreateIcoSphere("jointParent", WebXRHandTracking._ICOSPHERE_PARAMS);
      this._originalMesh.isVisible = false;
      this._handResources.jointMeshes = WebXRHandTracking._GenerateTrackedJointMeshes(this.options, this._originalMesh);
    }
    this._handResources.handMeshes = this.options.handMeshes?.customMeshes || null;
    this._handResources.rigMappings = this.options.handMeshes?.customRigMappings || null;
    if (!this.options.handMeshes?.customMeshes && !this.options.handMeshes?.disableDefaultMeshes) {
      WebXRHandTracking._GenerateDefaultHandMeshesAsync(EngineStore.LastCreatedScene, this._xrSessionManager, this.options).then((defaultHandMeshes) => {
        this._handResources.handMeshes = defaultHandMeshes;
        this._handResources.rigMappings = {
          left: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"),
          right: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("right")
        };
        this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left, this._handResources.rigMappings.left, this._xrSessionManager);
        this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right, this._handResources.rigMappings.right, this._xrSessionManager);
        this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor);
        this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor);
      });
      this._worldScaleObserver = this._xrSessionManager.onWorldScaleFactorChangedObservable.add((scalingFactors) => {
        if (this._handResources.handMeshes) {
          this._handResources.handMeshes.left.scaling.scaleInPlace(scalingFactors.newScaleFactor / scalingFactors.previousScaleFactor);
          this._handResources.handMeshes.right.scaling.scaleInPlace(scalingFactors.newScaleFactor / scalingFactors.previousScaleFactor);
        }
      });
    }
    this.options.xrInput.controllers.forEach(this._attachHand);
    this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);
    this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, this._detachHand);
    return true;
  }
  _onXRFrame(_xrFrame) {
    this._trackingHands.left?.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);
    this._trackingHands.right?.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);
  }
  _detachHandById(controllerId, disposeMesh) {
    const hand = this.getHandByControllerId(controllerId);
    if (hand) {
      const handedness = hand.xrController.inputSource.handedness == "left" ? "left" : "right";
      if (this._trackingHands[handedness]?.xrController.uniqueId === controllerId) {
        this._trackingHands[handedness] = null;
      }
      this.onHandRemovedObservable.notifyObservers(hand);
      hand.dispose(disposeMesh);
      delete this._attachedHands[controllerId];
    }
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._attachedHands).forEach((uniqueId) => this._detachHandById(uniqueId, this.options.handMeshes?.disposeOnSessionEnd));
    if (this.options.handMeshes?.disposeOnSessionEnd) {
      if (this._handResources.jointMeshes) {
        this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose());
        this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose());
        this._handResources.jointMeshes = null;
      }
      if (this._handResources.handMeshes) {
        this._handResources.handMeshes.left.dispose();
        this._handResources.handMeshes.right.dispose();
        this._handResources.handMeshes = null;
      }
      WebXRHandTracking._RightHandGLB?.meshes.forEach((mesh) => mesh.dispose());
      WebXRHandTracking._LeftHandGLB?.meshes.forEach((mesh) => mesh.dispose());
      WebXRHandTracking._RightHandGLB = null;
      WebXRHandTracking._LeftHandGLB = null;
      this._originalMesh?.dispose();
      this._originalMesh = undefined;
    }
    if (this._worldScaleObserver) {
      this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver);
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.onHandAddedObservable.clear();
    this.onHandRemovedObservable.clear();
    if (this._handResources.handMeshes && !this.options.handMeshes?.customMeshes) {
      this._handResources.handMeshes.left.dispose();
      this._handResources.handMeshes.right.dispose();
      WebXRHandTracking._RightHandGLB?.meshes.forEach((mesh) => mesh.dispose());
      WebXRHandTracking._LeftHandGLB?.meshes.forEach((mesh) => mesh.dispose());
      WebXRHandTracking._RightHandGLB = null;
      WebXRHandTracking._LeftHandGLB = null;
    }
    if (this._handResources.jointMeshes) {
      this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose());
      this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose());
    }
  }
}
WebXRHandTracking.Name = WebXRFeatureName.HAND_TRACKING;
WebXRHandTracking.Version = 1;
WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL = "https://assets.babylonjs.com/core/HandMeshes/";
WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME = "r_hand_rhs.glb";
WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME = "l_hand_rhs.glb";
WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL = "https://assets.babylonjs.com/core/HandMeshes/handsShader.json";
WebXRHandTracking._ICOSPHERE_PARAMS = { radius: 0.5, flat: false, subdivisions: 2 };
WebXRHandTracking._RightHandGLB = null;
WebXRHandTracking._LeftHandGLB = null;
WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name, (xrSessionManager, options) => {
  return () => new WebXRHandTracking(xrSessionManager, options);
}, WebXRHandTracking.Version, false);

// node_modules/@babylonjs/core/XR/features/WebXRControllerTeleportation.js
init_observable();
init_math_vector();
init_easing();
init_animation();
init_math_axis();
init_math_path();
init_math_color();
init_pointerEvents();
init_timer();

class WebXRMotionControllerTeleportation extends WebXRAbstractFeature {
  get rotationEnabled() {
    return this._rotationEnabled;
  }
  set rotationEnabled(enabled) {
    this._rotationEnabled = enabled;
    if (this._options.teleportationTargetMesh) {
      const children = this._options.teleportationTargetMesh.getChildMeshes(false, (node) => node.name === "rotationCone");
      if (children[0]) {
        children[0].setEnabled(enabled);
      }
    }
  }
  get teleportationTargetMesh() {
    return this._options.teleportationTargetMesh || null;
  }
  constructor(_xrSessionManager, _options) {
    super(_xrSessionManager);
    this._options = _options;
    this._controllers = {};
    this._snappedToPoint = false;
    this._cachedColor4White = new Color4(1, 1, 1, 1);
    this._tmpRay = new Ray(new Vector3, new Vector3);
    this._tmpVector = new Vector3;
    this._tmpQuaternion = new Quaternion;
    this._worldScaleObserver = null;
    this.skipNextTeleportation = false;
    this.backwardsMovementEnabled = true;
    this.backwardsTeleportationDistance = 0.7;
    this.parabolicCheckRadius = 5;
    this.parabolicRayEnabled = true;
    this.straightRayEnabled = true;
    this.rotationAngle = Math.PI / 8;
    this.onTargetMeshPositionUpdatedObservable = new Observable;
    this.teleportationEnabled = true;
    this._rotationEnabled = true;
    this.onBeforeCameraTeleportRotation = new Observable;
    this.onAfterCameraTeleportRotation = new Observable;
    this._attachController = (xrController) => {
      if (this._controllers[xrController.uniqueId] || this._options.forceHandedness && xrController.inputSource.handedness !== this._options.forceHandedness) {
        return;
      }
      this._controllers[xrController.uniqueId] = {
        xrController,
        teleportationState: {
          forward: false,
          backwards: false,
          rotating: false,
          currentRotation: 0,
          baseRotation: 0,
          blocked: false,
          initialHit: false,
          mainComponentUsed: false
        }
      };
      const controllerData = this._controllers[xrController.uniqueId];
      if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) {
        const initMotionController = () => {
          if (xrController.motionController) {
            const movementController = xrController.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) || xrController.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);
            if (!movementController || this._options.useMainComponentOnly) {
              const mainComponent = xrController.motionController.getMainComponent();
              if (!mainComponent) {
                return;
              }
              controllerData.teleportationState.mainComponentUsed = true;
              controllerData.teleportationComponent = mainComponent;
              controllerData.onButtonChangedObserver = mainComponent.onButtonStateChangedObservable.add(() => {
                if (!this.teleportationEnabled) {
                  return;
                }
                const teleportLocal = () => {
                  controllerData.teleportationState.forward = true;
                  controllerData.teleportationState.initialHit = false;
                  this._currentTeleportationControllerId = controllerData.xrController.uniqueId;
                  controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;
                  controllerData.teleportationState.currentRotation = 0;
                  const timeToSelect = this._options.timeToTeleport || 3000;
                  setAndStartTimer({
                    timeout: timeToSelect,
                    contextObservable: this._xrSessionManager.onXRFrameObservable,
                    breakCondition: () => !mainComponent.pressed,
                    onEnded: () => {
                      if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {
                        this._teleportForward(xrController.uniqueId);
                      }
                    }
                  });
                };
                if (mainComponent.changes.pressed) {
                  if (mainComponent.changes.pressed.current) {
                    if (this._options.timeToTeleportStart) {
                      setAndStartTimer({
                        timeout: this._options.timeToTeleportStart,
                        contextObservable: this._xrSessionManager.onXRFrameObservable,
                        onEnded: () => {
                          if (mainComponent.pressed) {
                            teleportLocal();
                          }
                        }
                      });
                    } else {
                      teleportLocal();
                    }
                  } else {
                    controllerData.teleportationState.forward = false;
                    this._currentTeleportationControllerId = "";
                  }
                }
              });
            } else {
              controllerData.teleportationComponent = movementController;
              controllerData.onAxisChangedObserver = movementController.onAxisValueChangedObservable.add((axesData) => {
                if (axesData.y <= 0.7 && controllerData.teleportationState.backwards) {
                  controllerData.teleportationState.backwards = false;
                }
                if (axesData.y > 0.7 && !controllerData.teleportationState.forward && this.backwardsMovementEnabled && !this.snapPointsOnly) {
                  if (!controllerData.teleportationState.backwards) {
                    controllerData.teleportationState.backwards = true;
                    this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion);
                    this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector);
                    this._tmpVector.x = 0;
                    this._tmpVector.z = 0;
                    Quaternion.FromEulerVectorToRef(this._tmpVector, this._tmpQuaternion);
                    this._tmpVector.set(0, 0, this.backwardsTeleportationDistance * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1));
                    this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector);
                    this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position);
                    this._tmpRay.origin.copyFrom(this._tmpVector);
                    this._tmpRay.length = this._options.xrInput.xrCamera.realWorldHeight + 0.1;
                    this._tmpRay.direction.set(0, -1, 0);
                    const pick = this._xrSessionManager.scene.pickWithRay(this._tmpRay, (o) => {
                      return this._floorMeshes.indexOf(o) !== -1;
                    });
                    if (pick && pick.pickedPoint) {
                      this._options.xrInput.xrCamera.position.x = pick.pickedPoint.x;
                      this._options.xrInput.xrCamera.position.z = pick.pickedPoint.z;
                    }
                  }
                }
                if (axesData.y < -0.7 && !this._currentTeleportationControllerId && !controllerData.teleportationState.rotating && this.teleportationEnabled) {
                  controllerData.teleportationState.forward = true;
                  this._currentTeleportationControllerId = controllerData.xrController.uniqueId;
                  controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;
                }
                if (axesData.x) {
                  if (!controllerData.teleportationState.forward) {
                    if (!controllerData.teleportationState.rotating && Math.abs(axesData.x) > 0.7) {
                      controllerData.teleportationState.rotating = true;
                      const rotation = this.rotationAngle * (axesData.x > 0 ? 1 : -1) * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);
                      this.onBeforeCameraTeleportRotation.notifyObservers(rotation);
                      Quaternion.FromEulerAngles(0, rotation, 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);
                      this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion);
                    }
                  } else {
                    if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) {
                      if (this.rotationEnabled) {
                        setTimeout(() => {
                          controllerData.teleportationState.currentRotation = Math.atan2(axesData.x, axesData.y * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1));
                        });
                      } else {
                        controllerData.teleportationState.currentRotation = 0;
                      }
                    }
                  }
                } else {
                  controllerData.teleportationState.rotating = false;
                }
                if (axesData.x === 0 && axesData.y === 0) {
                  if (controllerData.teleportationState.blocked) {
                    controllerData.teleportationState.blocked = false;
                    this._setTargetMeshVisibility(false);
                  }
                  if (controllerData.teleportationState.forward) {
                    this._teleportForward(xrController.uniqueId);
                  }
                }
              });
            }
          }
        };
        if (xrController.motionController) {
          initMotionController();
        } else {
          xrController.onMotionControllerInitObservable.addOnce(() => {
            initMotionController();
          });
        }
      } else {
        controllerData.teleportationState.mainComponentUsed = true;
        let breakObserver = false;
        const teleportLocal = () => {
          this._currentTeleportationControllerId = controllerData.xrController.uniqueId;
          controllerData.teleportationState.forward = true;
          controllerData.teleportationState.initialHit = false;
          controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;
          controllerData.teleportationState.currentRotation = 0;
          const timeToSelect = this._options.timeToTeleport || 3000;
          setAndStartTimer({
            timeout: timeToSelect,
            contextObservable: this._xrSessionManager.onXRFrameObservable,
            onEnded: () => {
              if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {
                this._teleportForward(xrController.uniqueId);
              }
            }
          });
        };
        this._xrSessionManager.scene.onPointerObservable.add((pointerInfo) => {
          if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {
            breakObserver = false;
            if (this._options.timeToTeleportStart) {
              setAndStartTimer({
                timeout: this._options.timeToTeleportStart,
                contextObservable: this._xrSessionManager.onXRFrameObservable,
                onEnded: () => {
                  if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) {
                    teleportLocal();
                  }
                },
                breakCondition: () => {
                  if (breakObserver) {
                    breakObserver = false;
                    return true;
                  }
                  return false;
                }
              });
            } else {
              teleportLocal();
            }
          } else if (pointerInfo.type === PointerEventTypes.POINTERUP) {
            breakObserver = true;
            controllerData.teleportationState.forward = false;
            this._currentTeleportationControllerId = "";
          }
        });
      }
    };
    this._colorArray = Array(24).fill(this._cachedColor4White);
    if (!this._options.teleportationTargetMesh) {
      this._createDefaultTargetMesh();
    }
    this._floorMeshes = this._options.floorMeshes || [];
    this._snapToPositions = this._options.snapPositions || [];
    this._blockedRayColor = this._options.blockedRayColor || new Color4(1, 0, 0, 0.75);
    this._setTargetMeshVisibility(false);
    this.onBeforeCameraTeleport = _options.xrInput.xrCamera.onBeforeCameraTeleport;
    this.onAfterCameraTeleport = _options.xrInput.xrCamera.onAfterCameraTeleport;
    this.parabolicCheckRadius *= this._xrSessionManager.worldScalingFactor;
    this._worldScaleObserver = _xrSessionManager.onWorldScaleFactorChangedObservable.add((values) => {
      this.parabolicCheckRadius = this.parabolicCheckRadius / values.previousScaleFactor * values.newScaleFactor;
      this._options.teleportationTargetMesh?.scaling.scaleInPlace(values.newScaleFactor / values.previousScaleFactor);
    });
  }
  get snapPointsOnly() {
    return !!this._options.snapPointsOnly;
  }
  set snapPointsOnly(snapToPoints) {
    this._options.snapPointsOnly = snapToPoints;
  }
  addFloorMesh(mesh) {
    this._floorMeshes.push(mesh);
  }
  addBlockerMesh(mesh) {
    this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];
    this._options.pickBlockerMeshes.push(mesh);
  }
  addSnapPoint(newSnapPoint) {
    this._snapToPositions.push(newSnapPoint);
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    this._currentTeleportationControllerId = "";
    this._options.xrInput.controllers.forEach(this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
      this._detachController(controller.uniqueId);
    });
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      this._detachController(controllerId);
    });
    this._setTargetMeshVisibility(false);
    this._currentTeleportationControllerId = "";
    this._controllers = {};
    return true;
  }
  dispose() {
    super.dispose();
    this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(false, true);
    if (this._worldScaleObserver) {
      this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver);
    }
    this.onTargetMeshPositionUpdatedObservable.clear();
    this.onTargetMeshPositionUpdatedObservable.clear();
    this.onBeforeCameraTeleportRotation.clear();
    this.onAfterCameraTeleportRotation.clear();
    this.onBeforeCameraTeleport.clear();
    this.onAfterCameraTeleport.clear();
  }
  removeFloorMesh(mesh) {
    const index = this._floorMeshes.indexOf(mesh);
    if (index !== -1) {
      this._floorMeshes.splice(index, 1);
    }
  }
  removeBlockerMesh(mesh) {
    this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];
    const index = this._options.pickBlockerMeshes.indexOf(mesh);
    if (index !== -1) {
      this._options.pickBlockerMeshes.splice(index, 1);
    }
  }
  removeFloorMeshByName(name327) {
    const mesh = this._xrSessionManager.scene.getMeshByName(name327);
    if (mesh) {
      this.removeFloorMesh(mesh);
    }
  }
  removeSnapPoint(snapPointToRemove) {
    let index = this._snapToPositions.indexOf(snapPointToRemove);
    if (index === -1) {
      for (let i = 0;i < this._snapToPositions.length; ++i) {
        if (this._snapToPositions[i].equals(snapPointToRemove)) {
          index = i;
          break;
        }
      }
    }
    if (index !== -1) {
      this._snapToPositions.splice(index, 1);
      return true;
    }
    return false;
  }
  setSelectionFeature(selectionFeature) {
    this._selectionFeature = selectionFeature;
  }
  _onXRFrame(_xrFrame) {
    const frame = this._xrSessionManager.currentFrame;
    const scene = this._xrSessionManager.scene;
    if (!this.attach || !frame) {
      return;
    }
    const targetMesh = this._options.teleportationTargetMesh;
    if (this._currentTeleportationControllerId) {
      if (!targetMesh) {
        return;
      }
      targetMesh.rotationQuaternion = targetMesh.rotationQuaternion || new Quaternion;
      const controllerData = this._controllers[this._currentTeleportationControllerId];
      if (controllerData && controllerData.teleportationState.forward) {
        Quaternion.RotationYawPitchRollToRef(controllerData.teleportationState.currentRotation + controllerData.teleportationState.baseRotation, 0, 0, targetMesh.rotationQuaternion);
        let hitPossible = false;
        const controlSelectionFeature = controllerData.xrController.inputSource.targetRayMode !== "transient-pointer";
        controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);
        if (this.straightRayEnabled) {
          const pick = scene.pickWithRay(this._tmpRay, (o) => {
            if (this._options.blockerMeshesPredicate && this._options.blockerMeshesPredicate(o)) {
              return true;
            }
            if (this._options.blockAllPickableMeshes && o.isPickable) {
              return true;
            }
            if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {
              return true;
            }
            const index = this._floorMeshes.indexOf(o);
            if (index === -1) {
              return false;
            }
            return this._floorMeshes[index].absolutePosition.y < this._options.xrInput.xrCamera.globalPosition.y;
          });
          const floorMeshPicked = pick && pick.pickedMesh && this._floorMeshes.indexOf(pick.pickedMesh) !== -1;
          if (pick && pick.pickedMesh && !floorMeshPicked) {
            if (controllerData.teleportationState.mainComponentUsed && !controllerData.teleportationState.initialHit) {
              controllerData.teleportationState.forward = false;
              return;
            }
            controllerData.teleportationState.blocked = true;
            this._setTargetMeshVisibility(false, false, controlSelectionFeature);
            this._showParabolicPath(pick);
            return;
          } else if (pick && pick.pickedPoint) {
            controllerData.teleportationState.initialHit = true;
            controllerData.teleportationState.blocked = false;
            hitPossible = true;
            this._setTargetMeshPosition(pick);
            this._setTargetMeshVisibility(true, false, controlSelectionFeature);
            this._showParabolicPath(pick);
          }
        }
        if (this.parabolicRayEnabled && !hitPossible) {
          const xRotation = controllerData.xrController.pointer.rotationQuaternion.toEulerAngles().x;
          const compensation = 1 + (Math.PI / 2 - Math.abs(xRotation));
          const radius = this.parabolicCheckRadius * compensation;
          this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(radius * 2), this._tmpVector);
          this._tmpVector.y = this._tmpRay.origin.y;
          this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(radius));
          this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction);
          this._tmpRay.direction.normalize();
          const pick = scene.pickWithRay(this._tmpRay, (o) => {
            if (this._options.blockerMeshesPredicate && this._options.blockerMeshesPredicate(o)) {
              return true;
            }
            if (this._options.blockAllPickableMeshes && o.isPickable) {
              return true;
            }
            if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {
              return true;
            }
            return this._floorMeshes.indexOf(o) !== -1;
          });
          const floorMeshPicked = pick && pick.pickedMesh && this._floorMeshes.indexOf(pick.pickedMesh) !== -1;
          if (pick && pick.pickedMesh && !floorMeshPicked) {
            if (controllerData.teleportationState.mainComponentUsed && !controllerData.teleportationState.initialHit) {
              controllerData.teleportationState.forward = false;
              return;
            }
            controllerData.teleportationState.blocked = true;
            this._setTargetMeshVisibility(false, false, controlSelectionFeature);
            this._showParabolicPath(pick);
            return;
          } else if (pick && pick.pickedPoint) {
            controllerData.teleportationState.initialHit = true;
            controllerData.teleportationState.blocked = false;
            hitPossible = true;
            this._setTargetMeshPosition(pick);
            this._setTargetMeshVisibility(true, false, controlSelectionFeature);
            this._showParabolicPath(pick);
          }
        }
        this._setTargetMeshVisibility(hitPossible, false, controlSelectionFeature);
      } else {
        this._setTargetMeshVisibility(false, false, true);
      }
    } else {
      this._disposeBezierCurve();
      this._setTargetMeshVisibility(false, false, true);
    }
  }
  _createDefaultTargetMesh() {
    this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {};
    const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene;
    const teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, sceneToRenderTo);
    teleportationTarget.isPickable = false;
    if (this._options.defaultTargetMeshOptions.teleportationCircleMaterial) {
      teleportationTarget.material = this._options.defaultTargetMeshOptions.teleportationCircleMaterial;
    } else {
      const length = 512;
      const dynamicTexture = new DynamicTexture("teleportationPlaneDynamicTexture", length, sceneToRenderTo, true);
      dynamicTexture.hasAlpha = true;
      const context = dynamicTexture.getContext();
      const centerX = length / 2;
      const centerY = length / 2;
      const radius = 200;
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
      context.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || "#444444";
      context.fill();
      context.lineWidth = 10;
      context.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || "#FFFFFF";
      context.stroke();
      context.closePath();
      dynamicTexture.update();
      const teleportationCircleMaterial = new StandardMaterial("teleportationPlaneMaterial", sceneToRenderTo);
      teleportationCircleMaterial.diffuseTexture = dynamicTexture;
      teleportationTarget.material = teleportationCircleMaterial;
    }
    const torus = CreateTorus("torusTeleportation", {
      diameter: 0.75,
      thickness: 0.1,
      tessellation: 20
    }, sceneToRenderTo);
    torus.isPickable = false;
    torus.parent = teleportationTarget;
    if (!this._options.defaultTargetMeshOptions.disableAnimation) {
      const animationInnerCircle = new Animation("animationInnerCircle", "position.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);
      const keys = [];
      keys.push({
        frame: 0,
        value: 0
      });
      keys.push({
        frame: 30,
        value: 0.4
      });
      keys.push({
        frame: 60,
        value: 0
      });
      animationInnerCircle.setKeys(keys);
      const easingFunction = new SineEase;
      easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
      animationInnerCircle.setEasingFunction(easingFunction);
      torus.animations = [];
      torus.animations.push(animationInnerCircle);
      sceneToRenderTo.beginAnimation(torus, 0, 60, true);
    }
    const cone = CreateCylinder("rotationCone", { diameterTop: 0, tessellation: 4 }, sceneToRenderTo);
    cone.isPickable = false;
    cone.scaling.set(0.5, 0.12, 0.2);
    cone.rotate(Axis.X, Math.PI / 2);
    cone.position.z = 0.6;
    cone.parent = torus;
    if (this._options.defaultTargetMeshOptions.torusArrowMaterial) {
      torus.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;
      cone.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;
    } else {
      const torusConeMaterial = new StandardMaterial("torusConsMat", sceneToRenderTo);
      torusConeMaterial.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting;
      if (torusConeMaterial.disableLighting) {
        torusConeMaterial.emissiveColor = new Color3(0.3, 0.3, 1);
      } else {
        torusConeMaterial.diffuseColor = new Color3(0.3, 0.3, 1);
      }
      torusConeMaterial.alpha = 0.9;
      torus.material = torusConeMaterial;
      cone.material = torusConeMaterial;
      this._teleportationRingMaterial = torusConeMaterial;
    }
    if (this._options.renderingGroupId !== undefined) {
      teleportationTarget.renderingGroupId = this._options.renderingGroupId;
      torus.renderingGroupId = this._options.renderingGroupId;
      cone.renderingGroupId = this._options.renderingGroupId;
    }
    this._options.teleportationTargetMesh = teleportationTarget;
    this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor);
    this._setTargetMeshVisibility(false);
  }
  _detachController(xrControllerUniqueId) {
    const controllerData = this._controllers[xrControllerUniqueId];
    if (!controllerData) {
      return;
    }
    if (controllerData.teleportationComponent) {
      if (controllerData.onAxisChangedObserver) {
        controllerData.teleportationComponent.onAxisValueChangedObservable.remove(controllerData.onAxisChangedObserver);
      }
      if (controllerData.onButtonChangedObserver) {
        controllerData.teleportationComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
      }
    }
    delete this._controllers[xrControllerUniqueId];
  }
  _findClosestSnapPointWithRadius(realPosition, radius = this._options.snapToPositionRadius || 0.8) {
    let closestPoint = null;
    let closestDistance = Number.MAX_VALUE;
    if (this._snapToPositions.length) {
      const radiusSquared = radius * radius;
      this._snapToPositions.forEach((position) => {
        const dist = Vector3.DistanceSquared(position, realPosition);
        if (dist <= radiusSquared && dist < closestDistance) {
          closestDistance = dist;
          closestPoint = position;
        }
      });
    }
    return closestPoint;
  }
  _setTargetMeshPosition(pickInfo) {
    const newPosition = pickInfo.pickedPoint;
    if (!this._options.teleportationTargetMesh || !newPosition) {
      return;
    }
    const snapPosition = this._findClosestSnapPointWithRadius(newPosition);
    this._snappedToPoint = !!snapPosition;
    if (this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial) {
      this._teleportationRingMaterial.diffuseColor.set(1, 0.3, 0.3);
    } else if (this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial) {
      this._teleportationRingMaterial.diffuseColor.set(0.3, 0.3, 1);
    }
    this._options.teleportationTargetMesh.position.copyFrom(snapPosition || newPosition);
    this._options.teleportationTargetMesh.position.y += 0.01;
    this.onTargetMeshPositionUpdatedObservable.notifyObservers(pickInfo);
  }
  _setTargetMeshVisibility(visible, force, controlSelectionFeature) {
    if (!this._options.teleportationTargetMesh) {
      return;
    }
    if (this._options.teleportationTargetMesh.isVisible === visible && !force) {
      return;
    }
    this._options.teleportationTargetMesh.isVisible = visible;
    this._options.teleportationTargetMesh.getChildren(undefined, false).forEach((m) => {
      m.isVisible = visible;
    });
    if (!visible) {
      if (this._quadraticBezierCurve) {
        this._quadraticBezierCurve.dispose();
        this._quadraticBezierCurve = null;
      }
      if (this._selectionFeature && controlSelectionFeature) {
        this._selectionFeature.attach();
      }
    } else {
      if (this._selectionFeature && controlSelectionFeature) {
        this._selectionFeature.detach();
      }
    }
  }
  _disposeBezierCurve() {
    if (this._quadraticBezierCurve) {
      this._quadraticBezierCurve.dispose();
      this._quadraticBezierCurve = null;
    }
  }
  _showParabolicPath(pickInfo) {
    if (!pickInfo.pickedPoint || !this._currentTeleportationControllerId) {
      return;
    }
    const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._xrSessionManager.scene;
    const controllerData = this._controllers[this._currentTeleportationControllerId];
    const quadraticBezierVectors = Curve3.CreateQuadraticBezier(controllerData.xrController.pointer.absolutePosition, pickInfo.ray.origin, pickInfo.pickedPoint, 25);
    const color = controllerData.teleportationState.blocked ? this._blockedRayColor : undefined;
    const colorsArray = this._colorArray.fill(color || this._cachedColor4White);
    const points = quadraticBezierVectors.getPoints();
    points.shift();
    points.shift();
    if (!this._options.generateRayPathMesh) {
      this._quadraticBezierCurve = CreateLines("teleportation path line", { points, instance: this._quadraticBezierCurve, updatable: true, colors: colorsArray }, sceneToRenderTo);
    } else {
      this._quadraticBezierCurve = this._options.generateRayPathMesh(quadraticBezierVectors.getPoints(), pickInfo);
    }
    this._quadraticBezierCurve.isPickable = false;
    if (this._options.renderingGroupId !== undefined) {
      this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId;
    }
  }
  _teleportForward(controllerId) {
    const controllerData = this._controllers[controllerId];
    if (!controllerData || !controllerData.teleportationState.forward || !this.teleportationEnabled) {
      return;
    }
    controllerData.teleportationState.forward = false;
    this._currentTeleportationControllerId = "";
    if (this.snapPointsOnly && !this._snappedToPoint) {
      return;
    }
    if (this.skipNextTeleportation) {
      this.skipNextTeleportation = false;
      return;
    }
    if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) {
      const height = this._options.xrInput.xrCamera.realWorldHeight;
      this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);
      this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position);
      this._options.xrInput.xrCamera.position.y += height;
      Quaternion.FromEulerAngles(0, controllerData.teleportationState.currentRotation - (this._xrSessionManager.scene.useRightHandedSystem ? Math.PI : 0), 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);
      this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);
    }
  }
}
WebXRMotionControllerTeleportation.Name = WebXRFeatureName.TELEPORTATION;
WebXRMotionControllerTeleportation.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, (xrSessionManager, options) => {
  return () => new WebXRMotionControllerTeleportation(xrSessionManager, options);
}, WebXRMotionControllerTeleportation.Version, true);

// node_modules/@babylonjs/core/XR/webXRDefaultExperience.js
init_logger();
class WebXRDefaultExperience {
  constructor() {}
  static CreateAsync(scene, options = {}) {
    const result = new WebXRDefaultExperience;
    scene.onDisposeObservable.addOnce(() => {
      result.dispose();
    });
    if (!options.disableDefaultUI) {
      const uiOptions = {
        renderTarget: result.renderTarget,
        ...options.uiOptions || {}
      };
      if (options.optionalFeatures) {
        if (typeof options.optionalFeatures === "boolean") {
          uiOptions.optionalFeatures = ["hit-test", "anchors", "plane-detection", "hand-tracking"];
        } else {
          uiOptions.optionalFeatures = options.optionalFeatures;
        }
      }
      result.enterExitUI = new WebXREnterExitUI(scene, uiOptions);
    }
    return WebXRExperienceHelper.CreateAsync(scene).then((xrHelper) => {
      result.baseExperience = xrHelper;
      if (options.ignoreNativeCameraTransformation) {
        result.baseExperience.camera.compensateOnFirstFrame = false;
      }
      result.input = new WebXRInput(xrHelper.sessionManager, xrHelper.camera, {
        controllerOptions: {
          renderingGroupId: options.renderingGroupId
        },
        ...options.inputOptions || {}
      });
      if (!options.disablePointerSelection) {
        const pointerSelectionOptions = {
          ...options.pointerSelectionOptions,
          xrInput: result.input,
          renderingGroupId: options.renderingGroupId
        };
        result.pointerSelection = result.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, options.useStablePlugins ? "stable" : "latest", pointerSelectionOptions);
        if (!options.disableTeleportation) {
          result.teleportation = result.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, options.useStablePlugins ? "stable" : "latest", {
            floorMeshes: options.floorMeshes,
            xrInput: result.input,
            renderingGroupId: options.renderingGroupId,
            ...options.teleportationOptions
          });
          result.teleportation.setSelectionFeature(result.pointerSelection);
        }
      }
      if (!options.disableNearInteraction) {
        result.nearInteraction = result.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, options.useStablePlugins ? "stable" : "latest", {
          xrInput: result.input,
          farInteractionFeature: result.pointerSelection,
          renderingGroupId: options.renderingGroupId,
          useUtilityLayer: true,
          enableNearInteractionOnAllControllers: true,
          ...options.nearInteractionOptions
        });
      }
      if (!options.disableHandTracking) {
        result.baseExperience.featuresManager.enableFeature(WebXRHandTracking.Name, options.useStablePlugins ? "stable" : "latest", {
          xrInput: result.input,
          ...options.handSupportOptions
        }, undefined, false);
      }
      result.renderTarget = result.baseExperience.sessionManager.getWebXRRenderTarget(options.outputCanvasOptions);
      if (!options.disableDefaultUI) {
        return result.enterExitUI.setHelperAsync(result.baseExperience, result.renderTarget);
      } else {
        return;
      }
    }).then(() => {
      return result;
    }).catch((error) => {
      Logger.Error("Error initializing XR");
      Logger.Error(error);
      return result;
    });
  }
  dispose() {
    if (this.baseExperience) {
      this.baseExperience.dispose();
    }
    if (this.input) {
      this.input.dispose();
    }
    if (this.enterExitUI) {
      this.enterExitUI.dispose();
    }
    if (this.renderTarget) {
      this.renderTarget.dispose();
    }
  }
}

// node_modules/@babylonjs/core/Helpers/sceneHelpers.js
Scene.prototype.createDefaultLight = function(replace = false) {
  if (replace) {
    if (this.lights) {
      for (let i = 0;i < this.lights.length; i++) {
        this.lights[i].dispose();
      }
    }
  }
  if (this.lights.length === 0) {
    new HemisphericLight("default light", Vector3.Up(), this);
  }
};
Scene.prototype.createDefaultCamera = function(createArcRotateCamera = false, replace = false, attachCameraControls = false) {
  if (replace) {
    if (this.activeCamera) {
      this.activeCamera.dispose();
      this.activeCamera = null;
    }
  }
  if (!this.activeCamera) {
    const worldExtends = this.getWorldExtends((mesh) => mesh.isVisible && mesh.isEnabled());
    const worldSize = worldExtends.max.subtract(worldExtends.min);
    const worldCenter = worldExtends.min.add(worldSize.scale(0.5));
    let camera2;
    let radius = worldSize.length() * 1.5;
    if (!isFinite(radius)) {
      radius = 1;
      worldCenter.copyFromFloats(0, 0, 0);
    }
    if (createArcRotateCamera) {
      const arcRotateCamera2 = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
      arcRotateCamera2.lowerRadiusLimit = radius * 0.01;
      arcRotateCamera2.wheelPrecision = 100 / radius;
      camera2 = arcRotateCamera2;
    } else {
      const freeCamera2 = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
      freeCamera2.setTarget(worldCenter);
      camera2 = freeCamera2;
    }
    camera2.minZ = radius * 0.01;
    camera2.maxZ = radius * 1000;
    camera2.speed = radius * 0.2;
    this.activeCamera = camera2;
    if (attachCameraControls) {
      camera2.attachControl();
    }
  }
};
Scene.prototype.createDefaultCameraOrLight = function(createArcRotateCamera = false, replace = false, attachCameraControls = false) {
  this.createDefaultLight(replace);
  this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
};
Scene.prototype.createDefaultSkybox = function(environmentTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true) {
  if (!environmentTexture) {
    Logger.Warn("Can not create default skybox without environment texture.");
    return null;
  }
  if (setGlobalEnvTexture) {
    if (environmentTexture) {
      this.environmentTexture = environmentTexture;
    }
  }
  const hdrSkybox = CreateBox("hdrSkyBox", { size: scale }, this);
  if (pbr) {
    const hdrSkyboxMaterial = new PBRMaterial("skyBox", this);
    hdrSkyboxMaterial.backFaceCulling = false;
    hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
    if (hdrSkyboxMaterial.reflectionTexture) {
      hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
    }
    hdrSkyboxMaterial.microSurface = 1 - blur;
    hdrSkyboxMaterial.disableLighting = true;
    hdrSkyboxMaterial.twoSidedLighting = true;
    hdrSkybox.material = hdrSkyboxMaterial;
  } else {
    const skyboxMaterial = new StandardMaterial("skyBox", this);
    skyboxMaterial.backFaceCulling = false;
    skyboxMaterial.reflectionTexture = environmentTexture.clone();
    if (skyboxMaterial.reflectionTexture) {
      skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;
    }
    skyboxMaterial.disableLighting = true;
    hdrSkybox.material = skyboxMaterial;
  }
  hdrSkybox.isPickable = false;
  hdrSkybox.infiniteDistance = true;
  hdrSkybox.ignoreCameraMaxZ = true;
  return hdrSkybox;
};
Scene.prototype.createDefaultEnvironment = function(options) {
  if (EnvironmentHelper) {
    return new EnvironmentHelper(options, this);
  }
  return null;
};
Scene.prototype.createDefaultVRExperience = function(webVROptions = {}) {
  return new VRExperienceHelper(this, webVROptions);
};
Scene.prototype.createDefaultXRExperienceAsync = function(options = {}) {
  return WebXRDefaultExperience.CreateAsync(this, options).then((helper) => {
    return helper;
  });
};
// node_modules/@babylonjs/core/Helpers/videoDome.js
init_texture();

// node_modules/@babylonjs/core/Materials/Textures/videoTexture.js
init_tslib_es6();
init_observable();
init_tools();
init_logger();
init_texture();
init_decorators();
init_typeStore();
function removeSource(video) {
  while (video.firstChild) {
    video.removeChild(video.firstChild);
  }
  video.srcObject = null;
  video.src = "";
  video.removeAttribute("src");
}

class VideoTexture extends Texture {
  get onUserActionRequestedObservable() {
    if (!this._onUserActionRequestedObservable) {
      this._onUserActionRequestedObservable = new Observable;
    }
    return this._onUserActionRequestedObservable;
  }
  _processError(reason) {
    this._errorFound = true;
    if (this._onError) {
      this._onError(reason?.message);
    } else {
      Logger.Error(reason?.message);
    }
  }
  _handlePlay() {
    this._errorFound = false;
    this.video.play().catch((reason) => {
      if (reason?.name === "NotAllowedError") {
        if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) {
          this._onUserActionRequestedObservable.notifyObservers(this);
          return;
        } else if (!this.video.muted) {
          Logger.Warn("Unable to autoplay a video with sound. Trying again with muted turned true");
          this.video.muted = true;
          this._errorFound = false;
          this.video.play().catch((otherReason) => {
            this._processError(otherReason);
          });
          return;
        }
      }
      this._processError(reason);
    });
  }
  constructor(name327, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) {
    super(null, scene, !generateMipMaps, invertY);
    this._externalTexture = null;
    this._onUserActionRequestedObservable = null;
    this._stillImageCaptured = false;
    this._displayingPosterTexture = false;
    this._frameId = -1;
    this._currentSrc = null;
    this._errorFound = false;
    this.isVideo = true;
    this._resizeInternalTexture = () => {
      if (this._texture != null) {
        this._texture.dispose();
      }
      if (!this._getEngine().needPOTTextures || Tools.IsExponentOfTwo(this.video.videoWidth) && Tools.IsExponentOfTwo(this.video.videoHeight)) {
        this.wrapU = Texture.WRAP_ADDRESSMODE;
        this.wrapV = Texture.WRAP_ADDRESSMODE;
      } else {
        this.wrapU = Texture.CLAMP_ADDRESSMODE;
        this.wrapV = Texture.CLAMP_ADDRESSMODE;
        this._generateMipMaps = false;
      }
      this._texture = this._getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this.samplingMode);
      this._texture.format = this._format ?? 5;
      this._frameId = -1;
      this._updateInternalTexture();
    };
    this._createInternalTexture = () => {
      if (this._texture != null) {
        if (this._displayingPosterTexture) {
          this._displayingPosterTexture = false;
        } else {
          return;
        }
      }
      this.video.addEventListener("resize", this._resizeInternalTexture);
      this._resizeInternalTexture();
      if (!this.video.autoplay && !this._settings.poster && !this._settings.independentVideoSource) {
        const oldHandler = this.video.onplaying;
        const oldMuted = this.video.muted;
        this.video.muted = true;
        this.video.onplaying = () => {
          this.video.muted = oldMuted;
          this.video.onplaying = oldHandler;
          this._updateInternalTexture();
          if (!this._errorFound) {
            this.video.pause();
          }
          if (this.onLoadObservable.hasObservers()) {
            this.onLoadObservable.notifyObservers(this);
          }
        };
        this._handlePlay();
      } else {
        this._updateInternalTexture();
        if (this.onLoadObservable.hasObservers()) {
          this.onLoadObservable.notifyObservers(this);
        }
      }
    };
    this._reset = () => {
      if (this._texture == null) {
        return;
      }
      if (!this._displayingPosterTexture) {
        this._texture.dispose();
        this._texture = null;
      }
    };
    this._updateInternalTexture = () => {
      if (this._texture == null) {
        return;
      }
      if (this.video.readyState < this.video.HAVE_CURRENT_DATA) {
        return;
      }
      if (this._displayingPosterTexture) {
        return;
      }
      const frameId = this.getScene().getFrameId();
      if (this._frameId === frameId) {
        return;
      }
      this._frameId = frameId;
      this._getEngine().updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : this.video, this._invertY);
    };
    this._settings = {
      autoPlay: true,
      loop: true,
      autoUpdateTexture: true,
      ...settings
    };
    this._onError = onError;
    this._generateMipMaps = generateMipMaps;
    this._initialSamplingMode = samplingMode;
    this.autoUpdateTexture = this._settings.autoUpdateTexture;
    this._currentSrc = src;
    this.name = name327 || this._getName(src);
    this.video = this._getVideo(src);
    const engineWebGPU = this._engine;
    const createExternalTexture = engineWebGPU?.createExternalTexture;
    if (createExternalTexture) {
      this._externalTexture = createExternalTexture.call(engineWebGPU, this.video);
    }
    if (!this._settings.independentVideoSource) {
      if (this._settings.poster) {
        this.video.poster = this._settings.poster;
      }
      if (this._settings.autoPlay !== undefined) {
        this.video.autoplay = this._settings.autoPlay;
      }
      if (this._settings.loop !== undefined) {
        this.video.loop = this._settings.loop;
      }
      if (this._settings.muted !== undefined) {
        this.video.muted = this._settings.muted;
      }
      this.video.setAttribute("playsinline", "");
      this.video.addEventListener("paused", this._updateInternalTexture);
      this.video.addEventListener("seeked", this._updateInternalTexture);
      this.video.addEventListener("loadeddata", this._updateInternalTexture);
      this.video.addEventListener("emptied", this._reset);
      if (this._settings.autoPlay) {
        this._handlePlay();
      }
    }
    this._createInternalTextureOnEvent = this._settings.poster && !this._settings.autoPlay ? "play" : "canplay";
    this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
    this._format = format;
    const videoHasEnoughData = this.video.readyState >= this.video.HAVE_CURRENT_DATA;
    if (this._settings.poster && (!this._settings.autoPlay || !videoHasEnoughData)) {
      this._texture = this._getEngine().createTexture(this._settings.poster, false, !this.invertY, scene);
      this._displayingPosterTexture = true;
    } else if (videoHasEnoughData) {
      this._createInternalTexture();
    }
  }
  getClassName() {
    return "VideoTexture";
  }
  _getName(src) {
    if (src instanceof HTMLVideoElement) {
      return src.currentSrc;
    }
    if (typeof src === "object") {
      return src.toString();
    }
    return src;
  }
  _getVideo(src) {
    if (src.isNative) {
      return src;
    }
    if (src instanceof HTMLVideoElement) {
      Tools.SetCorsBehavior(src.currentSrc, src);
      return src;
    }
    const video = document.createElement("video");
    if (typeof src === "string") {
      Tools.SetCorsBehavior(src, video);
      video.src = src;
    } else {
      Tools.SetCorsBehavior(src[0], video);
      src.forEach((url) => {
        const source = document.createElement("source");
        source.src = url;
        video.appendChild(source);
      });
    }
    this.onDisposeObservable.addOnce(() => {
      removeSource(video);
    });
    return video;
  }
  _rebuild() {
    this.update();
  }
  update() {
    if (!this.autoUpdateTexture) {
      return;
    }
    this.updateTexture(true);
  }
  updateTexture(isVisible) {
    if (!isVisible) {
      return;
    }
    if (this.video.paused && this._stillImageCaptured) {
      return;
    }
    this._stillImageCaptured = true;
    this._updateInternalTexture();
  }
  get externalTexture() {
    return this._externalTexture;
  }
  updateURL(url) {
    this.video.src = url;
    this._currentSrc = url;
  }
  clone() {
    return new VideoTexture(this.name, this._currentSrc, this.getScene(), this._generateMipMaps, this.invertY, this.samplingMode, this._settings);
  }
  dispose() {
    super.dispose();
    this._currentSrc = null;
    if (this._onUserActionRequestedObservable) {
      this._onUserActionRequestedObservable.clear();
      this._onUserActionRequestedObservable = null;
    }
    this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
    if (!this._settings.independentVideoSource) {
      this.video.removeEventListener("paused", this._updateInternalTexture);
      this.video.removeEventListener("seeked", this._updateInternalTexture);
      this.video.removeEventListener("loadeddata", this._updateInternalTexture);
      this.video.removeEventListener("emptied", this._reset);
      this.video.removeEventListener("resize", this._resizeInternalTexture);
      this.video.pause();
    }
    this._externalTexture?.dispose();
  }
  static CreateFromStreamAsync(scene, stream, constraints, invertY = true) {
    const video = scene.getEngine().createVideoElement(constraints);
    if (scene.getEngine()._badOS) {
      document.body.appendChild(video);
      video.style.transform = "scale(0.0001, 0.0001)";
      video.style.opacity = "0";
      video.style.position = "fixed";
      video.style.bottom = "0px";
      video.style.right = "0px";
    }
    video.setAttribute("autoplay", "");
    video.setAttribute("muted", "true");
    video.setAttribute("playsinline", "");
    video.muted = true;
    if (video.isNative) {} else {
      if (typeof video.srcObject == "object") {
        video.srcObject = stream;
      } else {
        video.src = window.URL && window.URL.createObjectURL(stream);
      }
    }
    return new Promise((resolve3) => {
      const onPlaying = () => {
        const videoTexture = new VideoTexture("video", video, scene, true, invertY, undefined, undefined, undefined, 4);
        if (scene.getEngine()._badOS) {
          videoTexture.onDisposeObservable.addOnce(() => {
            video.remove();
          });
        }
        videoTexture.onDisposeObservable.addOnce(() => {
          removeSource(video);
        });
        resolve3(videoTexture);
        video.removeEventListener("playing", onPlaying);
      };
      video.addEventListener("playing", onPlaying);
      video.play();
    });
  }
  static async CreateFromWebCamAsync(scene, constraints, audioConstaints = false, invertY = true) {
    if (navigator.mediaDevices) {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: constraints,
        audio: audioConstaints
      });
      const videoTexture = await this.CreateFromStreamAsync(scene, stream, constraints, invertY);
      videoTexture.onDisposeObservable.addOnce(() => {
        stream.getTracks().forEach((track) => {
          track.stop();
        });
      });
      return videoTexture;
    }
    return Promise.reject("No support for userMedia on this device");
  }
  static CreateFromWebCam(scene, onReady, constraints, audioConstaints = false, invertY = true) {
    this.CreateFromWebCamAsync(scene, constraints, audioConstaints, invertY).then(function(videoTexture) {
      if (onReady) {
        onReady(videoTexture);
      }
    }).catch(function(err) {
      Logger.Error(err.name);
    });
  }
}
__decorate([
  serialize("settings")
], VideoTexture.prototype, "_settings", undefined);
__decorate([
  serialize("src")
], VideoTexture.prototype, "_currentSrc", undefined);
__decorate([
  serialize()
], VideoTexture.prototype, "isVideo", undefined);
Texture._CreateVideoTexture = (name327, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) => {
  return new VideoTexture(name327, src, scene, generateMipMaps, invertY, samplingMode, settings, onError, format);
};
RegisterClass("BABYLON.VideoTexture", VideoTexture);

// node_modules/@babylonjs/core/Helpers/videoDome.js
init_pointerEvents();

class VideoDome extends TextureDome {
  get videoTexture() {
    return this._texture;
  }
  get videoMode() {
    return this.textureMode;
  }
  set videoMode(value) {
    this.textureMode = value;
  }
  _initTexture(urlsOrElement, scene, options) {
    const tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
    const texture = new VideoTexture((this.name || "videoDome") + "_texture", urlsOrElement, scene, options.generateMipMaps, this._useDirectMapping, Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
    if (options.clickToPlay) {
      this._pointerObserver = scene.onPointerObservable.add((data) => {
        data.pickInfo?.pickedMesh === this.mesh && this._texture.video.play();
      }, PointerEventTypes.POINTERDOWN);
    }
    this._textureObserver = texture.onLoadObservable.add(() => {
      this.onLoadObservable.notifyObservers();
    });
    return texture;
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    this._texture.onLoadObservable.remove(this._textureObserver);
    this._scene.onPointerObservable.remove(this._pointerObserver);
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
}
VideoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;
VideoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;
VideoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;
// node_modules/@babylonjs/core/Helpers/materialConversionHelper.js
init_math_vector();
// node_modules/@babylonjs/core/Instrumentation/engineInstrumentation.js
init_perfCounter();
// node_modules/@babylonjs/core/Instrumentation/sceneInstrumentation.js
init_tools();
init_perfCounter();
// node_modules/@babylonjs/core/Layers/effectLayer.js
init_tslib_es6();
init_decorators();
init_tools();
init_observable();
init_engineStore();
init_texture();
init_renderTargetTexture();
init_devTools();
class EffectLayer {
  get _shouldRender() {
    return this._thinEffectLayer._shouldRender;
  }
  set _shouldRender(value) {
    this._thinEffectLayer._shouldRender = value;
  }
  get _emissiveTextureAndColor() {
    return this._thinEffectLayer._emissiveTextureAndColor;
  }
  set _emissiveTextureAndColor(value) {
    this._thinEffectLayer._emissiveTextureAndColor = value;
  }
  get _effectIntensity() {
    return this._thinEffectLayer._effectIntensity;
  }
  set _effectIntensity(value) {
    this._thinEffectLayer._effectIntensity = value;
  }
  static get ForceGLSL() {
    return ThinEffectLayer.ForceGLSL;
  }
  static set ForceGLSL(value) {
    ThinEffectLayer.ForceGLSL = value;
  }
  get name() {
    return this._thinEffectLayer.name;
  }
  set name(value) {
    this._thinEffectLayer.name = value;
  }
  get neutralColor() {
    return this._thinEffectLayer.neutralColor;
  }
  set neutralColor(value) {
    this._thinEffectLayer.neutralColor = value;
  }
  get isEnabled() {
    return this._thinEffectLayer.isEnabled;
  }
  set isEnabled(value) {
    this._thinEffectLayer.isEnabled = value;
  }
  get camera() {
    return this._thinEffectLayer.camera;
  }
  get renderingGroupId() {
    return this._thinEffectLayer.renderingGroupId;
  }
  set renderingGroupId(renderingGroupId) {
    this._thinEffectLayer.renderingGroupId = renderingGroupId;
  }
  get disableBoundingBoxesFromEffectLayer() {
    return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer;
  }
  set disableBoundingBoxesFromEffectLayer(value) {
    this._thinEffectLayer.disableBoundingBoxesFromEffectLayer = value;
  }
  get mainTexture() {
    return this._mainTexture;
  }
  get _shaderLanguage() {
    return this._thinEffectLayer.shaderLanguage;
  }
  get shaderLanguage() {
    return this._thinEffectLayer.shaderLanguage;
  }
  setMaterialForRendering(mesh, material) {
    this._thinEffectLayer.setMaterialForRendering(mesh, material);
  }
  getEffectIntensity(mesh) {
    return this._thinEffectLayer.getEffectIntensity(mesh);
  }
  setEffectIntensity(mesh, intensity) {
    this._thinEffectLayer.setEffectIntensity(mesh, intensity);
  }
  constructor(name327, scene, forceGLSL = false, thinEffectLayer) {
    this._maxSize = 0;
    this._mainTextureDesiredSize = { width: 0, height: 0 };
    this._postProcesses = [];
    this._textures = [];
    this.onDisposeObservable = new Observable;
    this.onBeforeRenderMainTextureObservable = new Observable;
    this.onBeforeComposeObservable = new Observable;
    this.onBeforeRenderMeshToEffect = new Observable;
    this.onAfterRenderMeshToEffect = new Observable;
    this.onAfterComposeObservable = new Observable;
    this.onSizeChangedObservable = new Observable;
    this._internalThinEffectLayer = !thinEffectLayer;
    if (!thinEffectLayer) {
      thinEffectLayer = new ThinEffectLayer(name327, scene, forceGLSL, false, this._importShadersAsync.bind(this));
      thinEffectLayer.getEffectName = this.getEffectName.bind(this);
      thinEffectLayer.isReady = this.isReady.bind(this);
      thinEffectLayer._createMergeEffect = this._createMergeEffect.bind(this);
      thinEffectLayer._createTextureAndPostProcesses = this._createTextureAndPostProcesses.bind(this);
      thinEffectLayer._internalCompose = this._internalRender.bind(this);
      thinEffectLayer._setEmissiveTextureAndColor = this._setEmissiveTextureAndColor.bind(this);
      thinEffectLayer._numInternalDraws = this._numInternalDraws.bind(this);
      thinEffectLayer._addCustomEffectDefines = this._addCustomEffectDefines.bind(this);
      thinEffectLayer.hasMesh = this.hasMesh.bind(this);
      thinEffectLayer.shouldRender = this.shouldRender.bind(this);
      thinEffectLayer._shouldRenderMesh = this._shouldRenderMesh.bind(this);
      thinEffectLayer._canRenderMesh = this._canRenderMesh.bind(this);
      thinEffectLayer._useMeshMaterial = this._useMeshMaterial.bind(this);
    }
    this._thinEffectLayer = thinEffectLayer;
    this.name = name327;
    this._scene = scene || EngineStore.LastCreatedScene;
    EffectLayer._SceneComponentInitialization(this._scene);
    this._engine = this._scene.getEngine();
    this._maxSize = this._engine.getCaps().maxTextureSize;
    this._scene.effectLayers.push(this);
    this._thinEffectLayer.onDisposeObservable.add(() => {
      this.onDisposeObservable.notifyObservers(this);
    });
    this._thinEffectLayer.onBeforeRenderLayerObservable.add(() => {
      this.onBeforeRenderMainTextureObservable.notifyObservers(this);
    });
    this._thinEffectLayer.onBeforeComposeObservable.add(() => {
      this.onBeforeComposeObservable.notifyObservers(this);
    });
    this._thinEffectLayer.onBeforeRenderMeshToEffect.add((mesh) => {
      this.onBeforeRenderMeshToEffect.notifyObservers(mesh);
    });
    this._thinEffectLayer.onAfterRenderMeshToEffect.add((mesh) => {
      this.onAfterRenderMeshToEffect.notifyObservers(mesh);
    });
    this._thinEffectLayer.onAfterComposeObservable.add(() => {
      this.onAfterComposeObservable.notifyObservers(this);
    });
  }
  get _shadersLoaded() {
    return this._thinEffectLayer._shadersLoaded;
  }
  set _shadersLoaded(value) {
    this._thinEffectLayer._shadersLoaded = value;
  }
  _numInternalDraws() {
    return this._internalThinEffectLayer ? 1 : this._thinEffectLayer._numInternalDraws();
  }
  _init(options) {
    this._effectLayerOptions = {
      mainTextureRatio: 0.5,
      alphaBlendingMode: 2,
      camera: null,
      renderingGroupId: -1,
      mainTextureType: 0,
      generateStencilBuffer: false,
      ...options
    };
    this._setMainTextureSize();
    this._thinEffectLayer._init(options);
    this._createMainTexture();
    this._createTextureAndPostProcesses();
  }
  _setMainTextureSize() {
    if (this._effectLayerOptions.mainTextureFixedSize) {
      this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
      this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
    } else {
      this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
      this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
      this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
      this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
    }
    this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
    this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  }
  _createMainTexture() {
    this._mainTexture = new RenderTargetTexture("EffectLayerMainRTT", {
      width: this._mainTextureDesiredSize.width,
      height: this._mainTextureDesiredSize.height
    }, this._scene, {
      type: this._effectLayerOptions.mainTextureType,
      samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
      generateStencilBuffer: this._effectLayerOptions.generateStencilBuffer,
      existingObjectRenderer: this._thinEffectLayer.objectRenderer
    });
    this._mainTexture.activeCamera = this._effectLayerOptions.camera;
    this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._mainTexture.anisotropicFilteringLevel = 1;
    this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    this._mainTexture.renderParticles = false;
    this._mainTexture.renderList = null;
    this._mainTexture.ignoreCameraViewport = true;
    this._mainTexture.onClearObservable.add((engine2) => {
      engine2.clear(this.neutralColor, true, true, true);
    });
  }
  _addCustomEffectDefines(defines) {}
  _isReady(subMesh, useInstances, emissiveTexture) {
    return this._internalThinEffectLayer ? this._thinEffectLayer._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) : this._thinEffectLayer._isSubMeshReady(subMesh, useInstances, emissiveTexture);
  }
  async _importShadersAsync() {}
  _arePostProcessAndMergeReady() {
    return this._internalThinEffectLayer ? this._thinEffectLayer._internalIsLayerReady() : this._thinEffectLayer.isLayerReady();
  }
  isLayerReady() {
    return this._arePostProcessAndMergeReady() && this._mainTexture.isReady();
  }
  render() {
    if (!this._thinEffectLayer.compose()) {
      return;
    }
    const size = this._mainTexture.getSize();
    this._setMainTextureSize();
    if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) && this._mainTextureDesiredSize.width !== 0 && this._mainTextureDesiredSize.height !== 0) {
      this.onSizeChangedObservable.notifyObservers(this);
      this._disposeTextureAndPostProcesses();
      this._createMainTexture();
      this._createTextureAndPostProcesses();
    }
  }
  hasMesh(mesh) {
    return this._internalThinEffectLayer ? this._thinEffectLayer._internalHasMesh(mesh) : this._thinEffectLayer.hasMesh(mesh);
  }
  shouldRender() {
    return this._internalThinEffectLayer ? this._thinEffectLayer._internalShouldRender() : this._thinEffectLayer.shouldRender();
  }
  _shouldRenderMesh(mesh) {
    return this._internalThinEffectLayer ? true : this._thinEffectLayer._shouldRenderMesh(mesh);
  }
  _canRenderMesh(mesh, material) {
    return this._internalThinEffectLayer ? this._thinEffectLayer._internalCanRenderMesh(mesh, material) : this._thinEffectLayer._canRenderMesh(mesh, material);
  }
  _shouldRenderEmissiveTextureForMesh() {
    return true;
  }
  _useMeshMaterial(mesh) {
    return this._internalThinEffectLayer ? false : this._thinEffectLayer._useMeshMaterial(mesh);
  }
  _rebuild() {
    this._thinEffectLayer._rebuild();
  }
  _disposeTextureAndPostProcesses() {
    this._mainTexture.dispose();
    for (let i = 0;i < this._postProcesses.length; i++) {
      if (this._postProcesses[i]) {
        this._postProcesses[i].dispose();
      }
    }
    this._postProcesses = [];
    for (let i = 0;i < this._textures.length; i++) {
      if (this._textures[i]) {
        this._textures[i].dispose();
      }
    }
    this._textures = [];
  }
  dispose() {
    this._thinEffectLayer.dispose();
    this._disposeTextureAndPostProcesses();
    const index = this._scene.effectLayers.indexOf(this, 0);
    if (index > -1) {
      this._scene.effectLayers.splice(index, 1);
    }
    this.onDisposeObservable.clear();
    this.onBeforeRenderMainTextureObservable.clear();
    this.onBeforeComposeObservable.clear();
    this.onBeforeRenderMeshToEffect.clear();
    this.onAfterRenderMeshToEffect.clear();
    this.onAfterComposeObservable.clear();
    this.onSizeChangedObservable.clear();
  }
  getClassName() {
    return "EffectLayer";
  }
  static Parse(parsedEffectLayer, scene, rootUrl) {
    const effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);
    return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  }
}
EffectLayer._SceneComponentInitialization = (_) => {
  throw _WarnImport("EffectLayerSceneComponent");
};
__decorate([
  serialize()
], EffectLayer.prototype, "name", null);
__decorate([
  serializeAsColor4()
], EffectLayer.prototype, "neutralColor", null);
__decorate([
  serialize()
], EffectLayer.prototype, "isEnabled", null);
__decorate([
  serializeAsCameraReference()
], EffectLayer.prototype, "camera", null);
__decorate([
  serialize()
], EffectLayer.prototype, "renderingGroupId", null);
__decorate([
  serialize()
], EffectLayer.prototype, "disableBoundingBoxesFromEffectLayer", null);
// node_modules/@babylonjs/core/Layers/effectLayerSceneComponent.js
init_scene();
init_sceneComponent();
init_engineStore();
AddParser(SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => {
  if (parsedData.effectLayers) {
    if (!container.effectLayers) {
      container.effectLayers = [];
    }
    for (let index = 0;index < parsedData.effectLayers.length; index++) {
      const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
      container.effectLayers.push(effectLayer);
    }
  }
});
Scene.prototype.removeEffectLayer = function(toRemove) {
  const index = this.effectLayers.indexOf(toRemove);
  if (index !== -1) {
    this.effectLayers.splice(index, 1);
  }
  return index;
};
Scene.prototype.addEffectLayer = function(newEffectLayer) {
  this.effectLayers.push(newEffectLayer);
};

class EffectLayerSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_EFFECTLAYER;
    this._renderEffects = false;
    this._needStencil = false;
    this._previousStencilState = false;
    this.scene = scene || EngineStore.LastCreatedScene;
    if (!this.scene) {
      return;
    }
    this._engine = this.scene.getEngine();
  }
  register() {
    this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
    this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
    this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
    this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  }
  rebuild() {
    const layers = this.scene.effectLayers;
    for (const effectLayer of layers) {
      effectLayer._rebuild();
    }
  }
  serialize(serializationObject) {
    serializationObject.effectLayers = [];
    const layers = this.scene.effectLayers;
    for (const effectLayer of layers) {
      if (effectLayer.serialize) {
        serializationObject.effectLayers.push(effectLayer.serialize());
      }
    }
  }
  addFromContainer(container) {
    if (!container.effectLayers) {
      return;
    }
    container.effectLayers.forEach((o) => {
      this.scene.addEffectLayer(o);
    });
  }
  removeFromContainer(container, dispose) {
    if (!container.effectLayers) {
      return;
    }
    container.effectLayers.forEach((o) => {
      this.scene.removeEffectLayer(o);
      if (dispose) {
        o.dispose();
      }
    });
  }
  dispose() {
    const layers = this.scene.effectLayers;
    while (layers.length) {
      layers[0].dispose();
    }
  }
  _isReadyForMesh(mesh, hardwareInstancedRendering) {
    const currentRenderPassId = this._engine.currentRenderPassId;
    const layers = this.scene.effectLayers;
    for (const layer of layers) {
      if (!layer.hasMesh(mesh)) {
        continue;
      }
      const renderTarget = layer._mainTexture;
      this._engine.currentRenderPassId = renderTarget.renderPassId;
      for (const subMesh of mesh.subMeshes) {
        if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
          this._engine.currentRenderPassId = currentRenderPassId;
          return false;
        }
      }
    }
    this._engine.currentRenderPassId = currentRenderPassId;
    return true;
  }
  _renderMainTexture(camera2) {
    this._renderEffects = false;
    this._needStencil = false;
    let needRebind = false;
    const layers = this.scene.effectLayers;
    if (layers && layers.length > 0) {
      this._previousStencilState = this._engine.getStencilBuffer();
      for (const effectLayer of layers) {
        if (effectLayer.shouldRender() && (!effectLayer.camera || effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera2 === effectLayer.camera || effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera2) > -1)) {
          this._renderEffects = true;
          this._needStencil = this._needStencil || effectLayer.needStencil();
          const renderTarget = effectLayer._mainTexture;
          if (renderTarget._shouldRender()) {
            this.scene.incrementRenderId();
            renderTarget.render(false, false);
            needRebind = true;
          }
        }
      }
      this.scene.incrementRenderId();
    }
    return needRebind;
  }
  _setStencil() {
    if (this._needStencil) {
      this._engine.setStencilBuffer(true);
    }
  }
  _setStencilBack() {
    if (this._needStencil) {
      this._engine.setStencilBuffer(this._previousStencilState);
    }
  }
  _draw(renderingGroupId) {
    if (this._renderEffects) {
      this._engine.setDepthBuffer(false);
      const layers = this.scene.effectLayers;
      for (let i = 0;i < layers.length; i++) {
        const effectLayer = layers[i];
        if (effectLayer.renderingGroupId === renderingGroupId) {
          if (effectLayer.shouldRender()) {
            effectLayer.render();
          }
        }
      }
      this._engine.setDepthBuffer(true);
    }
  }
  _drawCamera() {
    if (this._renderEffects) {
      this._draw(-1);
    }
  }
  _drawRenderingGroup(index) {
    if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
      this._draw(index);
    }
  }
}
EffectLayer._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);
  if (!component) {
    component = new EffectLayerSceneComponent(scene);
    scene._addComponent(component);
  }
};
// node_modules/@babylonjs/core/Layers/glowLayer.js
init_tslib_es6();
init_decorators();
init_scene();
init_texture();
init_renderTargetTexture();
init_typeStore();
init_decorators_serialization();
Scene.prototype.getGlowLayerByName = function(name327) {
  for (let index = 0;index < this.effectLayers?.length; index++) {
    if (this.effectLayers[index].name === name327 && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
      return this.effectLayers[index];
    }
  }
  return null;
};

class GlowLayer extends EffectLayer {
  static get EffectName() {
    return ThinGlowLayer.EffectName;
  }
  set blurKernelSize(value) {
    this._thinEffectLayer.blurKernelSize = value;
  }
  get blurKernelSize() {
    return this._thinEffectLayer.blurKernelSize;
  }
  set intensity(value) {
    this._thinEffectLayer.intensity = value;
  }
  get intensity() {
    return this._thinEffectLayer.intensity;
  }
  get customEmissiveColorSelector() {
    return this._thinEffectLayer.customEmissiveColorSelector;
  }
  set customEmissiveColorSelector(value) {
    this._thinEffectLayer.customEmissiveColorSelector = value;
  }
  get customEmissiveTextureSelector() {
    return this._thinEffectLayer.customEmissiveTextureSelector;
  }
  set customEmissiveTextureSelector(value) {
    this._thinEffectLayer.customEmissiveTextureSelector = value;
  }
  constructor(name327, scene, options) {
    super(name327, scene, false, new ThinGlowLayer(name327, scene, options));
    this._options = {
      mainTextureRatio: GlowLayer.DefaultTextureRatio,
      blurKernelSize: 32,
      mainTextureFixedSize: undefined,
      camera: null,
      mainTextureSamples: 1,
      renderingGroupId: -1,
      ldrMerge: false,
      alphaBlendingMode: 1,
      mainTextureType: 0,
      generateStencilBuffer: false,
      ...options
    };
    this._init(this._options);
  }
  getEffectName() {
    return GlowLayer.EffectName;
  }
  _createMergeEffect() {
    return this._thinEffectLayer._createMergeEffect();
  }
  _createTextureAndPostProcesses() {
    this._thinEffectLayer._renderPassId = this._mainTexture.renderPassId;
    let blurTextureWidth = this._mainTextureDesiredSize.width;
    let blurTextureHeight = this._mainTextureDesiredSize.height;
    blurTextureWidth = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
    blurTextureHeight = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
    let textureType = 0;
    if (this._engine.getCaps().textureHalfFloatRender) {
      textureType = 2;
    } else {
      textureType = 0;
    }
    this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT", {
      width: blurTextureWidth,
      height: blurTextureHeight
    }, this._scene, false, true, textureType);
    this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    this._blurTexture1.renderParticles = false;
    this._blurTexture1.ignoreCameraViewport = true;
    const blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
    const blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
    this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2", {
      width: blurTextureWidth2,
      height: blurTextureHeight2
    }, this._scene, false, true, textureType);
    this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
    this._blurTexture2.renderParticles = false;
    this._blurTexture2.ignoreCameraViewport = true;
    this._textures = [this._blurTexture1, this._blurTexture2];
    this._thinEffectLayer.bindTexturesForCompose = (effect) => {
      effect.setTexture("textureSampler", this._blurTexture1);
      effect.setTexture("textureSampler2", this._blurTexture2);
      effect.setFloat("offset", this.intensity);
    };
    this._thinEffectLayer._createTextureAndPostProcesses();
    const thinBlurPostProcesses1 = this._thinEffectLayer._postProcesses[0];
    this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1", thinBlurPostProcesses1.direction, thinBlurPostProcesses1.kernel, {
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: this._scene.getEngine(),
      width: blurTextureWidth,
      height: blurTextureHeight,
      textureType,
      effectWrapper: thinBlurPostProcesses1
    });
    this._horizontalBlurPostprocess1.width = blurTextureWidth;
    this._horizontalBlurPostprocess1.height = blurTextureHeight;
    this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true;
    this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => {
      effect.setTexture("textureSampler", this._mainTexture);
    });
    const thinBlurPostProcesses2 = this._thinEffectLayer._postProcesses[1];
    this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1", thinBlurPostProcesses2.direction, thinBlurPostProcesses2.kernel, {
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: this._scene.getEngine(),
      width: blurTextureWidth,
      height: blurTextureHeight,
      textureType,
      effectWrapper: thinBlurPostProcesses2
    });
    const thinBlurPostProcesses3 = this._thinEffectLayer._postProcesses[2];
    this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2", thinBlurPostProcesses3.direction, thinBlurPostProcesses3.kernel, {
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: this._scene.getEngine(),
      width: blurTextureWidth2,
      height: blurTextureHeight2,
      textureType,
      effectWrapper: thinBlurPostProcesses3
    });
    this._horizontalBlurPostprocess2.width = blurTextureWidth2;
    this._horizontalBlurPostprocess2.height = blurTextureHeight2;
    this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true;
    this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => {
      effect.setTexture("textureSampler", this._blurTexture1);
    });
    const thinBlurPostProcesses4 = this._thinEffectLayer._postProcesses[3];
    this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2", thinBlurPostProcesses4.direction, thinBlurPostProcesses4.kernel, {
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: this._scene.getEngine(),
      width: blurTextureWidth2,
      height: blurTextureHeight2,
      textureType,
      effectWrapper: thinBlurPostProcesses4
    });
    this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
    this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
    this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
    this._mainTexture.samples = this._options.mainTextureSamples;
    this._mainTexture.onAfterUnbindObservable.add(() => {
      const internalTexture = this._blurTexture1.renderTarget;
      if (internalTexture) {
        this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true);
        const internalTexture2 = this._blurTexture2.renderTarget;
        if (internalTexture2) {
          this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true);
        }
        this._engine.unBindFramebuffer(internalTexture2 ?? internalTexture, true);
      }
    });
    this._postProcesses.map((pp) => {
      pp.autoClear = false;
    });
  }
  isReady(subMesh, useInstances) {
    return this._thinEffectLayer.isReady(subMesh, useInstances);
  }
  needStencil() {
    return false;
  }
  _canRenderMesh(mesh, material) {
    return this._thinEffectLayer._canRenderMesh(mesh, material);
  }
  _internalRender(effect) {
    this._thinEffectLayer._internalCompose(effect);
  }
  _setEmissiveTextureAndColor(mesh, subMesh, material) {
    this._thinEffectLayer._setEmissiveTextureAndColor(mesh, subMesh, material);
  }
  _shouldRenderMesh(mesh) {
    return this._thinEffectLayer._shouldRenderMesh(mesh);
  }
  _addCustomEffectDefines(defines) {
    this._thinEffectLayer._addCustomEffectDefines(defines);
  }
  addExcludedMesh(mesh) {
    this._thinEffectLayer.addExcludedMesh(mesh);
  }
  removeExcludedMesh(mesh) {
    this._thinEffectLayer.removeExcludedMesh(mesh);
  }
  addIncludedOnlyMesh(mesh) {
    this._thinEffectLayer.addIncludedOnlyMesh(mesh);
  }
  removeIncludedOnlyMesh(mesh) {
    this._thinEffectLayer.removeIncludedOnlyMesh(mesh);
  }
  hasMesh(mesh) {
    return this._thinEffectLayer.hasMesh(mesh);
  }
  _useMeshMaterial(mesh) {
    return this._thinEffectLayer._useMeshMaterial(mesh);
  }
  referenceMeshToUseItsOwnMaterial(mesh) {
    this._thinEffectLayer.referenceMeshToUseItsOwnMaterial(mesh);
  }
  unReferenceMeshFromUsingItsOwnMaterial(mesh) {
    this._thinEffectLayer.unReferenceMeshFromUsingItsOwnMaterial(mesh, this._mainTexture.renderPassId);
  }
  _disposeMesh(mesh) {
    this._thinEffectLayer._disposeMesh(mesh);
  }
  getClassName() {
    return "GlowLayer";
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "BABYLON.GlowLayer";
    let index;
    serializationObject.includedMeshes = [];
    const includedOnlyMeshes = this._thinEffectLayer._includedOnlyMeshes;
    if (includedOnlyMeshes.length) {
      for (index = 0;index < includedOnlyMeshes.length; index++) {
        const mesh = this._scene.getMeshByUniqueId(includedOnlyMeshes[index]);
        if (mesh) {
          serializationObject.includedMeshes.push(mesh.id);
        }
      }
    }
    serializationObject.excludedMeshes = [];
    const excludedMeshes = this._thinEffectLayer._excludedMeshes;
    if (excludedMeshes.length) {
      for (index = 0;index < excludedMeshes.length; index++) {
        const mesh = this._scene.getMeshByUniqueId(excludedMeshes[index]);
        if (mesh) {
          serializationObject.excludedMeshes.push(mesh.id);
        }
      }
    }
    return serializationObject;
  }
  static Parse(parsedGlowLayer, scene, rootUrl) {
    const gl = SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl);
    let index;
    for (index = 0;index < parsedGlowLayer.excludedMeshes.length; index++) {
      const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]);
      if (mesh) {
        gl.addExcludedMesh(mesh);
      }
    }
    for (index = 0;index < parsedGlowLayer.includedMeshes.length; index++) {
      const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]);
      if (mesh) {
        gl.addIncludedOnlyMesh(mesh);
      }
    }
    return gl;
  }
}
GlowLayer.DefaultBlurKernelSize = 32;
GlowLayer.DefaultTextureRatio = 0.5;
__decorate([
  serialize()
], GlowLayer.prototype, "blurKernelSize", null);
__decorate([
  serialize()
], GlowLayer.prototype, "intensity", null);
__decorate([
  serialize("options")
], GlowLayer.prototype, "_options", undefined);
RegisterClass("BABYLON.GlowLayer", GlowLayer);
// node_modules/@babylonjs/core/Layers/highlightLayer.js
init_tslib_es6();
init_decorators();
init_observable();
init_scene();
init_math_vector();
init_texture();
init_renderTargetTexture();
init_postProcess();
init_passPostProcess();
init_logger();
init_typeStore();
init_math_color();
init_decorators_serialization();
Scene.prototype.getHighlightLayerByName = function(name327) {
  for (let index = 0;index < this.effectLayers?.length; index++) {
    if (this.effectLayers[index].name === name327 && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
      return this.effectLayers[index];
    }
  }
  return null;
};

class GlowBlurPostProcess extends PostProcess {
  constructor(name327, direction, kernel, options, camera2 = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine2, reusable) {
    const localOptions = {
      uniforms: ThinGlowBlurPostProcess.Uniforms,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      ...options
    };
    super(name327, ThinGlowBlurPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinGlowBlurPostProcess(name327, engine2, direction, kernel, localOptions) : undefined,
      ...localOptions
    });
    this.direction = direction;
    this.kernel = kernel;
    this.onApplyObservable.add(() => {
      this._effectWrapper.textureWidth = this.width;
      this._effectWrapper.textureHeight = this.height;
    });
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), exports_glowBlurPostProcess_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), exports_glowBlurPostProcess_fragment2)));
    }
    super._gatherImports(useWebGPU, list);
  }
}

class HighlightLayer extends EffectLayer {
  static get NeutralColor() {
    return ThinHighlightLayer.NeutralColor;
  }
  static set NeutralColor(value) {
    ThinHighlightLayer.NeutralColor = value;
  }
  get innerGlow() {
    return this._thinEffectLayer.innerGlow;
  }
  set innerGlow(value) {
    this._thinEffectLayer.innerGlow = value;
  }
  get outerGlow() {
    return this._thinEffectLayer.outerGlow;
  }
  set outerGlow(value) {
    this._thinEffectLayer.outerGlow = value;
  }
  set blurHorizontalSize(value) {
    this._thinEffectLayer.blurHorizontalSize = value;
  }
  set blurVerticalSize(value) {
    this._thinEffectLayer.blurVerticalSize = value;
  }
  get blurHorizontalSize() {
    return this._thinEffectLayer.blurHorizontalSize;
  }
  get blurVerticalSize() {
    return this._thinEffectLayer.blurVerticalSize;
  }
  constructor(name327, scene, options) {
    super(name327, scene, options !== undefined ? !!options.forceGLSL : false, new ThinHighlightLayer(name327, scene, options));
    this.onBeforeBlurObservable = new Observable;
    this.onAfterBlurObservable = new Observable;
    if (!this._engine.isStencilEnable) {
      Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }");
    }
    this._options = {
      mainTextureRatio: 0.5,
      blurTextureSizeRatio: 0.5,
      mainTextureFixedSize: 0,
      blurHorizontalSize: 1,
      blurVerticalSize: 1,
      alphaBlendingMode: 2,
      camera: null,
      renderingGroupId: -1,
      mainTextureType: 0,
      forceGLSL: false,
      isStroke: false,
      ...options
    };
    this._init(this._options);
    this._shouldRender = false;
  }
  getEffectName() {
    return HighlightLayer.EffectName;
  }
  _numInternalDraws() {
    return 2;
  }
  _createMergeEffect() {
    return this._thinEffectLayer._createMergeEffect();
  }
  _createTextureAndPostProcesses() {
    let blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
    let blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
    blurTextureWidth = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
    blurTextureHeight = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
    let textureType = 0;
    if (this._engine.getCaps().textureHalfFloatRender) {
      textureType = 2;
    } else {
      textureType = 0;
    }
    this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT", {
      width: blurTextureWidth,
      height: blurTextureHeight
    }, this._scene, false, true, textureType);
    this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._blurTexture.anisotropicFilteringLevel = 16;
    this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
    this._blurTexture.renderParticles = false;
    this._blurTexture.ignoreCameraViewport = true;
    this._textures = [this._blurTexture];
    this._thinEffectLayer.bindTexturesForCompose = (effect) => {
      effect.setTexture("textureSampler", this._blurTexture);
    };
    this._thinEffectLayer._createTextureAndPostProcesses();
    if (this._options.alphaBlendingMode === 2) {
      this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", {
        size: this._options.blurTextureSizeRatio,
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: this._scene.getEngine(),
        effectWrapper: this._thinEffectLayer._postProcesses[0]
      });
      this._downSamplePostprocess.externalTextureSamplerBinding = true;
      this._downSamplePostprocess.onApplyObservable.add((effect) => {
        effect.setTexture("textureSampler", this._mainTexture);
      });
      this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new Vector2(1, 0), this._options.blurHorizontalSize, {
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: this._scene.getEngine(),
        effectWrapper: this._thinEffectLayer._postProcesses[1]
      });
      this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
        effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
      });
      this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new Vector2(0, 1), this._options.blurVerticalSize, {
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: this._scene.getEngine(),
        effectWrapper: this._thinEffectLayer._postProcesses[2]
      });
      this._verticalBlurPostprocess.onApplyObservable.add((effect) => {
        effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
      });
      this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
    } else {
      this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new Vector2(1, 0), this._options.blurHorizontalSize / 2, {
        size: {
          width: blurTextureWidth,
          height: blurTextureHeight
        },
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: this._scene.getEngine(),
        textureType,
        effectWrapper: this._thinEffectLayer._postProcesses[0]
      });
      this._horizontalBlurPostprocess.width = blurTextureWidth;
      this._horizontalBlurPostprocess.height = blurTextureHeight;
      this._horizontalBlurPostprocess.externalTextureSamplerBinding = true;
      this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
        effect.setTexture("textureSampler", this._mainTexture);
      });
      this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new Vector2(0, 1), this._options.blurVerticalSize / 2, {
        size: {
          width: blurTextureWidth,
          height: blurTextureHeight
        },
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: this._scene.getEngine(),
        textureType
      });
      this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
    }
    this._mainTexture.onAfterUnbindObservable.add(() => {
      this.onBeforeBlurObservable.notifyObservers(this);
      const internalTexture = this._blurTexture.renderTarget;
      if (internalTexture) {
        this._scene.postProcessManager.directRender(this._postProcesses, internalTexture, true);
        this._engine.unBindFramebuffer(internalTexture, true);
      }
      this.onAfterBlurObservable.notifyObservers(this);
    });
    this._postProcesses.map((pp) => {
      pp.autoClear = false;
    });
  }
  needStencil() {
    return this._thinEffectLayer.needStencil();
  }
  isReady(subMesh, useInstances) {
    return this._thinEffectLayer.isReady(subMesh, useInstances);
  }
  _internalRender(effect, renderIndex) {
    this._thinEffectLayer._internalCompose(effect, renderIndex);
  }
  shouldRender() {
    return this._thinEffectLayer.shouldRender();
  }
  _shouldRenderMesh(mesh) {
    return this._thinEffectLayer._shouldRenderMesh(mesh);
  }
  _canRenderMesh(mesh, material) {
    return this._thinEffectLayer._canRenderMesh(mesh, material);
  }
  _addCustomEffectDefines(defines) {
    this._thinEffectLayer._addCustomEffectDefines(defines);
  }
  _setEmissiveTextureAndColor(mesh, subMesh, material) {
    this._thinEffectLayer._setEmissiveTextureAndColor(mesh, subMesh, material);
  }
  addExcludedMesh(mesh) {
    this._thinEffectLayer.addExcludedMesh(mesh);
  }
  removeExcludedMesh(mesh) {
    this._thinEffectLayer.removeExcludedMesh(mesh);
  }
  hasMesh(mesh) {
    return this._thinEffectLayer.hasMesh(mesh);
  }
  addMesh(mesh, color, glowEmissiveOnly = false) {
    this._thinEffectLayer.addMesh(mesh, color, glowEmissiveOnly);
  }
  removeMesh(mesh) {
    this._thinEffectLayer.removeMesh(mesh);
  }
  removeAllMeshes() {
    this._thinEffectLayer.removeAllMeshes();
  }
  _disposeMesh(mesh) {
    this._thinEffectLayer._disposeMesh(mesh);
  }
  getClassName() {
    return "HighlightLayer";
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "BABYLON.HighlightLayer";
    serializationObject.meshes = [];
    const meshes = this._thinEffectLayer._meshes;
    if (meshes) {
      for (const m in meshes) {
        const mesh = meshes[m];
        if (mesh) {
          serializationObject.meshes.push({
            glowEmissiveOnly: mesh.glowEmissiveOnly,
            color: mesh.color.asArray(),
            meshId: mesh.mesh.id
          });
        }
      }
    }
    serializationObject.excludedMeshes = [];
    const excludedMeshes = this._thinEffectLayer._excludedMeshes;
    if (excludedMeshes) {
      for (const e in excludedMeshes) {
        const excludedMesh = excludedMeshes[e];
        if (excludedMesh) {
          serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
        }
      }
    }
    return serializationObject;
  }
  static Parse(parsedHightlightLayer, scene, rootUrl) {
    const hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl);
    let index;
    for (index = 0;index < parsedHightlightLayer.excludedMeshes.length; index++) {
      const mesh = scene.getMeshById(parsedHightlightLayer.excludedMeshes[index]);
      if (mesh) {
        hl.addExcludedMesh(mesh);
      }
    }
    for (index = 0;index < parsedHightlightLayer.meshes.length; index++) {
      const highlightedMesh = parsedHightlightLayer.meshes[index];
      const mesh = scene.getMeshById(highlightedMesh.meshId);
      if (mesh) {
        hl.addMesh(mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
      }
    }
    return hl;
  }
}
HighlightLayer.EffectName = "HighlightLayer";
__decorate([
  serialize()
], HighlightLayer.prototype, "innerGlow", null);
__decorate([
  serialize()
], HighlightLayer.prototype, "outerGlow", null);
__decorate([
  serialize()
], HighlightLayer.prototype, "blurHorizontalSize", null);
__decorate([
  serialize()
], HighlightLayer.prototype, "blurVerticalSize", null);
__decorate([
  serialize("options")
], HighlightLayer.prototype, "_options", undefined);
RegisterClass("BABYLON.HighlightLayer", HighlightLayer);
// node_modules/@babylonjs/core/Layers/layer.js
init_observable();
init_math_vector();
init_math_color();
init_engineStore();
init_buffer();
init_texture();
init_sceneComponent();

// node_modules/@babylonjs/core/Layers/layerSceneComponent.js
init_sceneComponent();
init_engineStore();

class LayerSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_LAYER;
    this.scene = scene || EngineStore.LastCreatedScene;
    if (!this.scene) {
      return;
    }
    this._engine = this.scene.getEngine();
  }
  register() {
    this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForegroundWithPostProcessing);
    this.scene._afterCameraPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER, this, this._drawCameraForegroundWithoutPostProcessing);
    this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);
    this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForegroundWithPostProcessing);
    this.scene._afterRenderTargetPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER, this, this._drawRenderTargetForegroundWithoutPostProcessing);
  }
  rebuild() {
    const layers = this.scene.layers;
    for (const layer of layers) {
      layer._rebuild();
    }
  }
  dispose() {
    const layers = this.scene.layers;
    while (layers.length) {
      layers[0].dispose();
    }
  }
  _draw(predicate) {
    const layers = this.scene.layers;
    if (layers.length) {
      this._engine.setDepthBuffer(false);
      for (const layer of layers) {
        if (predicate(layer)) {
          layer.render();
        }
      }
      this._engine.setDepthBuffer(true);
    }
  }
  _drawCameraPredicate(layer, isBackground, applyPostProcess, cameraLayerMask) {
    return !layer.renderOnlyInRenderTargetTextures && layer.isBackground === isBackground && layer.applyPostProcess === applyPostProcess && (layer.layerMask & cameraLayerMask) !== 0;
  }
  _drawCameraBackground(camera2) {
    this._draw((layer) => {
      return this._drawCameraPredicate(layer, true, true, camera2.layerMask);
    });
  }
  _drawCameraForegroundWithPostProcessing(camera2) {
    this._draw((layer) => {
      return this._drawCameraPredicate(layer, false, true, camera2.layerMask);
    });
  }
  _drawCameraForegroundWithoutPostProcessing(camera2) {
    this._draw((layer) => {
      return this._drawCameraPredicate(layer, false, false, camera2.layerMask);
    });
  }
  _drawRenderTargetPredicate(layer, isBackground, applyPostProcess, cameraLayerMask, renderTargetTexture) {
    return layer.renderTargetTextures.length > 0 && layer.isBackground === isBackground && layer.applyPostProcess === applyPostProcess && layer.renderTargetTextures.indexOf(renderTargetTexture) > -1 && (layer.layerMask & cameraLayerMask) !== 0;
  }
  _drawRenderTargetBackground(renderTarget) {
    this._draw((layer) => {
      return this._drawRenderTargetPredicate(layer, true, true, this.scene.activeCamera.layerMask, renderTarget);
    });
  }
  _drawRenderTargetForegroundWithPostProcessing(renderTarget) {
    this._draw((layer) => {
      return this._drawRenderTargetPredicate(layer, false, true, this.scene.activeCamera.layerMask, renderTarget);
    });
  }
  _drawRenderTargetForegroundWithoutPostProcessing(renderTarget) {
    this._draw((layer) => {
      return this._drawRenderTargetPredicate(layer, false, false, this.scene.activeCamera.layerMask, renderTarget);
    });
  }
  addFromContainer(container) {
    if (!container.layers) {
      return;
    }
    container.layers.forEach((layer) => {
      this.scene.layers.push(layer);
    });
  }
  removeFromContainer(container, dispose = false) {
    if (!container.layers) {
      return;
    }
    container.layers.forEach((layer) => {
      const index = this.scene.layers.indexOf(layer);
      if (index !== -1) {
        this.scene.layers.splice(index, 1);
      }
      if (dispose) {
        layer.dispose();
      }
    });
  }
}

// node_modules/@babylonjs/core/Layers/layer.js
init_drawWrapper();

class Layer {
  set applyPostProcess(value) {
    this._applyPostProcess = value;
  }
  get applyPostProcess() {
    return this.isBackground || this._applyPostProcess;
  }
  set onDispose(callback) {
    if (this._onDisposeObserver) {
      this.onDisposeObservable.remove(this._onDisposeObserver);
    }
    this._onDisposeObserver = this.onDisposeObservable.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 shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(name331, imgUrl, scene, isBackground, color, forceGLSL = false) {
    this.name = name331;
    this._applyPostProcess = true;
    this.scale = new Vector2(1, 1);
    this.offset = new Vector2(0, 0);
    this.alphaBlendingMode = 2;
    this.layerMask = 268435455;
    this.renderTargetTextures = [];
    this.renderOnlyInRenderTargetTextures = false;
    this.convertToLinearSpace = false;
    this.isEnabled = true;
    this._vertexBuffers = {};
    this.onDisposeObservable = new Observable;
    this.onBeforeRenderObservable = new Observable;
    this.onAfterRenderObservable = new Observable;
    this._shaderLanguage = 0;
    this._shadersLoaded = false;
    this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null;
    this.isBackground = isBackground === undefined ? true : isBackground;
    this.color = color === undefined ? new Color4(1, 1, 1, 1) : color;
    this._scene = scene || EngineStore.LastCreatedScene;
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !forceGLSL && !Layer.ForceGLSL) {
      this._shaderLanguage = 1;
    }
    let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER);
    if (!layerComponent) {
      layerComponent = new LayerSceneComponent(this._scene);
      this._scene._addComponent(layerComponent);
    }
    this._scene.layers.push(this);
    this._drawWrapper = new DrawWrapper(engine2);
    const vertices = [];
    vertices.push(1, 1);
    vertices.push(-1, 1);
    vertices.push(-1, -1);
    vertices.push(1, -1);
    const vertexBuffer = new VertexBuffer(engine2, vertices, VertexBuffer.PositionKind, false, false, 2);
    this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
    this._createIndexBuffer();
  }
  _createIndexBuffer() {
    const engine2 = this._scene.getEngine();
    const indices = [];
    indices.push(0);
    indices.push(1);
    indices.push(2);
    indices.push(0);
    indices.push(2);
    indices.push(3);
    this._indexBuffer = engine2.createIndexBuffer(indices);
  }
  _rebuild() {
    const vb = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vb) {
      vb._rebuild();
    }
    this._createIndexBuffer();
  }
  isReady() {
    const engine2 = this._scene.getEngine();
    let defines = "";
    if (this.alphaTest) {
      defines = "#define ALPHATEST";
    }
    if (this.texture) {
      if (this.texture.gammaSpace) {
        if (this.convertToLinearSpace) {
          defines += `
#define CONVERT_TO_LINEAR`;
        }
      } else if (!this.convertToLinearSpace) {
        defines += `
#define CONVERT_TO_GAMMA`;
      }
    }
    if (this._previousDefines !== defines) {
      this._previousDefines = defines;
      this._drawWrapper.effect = engine2.createEffect("layer", [VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], defines, undefined, undefined, undefined, undefined, this._shaderLanguage, this._shadersLoaded ? undefined : async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_layer_vertex(), exports_layer_vertex)), Promise.resolve().then(() => (init_layer_fragment(), exports_layer_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_layer_vertex2(), exports_layer_vertex2)), Promise.resolve().then(() => (init_layer_fragment2(), exports_layer_fragment2))]);
        }
        this._shadersLoaded = true;
      });
    }
    const currentEffect = this._drawWrapper.effect;
    return !!currentEffect?.isReady() && (!this.texture || this.texture.isReady());
  }
  render() {
    if (!this.isEnabled) {
      return;
    }
    const engine2 = this._scene.getEngine();
    if (!this.isReady()) {
      return;
    }
    const currentEffect = this._drawWrapper.effect;
    this.onBeforeRenderObservable.notifyObservers(this);
    engine2.enableEffect(this._drawWrapper);
    engine2.setState(false);
    if (this.texture) {
      currentEffect.setTexture("textureSampler", this.texture);
      currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
    }
    currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
    currentEffect.setVector2("offset", this.offset);
    currentEffect.setVector2("scale", this.scale);
    engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
    if (!this.alphaTest) {
      engine2.setAlphaMode(this.alphaBlendingMode);
      engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
      engine2.setAlphaMode(0);
    } else {
      engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
    }
    this.onAfterRenderObservable.notifyObservers(this);
  }
  dispose() {
    const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vertexBuffer) {
      vertexBuffer.dispose();
      this._vertexBuffers[VertexBuffer.PositionKind] = null;
    }
    if (this._indexBuffer) {
      this._scene.getEngine()._releaseBuffer(this._indexBuffer);
      this._indexBuffer = null;
    }
    if (this.texture) {
      this.texture.dispose();
      this.texture = null;
    }
    this.renderTargetTextures = [];
    const index = this._scene.layers.indexOf(this);
    this._scene.layers.splice(index, 1);
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    this.onAfterRenderObservable.clear();
    this.onBeforeRenderObservable.clear();
  }
}
Layer.ForceGLSL = false;

// node_modules/@babylonjs/core/Layers/index.js
init_glowMapGeneration_fragment2();
init_glowMapGeneration_vertex2();
init_glowMapGeneration_fragment();
init_glowMapGeneration_vertex();
init_glowMapMerge_fragment2();
init_glowMapMerge_vertex2();
init_glowBlurPostProcess_fragment2();
init_glowMapMerge_fragment();
init_glowMapMerge_vertex();
init_glowBlurPostProcess_fragment();
init_layer_fragment2();
init_layer_vertex2();
init_layer_fragment();
init_layer_vertex();
// node_modules/@babylonjs/core/LensFlares/lensFlare.js
init_math_color();
init_texture();
init_drawWrapper();
init_buffer();

class LensFlare {
  static AddFlare(size, position, color, imgUrl, system) {
    return new LensFlare(size, position, color, imgUrl, system);
  }
  constructor(size, position, color, imgUrl, system) {
    this.size = size;
    this.position = position;
    this.alphaMode = 6;
    this.color = color || new Color3(1, 1, 1);
    this.texture = imgUrl ? new Texture(imgUrl, system.getScene(), true) : null;
    this._system = system;
    const engine2 = system.scene.getEngine();
    system._onShadersLoaded.addOnce(() => {
      this._drawWrapper = new DrawWrapper(engine2);
      this._drawWrapper.effect = engine2.createEffect("lensFlare", [VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "", undefined, undefined, undefined, undefined, system.shaderLanguage);
    });
    system.lensFlares.push(this);
  }
  dispose() {
    if (this.texture) {
      this.texture.dispose();
    }
    const index = this._system.lensFlares.indexOf(this);
    this._system.lensFlares.splice(index, 1);
  }
}
// node_modules/@babylonjs/core/LensFlares/lensFlareSystem.js
init_tools();
init_math_vector();
init_engineStore();
init_buffer();
init_devTools();
init_math_color();
init_observable();

class LensFlareSystem {
  get scene() {
    return this._scene;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(name335, emitter, scene) {
    this.name = name335;
    this.lensFlares = [];
    this.borderLimit = 300;
    this.viewportBorder = 0;
    this.layerMask = 268435455;
    this._shaderLanguage = 0;
    this._vertexBuffers = {};
    this._isEnabled = true;
    this._onShadersLoaded = new Observable(undefined, true);
    this._shadersLoaded = false;
    this._scene = scene || EngineStore.LastCreatedScene;
    LensFlareSystem._SceneComponentInitialization(this._scene);
    this._emitter = emitter;
    this.id = name335;
    scene.lensFlareSystems.push(this);
    this.meshesSelectionPredicate = (m) => scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0;
    const engine2 = scene.getEngine();
    const vertices = [];
    vertices.push(1, 1);
    vertices.push(-1, 1);
    vertices.push(-1, -1);
    vertices.push(1, -1);
    this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine2, vertices, VertexBuffer.PositionKind, false, false, 2);
    this._createIndexBuffer();
    this._initShaderSourceAsync();
  }
  async _initShaderSourceAsync() {
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !LensFlareSystem.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([Promise.resolve().then(() => (init_lensFlare_fragment(), exports_lensFlare_fragment)), Promise.resolve().then(() => (init_lensFlare_vertex(), exports_lensFlare_vertex))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_lensFlare_fragment2(), exports_lensFlare_fragment2)), Promise.resolve().then(() => (init_lensFlare_vertex2(), exports_lensFlare_vertex2))]);
    }
    this._shadersLoaded = true;
    this._onShadersLoaded.notifyObservers();
  }
  _createIndexBuffer() {
    const indices = [];
    indices.push(0);
    indices.push(1);
    indices.push(2);
    indices.push(0);
    indices.push(2);
    indices.push(3);
    this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  }
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    this._isEnabled = value;
  }
  getScene() {
    return this._scene;
  }
  getEmitter() {
    return this._emitter;
  }
  setEmitter(newEmitter) {
    this._emitter = newEmitter;
  }
  getEmitterPosition() {
    return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  }
  computeEffectivePosition(globalViewport) {
    let position = this.getEmitterPosition();
    position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
    this._positionX = position.x;
    this._positionY = position.y;
    position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
    if (this.viewportBorder > 0) {
      globalViewport.x -= this.viewportBorder;
      globalViewport.y -= this.viewportBorder;
      globalViewport.width += this.viewportBorder * 2;
      globalViewport.height += this.viewportBorder * 2;
      position.x += this.viewportBorder;
      position.y += this.viewportBorder;
      this._positionX += this.viewportBorder;
      this._positionY += this.viewportBorder;
    }
    const rhs = this._scene.useRightHandedSystem;
    const okZ = position.z > 0 && !rhs || position.z < 0 && rhs;
    if (okZ) {
      if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) {
        if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) {
          return true;
        }
      }
      return true;
    }
    return false;
  }
  _isVisible() {
    if (!this._isEnabled || !this._scene.activeCamera) {
      return false;
    }
    const emitterPosition = this.getEmitterPosition();
    const direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
    const distance = direction.length();
    direction.normalize();
    const ray2 = new Ray(this._scene.activeCamera.globalPosition, direction);
    const pickInfo = this._scene.pickWithRay(ray2, this.meshesSelectionPredicate, true);
    return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  }
  render() {
    if (!this._scene.activeCamera || !this._shadersLoaded) {
      return false;
    }
    const engine2 = this._scene.getEngine();
    const viewport = this._scene.activeCamera.viewport;
    const globalViewport = viewport.toGlobal(engine2.getRenderWidth(true), engine2.getRenderHeight(true));
    if (!this.computeEffectivePosition(globalViewport)) {
      return false;
    }
    if (!this._isVisible()) {
      return false;
    }
    let awayX;
    let awayY;
    if (this._positionX < this.borderLimit + globalViewport.x) {
      awayX = this.borderLimit + globalViewport.x - this._positionX;
    } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
      awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
    } else {
      awayX = 0;
    }
    if (this._positionY < this.borderLimit + globalViewport.y) {
      awayY = this.borderLimit + globalViewport.y - this._positionY;
    } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
      awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
    } else {
      awayY = 0;
    }
    let away = awayX > awayY ? awayX : awayY;
    away -= this.viewportBorder;
    if (away > this.borderLimit) {
      away = this.borderLimit;
    }
    let intensity = 1 - Clamp(away / this.borderLimit, 0, 1);
    if (intensity < 0) {
      return false;
    }
    if (intensity > 1) {
      intensity = 1;
    }
    if (this.viewportBorder > 0) {
      globalViewport.x += this.viewportBorder;
      globalViewport.y += this.viewportBorder;
      globalViewport.width -= this.viewportBorder * 2;
      globalViewport.height -= this.viewportBorder * 2;
      this._positionX -= this.viewportBorder;
      this._positionY -= this.viewportBorder;
    }
    const centerX = globalViewport.x + globalViewport.width / 2;
    const centerY = globalViewport.y + globalViewport.height / 2;
    const distX = centerX - this._positionX;
    const distY = centerY - this._positionY;
    engine2.setState(false);
    engine2.setDepthBuffer(false);
    for (let index = 0;index < this.lensFlares.length; index++) {
      const flare = this.lensFlares[index];
      if (!flare._drawWrapper.effect.isReady() || flare.texture && !flare.texture.isReady()) {
        continue;
      }
      engine2.enableEffect(flare._drawWrapper);
      engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, flare._drawWrapper.effect);
      engine2.setAlphaMode(flare.alphaMode);
      const x = centerX - distX * flare.position;
      const y = centerY - distY * flare.position;
      const cw = flare.size;
      const ch = flare.size * engine2.getAspectRatio(this._scene.activeCamera, true);
      const cx = 2 * ((x - globalViewport.x) / globalViewport.width) - 1;
      const cy = 1 - 2 * ((y - globalViewport.y) / globalViewport.height);
      const viewportMatrix = Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
      flare._drawWrapper.effect.setMatrix("viewportMatrix", viewportMatrix);
      flare._drawWrapper.effect.setTexture("textureSampler", flare.texture);
      flare._drawWrapper.effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1);
      engine2.drawElementsType(Material.TriangleFillMode, 0, 6);
    }
    engine2.setDepthBuffer(true);
    engine2.setAlphaMode(0);
    return true;
  }
  rebuild() {
    this._createIndexBuffer();
    for (const key in this._vertexBuffers) {
      this._vertexBuffers[key]?._rebuild();
    }
  }
  dispose() {
    this._onShadersLoaded.clear();
    const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vertexBuffer) {
      vertexBuffer.dispose();
      this._vertexBuffers[VertexBuffer.PositionKind] = null;
    }
    if (this._indexBuffer) {
      this._scene.getEngine()._releaseBuffer(this._indexBuffer);
      this._indexBuffer = null;
    }
    while (this.lensFlares.length) {
      this.lensFlares[0].dispose();
    }
    const index = this._scene.lensFlareSystems.indexOf(this);
    this._scene.lensFlareSystems.splice(index, 1);
  }
  static Parse(parsedLensFlareSystem, scene, rootUrl) {
    const emitter = scene.getLastEntryById(parsedLensFlareSystem.emitterId);
    const name335 = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
    const lensFlareSystem = new LensFlareSystem(name335, emitter, scene);
    lensFlareSystem.id = parsedLensFlareSystem.id || name335;
    lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
    for (let index = 0;index < parsedLensFlareSystem.flares.length; index++) {
      const parsedFlare = parsedLensFlareSystem.flares[index];
      LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
    }
    return lensFlareSystem;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.id = this.id;
    serializationObject.name = this.name;
    serializationObject.emitterId = this.getEmitter().id;
    serializationObject.borderLimit = this.borderLimit;
    serializationObject.flares = [];
    for (let index = 0;index < this.lensFlares.length; index++) {
      const flare = this.lensFlares[index];
      serializationObject.flares.push({
        size: flare.size,
        position: flare.position,
        color: flare.color.asArray(),
        textureName: Tools.GetFilename(flare.texture ? flare.texture.name : "")
      });
    }
    return serializationObject;
  }
}
LensFlareSystem.ForceGLSL = false;
LensFlareSystem._SceneComponentInitialization = (_) => {
  throw _WarnImport("LensFlareSystemSceneComponent");
};
// node_modules/@babylonjs/core/LensFlares/lensFlareSystemSceneComponent.js
init_tools();
init_scene();
init_sceneComponent();
AddParser(SceneComponentConstants.NAME_LENSFLARESYSTEM, (parsedData, scene, container, rootUrl) => {
  if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
    if (!container.lensFlareSystems) {
      container.lensFlareSystems = [];
    }
    for (let index = 0, cache = parsedData.lensFlareSystems.length;index < cache; index++) {
      const parsedLensFlareSystem = parsedData.lensFlareSystems[index];
      const lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
      container.lensFlareSystems.push(lf);
    }
  }
});
Scene.prototype.getLensFlareSystemByName = function(name335) {
  for (let index = 0;index < this.lensFlareSystems.length; index++) {
    if (this.lensFlareSystems[index].name === name335) {
      return this.lensFlareSystems[index];
    }
  }
  return null;
};
Scene.prototype.getLensFlareSystemById = function(id) {
  for (let index = 0;index < this.lensFlareSystems.length; index++) {
    if (this.lensFlareSystems[index].id === id) {
      return this.lensFlareSystems[index];
    }
  }
  return null;
};
Scene.prototype.getLensFlareSystemByID = function(id) {
  return this.getLensFlareSystemById(id);
};
Scene.prototype.removeLensFlareSystem = function(toRemove) {
  const index = this.lensFlareSystems.indexOf(toRemove);
  if (index !== -1) {
    this.lensFlareSystems.splice(index, 1);
  }
  return index;
};
Scene.prototype.addLensFlareSystem = function(newLensFlareSystem) {
  this.lensFlareSystems.push(newLensFlareSystem);
};

class LensFlareSystemSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_LENSFLARESYSTEM;
    this.scene = scene;
  }
  register() {
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  }
  rebuild() {
    for (let index = 0;index < this.scene.lensFlareSystems.length; index++) {
      this.scene.lensFlareSystems[index].rebuild();
    }
  }
  addFromContainer(container) {
    if (!container.lensFlareSystems) {
      return;
    }
    container.lensFlareSystems.forEach((o) => {
      this.scene.addLensFlareSystem(o);
    });
  }
  removeFromContainer(container, dispose) {
    if (!container.lensFlareSystems) {
      return;
    }
    container.lensFlareSystems.forEach((o) => {
      this.scene.removeLensFlareSystem(o);
      if (dispose) {
        o.dispose();
      }
    });
  }
  serialize(serializationObject) {
    serializationObject.lensFlareSystems = [];
    const lensFlareSystems = this.scene.lensFlareSystems;
    for (const lensFlareSystem of lensFlareSystems) {
      serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
    }
  }
  dispose() {
    const lensFlareSystems = this.scene.lensFlareSystems;
    while (lensFlareSystems.length) {
      lensFlareSystems[0].dispose();
    }
  }
  _draw(camera2) {
    if (this.scene.lensFlaresEnabled) {
      const lensFlareSystems = this.scene.lensFlareSystems;
      Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
      for (const lensFlareSystem of lensFlareSystems) {
        if ((camera2.layerMask & lensFlareSystem.layerMask) !== 0) {
          lensFlareSystem.render();
        }
      }
      Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
    }
  }
}
LensFlareSystem._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_LENSFLARESYSTEM);
  if (!component) {
    component = new LensFlareSystemSceneComponent(scene);
    scene._addComponent(component);
  }
};

// node_modules/@babylonjs/core/LensFlares/index.js
init_lensFlare_fragment2();
init_lensFlare_vertex2();
init_lensFlare_fragment();
init_lensFlare_vertex();
// node_modules/@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js
init_sceneComponent();
AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => {
  if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
    for (let index = 0, cache = parsedData.shadowGenerators.length;index < cache; index++) {
      const parsedShadowGenerator = parsedData.shadowGenerators[index];
      if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) {
        CascadedShadowGenerator.Parse(parsedShadowGenerator, scene);
      } else {
        ShadowGenerator.Parse(parsedShadowGenerator, scene);
      }
    }
  }
});

class ShadowGeneratorSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_SHADOWGENERATOR;
    this.scene = scene;
  }
  register() {
    this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  }
  rebuild() {}
  serialize(serializationObject) {
    serializationObject.shadowGenerators = [];
    const lights = this.scene.lights;
    for (const light of lights) {
      if (light.doNotSerialize) {
        continue;
      }
      const shadowGenerators = light.getShadowGenerators();
      if (shadowGenerators) {
        const iterator = shadowGenerators.values();
        for (let key = iterator.next();key.done !== true; key = iterator.next()) {
          const shadowGenerator = key.value;
          if (shadowGenerator.doNotSerialize) {
            continue;
          }
          serializationObject.shadowGenerators.push(shadowGenerator.serialize());
        }
      }
    }
  }
  addFromContainer(container) {}
  removeFromContainer(container, dispose) {}
  dispose() {}
  _gatherRenderTargets(renderTargets) {
    const scene = this.scene;
    if (this.scene.shadowsEnabled) {
      for (let lightIndex = 0;lightIndex < scene.lights.length; lightIndex++) {
        const light = scene.lights[lightIndex];
        const shadowGenerators = light.getShadowGenerators();
        if (light.isEnabled() && light.shadowEnabled && shadowGenerators) {
          const iterator = shadowGenerators.values();
          for (let key = iterator.next();key.done !== true; key = iterator.next()) {
            const shadowGenerator = key.value;
            const shadowMap = shadowGenerator.getShadowMap();
            if (scene.textures.indexOf(shadowMap) !== -1) {
              renderTargets.push(shadowMap);
            }
          }
        }
      }
    }
  }
}
ShadowGenerator._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);
  if (!component) {
    component = new ShadowGeneratorSceneComponent(scene);
    scene._addComponent(component);
  }
};

// node_modules/@babylonjs/core/Lights/Shadows/index.js
init_shadowMap_fragment();
init_shadowMap_vertex();
init_depthBoxBlur_fragment();
init_shadowMapFragmentSoftTransparentShadow();
init_shadowMap_fragment2();
init_shadowMap_vertex2();
init_depthBoxBlur_fragment2();
init_shadowMapFragmentSoftTransparentShadow2();
// node_modules/@babylonjs/core/Lights/pointLight.js
init_tslib_es6();
init_decorators();
init_math_vector();
init_node();
init_typeStore();
Node2.AddNodeConstructor("Light_Type_0", (name335, scene) => {
  return () => new PointLight(name335, Vector3.Zero(), scene);
});

class PointLight extends ShadowLight {
  get shadowAngle() {
    return this._shadowAngle;
  }
  set shadowAngle(value) {
    this._shadowAngle = value;
    this.forceProjectionMatrixCompute();
  }
  get direction() {
    return this._direction;
  }
  set direction(value) {
    const previousNeedCube = this.needCube();
    this._direction = value;
    if (this.needCube() !== previousNeedCube && this._shadowGenerators) {
      const iterator = this._shadowGenerators.values();
      for (let key = iterator.next();key.done !== true; key = iterator.next()) {
        const shadowGenerator2 = key.value;
        shadowGenerator2.recreateShadowMap();
      }
    }
  }
  constructor(name335, position, scene) {
    super(name335, scene);
    this._shadowAngle = Math.PI / 2;
    this.position = position;
  }
  getClassName() {
    return "PointLight";
  }
  getTypeID() {
    return Light.LIGHTTYPEID_POINTLIGHT;
  }
  needCube() {
    return !this.direction;
  }
  getShadowDirection(faceIndex) {
    if (this.direction) {
      return super.getShadowDirection(faceIndex);
    } else {
      switch (faceIndex) {
        case 0:
          return new Vector3(1, 0, 0);
        case 1:
          return new Vector3(-1, 0, 0);
        case 2:
          return new Vector3(0, -1, 0);
        case 3:
          return new Vector3(0, 1, 0);
        case 4:
          return new Vector3(0, 0, 1);
        case 5:
          return new Vector3(0, 0, -1);
      }
    }
    return Vector3.Zero();
  }
  _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {
    const activeCamera = this.getScene().activeCamera;
    if (!activeCamera) {
      return;
    }
    const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
    const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
    const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;
    Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("vLightData", 4);
    this._uniformBuffer.addUniform("vLightDiffuse", 4);
    this._uniformBuffer.addUniform("vLightSpecular", 4);
    this._uniformBuffer.addUniform("vLightFalloff", 4);
    this._uniformBuffer.addUniform("shadowsInfo", 3);
    this._uniformBuffer.addUniform("depthValues", 2);
    this._uniformBuffer.create();
  }
  transferToEffect(effect, lightIndex) {
    if (this.computeTransformedInformation()) {
      this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0, lightIndex);
    } else {
      this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
    }
    this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
    return this;
  }
  transferToNodeMaterialEffect(effect, lightDataUniformName) {
    if (this.computeTransformedInformation()) {
      effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z);
    } else {
      effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);
    }
    return this;
  }
  prepareLightSpecificDefines(defines, lightIndex) {
    defines["POINTLIGHT" + lightIndex] = true;
  }
}
__decorate([
  serialize()
], PointLight.prototype, "shadowAngle", null);
RegisterClass("BABYLON.PointLight", PointLight);
// node_modules/@babylonjs/core/Lights/areaLight.js
init_texture();

// node_modules/@babylonjs/core/Lights/LTC/ltcTextureTool.js
init_tools();
async function DecodeLTCTextureDataAsync() {
  const ltc1 = new Uint16Array(64 * 64 * 4);
  const ltc2 = new Uint16Array(64 * 64 * 4);
  const file = await Tools.LoadFileAsync(Tools.GetAssetUrl("https://assets.babylonjs.com/core/areaLights/areaLightsLTC.bin"));
  const ltcEncoded = new Uint16Array(file);
  const pixelCount = ltcEncoded.length / 8;
  for (let pixelIndex = 0;pixelIndex < pixelCount; pixelIndex++) {
    ltc1[pixelIndex * 4] = ltcEncoded[pixelIndex * 8];
    ltc1[pixelIndex * 4 + 1] = ltcEncoded[pixelIndex * 8 + 1];
    ltc1[pixelIndex * 4 + 2] = ltcEncoded[pixelIndex * 8 + 2];
    ltc1[pixelIndex * 4 + 3] = ltcEncoded[pixelIndex * 8 + 3];
    ltc2[pixelIndex * 4] = ltcEncoded[pixelIndex * 8 + 4];
    ltc2[pixelIndex * 4 + 1] = ltcEncoded[pixelIndex * 8 + 5];
    ltc2[pixelIndex * 4 + 2] = ltcEncoded[pixelIndex * 8 + 6];
    ltc2[pixelIndex * 4 + 3] = ltcEncoded[pixelIndex * 8 + 7];
  }
  return [ltc1, ltc2];
}

// node_modules/@babylonjs/core/Lights/areaLight.js
init_logger();
function CreateSceneLTCTextures(scene) {
  const useDelayedTextureLoading = scene.useDelayedTextureLoading;
  scene.useDelayedTextureLoading = false;
  const previousState = scene._blockEntityCollection;
  scene._blockEntityCollection = false;
  scene._ltcTextures = {
    LTC1: RawTexture.CreateRGBATexture(null, 64, 64, scene.getEngine(), false, false, 2, 2, 0, false, true),
    LTC2: RawTexture.CreateRGBATexture(null, 64, 64, scene.getEngine(), false, false, 2, 2, 0, false, true)
  };
  scene._blockEntityCollection = previousState;
  scene._ltcTextures.LTC1.wrapU = Texture.CLAMP_ADDRESSMODE;
  scene._ltcTextures.LTC1.wrapV = Texture.CLAMP_ADDRESSMODE;
  scene._ltcTextures.LTC2.wrapU = Texture.CLAMP_ADDRESSMODE;
  scene._ltcTextures.LTC2.wrapV = Texture.CLAMP_ADDRESSMODE;
  scene.useDelayedTextureLoading = useDelayedTextureLoading;
  DecodeLTCTextureDataAsync().then((textureData) => {
    if (scene._ltcTextures) {
      const ltc1 = scene._ltcTextures?.LTC1;
      ltc1.update(textureData[0]);
      const ltc2 = scene._ltcTextures?.LTC2;
      ltc2.update(textureData[1]);
      scene.onDisposeObservable.addOnce(() => {
        scene._ltcTextures?.LTC1.dispose();
        scene._ltcTextures?.LTC2.dispose();
      });
    }
  }).catch((error) => {
    Logger.Error(`Area Light fail to get LTC textures data. Error: ${error}`);
  });
}

class AreaLight extends Light {
  constructor(name335, position, scene) {
    super(name335, scene);
    this.position = position;
    if (!this._scene._ltcTextures) {
      CreateSceneLTCTextures(this._scene);
    }
  }
  transferTexturesToEffect(effect) {
    if (this._scene._ltcTextures) {
      effect.setTexture("areaLightsLTC1Sampler", this._scene._ltcTextures.LTC1);
      effect.setTexture("areaLightsLTC2Sampler", this._scene._ltcTextures.LTC2);
    }
    return this;
  }
  prepareLightSpecificDefines(defines, lightIndex) {
    defines["AREALIGHT" + lightIndex] = true;
    defines["AREALIGHTUSED"] = true;
  }
  _isReady() {
    if (this._scene._ltcTextures) {
      return this._scene._ltcTextures.LTC1.isReady() && this._scene._ltcTextures.LTC2.isReady();
    }
    return false;
  }
}
// node_modules/@babylonjs/core/Lights/rectAreaLight.js
init_tslib_es6();
init_math_vector();
init_node();
init_typeStore();
init_decorators();
Node2.AddNodeConstructor("Light_Type_4", (name335, scene) => {
  return () => new RectAreaLight(name335, Vector3.Zero(), 1, 1, scene);
});

class RectAreaLight extends AreaLight {
  get width() {
    return this._width.x;
  }
  set width(value) {
    this._width.x = value;
  }
  get height() {
    return this._height.y;
  }
  set height(value) {
    this._height.y = value;
  }
  constructor(name335, position, width, height, scene) {
    super(name335, position, scene);
    this._width = new Vector3(width, 0, 0);
    this._height = new Vector3(0, height, 0);
    this._pointTransformedPosition = Vector3.Zero();
    this._pointTransformedWidth = Vector3.Zero();
    this._pointTransformedHeight = Vector3.Zero();
  }
  getClassName() {
    return "RectAreaLight";
  }
  getTypeID() {
    return Light.LIGHTTYPEID_RECT_AREALIGHT;
  }
  _buildUniformLayout() {
    this._uniformBuffer.addUniform("vLightData", 4);
    this._uniformBuffer.addUniform("vLightDiffuse", 4);
    this._uniformBuffer.addUniform("vLightSpecular", 4);
    this._uniformBuffer.addUniform("vLightWidth", 4);
    this._uniformBuffer.addUniform("vLightHeight", 4);
    this._uniformBuffer.addUniform("shadowsInfo", 3);
    this._uniformBuffer.addUniform("depthValues", 2);
    this._uniformBuffer.create();
  }
  _computeTransformedInformation() {
    if (this.parent && this.parent.getWorldMatrix) {
      Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._pointTransformedPosition);
      Vector3.TransformNormalToRef(this._width, this.parent.getWorldMatrix(), this._pointTransformedWidth);
      Vector3.TransformNormalToRef(this._height, this.parent.getWorldMatrix(), this._pointTransformedHeight);
      return true;
    }
    return false;
  }
  transferToEffect(effect, lightIndex) {
    if (this._computeTransformedInformation()) {
      this._uniformBuffer.updateFloat4("vLightData", this._pointTransformedPosition.x, this._pointTransformedPosition.y, this._pointTransformedPosition.z, 0, lightIndex);
      this._uniformBuffer.updateFloat4("vLightWidth", this._pointTransformedWidth.x / 2, this._pointTransformedWidth.y / 2, this._pointTransformedWidth.z / 2, 0, lightIndex);
      this._uniformBuffer.updateFloat4("vLightHeight", this._pointTransformedHeight.x / 2, this._pointTransformedHeight.y / 2, this._pointTransformedHeight.z / 2, 0, lightIndex);
    } else {
      this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
      this._uniformBuffer.updateFloat4("vLightWidth", this._width.x / 2, this._width.y / 2, this._width.z / 2, 0, lightIndex);
      this._uniformBuffer.updateFloat4("vLightHeight", this._height.x / 2, this._height.y / 2, this._height.z / 2, 0, lightIndex);
    }
    return this;
  }
  transferToNodeMaterialEffect(effect, lightDataUniformName) {
    if (this._computeTransformedInformation()) {
      effect.setFloat3(lightDataUniformName, this._pointTransformedPosition.x, this._pointTransformedPosition.y, this._pointTransformedPosition.z);
    } else {
      effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);
    }
    return this;
  }
}
__decorate([
  serialize()
], RectAreaLight.prototype, "width", null);
__decorate([
  serialize()
], RectAreaLight.prototype, "height", null);
RegisterClass("BABYLON.RectAreaLight", RectAreaLight);

// node_modules/@babylonjs/core/Lights/index.js
init_iesLoader();
// node_modules/@babylonjs/core/Loading/loadingScreen.js
init_abstractEngine();
init_engineStore();

class DefaultLoadingScreen {
  constructor(_renderingCanvas, _loadingText = "", _loadingDivBackgroundColor = "black") {
    this._renderingCanvas = _renderingCanvas;
    this._loadingText = _loadingText;
    this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
    this._loadingDivToRenderingCanvasMap = new Map;
    this._resizeLoadingUI = () => {
      if (!this._isLoading) {
        return;
      }
      this._loadingDivToRenderingCanvasMap.forEach(([canvas, previousCanvasRect], loadingDiv) => {
        const currentCanvasRect = canvas.getBoundingClientRect();
        if (this._isCanvasLayoutChanged(previousCanvasRect, currentCanvasRect)) {
          const canvasPositioning = window.getComputedStyle(canvas).position;
          loadingDiv.style.position = canvasPositioning === "fixed" ? "fixed" : "absolute";
          loadingDiv.style.left = currentCanvasRect.left + window.scrollX + "px";
          loadingDiv.style.top = currentCanvasRect.top + window.scrollY + "px";
          loadingDiv.style.width = currentCanvasRect.width + "px";
          loadingDiv.style.height = currentCanvasRect.height + "px";
          this._loadingDivToRenderingCanvasMap.set(loadingDiv, [canvas, currentCanvasRect]);
        }
      });
    };
  }
  displayLoadingUI() {
    if (this._isLoading) {
      return;
    }
    this._isLoading = true;
    this._engine = EngineStore.Instances.find((engine2) => engine2.getRenderingCanvas() === this._renderingCanvas);
    const loadingDiv = document.createElement("div");
    loadingDiv.id = "babylonjsLoadingDiv";
    loadingDiv.style.opacity = "0";
    loadingDiv.style.transition = "opacity 1.5s ease";
    loadingDiv.style.pointerEvents = "none";
    loadingDiv.style.display = "grid";
    loadingDiv.style.gridTemplateRows = "100%";
    loadingDiv.style.gridTemplateColumns = "100%";
    loadingDiv.style.justifyItems = "center";
    loadingDiv.style.alignItems = "center";
    this._loadingTextDiv = document.createElement("div");
    this._loadingTextDiv.style.position = "absolute";
    this._loadingTextDiv.style.left = "0";
    this._loadingTextDiv.style.top = "50%";
    this._loadingTextDiv.style.marginTop = "80px";
    this._loadingTextDiv.style.width = "100%";
    this._loadingTextDiv.style.height = "20px";
    this._loadingTextDiv.style.fontFamily = "Arial";
    this._loadingTextDiv.style.fontSize = "14px";
    this._loadingTextDiv.style.color = "white";
    this._loadingTextDiv.style.textAlign = "center";
    this._loadingTextDiv.style.zIndex = "1";
    this._loadingTextDiv.innerHTML = "Loading";
    loadingDiv.appendChild(this._loadingTextDiv);
    this._loadingTextDiv.innerHTML = this._loadingText;
    this._style = document.createElement("style");
    this._style.type = "text/css";
    const keyFrames = `@-webkit-keyframes spin1 {                            0% { -webkit-transform: rotate(0deg);}
                            100% { -webkit-transform: rotate(360deg);}
                        }                        @keyframes spin1 {                            0% { transform: rotate(0deg);}
                            100% { transform: rotate(360deg);}
                        }`;
    this._style.innerHTML = keyFrames;
    document.getElementsByTagName("head")[0].appendChild(this._style);
    const svgSupport = !!window.SVGSVGElement;
    const imgBack = new Image;
    if (!DefaultLoadingScreen.DefaultLogoUrl) {
      imgBack.src = !svgSupport ? "https://cdn.babylonjs.com/Assets/babylonLogo.png" : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+`;
    } else {
      imgBack.src = DefaultLoadingScreen.DefaultLogoUrl;
    }
    imgBack.style.width = "150px";
    imgBack.style.gridColumn = "1";
    imgBack.style.gridRow = "1";
    imgBack.style.top = "50%";
    imgBack.style.left = "50%";
    imgBack.style.transform = "translate(-50%, -50%)";
    imgBack.style.position = "absolute";
    const imageSpinnerContainer = document.createElement("div");
    imageSpinnerContainer.style.width = "300px";
    imageSpinnerContainer.style.gridColumn = "1";
    imageSpinnerContainer.style.gridRow = "1";
    imageSpinnerContainer.style.top = "50%";
    imageSpinnerContainer.style.left = "50%";
    imageSpinnerContainer.style.transform = "translate(-50%, -50%)";
    imageSpinnerContainer.style.position = "absolute";
    const imgSpinner = new Image;
    if (!DefaultLoadingScreen.DefaultSpinnerUrl) {
      imgSpinner.src = !svgSupport ? "https://cdn.babylonjs.com/Assets/loadingIcon.png" : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==`;
    } else {
      imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl;
    }
    imgSpinner.style.animation = "spin1 0.75s infinite linear";
    imgSpinner.style.transformOrigin = "50% 50%";
    if (!svgSupport) {
      const logoSize = { w: 16, h: 18.5 };
      const loadingSize = { w: 30, h: 30 };
      imgBack.style.width = `${logoSize.w}vh`;
      imgBack.style.height = `${logoSize.h}vh`;
      imgBack.style.left = `calc(50% - ${logoSize.w / 2}vh)`;
      imgBack.style.top = `calc(50% - ${logoSize.h / 2}vh)`;
      imgSpinner.style.width = `${loadingSize.w}vh`;
      imgSpinner.style.height = `${loadingSize.h}vh`;
      imgSpinner.style.left = `calc(50% - ${loadingSize.w / 2}vh)`;
      imgSpinner.style.top = `calc(50% - ${loadingSize.h / 2}vh)`;
    }
    imageSpinnerContainer.appendChild(imgSpinner);
    loadingDiv.appendChild(imgBack);
    loadingDiv.appendChild(imageSpinnerContainer);
    loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
    loadingDiv.style.opacity = "1";
    const canvases = [];
    const views = this._engine.views;
    if (views?.length) {
      for (const view of views) {
        if (view.enabled) {
          canvases.push(view.target);
        }
      }
    } else {
      canvases.push(this._renderingCanvas);
    }
    canvases.forEach((canvas, index) => {
      const clonedLoadingDiv = loadingDiv.cloneNode(true);
      clonedLoadingDiv.id += `-${index}`;
      this._loadingDivToRenderingCanvasMap.set(clonedLoadingDiv, [canvas, null]);
    });
    this._resizeLoadingUI();
    this._resizeObserver = this._engine.onResizeObservable.add(() => {
      this._resizeLoadingUI();
    });
    this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv2) => {
      document.body.appendChild(loadingDiv2);
    });
  }
  hideLoadingUI() {
    if (!this._isLoading) {
      return;
    }
    let completedTransitions = 0;
    const onTransitionEnd = (event) => {
      const loadingDiv = event.target;
      const isTransitionEndOnLoadingDiv = this._loadingDivToRenderingCanvasMap.has(loadingDiv);
      if (isTransitionEndOnLoadingDiv) {
        completedTransitions++;
        loadingDiv.remove();
        const allTransitionsCompleted = completedTransitions === this._loadingDivToRenderingCanvasMap.size;
        if (allTransitionsCompleted) {
          if (this._loadingTextDiv) {
            this._loadingTextDiv.remove();
            this._loadingTextDiv = null;
          }
          if (this._style) {
            this._style.remove();
            this._style = null;
          }
          window.removeEventListener("transitionend", onTransitionEnd);
          this._engine.onResizeObservable.remove(this._resizeObserver);
          this._loadingDivToRenderingCanvasMap.clear();
          this._engine = null;
          this._isLoading = false;
        }
      }
    };
    this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => {
      loadingDiv.style.opacity = "0";
    });
    window.addEventListener("transitionend", onTransitionEnd);
  }
  set loadingUIText(text) {
    this._loadingText = text;
    if (this._loadingTextDiv) {
      this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => {
        loadingDiv.children[0].innerHTML = this._loadingText;
      });
    }
  }
  get loadingUIText() {
    return this._loadingText;
  }
  get loadingUIBackgroundColor() {
    return this._loadingDivBackgroundColor;
  }
  set loadingUIBackgroundColor(color) {
    this._loadingDivBackgroundColor = color;
    if (!this._isLoading) {
      return;
    }
    this._loadingDivToRenderingCanvasMap.forEach((_, loadingDiv) => {
      loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
    });
  }
  _isCanvasLayoutChanged(previousCanvasRect, currentCanvasRect) {
    return !previousCanvasRect || previousCanvasRect.left !== currentCanvasRect.left || previousCanvasRect.top !== currentCanvasRect.top || previousCanvasRect.right !== currentCanvasRect.right || previousCanvasRect.bottom !== currentCanvasRect.bottom || previousCanvasRect.width !== currentCanvasRect.width || previousCanvasRect.height !== currentCanvasRect.height || previousCanvasRect.x !== currentCanvasRect.x || previousCanvasRect.y !== currentCanvasRect.y;
  }
}
DefaultLoadingScreen.DefaultLogoUrl = "";
DefaultLoadingScreen.DefaultSpinnerUrl = "";
AbstractEngine.DefaultLoadingScreenFactory = (canvas) => {
  return new DefaultLoadingScreen(canvas);
};
// node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js
init_logger();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Materials/Textures/hdrCubeTexture.js
init_math_vector();
init_baseTexture();
init_texture();
init_hdr();
init_cubemapToSphericalPolynomial();
init_typeStore();
init_observable();
init_tools();
init_math_constants();

// node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrFiltering.js
init_math();
init_effectRenderer();

class HDRFiltering {
  constructor(engine2, options = {}) {
    this._lodGenerationOffset = 0;
    this._lodGenerationScale = 0.8;
    this.quality = 4096;
    this.hdrScale = 1;
    this._engine = engine2;
    this.hdrScale = options.hdrScale || this.hdrScale;
    this.quality = options.quality || this.quality;
  }
  _createRenderTarget(size) {
    let textureType = 0;
    if (this._engine.getCaps().textureHalfFloatRender) {
      textureType = 2;
    } else if (this._engine.getCaps().textureFloatRender) {
      textureType = 1;
    }
    const rtWrapper = this._engine.createRenderTargetCubeTexture(size, {
      format: 5,
      type: textureType,
      createMipMaps: true,
      generateMipMaps: false,
      generateDepthBuffer: false,
      generateStencilBuffer: false,
      samplingMode: 1,
      label: "HDR_Radiance_Filtering_Target"
    });
    this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0);
    this._engine.updateTextureSamplingMode(3, rtWrapper.texture, true);
    return rtWrapper;
  }
  _prefilterInternal(texture) {
    const width = texture.getSize().width;
    const mipmapsCount = ILog2(width) + 1;
    const effect = this._effectWrapper.effect;
    const outputTexture = this._createRenderTarget(width);
    this._effectRenderer.saveStates();
    this._effectRenderer.setViewport();
    const intTexture = texture.getInternalTexture();
    if (intTexture) {
      this._engine.updateTextureSamplingMode(3, intTexture, true);
    }
    this._effectRenderer.applyEffectWrapper(this._effectWrapper);
    const directions = [
      [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)],
      [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)],
      [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)]
    ];
    effect.setFloat("hdrScale", this.hdrScale);
    effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount);
    effect.setTexture("inputTexture", texture);
    for (let face = 0;face < 6; face++) {
      effect.setVector3("up", directions[face][0]);
      effect.setVector3("right", directions[face][1]);
      effect.setVector3("front", directions[face][2]);
      for (let lod = 0;lod < mipmapsCount; lod++) {
        this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod);
        this._effectRenderer.applyEffectWrapper(this._effectWrapper);
        let alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width;
        if (lod === 0) {
          alpha = 0;
        }
        effect.setFloat("alphaG", alpha);
        this._effectRenderer.draw();
      }
    }
    this._effectRenderer.restoreStates();
    this._engine.restoreDefaultFramebuffer();
    this._engine._releaseTexture(texture._texture);
    const type = outputTexture.texture.type;
    const format = outputTexture.texture.format;
    outputTexture._swapAndDie(texture._texture);
    texture._texture.type = type;
    texture._texture.format = format;
    texture.gammaSpace = false;
    texture.lodGenerationOffset = this._lodGenerationOffset;
    texture.lodGenerationScale = this._lodGenerationScale;
    texture._prefiltered = true;
    return texture;
  }
  _createEffect(texture, onCompiled) {
    const defines = [];
    if (texture.gammaSpace) {
      defines.push("#define GAMMA_INPUT");
    }
    defines.push("#define NUM_SAMPLES " + this.quality + "u");
    const isWebGPU = this._engine.isWebGPU;
    const effectWrapper = new EffectWrapper({
      engine: this._engine,
      name: "hdrFiltering",
      vertexShader: "hdrFiltering",
      fragmentShader: "hdrFiltering",
      samplerNames: ["inputTexture"],
      uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale", "alphaG"],
      useShaderStore: true,
      defines,
      onCompiled,
      shaderLanguage: isWebGPU ? 1 : 0,
      extraInitializationsAsync: async () => {
        if (isWebGPU) {
          await Promise.all([Promise.resolve().then(() => (init_hdrFiltering_vertex(), exports_hdrFiltering_vertex)), Promise.resolve().then(() => (init_hdrFiltering_fragment(), exports_hdrFiltering_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_hdrFiltering_vertex2(), exports_hdrFiltering_vertex2)), Promise.resolve().then(() => (init_hdrFiltering_fragment2(), exports_hdrFiltering_fragment2))]);
        }
      }
    });
    return effectWrapper;
  }
  isReady(texture) {
    return texture.isReady() && this._effectWrapper.effect.isReady();
  }
  async prefilter(texture) {
    if (!this._engine._features.allowTexturePrefiltering) {
      throw new Error("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.");
    }
    this._effectRenderer = new EffectRenderer(this._engine);
    this._effectWrapper = this._createEffect(texture);
    await this._effectWrapper.effect.whenCompiledAsync();
    this._prefilterInternal(texture);
    this._effectRenderer.dispose();
    this._effectWrapper.dispose();
  }
}

// node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrIrradianceFiltering.js
init_math();
init_baseTexture();
init_effectRenderer();

// node_modules/@babylonjs/core/Rendering/iblCdfGenerator.js
init_texture();
init_postProcess();
init_math_vector();
init_observable();
init_engine();
init_devTools();
init_engineStore();

class IblCdfGenerator {
  get iblSource() {
    return this._iblSource;
  }
  set iblSource(source) {
    if (this._iblSource === source) {
      return;
    }
    this._disposeTextures();
    this._iblSource = source;
    if (!source) {
      return;
    }
    if (source.isCube) {
      if (source.isReadyOrNotBlocking()) {
        this._recreateAssetsFromNewIbl();
      } else {
        source.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this, source));
      }
    } else {
      if (source.isReadyOrNotBlocking()) {
        this._recreateAssetsFromNewIbl();
      } else {
        source.onLoadObservable.addOnce(this._recreateAssetsFromNewIbl.bind(this, source));
      }
    }
  }
  _recreateAssetsFromNewIbl() {
    if (this._debugPass) {
      this._debugPass.dispose();
    }
    this._createTextures();
    if (this._debugPass) {
      this._createDebugPass();
    }
  }
  getIcdfTexture() {
    return this._icdfPT ? this._icdfPT : this._dummyTexture;
  }
  setDebugDisplayParams(x, y, widthScale, heightScale) {
    this._debugSizeParams.set(x, y, widthScale, heightScale);
  }
  get debugPassName() {
    return this._debugPassName;
  }
  getDebugPassPP() {
    if (!this._debugPass) {
      this._createDebugPass();
    }
    return this._debugPass;
  }
  constructor(sceneOrEngine) {
    this.debugEnabled = false;
    this._debugSizeParams = new Vector4(0, 0, 1, 1);
    this._debugPassName = "CDF Debug";
    this.onGeneratedObservable = new Observable;
    if (sceneOrEngine) {
      if (IblCdfGenerator._IsScene(sceneOrEngine)) {
        this._scene = sceneOrEngine;
      } else {
        this._engine = sceneOrEngine;
      }
    } else {
      this._scene = EngineStore.LastCreatedScene;
    }
    if (this._scene) {
      this._engine = this._scene.getEngine();
    }
    const blackPixels = new Uint16Array([0, 0, 0, 255]);
    this._dummyTexture = new RawTexture(blackPixels, 1, 1, Engine.TEXTUREFORMAT_RGBA, sceneOrEngine, false, false, undefined, 2);
    if (this._scene) {
      IblCdfGenerator._SceneComponentInitialization(this._scene);
    }
  }
  _createTextures() {
    const size = this._iblSource ? { width: this._iblSource.getSize().width, height: this._iblSource.getSize().height } : { width: 1, height: 1 };
    if (!this._iblSource) {
      this._iblSource = RawTexture.CreateRTexture(new Uint8Array([255]), 1, 1, this._engine, false, false, 1, 0);
      this._iblSource.name = "Placeholder IBL Source";
    }
    if (this._iblSource.isCube) {
      size.width *= 4;
      size.height *= 2;
      size.width = 1 << Math.floor(Math.log2(size.width));
      size.height = 1 << Math.floor(Math.log2(size.height));
    }
    const isWebGPU = this._engine.isWebGPU;
    const cdfOptions = {
      generateDepthBuffer: false,
      generateMipMaps: false,
      format: 6,
      type: 1,
      samplingMode: 1,
      shaderLanguage: isWebGPU ? 1 : 0,
      gammaSpace: false,
      extraInitializationsAsync: async () => {
        if (isWebGPU) {
          await Promise.all([Promise.resolve().then(() => (init_iblCdfx_fragment(), exports_iblCdfx_fragment)), Promise.resolve().then(() => (init_iblCdfy_fragment(), exports_iblCdfy_fragment)), Promise.resolve().then(() => (init_iblScaledLuminance_fragment(), exports_iblScaledLuminance_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_iblCdfx_fragment2(), exports_iblCdfx_fragment2)), Promise.resolve().then(() => (init_iblCdfy_fragment2(), exports_iblCdfy_fragment2)), Promise.resolve().then(() => (init_iblScaledLuminance_fragment2(), exports_iblScaledLuminance_fragment2))]);
        }
      }
    };
    const icdfOptions = {
      generateDepthBuffer: false,
      generateMipMaps: false,
      format: 5,
      type: 2,
      samplingMode: 1,
      shaderLanguage: isWebGPU ? 1 : 0,
      gammaSpace: false,
      extraInitializationsAsync: async () => {
        if (isWebGPU) {
          await Promise.all([Promise.resolve().then(() => (init_iblIcdf_fragment(), exports_iblIcdf_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_iblIcdf_fragment2(), exports_iblIcdf_fragment2))]);
        }
      }
    };
    this._cdfyPT = new ProceduralTexture("cdfyTexture", { width: size.width, height: size.height + 1 }, "iblCdfy", this._scene, cdfOptions, false, false);
    this._cdfyPT.autoClear = false;
    this._cdfyPT.setTexture("iblSource", this._iblSource);
    this._cdfyPT.setInt("iblHeight", size.height);
    this._cdfyPT.wrapV = 0;
    this._cdfyPT.refreshRate = 0;
    if (this._iblSource.isCube) {
      this._cdfyPT.defines = `#define IBL_USE_CUBE_MAP
`;
    }
    this._cdfxPT = new ProceduralTexture("cdfxTexture", { width: size.width + 1, height: 1 }, "iblCdfx", this._scene, cdfOptions, false, false);
    this._cdfxPT.autoClear = false;
    this._cdfxPT.setTexture("cdfy", this._cdfyPT);
    this._cdfxPT.refreshRate = 0;
    this._cdfxPT.wrapU = 0;
    this._scaledLuminancePT = new ProceduralTexture("iblScaledLuminance", { width: size.width, height: size.height }, "iblScaledLuminance", this._scene, { ...cdfOptions, samplingMode: 3, generateMipMaps: true }, true, false);
    this._scaledLuminancePT.autoClear = false;
    this._scaledLuminancePT.setTexture("iblSource", this._iblSource);
    this._scaledLuminancePT.setInt("iblHeight", size.height);
    this._scaledLuminancePT.setInt("iblWidth", size.width);
    this._scaledLuminancePT.refreshRate = 0;
    if (this._iblSource.isCube) {
      this._scaledLuminancePT.defines = `#define IBL_USE_CUBE_MAP
`;
    }
    this._icdfPT = new ProceduralTexture("icdfTexture", { width: size.width, height: size.height }, "iblIcdf", this._scene, icdfOptions, false, false);
    this._icdfPT.autoClear = false;
    this._icdfPT.setTexture("cdfy", this._cdfyPT);
    this._icdfPT.setTexture("cdfx", this._cdfxPT);
    this._icdfPT.setTexture("iblSource", this._iblSource);
    this._icdfPT.setTexture("scaledLuminanceSampler", this._scaledLuminancePT);
    this._icdfPT.refreshRate = 0;
    this._icdfPT.wrapV = 0;
    this._icdfPT.wrapU = 0;
    if (this._iblSource.isCube) {
      this._icdfPT.defines = `#define IBL_USE_CUBE_MAP
`;
    }
    this._icdfPT.onGeneratedObservable.addOnce(() => {
      this.onGeneratedObservable.notifyObservers();
    });
  }
  _disposeTextures() {
    this._cdfyPT?.dispose();
    this._cdfxPT?.dispose();
    this._icdfPT?.dispose();
    this._scaledLuminancePT?.dispose();
  }
  _createDebugPass() {
    if (this._debugPass) {
      this._debugPass.dispose();
    }
    const isWebGPU = this._engine.isWebGPU;
    const debugOptions = {
      width: this._engine.getRenderWidth(),
      height: this._engine.getRenderHeight(),
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: this._engine,
      textureType: 0,
      uniforms: ["sizeParams"],
      samplers: ["cdfy", "icdf", "cdfx", "iblSource"],
      defines: this._iblSource?.isCube ? `#define IBL_USE_CUBE_MAP
` : "",
      shaderLanguage: isWebGPU ? 1 : 0,
      extraInitializations: (useWebGPU, list) => {
        if (useWebGPU) {
          list.push(Promise.resolve().then(() => (init_iblCdfDebug_fragment(), exports_iblCdfDebug_fragment)));
        } else {
          list.push(Promise.resolve().then(() => (init_iblCdfDebug_fragment2(), exports_iblCdfDebug_fragment2)));
        }
      }
    };
    this._debugPass = new PostProcess(this._debugPassName, "iblCdfDebug", debugOptions);
    const debugEffect = this._debugPass.getEffect();
    if (debugEffect) {
      debugEffect.defines = this._iblSource?.isCube ? `#define IBL_USE_CUBE_MAP
` : "";
    }
    if (this._iblSource?.isCube) {
      this._debugPass.updateEffect(`#define IBL_USE_CUBE_MAP
`);
    }
    this._debugPass.onApplyObservable.add((effect) => {
      effect.setTexture("cdfy", this._cdfyPT);
      effect.setTexture("icdf", this._icdfPT);
      effect.setTexture("cdfx", this._cdfxPT);
      effect.setTexture("iblSource", this._iblSource);
      effect.setFloat4("sizeParams", this._debugSizeParams.x, this._debugSizeParams.y, this._debugSizeParams.z, this._debugSizeParams.w);
    });
  }
  isReady() {
    return this._iblSource && this._iblSource.name !== "Placeholder IBL Source" && this._iblSource.isReady() && this._cdfyPT && this._cdfyPT.isReady() && this._icdfPT && this._icdfPT.isReady() && this._cdfxPT && this._cdfxPT.isReady() && this._scaledLuminancePT && this._scaledLuminancePT.isReady();
  }
  renderWhenReady() {
    this._icdfPT.onGeneratedObservable.addOnce(() => {
      this.onGeneratedObservable.notifyObservers();
    });
    const promises = [];
    const renderTargets = [this._cdfyPT, this._cdfxPT, this._scaledLuminancePT, this._icdfPT];
    renderTargets.forEach((target) => {
      promises.push(new Promise((resolve3) => {
        if (target.isReady()) {
          resolve3();
        } else {
          target.getEffect().executeWhenCompiled(() => {
            resolve3();
          });
        }
      }));
    });
    return Promise.all(promises).then(() => {
      renderTargets.forEach((target) => {
        target.render();
      });
    });
  }
  dispose() {
    this._disposeTextures();
    this._dummyTexture.dispose();
    if (this._debugPass) {
      this._debugPass.dispose();
    }
    this.onGeneratedObservable.clear();
  }
  static _IsScene(sceneOrEngine) {
    return sceneOrEngine.getClassName() === "Scene";
  }
}
IblCdfGenerator._SceneComponentInitialization = (_) => {
  throw _WarnImport("IblCdfGeneratorSceneComponentSceneComponent");
};

// node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrIrradianceFiltering.js
class HDRIrradianceFiltering {
  constructor(engine2, options = {}) {
    this.quality = 4096;
    this.hdrScale = 1;
    this.useCdf = false;
    this._engine = engine2;
    this.hdrScale = options.hdrScale || this.hdrScale;
    this.quality = options.quality || this.quality;
    this.useCdf = options.useCdf || this.useCdf;
  }
  _createRenderTarget(size) {
    let textureType = 0;
    if (this._engine.getCaps().textureHalfFloatRender) {
      textureType = 2;
    } else if (this._engine.getCaps().textureFloatRender) {
      textureType = 1;
    }
    const rtWrapper = this._engine.createRenderTargetCubeTexture(size, {
      format: 5,
      type: textureType,
      createMipMaps: false,
      generateMipMaps: false,
      generateDepthBuffer: false,
      generateStencilBuffer: false,
      samplingMode: 2,
      label: "HDR_Irradiance_Filtering_Target"
    });
    this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0);
    return rtWrapper;
  }
  _prefilterInternal(texture) {
    const width = texture.getSize().width;
    const mipmapsCount = ILog2(width);
    const effect = this._effectWrapper.effect;
    const irradianceSize = Math.max(32, 1 << ILog2(width >> 3));
    const outputTexture = this._createRenderTarget(irradianceSize);
    this._effectRenderer.saveStates();
    this._effectRenderer.setViewport();
    this._effectRenderer.applyEffectWrapper(this._effectWrapper);
    const directions = [
      [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)],
      [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)],
      [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)],
      [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)]
    ];
    effect.setFloat("hdrScale", this.hdrScale);
    effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount);
    effect.setTexture("inputTexture", texture);
    if (this._cdfGenerator) {
      effect.setTexture("icdfTexture", this._cdfGenerator.getIcdfTexture());
    }
    for (let face = 0;face < 6; face++) {
      effect.setVector3("up", directions[face][0]);
      effect.setVector3("right", directions[face][1]);
      effect.setVector3("front", directions[face][2]);
      this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true);
      this._effectRenderer.applyEffectWrapper(this._effectWrapper);
      this._effectRenderer.draw();
    }
    this._effectRenderer.restoreStates();
    this._engine.restoreDefaultFramebuffer();
    effect.setTexture("inputTexture", null);
    effect.setTexture("icdfTexture", null);
    const irradianceTexture = new BaseTexture(texture.getScene(), outputTexture.texture);
    irradianceTexture.name = texture.name + "_irradiance";
    irradianceTexture.displayName = texture.name + "_irradiance";
    irradianceTexture.gammaSpace = false;
    return irradianceTexture;
  }
  _createEffect(texture, onCompiled) {
    const defines = [];
    if (texture.gammaSpace) {
      defines.push("#define GAMMA_INPUT");
    }
    defines.push("#define NUM_SAMPLES " + this.quality + "u");
    const isWebGPU = this._engine.isWebGPU;
    const samplers = ["inputTexture"];
    if (this._cdfGenerator) {
      samplers.push("icdfTexture");
      defines.push("#define IBL_CDF_FILTERING");
    }
    const effectWrapper = new EffectWrapper({
      engine: this._engine,
      name: "HDRIrradianceFiltering",
      vertexShader: "hdrIrradianceFiltering",
      fragmentShader: "hdrIrradianceFiltering",
      samplerNames: samplers,
      uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale"],
      useShaderStore: true,
      defines,
      onCompiled,
      shaderLanguage: isWebGPU ? 1 : 0,
      extraInitializationsAsync: async () => {
        if (isWebGPU) {
          await Promise.all([Promise.resolve().then(() => (init_hdrIrradianceFiltering_vertex(), exports_hdrIrradianceFiltering_vertex)), Promise.resolve().then(() => (init_hdrIrradianceFiltering_fragment(), exports_hdrIrradianceFiltering_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_hdrIrradianceFiltering_vertex2(), exports_hdrIrradianceFiltering_vertex2)), Promise.resolve().then(() => (init_hdrIrradianceFiltering_fragment2(), exports_hdrIrradianceFiltering_fragment2))]);
        }
      }
    });
    return effectWrapper;
  }
  isReady(texture) {
    return texture.isReady() && this._effectWrapper.effect.isReady();
  }
  async prefilter(texture) {
    if (!this._engine._features.allowTexturePrefiltering) {
      throw new Error("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.");
    }
    if (this.useCdf) {
      this._cdfGenerator = new IblCdfGenerator(this._engine);
      this._cdfGenerator.iblSource = texture;
      await this._cdfGenerator.renderWhenReady();
    }
    this._effectRenderer = new EffectRenderer(this._engine);
    this._effectWrapper = this._createEffect(texture);
    await this._effectWrapper.effect.whenCompiledAsync();
    const irradianceTexture = this._prefilterInternal(texture);
    this._effectRenderer.dispose();
    this._effectWrapper.dispose();
    this._cdfGenerator?.dispose();
    return irradianceTexture;
  }
}

// node_modules/@babylonjs/core/Materials/Textures/hdrCubeTexture.js
init_textureTools();
init_baseTexture_polynomial();

class HDRCubeTexture extends BaseTexture {
  set isBlocking(value) {
    this._isBlocking = value;
  }
  get isBlocking() {
    return this._isBlocking;
  }
  set rotationY(value) {
    this._rotationY = value;
    this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));
  }
  get rotationY() {
    return this._rotationY;
  }
  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;
  }
  constructor(url, sceneOrEngine, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, prefilterOnLoad = false, onLoad = null, onError = null, supersample = false, prefilterIrradianceOnLoad = false, prefilterUsingCdf = false) {
    super(sceneOrEngine);
    this._generateHarmonics = true;
    this._onError = null;
    this._isBlocking = true;
    this._rotationY = 0;
    this.boundingBoxPosition = Vector3.Zero();
    this.onLoadObservable = new Observable;
    if (!url) {
      return;
    }
    this._coordinatesMode = Texture.CUBIC_MODE;
    this.name = url;
    this.url = url;
    this.hasAlpha = false;
    this.isCube = true;
    this._textureMatrix = Matrix.Identity();
    this._prefilterOnLoad = prefilterOnLoad;
    this._prefilterIrradianceOnLoad = prefilterIrradianceOnLoad;
    this._prefilterUsingCdf = prefilterUsingCdf;
    this._onLoad = () => {
      this.onLoadObservable.notifyObservers(this);
      if (onLoad) {
        onLoad();
      }
    };
    this._onError = onError;
    this.gammaSpace = gammaSpace;
    this._noMipmap = noMipmap;
    this._size = size;
    this._supersample = supersample || prefilterUsingCdf;
    this._generateHarmonics = generateHarmonics;
    this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);
    if (!this._texture) {
      if (!this.getScene()?.useDelayedTextureLoading) {
        this._loadTexture();
      } else {
        this.delayLoadState = 4;
      }
    } else {
      if (this._texture.isReady) {
        Tools.SetImmediate(() => this._onLoad());
      } else {
        this._texture.onLoadedObservable.add(this._onLoad);
      }
    }
  }
  getClassName() {
    return "HDRCubeTexture";
  }
  _loadTexture() {
    const engine2 = this._getEngine();
    const caps = engine2.getCaps();
    let textureType = 0;
    if (caps.textureFloat && caps.textureFloatLinearFiltering) {
      textureType = 1;
    } else if (caps.textureHalfFloat && caps.textureHalfFloatLinearFiltering) {
      textureType = 2;
    }
    const callback = (buffer2) => {
      this.lodGenerationOffset = 0;
      this.lodGenerationScale = 0.8;
      const data = GetCubeMapTextureData(buffer2, this._size, this._supersample);
      if (this._generateHarmonics) {
        const sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
        this.sphericalPolynomial = sphericalPolynomial;
      }
      const results = [];
      let byteArray = null;
      let shortArray = null;
      for (let j = 0;j < 6; j++) {
        if (textureType === 2) {
          shortArray = new Uint16Array(this._size * this._size * 3);
        } else if (textureType === 0) {
          byteArray = new Uint8Array(this._size * this._size * 3);
        }
        const dataFace = data[HDRCubeTexture._FacesMapping[j]];
        if (this.gammaSpace || shortArray || byteArray) {
          for (let i = 0;i < this._size * this._size; i++) {
            if (this.gammaSpace) {
              dataFace[i * 3 + 0] = Math.pow(dataFace[i * 3 + 0], ToGammaSpace);
              dataFace[i * 3 + 1] = Math.pow(dataFace[i * 3 + 1], ToGammaSpace);
              dataFace[i * 3 + 2] = Math.pow(dataFace[i * 3 + 2], ToGammaSpace);
            }
            if (shortArray) {
              shortArray[i * 3 + 0] = ToHalfFloat(dataFace[i * 3 + 0]);
              shortArray[i * 3 + 1] = ToHalfFloat(dataFace[i * 3 + 1]);
              shortArray[i * 3 + 2] = ToHalfFloat(dataFace[i * 3 + 2]);
            }
            if (byteArray) {
              let r = Math.max(dataFace[i * 3 + 0] * 255, 0);
              let g = Math.max(dataFace[i * 3 + 1] * 255, 0);
              let b = Math.max(dataFace[i * 3 + 2] * 255, 0);
              const max = Math.max(Math.max(r, g), b);
              if (max > 255) {
                const scale = 255 / max;
                r *= scale;
                g *= scale;
                b *= scale;
              }
              byteArray[i * 3 + 0] = r;
              byteArray[i * 3 + 1] = g;
              byteArray[i * 3 + 2] = b;
            }
          }
        }
        if (shortArray) {
          results.push(shortArray);
        } else if (byteArray) {
          results.push(byteArray);
        } else {
          results.push(dataFace);
        }
      }
      return results;
    };
    if (engine2._features.allowTexturePrefiltering && (this._prefilterOnLoad || this._prefilterIrradianceOnLoad)) {
      const previousOnLoad = this._onLoad;
      const hdrFiltering = new HDRFiltering(engine2);
      this._onLoad = () => {
        let irradiancePromise = Promise.resolve(null);
        let radiancePromise = Promise.resolve();
        if (this._prefilterIrradianceOnLoad) {
          const hdrIrradianceFiltering = new HDRIrradianceFiltering(engine2, { useCdf: this._prefilterUsingCdf });
          irradiancePromise = hdrIrradianceFiltering.prefilter(this);
        }
        if (this._prefilterOnLoad) {
          radiancePromise = hdrFiltering.prefilter(this);
        }
        Promise.all([irradiancePromise, radiancePromise]).then((results) => {
          const irradianceTexture = results[0];
          if (this._prefilterIrradianceOnLoad && irradianceTexture) {
            this.irradianceTexture = irradianceTexture;
            const scene = this.getScene();
            if (scene) {
              scene.markAllMaterialsAsDirty(1);
            }
          }
          if (previousOnLoad) {
            previousOnLoad();
          }
        });
      };
    }
    this._texture = engine2.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, textureType, this._noMipmap, callback, null, this._onLoad, this._onError);
  }
  clone() {
    const newTexture = new HDRCubeTexture(this.url, this.getScene() || this._getEngine(), this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
    newTexture.level = this.level;
    newTexture.wrapU = this.wrapU;
    newTexture.wrapV = this.wrapV;
    newTexture.coordinatesIndex = this.coordinatesIndex;
    newTexture.coordinatesMode = this.coordinatesMode;
    return newTexture;
  }
  delayLoad() {
    if (this.delayLoadState !== 4) {
      return;
    }
    this.delayLoadState = 1;
    this._texture = this._getFromCache(this.url, this._noMipmap);
    if (!this._texture) {
      this._loadTexture();
    }
  }
  getReflectionTextureMatrix() {
    return this._textureMatrix;
  }
  setReflectionTextureMatrix(value) {
    this._textureMatrix = value;
    if (value.updateFlag === this._textureMatrix.updateFlag) {
      return;
    }
    if (value.isIdentity() !== this._textureMatrix.isIdentity()) {
      this.getScene()?.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);
    }
  }
  dispose() {
    this.onLoadObservable.clear();
    super.dispose();
  }
  static Parse(parsedTexture, scene, rootUrl) {
    let texture = null;
    if (parsedTexture.name && !parsedTexture.isRenderTarget) {
      texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
      texture.name = parsedTexture.name;
      texture.hasAlpha = parsedTexture.hasAlpha;
      texture.level = parsedTexture.level;
      texture.coordinatesMode = parsedTexture.coordinatesMode;
      texture.isBlocking = parsedTexture.isBlocking;
    }
    if (texture) {
      if (parsedTexture.boundingBoxPosition) {
        texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);
      }
      if (parsedTexture.boundingBoxSize) {
        texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);
      }
      if (parsedTexture.rotationY) {
        texture.rotationY = parsedTexture.rotationY;
      }
    }
    return texture;
  }
  serialize() {
    if (!this.name) {
      return null;
    }
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.hasAlpha = this.hasAlpha;
    serializationObject.isCube = true;
    serializationObject.level = this.level;
    serializationObject.size = this._size;
    serializationObject.coordinatesMode = this.coordinatesMode;
    serializationObject.useInGammaSpace = this.gammaSpace;
    serializationObject.generateHarmonics = this._generateHarmonics;
    serializationObject.customType = "BABYLON.HDRCubeTexture";
    serializationObject.noMipmap = this._noMipmap;
    serializationObject.isBlocking = this._isBlocking;
    serializationObject.rotationY = this._rotationY;
    return serializationObject;
  }
}
HDRCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"];
RegisterClass("BABYLON.HDRCubeTexture", HDRCubeTexture);

// node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js
init_animationGroup();
init_sceneComponent();

// node_modules/@babylonjs/core/Morph/morphTargetManager.js
init_smartArray();
init_logger();
init_engineStore();

// node_modules/@babylonjs/core/Morph/morphTarget.js
init_tslib_es6();
init_observable();
init_engineStore();
init_buffer();
init_decorators();
init_decorators_serialization();
init_typeStore();

class MorphTarget {
  get influence() {
    return this._influence;
  }
  set influence(influence) {
    if (this._influence === influence) {
      return;
    }
    const previous = this._influence;
    this._influence = influence;
    if (this.onInfluenceChanged.hasObservers()) {
      this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
    }
  }
  get animationPropertiesOverride() {
    if (!this._animationPropertiesOverride && this._scene) {
      return this._scene.animationPropertiesOverride;
    }
    return this._animationPropertiesOverride;
  }
  set animationPropertiesOverride(value) {
    this._animationPropertiesOverride = value;
  }
  constructor(name353, influence = 0, scene = null) {
    this.name = name353;
    this.animations = [];
    this._positions = null;
    this._normals = null;
    this._tangents = null;
    this._uvs = null;
    this._uv2s = null;
    this._colors = null;
    this._uniqueId = 0;
    this.onInfluenceChanged = new Observable;
    this._onDataLayoutChanged = new Observable;
    this._animationPropertiesOverride = null;
    this.id = name353;
    this._scene = scene || EngineStore.LastCreatedScene;
    this.influence = influence;
    if (this._scene) {
      this._uniqueId = this._scene.getUniqueId();
    }
  }
  get uniqueId() {
    return this._uniqueId;
  }
  get hasPositions() {
    return !!this._positions;
  }
  get hasNormals() {
    return !!this._normals;
  }
  get hasTangents() {
    return !!this._tangents;
  }
  get hasUVs() {
    return !!this._uvs;
  }
  get hasUV2s() {
    return !!this._uv2s;
  }
  get hasColors() {
    return !!this._colors;
  }
  get vertexCount() {
    return this._positions ? this._positions.length / 3 : this._normals ? this._normals.length / 3 : this._tangents ? this._tangents.length / 3 : this._uvs ? this._uvs.length / 2 : this._uv2s ? this._uv2s.length / 2 : this._colors ? this._colors.length / 4 : 0;
  }
  setPositions(data) {
    const hadPositions = this.hasPositions;
    this._positions = data;
    if (hadPositions !== this.hasPositions) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getPositions() {
    return this._positions;
  }
  setNormals(data) {
    const hadNormals = this.hasNormals;
    this._normals = data;
    if (hadNormals !== this.hasNormals) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getNormals() {
    return this._normals;
  }
  setTangents(data) {
    const hadTangents = this.hasTangents;
    this._tangents = data;
    if (hadTangents !== this.hasTangents) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getTangents() {
    return this._tangents;
  }
  setUVs(data) {
    const hadUVs = this.hasUVs;
    this._uvs = data;
    if (hadUVs !== this.hasUVs) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getUVs() {
    return this._uvs;
  }
  setUV2s(data) {
    const hadUV2s = this.hasUV2s;
    this._uv2s = data;
    if (hadUV2s !== this.hasUV2s) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getUV2s() {
    return this._uv2s;
  }
  setColors(data) {
    const hadColors = this.hasColors;
    this._colors = data;
    if (hadColors !== this.hasColors) {
      this._onDataLayoutChanged.notifyObservers(undefined);
    }
  }
  getColors() {
    return this._colors;
  }
  clone() {
    const newOne = SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this);
    newOne._positions = this._positions;
    newOne._normals = this._normals;
    newOne._tangents = this._tangents;
    newOne._uvs = this._uvs;
    newOne._uv2s = this._uv2s;
    newOne._colors = this._colors;
    return newOne;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.influence = this.influence;
    serializationObject.positions = Array.prototype.slice.call(this.getPositions());
    if (this.id != null) {
      serializationObject.id = this.id;
    }
    if (this.hasNormals) {
      serializationObject.normals = Array.prototype.slice.call(this.getNormals());
    }
    if (this.hasTangents) {
      serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
    }
    if (this.hasUVs) {
      serializationObject.uvs = Array.prototype.slice.call(this.getUVs());
    }
    if (this.hasUV2s) {
      serializationObject.uv2s = Array.prototype.slice.call(this.getUV2s());
    }
    if (this.hasColors) {
      serializationObject.colors = Array.prototype.slice.call(this.getColors());
    }
    SerializationHelper.AppendSerializedAnimations(this, serializationObject);
    return serializationObject;
  }
  getClassName() {
    return "MorphTarget";
  }
  static Parse(serializationObject, scene) {
    const result = new MorphTarget(serializationObject.name, serializationObject.influence);
    result.setPositions(serializationObject.positions);
    if (serializationObject.id != null) {
      result.id = serializationObject.id;
    }
    if (serializationObject.normals) {
      result.setNormals(serializationObject.normals);
    }
    if (serializationObject.tangents) {
      result.setTangents(serializationObject.tangents);
    }
    if (serializationObject.uvs) {
      result.setUVs(serializationObject.uvs);
    }
    if (serializationObject.uv2s) {
      result.setUV2s(serializationObject.uv2s);
    }
    if (serializationObject.colors) {
      result.setColors(serializationObject.colors);
    }
    if (serializationObject.animations) {
      for (let animationIndex = 0;animationIndex < serializationObject.animations.length; animationIndex++) {
        const parsedAnimation = serializationObject.animations[animationIndex];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          result.animations.push(internalClass.Parse(parsedAnimation));
        }
      }
      if (serializationObject.autoAnimate && scene) {
        scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1);
      }
    }
    return result;
  }
  static FromMesh(mesh, name353, influence) {
    if (!name353) {
      name353 = mesh.name;
    }
    const result = new MorphTarget(name353, influence, mesh.getScene());
    result.setPositions(mesh.getVerticesData(VertexBuffer.PositionKind));
    if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
      result.setNormals(mesh.getVerticesData(VertexBuffer.NormalKind));
    }
    if (mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {
      result.setTangents(mesh.getVerticesData(VertexBuffer.TangentKind));
    }
    if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
      result.setUVs(mesh.getVerticesData(VertexBuffer.UVKind));
    }
    if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
      result.setUV2s(mesh.getVerticesData(VertexBuffer.UV2Kind));
    }
    if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {
      result.setColors(mesh.getVerticesData(VertexBuffer.ColorKind));
    }
    return result;
  }
}
__decorate([
  serialize()
], MorphTarget.prototype, "id", undefined);

// node_modules/@babylonjs/core/Materials/Textures/rawTexture2DArray.js
init_texture();

class RawTexture2DArray extends Texture {
  get depth() {
    return this._depth;
  }
  constructor(data, width, height, depth, format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0, creationFlags) {
    super(null, scene, !generateMipMaps, invertY);
    this.format = format;
    this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType, creationFlags);
    this._depth = depth;
    this.is2DArray = true;
  }
  update(data) {
    if (!this._texture) {
      return;
    }
    this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);
  }
  static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) {
    return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type);
  }
}

// node_modules/@babylonjs/core/Morph/morphTargetManager.js
class MorphTargetManager {
  set areUpdatesFrozen(block) {
    if (block) {
      this._blockCounter++;
    } else {
      this._blockCounter--;
      if (this._blockCounter <= 0) {
        this._blockCounter = 0;
        this._syncActiveTargets(this._forceUpdateWhenUnfrozen);
        this._forceUpdateWhenUnfrozen = false;
      }
    }
  }
  get areUpdatesFrozen() {
    return this._blockCounter > 0;
  }
  constructor(scene = null) {
    this._targets = new Array;
    this._targetInfluenceChangedObservers = new Array;
    this._targetDataLayoutChangedObservers = new Array;
    this._activeTargets = new SmartArray(16);
    this._supportsPositions = false;
    this._supportsNormals = false;
    this._supportsTangents = false;
    this._supportsUVs = false;
    this._supportsUV2s = false;
    this._supportsColors = false;
    this._vertexCount = 0;
    this._uniqueId = 0;
    this._tempInfluences = new Array;
    this._canUseTextureForTargets = false;
    this._blockCounter = 0;
    this._mustSynchronize = true;
    this._forceUpdateWhenUnfrozen = false;
    this._textureVertexStride = 0;
    this._textureWidth = 0;
    this._textureHeight = 1;
    this._parentContainer = null;
    this.optimizeInfluencers = true;
    this.enablePositionMorphing = true;
    this.enableNormalMorphing = true;
    this.enableTangentMorphing = true;
    this.enableUVMorphing = true;
    this.enableUV2Morphing = true;
    this.enableColorMorphing = true;
    this._numMaxInfluencers = 0;
    this._useTextureToStoreTargets = true;
    if (!scene) {
      scene = EngineStore.LastCreatedScene;
    }
    this._scene = scene;
    if (this._scene) {
      this._scene.addMorphTargetManager(this);
      this._uniqueId = this._scene.getUniqueId();
      const engineCaps = this._scene.getEngine().getCaps();
      this._canUseTextureForTargets = engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1;
    }
  }
  get numMaxInfluencers() {
    return this._numMaxInfluencers;
  }
  set numMaxInfluencers(value) {
    if (this._numMaxInfluencers === value) {
      return;
    }
    this._numMaxInfluencers = value;
    this._mustSynchronize = true;
    this._syncActiveTargets();
  }
  get uniqueId() {
    return this._uniqueId;
  }
  get vertexCount() {
    return this._vertexCount;
  }
  get supportsPositions() {
    return this._supportsPositions && this.enablePositionMorphing;
  }
  get supportsNormals() {
    return this._supportsNormals && this.enableNormalMorphing;
  }
  get supportsTangents() {
    return this._supportsTangents && this.enableTangentMorphing;
  }
  get supportsUVs() {
    return this._supportsUVs && this.enableUVMorphing;
  }
  get supportsUV2s() {
    return this._supportsUV2s && this.enableUV2Morphing;
  }
  get supportsColors() {
    return this._supportsColors && this.enableColorMorphing;
  }
  get hasPositions() {
    return this._supportsPositions;
  }
  get hasNormals() {
    return this._supportsNormals;
  }
  get hasTangents() {
    return this._supportsTangents;
  }
  get hasUVs() {
    return this._supportsUVs;
  }
  get hasUV2s() {
    return this._supportsUV2s;
  }
  get hasColors() {
    return this._supportsColors;
  }
  get numTargets() {
    return this._targets.length;
  }
  get numInfluencers() {
    return this._activeTargets.length;
  }
  get influences() {
    return this._influences;
  }
  get useTextureToStoreTargets() {
    return this._useTextureToStoreTargets;
  }
  set useTextureToStoreTargets(value) {
    if (this._useTextureToStoreTargets === value) {
      return;
    }
    this._useTextureToStoreTargets = value;
    this._mustSynchronize = true;
    this._syncActiveTargets();
  }
  get isUsingTextureForTargets() {
    return MorphTargetManager.EnableTextureStorage && this.useTextureToStoreTargets && this._canUseTextureForTargets && !this._scene?.getEngine().getCaps().disableMorphTargetTexture;
  }
  getActiveTarget(index) {
    return this._activeTargets.data[index];
  }
  getTarget(index) {
    return this._targets[index];
  }
  getTargetByName(name353) {
    for (const target of this._targets) {
      if (target.name === name353) {
        return target;
      }
    }
    return null;
  }
  addTarget(target) {
    this._targets.push(target);
    this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => {
      if (this.areUpdatesFrozen && needUpdate) {
        this._forceUpdateWhenUnfrozen = true;
      }
      this._syncActiveTargets(needUpdate);
    }));
    this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => {
      this._mustSynchronize = true;
      this._syncActiveTargets();
    }));
    this._mustSynchronize = true;
    this._syncActiveTargets();
  }
  removeTarget(target) {
    const index = this._targets.indexOf(target);
    if (index >= 0) {
      this._targets.splice(index, 1);
      target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
      target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
      this._mustSynchronize = true;
      this._syncActiveTargets();
    }
    if (this._scene) {
      this._scene.stopAnimation(target);
    }
  }
  _bind(effect) {
    effect.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight);
    effect.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices);
    effect.setTexture("morphTargets", this._targetStoreTexture);
    effect.setInt("morphTargetCount", this.numInfluencers);
  }
  clone() {
    const copy = new MorphTargetManager(this._scene);
    for (const target of this._targets) {
      copy.addTarget(target.clone());
    }
    copy.enablePositionMorphing = this.enablePositionMorphing;
    copy.enableNormalMorphing = this.enableNormalMorphing;
    copy.enableTangentMorphing = this.enableTangentMorphing;
    copy.enableUVMorphing = this.enableUVMorphing;
    copy.enableUV2Morphing = this.enableUV2Morphing;
    copy.enableColorMorphing = this.enableColorMorphing;
    return copy;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.id = this.uniqueId;
    serializationObject.targets = [];
    for (const target of this._targets) {
      serializationObject.targets.push(target.serialize());
    }
    return serializationObject;
  }
  _syncActiveTargets(needUpdate = false) {
    if (this.areUpdatesFrozen) {
      return;
    }
    const wasUsingTextureForTargets = !!this._targetStoreTexture;
    const isUsingTextureForTargets = this.isUsingTextureForTargets;
    if (this._mustSynchronize || wasUsingTextureForTargets !== isUsingTextureForTargets) {
      this._mustSynchronize = false;
      this.synchronize();
    }
    let influenceCount = 0;
    this._activeTargets.reset();
    if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) {
      this._morphTargetTextureIndices = new Float32Array(this._targets.length);
    }
    let targetIndex = -1;
    for (const target of this._targets) {
      targetIndex++;
      if (target.influence === 0 && this.optimizeInfluencers) {
        continue;
      }
      if (this._activeTargets.length >= MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) {
        break;
      }
      this._activeTargets.push(target);
      this._morphTargetTextureIndices[influenceCount] = targetIndex;
      this._tempInfluences[influenceCount++] = target.influence;
    }
    if (this._morphTargetTextureIndices.length !== influenceCount) {
      this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount);
    }
    if (!this._influences || this._influences.length !== influenceCount) {
      this._influences = new Float32Array(influenceCount);
    }
    for (let index = 0;index < influenceCount; index++) {
      this._influences[index] = this._tempInfluences[index];
    }
    if (needUpdate && this._scene) {
      for (const mesh of this._scene.meshes) {
        if (mesh.morphTargetManager === this) {
          if (isUsingTextureForTargets) {
            mesh._markSubMeshesAsAttributesDirty();
          } else {
            mesh._syncGeometryWithMorphTargetManager();
          }
        }
      }
    }
  }
  synchronize() {
    if (!this._scene || this.areUpdatesFrozen) {
      return;
    }
    const engine2 = this._scene.getEngine();
    this._supportsPositions = true;
    this._supportsNormals = true;
    this._supportsTangents = true;
    this._supportsUVs = true;
    this._supportsUV2s = true;
    this._supportsColors = true;
    this._vertexCount = 0;
    this._targetStoreTexture?.dispose();
    this._targetStoreTexture = null;
    if (this.isUsingTextureForTargets && this._targets.length > engine2.getCaps().texture2DArrayMaxLayerCount) {
      this.useTextureToStoreTargets = false;
    }
    for (const target of this._targets) {
      this._supportsPositions = this._supportsPositions && target.hasPositions;
      this._supportsNormals = this._supportsNormals && target.hasNormals;
      this._supportsTangents = this._supportsTangents && target.hasTangents;
      this._supportsUVs = this._supportsUVs && target.hasUVs;
      this._supportsUV2s = this._supportsUV2s && target.hasUV2s;
      this._supportsColors = this._supportsColors && target.hasColors;
      const vertexCount = target.vertexCount;
      if (this._vertexCount === 0) {
        this._vertexCount = vertexCount;
      } else if (this._vertexCount !== vertexCount) {
        Logger.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${target.name}": ${vertexCount}`);
        return;
      }
    }
    if (this.isUsingTextureForTargets) {
      this._textureVertexStride = 0;
      this._supportsPositions && this._textureVertexStride++;
      this._supportsNormals && this._textureVertexStride++;
      this._supportsTangents && this._textureVertexStride++;
      this._supportsUVs && this._textureVertexStride++;
      this._supportsUV2s && this._textureVertexStride++;
      this._supportsColors && this._textureVertexStride++;
      this._textureWidth = this._vertexCount * this._textureVertexStride || 1;
      this._textureHeight = 1;
      const maxTextureSize = engine2.getCaps().maxTextureSize;
      if (this._textureWidth > maxTextureSize) {
        this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize);
        this._textureWidth = maxTextureSize;
      }
      const targetCount = this._targets.length;
      const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4);
      let offset = 0;
      for (let index = 0;index < targetCount; index++) {
        const target = this._targets[index];
        const positions = target.getPositions();
        const normals = target.getNormals();
        const uvs = target.getUVs();
        const tangents = target.getTangents();
        const uv2s = target.getUV2s();
        const colors = target.getColors();
        offset = index * this._textureWidth * this._textureHeight * 4;
        for (let vertex = 0;vertex < this._vertexCount; vertex++) {
          if (this._supportsPositions && positions) {
            data[offset] = positions[vertex * 3];
            data[offset + 1] = positions[vertex * 3 + 1];
            data[offset + 2] = positions[vertex * 3 + 2];
            offset += 4;
          }
          if (this._supportsNormals && normals) {
            data[offset] = normals[vertex * 3];
            data[offset + 1] = normals[vertex * 3 + 1];
            data[offset + 2] = normals[vertex * 3 + 2];
            offset += 4;
          }
          if (this._supportsUVs && uvs) {
            data[offset] = uvs[vertex * 2];
            data[offset + 1] = uvs[vertex * 2 + 1];
            offset += 4;
          }
          if (this._supportsTangents && tangents) {
            data[offset] = tangents[vertex * 3];
            data[offset + 1] = tangents[vertex * 3 + 1];
            data[offset + 2] = tangents[vertex * 3 + 2];
            offset += 4;
          }
          if (this._supportsUV2s && uv2s) {
            data[offset] = uv2s[vertex * 2];
            data[offset + 1] = uv2s[vertex * 2 + 1];
            offset += 4;
          }
          if (this._supportsColors && colors) {
            data[offset] = colors[vertex * 4];
            data[offset + 1] = colors[vertex * 4 + 1];
            data[offset + 2] = colors[vertex * 4 + 2];
            data[offset + 3] = colors[vertex * 4 + 3];
            offset += 4;
          }
        }
      }
      this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1);
      this._targetStoreTexture.name = `Morph texture_${this.uniqueId}`;
    }
    for (const mesh of this._scene.meshes) {
      if (mesh.morphTargetManager === this) {
        mesh._syncGeometryWithMorphTargetManager();
      }
    }
  }
  dispose() {
    if (this._targetStoreTexture) {
      this._targetStoreTexture.dispose();
    }
    this._targetStoreTexture = null;
    if (this._scene) {
      this._scene.removeMorphTargetManager(this);
      if (this._parentContainer) {
        const index = this._parentContainer.morphTargetManagers.indexOf(this);
        if (index > -1) {
          this._parentContainer.morphTargetManagers.splice(index, 1);
        }
        this._parentContainer = null;
      }
      for (const morph of this._targets) {
        this._scene.stopAnimation(morph);
      }
    }
  }
  static Parse(serializationObject, scene) {
    const result = new MorphTargetManager(scene);
    for (const targetData of serializationObject.targets) {
      result.addTarget(MorphTarget.Parse(targetData, scene));
    }
    return result;
  }
}
MorphTargetManager.EnableTextureStorage = true;
MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8;

// node_modules/@babylonjs/core/Physics/v1/Plugins/cannonJSPlugin.js
init_logger();
init_math_vector();
init_buffer();

// node_modules/@babylonjs/core/Physics/physicsRaycastResult.js
init_math_vector();

// node_modules/@babylonjs/core/Physics/castingResult.js
init_math_vector();

class CastingResult {
  constructor() {
    this._hasHit = false;
    this._hitNormal = Vector3.Zero();
    this._hitPoint = Vector3.Zero();
    this._triangleIndex = -1;
  }
  get hitPoint() {
    return this._hitPoint;
  }
  get hitNormal() {
    return this._hitNormal;
  }
  get hasHit() {
    return this._hasHit;
  }
  get triangleIndex() {
    return this._triangleIndex;
  }
  setHitData(hitNormal, hitPoint, triangleIndex) {
    this._hasHit = true;
    this._hitNormal.set(hitNormal.x, hitNormal.y, hitNormal.z);
    this._hitPoint.set(hitPoint.x, hitPoint.y, hitPoint.z);
    this._triangleIndex = triangleIndex ?? -1;
  }
  reset() {
    this._hasHit = false;
    this._hitNormal.setAll(0);
    this._hitPoint.setAll(0);
    this._triangleIndex = -1;
    this.body = undefined;
    this.bodyIndex = undefined;
    this.shape = undefined;
  }
}

// node_modules/@babylonjs/core/Physics/physicsRaycastResult.js
class PhysicsRaycastResult extends CastingResult {
  constructor() {
    super(...arguments);
    this._hitDistance = 0;
    this._rayFromWorld = Vector3.Zero();
    this._rayToWorld = Vector3.Zero();
  }
  get hitDistance() {
    return this._hitDistance;
  }
  get hitNormalWorld() {
    return this._hitNormal;
  }
  get hitPointWorld() {
    return this._hitPoint;
  }
  get rayFromWorld() {
    return this._rayFromWorld;
  }
  get rayToWorld() {
    return this._rayToWorld;
  }
  setHitDistance(distance) {
    this._hitDistance = distance;
  }
  calculateHitDistance() {
    this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPoint);
  }
  reset(from = Vector3.Zero(), to = Vector3.Zero()) {
    super.reset();
    this._rayFromWorld.copyFrom(from);
    this._rayToWorld.copyFrom(to);
    this._hitDistance = 0;
  }
}

// node_modules/@babylonjs/core/Physics/v1/physicsEngine.js
init_math_vector();
init_devTools();

class PhysicsEngine {
  getPluginVersion() {
    return this._physicsPlugin.getPluginVersion();
  }
  static DefaultPluginFactory() {
    throw _WarnImport("CannonJSPlugin");
  }
  constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) {
    this._physicsPlugin = _physicsPlugin;
    this._impostors = [];
    this._joints = [];
    this._subTimeStep = 0;
    this._uniqueIdCounter = 0;
    if (!this._physicsPlugin.isSupported()) {
      throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. " + "Please make sure it is included.");
    }
    gravity = gravity || new Vector3(0, -9.807, 0);
    this.setGravity(gravity);
    this.setTimeStep();
  }
  setGravity(gravity) {
    this.gravity = gravity;
    this._physicsPlugin.setGravity(this.gravity);
  }
  setTimeStep(newTimeStep = 1 / 60) {
    this._physicsPlugin.setTimeStep(newTimeStep);
  }
  getTimeStep() {
    return this._physicsPlugin.getTimeStep();
  }
  setSubTimeStep(subTimeStep = 0) {
    this._subTimeStep = subTimeStep;
  }
  getSubTimeStep() {
    return this._subTimeStep;
  }
  dispose() {
    this._impostors.forEach(function(impostor) {
      impostor.dispose();
    });
    this._physicsPlugin.dispose();
  }
  getPhysicsPluginName() {
    return this._physicsPlugin.name;
  }
  addImpostor(impostor) {
    this._impostors.push(impostor);
    impostor.uniqueId = this._uniqueIdCounter++;
    if (!impostor.parent) {
      this._physicsPlugin.generatePhysicsBody(impostor);
    }
  }
  removeImpostor(impostor) {
    const index = this._impostors.indexOf(impostor);
    if (index > -1) {
      const removed = this._impostors.splice(index, 1);
      if (removed.length) {
        this.getPhysicsPlugin().removePhysicsBody(impostor);
      }
    }
  }
  addJoint(mainImpostor, connectedImpostor, joint) {
    const impostorJoint = {
      mainImpostor,
      connectedImpostor,
      joint
    };
    joint.physicsPlugin = this._physicsPlugin;
    this._joints.push(impostorJoint);
    this._physicsPlugin.generateJoint(impostorJoint);
  }
  removeJoint(mainImpostor, connectedImpostor, joint) {
    const matchingJoints = this._joints.filter(function(impostorJoint) {
      return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor;
    });
    if (matchingJoints.length) {
      this._physicsPlugin.removeJoint(matchingJoints[0]);
    }
  }
  _step(delta) {
    this._impostors.forEach((impostor) => {
      if (impostor.isBodyInitRequired()) {
        this._physicsPlugin.generatePhysicsBody(impostor);
      }
    });
    if (delta > 0.1) {
      delta = 0.1;
    } else if (delta <= 0) {
      delta = 1 / 60;
    }
    this._physicsPlugin.executeStep(delta, this._impostors);
  }
  getPhysicsPlugin() {
    return this._physicsPlugin;
  }
  getImpostors() {
    return this._impostors;
  }
  getImpostorForPhysicsObject(object) {
    for (let i = 0;i < this._impostors.length; ++i) {
      if (this._impostors[i].object === object) {
        return this._impostors[i];
      }
    }
    return null;
  }
  getImpostorWithPhysicsBody(body) {
    for (let i = 0;i < this._impostors.length; ++i) {
      if (this._impostors[i].physicsBody === body) {
        return this._impostors[i];
      }
    }
    return null;
  }
  raycast(from, to) {
    return this._physicsPlugin.raycast(from, to);
  }
  raycastToRef(from, to, result) {
    return this._physicsPlugin.raycastToRef(from, to, result);
  }
}

// node_modules/@babylonjs/core/Physics/v1/Plugins/cannonJSPlugin.js
init_math_constants();

class CannonJSPlugin {
  constructor(_useDeltaForWorldStep = true, iterations = 10, cannonInjection = CANNON) {
    this._useDeltaForWorldStep = _useDeltaForWorldStep;
    this.name = "CannonJSPlugin";
    this._physicsMaterials = new Array;
    this._fixedTimeStep = 1 / 60;
    this._physicsBodiesToRemoveAfterStep = new Array;
    this._firstFrame = true;
    this._tmpQuaternion = new Quaternion;
    this._minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
    this._plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
    this._tmpPosition = Vector3.Zero();
    this._tmpDeltaPosition = Vector3.Zero();
    this._tmpUnityRotation = new Quaternion;
    this.BJSCANNON = cannonInjection;
    if (!this.isSupported()) {
      Logger.Error("CannonJS is not available. Please make sure you included the js file.");
      return;
    }
    this._extendNamespace();
    this.world = new this.BJSCANNON.World;
    this.world.broadphase = new this.BJSCANNON.NaiveBroadphase;
    this.world.solver.iterations = iterations;
    this._cannonRaycastResult = new this.BJSCANNON.RaycastResult;
    this._raycastResult = new PhysicsRaycastResult;
  }
  getPluginVersion() {
    return 1;
  }
  setGravity(gravity) {
    const vec = gravity;
    this.world.gravity.set(vec.x, vec.y, vec.z);
  }
  setTimeStep(timeStep) {
    this._fixedTimeStep = timeStep;
  }
  getTimeStep() {
    return this._fixedTimeStep;
  }
  executeStep(delta, impostors) {
    if (this._firstFrame) {
      this._firstFrame = false;
      for (const impostor of impostors) {
        if (!(impostor.type == PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.PlaneImpostor)) {
          impostor.beforeStep();
        }
      }
    }
    this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep);
    this._removeMarkedPhysicsBodiesFromWorld();
  }
  _removeMarkedPhysicsBodiesFromWorld() {
    if (this._physicsBodiesToRemoveAfterStep.length > 0) {
      this._physicsBodiesToRemoveAfterStep.forEach((physicsBody) => {
        if (typeof this.world.removeBody === "function") {
          this.world.removeBody(physicsBody);
        } else {
          this.world.remove(physicsBody);
        }
      });
      this._physicsBodiesToRemoveAfterStep.length = 0;
    }
  }
  applyImpulse(impostor, force, contactPoint) {
    const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
    const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
    impostor.physicsBody.applyImpulse(impulse, worldPoint);
  }
  applyForce(impostor, force, contactPoint) {
    const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
    const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
    impostor.physicsBody.applyForce(impulse, worldPoint);
  }
  generatePhysicsBody(impostor) {
    this._removeMarkedPhysicsBodiesFromWorld();
    if (impostor.parent) {
      if (impostor.physicsBody) {
        this.removePhysicsBody(impostor);
        impostor.forceUpdate();
      }
      return;
    }
    if (impostor.isBodyInitRequired()) {
      const shape = this._createShape(impostor);
      if (!shape) {
        Logger.Warn("It was not possible to create a physics body for this object.");
        return;
      }
      const oldBody = impostor.physicsBody;
      if (oldBody) {
        this.removePhysicsBody(impostor);
      }
      const material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
      const bodyCreationObject = {
        mass: impostor.getParam("mass"),
        material
      };
      const nativeOptions = impostor.getParam("nativeOptions");
      for (const key in nativeOptions) {
        if (Object.prototype.hasOwnProperty.call(nativeOptions, key)) {
          bodyCreationObject[key] = nativeOptions[key];
        }
      }
      impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
      impostor.physicsBody.addEventListener("collide", impostor.onCollide);
      this.world.addEventListener("preStep", impostor.beforeStep);
      this.world.addEventListener("postStep", impostor.afterStep);
      impostor.physicsBody.addShape(shape);
      if (typeof this.world.addBody === "function") {
        this.world.addBody(impostor.physicsBody);
      } else {
        this.world.add(impostor.physicsBody);
      }
      if (oldBody) {
        ["force", "torque", "velocity", "angularVelocity"].forEach(function(param) {
          const vec = oldBody[param];
          impostor.physicsBody[param].set(vec.x, vec.y, vec.z);
        });
      }
      this._processChildMeshes(impostor);
    }
    this._updatePhysicsBodyTransformation(impostor);
  }
  _processChildMeshes(mainImpostor) {
    const meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
    const mainRotation = mainImpostor.object.rotationQuaternion;
    if (mainRotation) {
      mainRotation.conjugateToRef(this._tmpQuaternion);
    } else {
      this._tmpQuaternion.set(0, 0, 0, 1);
    }
    if (meshChildren.length) {
      const processMesh = (mesh) => {
        if (!mesh.rotationQuaternion) {
          return;
        }
        const childImpostor = mesh.getPhysicsImpostor();
        if (childImpostor) {
          const parent = childImpostor.parent;
          if (parent !== mainImpostor && mesh.parent) {
            const pPosition = mesh.getAbsolutePosition().subtract(mesh.parent.getAbsolutePosition());
            const q = mesh.rotationQuaternion.multiply(this._tmpQuaternion);
            if (childImpostor.physicsBody) {
              this.removePhysicsBody(childImpostor);
              childImpostor.physicsBody = null;
            }
            childImpostor.parent = mainImpostor;
            childImpostor.resetUpdateFlags();
            mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(q.x, q.y, q.z, q.w));
            mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
          }
        }
        mesh.getChildMeshes(true).filter((m) => !!m.physicsImpostor).forEach(processMesh);
      };
      meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh);
    }
  }
  removePhysicsBody(impostor) {
    impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
    this.world.removeEventListener("preStep", impostor.beforeStep);
    this.world.removeEventListener("postStep", impostor.afterStep);
    if (this._physicsBodiesToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) {
      this._physicsBodiesToRemoveAfterStep.push(impostor.physicsBody);
    }
  }
  generateJoint(impostorJoint) {
    const mainBody = impostorJoint.mainImpostor.physicsBody;
    const connectedBody = impostorJoint.connectedImpostor.physicsBody;
    if (!mainBody || !connectedBody) {
      return;
    }
    let constraint;
    const jointData = impostorJoint.joint.jointData;
    const constraintData = {
      pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().set(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z) : null,
      pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().set(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z) : null,
      axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null,
      axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null,
      maxForce: jointData.nativeParams.maxForce,
      collideConnected: !!jointData.collision
    };
    switch (impostorJoint.joint.type) {
      case PhysicsJoint.HingeJoint:
      case PhysicsJoint.Hinge2Joint:
        constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
        break;
      case PhysicsJoint.DistanceJoint:
        constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
        break;
      case PhysicsJoint.SpringJoint: {
        const springData = jointData;
        constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
          restLength: springData.length,
          stiffness: springData.stiffness,
          damping: springData.damping,
          localAnchorA: constraintData.pivotA,
          localAnchorB: constraintData.pivotB
        });
        break;
      }
      case PhysicsJoint.LockJoint:
        constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
        break;
      case PhysicsJoint.PointToPointJoint:
      case PhysicsJoint.BallAndSocketJoint:
      default:
        constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce);
        break;
    }
    constraint.collideConnected = !!jointData.collision;
    impostorJoint.joint.physicsJoint = constraint;
    if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
      this.world.addConstraint(constraint);
    } else {
      impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function() {
        constraint.applyForce();
      };
      impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
    }
  }
  removeJoint(impostorJoint) {
    if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
      this.world.removeConstraint(impostorJoint.joint.physicsJoint);
    } else {
      impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
    }
  }
  _addMaterial(name353, friction, restitution) {
    let index;
    let mat;
    for (index = 0;index < this._physicsMaterials.length; index++) {
      mat = this._physicsMaterials[index];
      if (mat.friction === friction && mat.restitution === restitution) {
        return mat;
      }
    }
    const currentMat = new this.BJSCANNON.Material(name353);
    currentMat.friction = friction;
    currentMat.restitution = restitution;
    this._physicsMaterials.push(currentMat);
    return currentMat;
  }
  _checkWithEpsilon(value) {
    return value < Epsilon ? Epsilon : value;
  }
  _createShape(impostor) {
    const object = impostor.object;
    let returnValue;
    const impostorExtents = impostor.getObjectExtents();
    switch (impostor.type) {
      case PhysicsImpostor.SphereImpostor: {
        const radiusX = impostorExtents.x;
        const radiusY = impostorExtents.y;
        const radiusZ = impostorExtents.z;
        returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
        break;
      }
      case PhysicsImpostor.CylinderImpostor: {
        let nativeParams = impostor.getParam("nativeOptions");
        if (!nativeParams) {
          nativeParams = {};
        }
        const radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(impostorExtents.x) / 2;
        const radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(impostorExtents.x) / 2;
        const height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(impostorExtents.y);
        const numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16;
        returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments);
        const quat = new this.BJSCANNON.Quaternion;
        quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2);
        const translation = new this.BJSCANNON.Vec3(0, 0, 0);
        returnValue.transformAllPoints(translation, quat);
        break;
      }
      case PhysicsImpostor.BoxImpostor: {
        const box = impostorExtents.scale(0.5);
        returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
        break;
      }
      case PhysicsImpostor.PlaneImpostor:
        Logger.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
        returnValue = new this.BJSCANNON.Plane;
        break;
      case PhysicsImpostor.MeshImpostor: {
        const rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
        const rawFaces = object.getIndices ? object.getIndices() : [];
        if (!rawVerts) {
          Logger.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");
          return;
        }
        const oldPosition = object.position.clone();
        const oldRotation = object.rotation && object.rotation.clone();
        const oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
        object.position.copyFromFloats(0, 0, 0);
        object.rotation && object.rotation.copyFromFloats(0, 0, 0);
        object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
        object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
        const transform = object.computeWorldMatrix(true);
        const transformedVertices = [];
        let index;
        for (index = 0;index < rawVerts.length; index += 3) {
          Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(transformedVertices, index);
        }
        Logger.Warn("MeshImpostor only collides against spheres.");
        returnValue = new this.BJSCANNON.Trimesh(transformedVertices, rawFaces);
        object.position.copyFrom(oldPosition);
        oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
        oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
        break;
      }
      case PhysicsImpostor.HeightmapImpostor: {
        const oldPosition2 = object.position.clone();
        const oldRotation2 = object.rotation && object.rotation.clone();
        const oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
        object.position.copyFromFloats(0, 0, 0);
        object.rotation && object.rotation.copyFromFloats(0, 0, 0);
        object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
        object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
        object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
        returnValue = this._createHeightmap(object);
        object.position.copyFrom(oldPosition2);
        oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
        oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
        object.computeWorldMatrix(true);
        break;
      }
      case PhysicsImpostor.ParticleImpostor:
        returnValue = new this.BJSCANNON.Particle;
        break;
      case PhysicsImpostor.NoImpostor:
        returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0));
        break;
    }
    return returnValue;
  }
  _createHeightmap(object, pointDepth) {
    let pos = object.getVerticesData(VertexBuffer.PositionKind);
    const transform = object.computeWorldMatrix(true);
    const transformedVertices = [];
    let index;
    for (index = 0;index < pos.length; index += 3) {
      Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(transformedVertices, index);
    }
    pos = transformedVertices;
    const matrix = new Array;
    const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
    const boundingInfo2 = object.getBoundingInfo();
    const dim = Math.min(boundingInfo2.boundingBox.extendSizeWorld.x, boundingInfo2.boundingBox.extendSizeWorld.y);
    const minY = boundingInfo2.boundingBox.extendSizeWorld.z;
    const elementSize = dim * 2 / arraySize;
    for (let i = 0;i < pos.length; i = i + 3) {
      const x = Math.round(pos[i + 0] / elementSize + arraySize / 2);
      const z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1);
      const y = -pos[i + 2] + minY;
      if (!matrix[x]) {
        matrix[x] = [];
      }
      if (!matrix[x][z]) {
        matrix[x][z] = y;
      }
      matrix[x][z] = Math.max(y, matrix[x][z]);
    }
    for (let x = 0;x <= arraySize; ++x) {
      if (!matrix[x]) {
        let loc = 1;
        while (!matrix[(x + loc) % arraySize]) {
          loc++;
        }
        matrix[x] = matrix[(x + loc) % arraySize].slice();
      }
      for (let z = 0;z <= arraySize; ++z) {
        if (!matrix[x][z]) {
          let loc = 1;
          let newValue;
          while (newValue === undefined) {
            newValue = matrix[x][(z + loc++) % arraySize];
          }
          matrix[x][z] = newValue;
        }
      }
    }
    const shape = new this.BJSCANNON.Heightfield(matrix, {
      elementSize
    });
    shape.minY = minY;
    return shape;
  }
  _updatePhysicsBodyTransformation(impostor) {
    const object = impostor.object;
    object.computeWorldMatrix && object.computeWorldMatrix(true);
    if (!object.getBoundingInfo()) {
      return;
    }
    const center = impostor.getObjectCenter();
    this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
    this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
    this._tmpPosition.copyFrom(center);
    let quaternion = object.rotationQuaternion;
    if (!quaternion) {
      return;
    }
    if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor) {
      quaternion = quaternion.multiply(this._minus90X);
      impostor.setDeltaRotation(this._plus90X);
    }
    if (impostor.type === PhysicsImpostor.HeightmapImpostor) {
      const mesh = object;
      let boundingInfo2 = mesh.getBoundingInfo();
      const rotationQuaternion = mesh.rotationQuaternion;
      mesh.rotationQuaternion = this._tmpUnityRotation;
      mesh.computeWorldMatrix(true);
      const c = center.clone();
      let oldPivot = mesh.getPivotMatrix();
      if (oldPivot) {
        oldPivot = oldPivot.clone();
      } else {
        oldPivot = Matrix.Identity();
      }
      const p = Matrix.Translation(boundingInfo2.boundingBox.extendSizeWorld.x, 0, -boundingInfo2.boundingBox.extendSizeWorld.z);
      mesh.setPreTransformMatrix(p);
      mesh.computeWorldMatrix(true);
      boundingInfo2 = mesh.getBoundingInfo();
      const translation = boundingInfo2.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
      this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo2.boundingBox.extendSizeWorld.y, translation.z);
      this._tmpDeltaPosition.copyFrom(boundingInfo2.boundingBox.centerWorld.subtract(c));
      this._tmpDeltaPosition.y += boundingInfo2.boundingBox.extendSizeWorld.y;
      mesh.rotationQuaternion = rotationQuaternion;
      mesh.setPreTransformMatrix(oldPivot);
      mesh.computeWorldMatrix(true);
    } else if (impostor.type === PhysicsImpostor.MeshImpostor) {
      this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
    }
    impostor.setDeltaPosition(this._tmpDeltaPosition);
    impostor.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z);
    impostor.physicsBody.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  }
  setTransformationFromPhysicsBody(impostor) {
    impostor.object.position.set(impostor.physicsBody.position.x, impostor.physicsBody.position.y, impostor.physicsBody.position.z);
    if (impostor.object.rotationQuaternion) {
      const q = impostor.physicsBody.quaternion;
      impostor.object.rotationQuaternion.set(q.x, q.y, q.z, q.w);
    }
  }
  setPhysicsBodyTransformation(impostor, newPosition, newRotation) {
    impostor.physicsBody.position.set(newPosition.x, newPosition.y, newPosition.z);
    impostor.physicsBody.quaternion.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  }
  isSupported() {
    return this.BJSCANNON !== undefined;
  }
  setLinearVelocity(impostor, velocity) {
    impostor.physicsBody.velocity.set(velocity.x, velocity.y, velocity.z);
  }
  setAngularVelocity(impostor, velocity) {
    impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);
  }
  getLinearVelocity(impostor) {
    const v = impostor.physicsBody.velocity;
    if (!v) {
      return null;
    }
    return new Vector3(v.x, v.y, v.z);
  }
  getAngularVelocity(impostor) {
    const v = impostor.physicsBody.angularVelocity;
    if (!v) {
      return null;
    }
    return new Vector3(v.x, v.y, v.z);
  }
  setBodyMass(impostor, mass) {
    impostor.physicsBody.mass = mass;
    impostor.physicsBody.updateMassProperties();
  }
  getBodyMass(impostor) {
    return impostor.physicsBody.mass;
  }
  getBodyFriction(impostor) {
    return impostor.physicsBody.material.friction;
  }
  setBodyFriction(impostor, friction) {
    impostor.physicsBody.material.friction = friction;
  }
  getBodyRestitution(impostor) {
    return impostor.physicsBody.material.restitution;
  }
  setBodyRestitution(impostor, restitution) {
    impostor.physicsBody.material.restitution = restitution;
  }
  sleepBody(impostor) {
    impostor.physicsBody.sleep();
  }
  wakeUpBody(impostor) {
    impostor.physicsBody.wakeUp();
  }
  updateDistanceJoint(joint, maxDistance) {
    joint.physicsJoint.distance = maxDistance;
  }
  setMotor(joint, speed, maxForce, motorIndex) {
    if (!motorIndex) {
      joint.physicsJoint.enableMotor();
      joint.physicsJoint.setMotorSpeed(speed);
      if (maxForce) {
        this.setLimit(joint, maxForce);
      }
    }
  }
  setLimit(joint, minForce, maxForce) {
    joint.physicsJoint.motorEquation.maxForce = maxForce;
    joint.physicsJoint.motorEquation.minForce = minForce === undefined ? -minForce : minForce;
  }
  syncMeshWithImpostor(mesh, impostor) {
    const body = impostor.physicsBody;
    mesh.position.x = body.position.x;
    mesh.position.y = body.position.y;
    mesh.position.z = body.position.z;
    if (mesh.rotationQuaternion) {
      mesh.rotationQuaternion.x = body.quaternion.x;
      mesh.rotationQuaternion.y = body.quaternion.y;
      mesh.rotationQuaternion.z = body.quaternion.z;
      mesh.rotationQuaternion.w = body.quaternion.w;
    }
  }
  getRadius(impostor) {
    const shape = impostor.physicsBody.shapes[0];
    return shape.boundingSphereRadius;
  }
  getBoxSizeToRef(impostor, result) {
    const shape = impostor.physicsBody.shapes[0];
    result.x = shape.halfExtents.x * 2;
    result.y = shape.halfExtents.y * 2;
    result.z = shape.halfExtents.z * 2;
  }
  dispose() {}
  _extendNamespace() {
    const step_tmp1 = new this.BJSCANNON.Vec3;
    const engine2 = this.BJSCANNON;
    this.BJSCANNON.World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps) {
      maxSubSteps = maxSubSteps || 10;
      timeSinceLastCalled = timeSinceLastCalled || 0;
      if (timeSinceLastCalled === 0) {
        this.internalStep(dt);
        this.time += dt;
      } else {
        let internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
        internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
        const t0 = performance.now();
        for (let i = 0;i !== internalSteps; i++) {
          this.internalStep(dt);
          if (performance.now() - t0 > dt * 1000) {
            break;
          }
        }
        this.time += timeSinceLastCalled;
        const h = this.time % dt;
        const h_div_dt = h / dt;
        const interpvelo = step_tmp1;
        const bodies = this.bodies;
        for (let j = 0;j !== bodies.length; j++) {
          const b = bodies[j];
          if (b.type !== engine2.Body.STATIC && b.sleepState !== engine2.Body.SLEEPING) {
            b.position.vsub(b.previousPosition, interpvelo);
            interpvelo.scale(h_div_dt, interpvelo);
            b.position.vadd(interpvelo, b.interpolatedPosition);
          } else {
            b.interpolatedPosition.set(b.position.x, b.position.y, b.position.z);
            b.interpolatedQuaternion.set(b.quaternion.x, b.quaternion.y, b.quaternion.z, b.quaternion.w);
          }
        }
      }
    };
  }
  raycast(from, to) {
    this._raycastResult.reset(from, to);
    this.raycastToRef(from, to, this._raycastResult);
    return this._raycastResult;
  }
  raycastToRef(from, to, result) {
    this._cannonRaycastResult.reset();
    this.world.raycastClosest(from, to, {}, this._cannonRaycastResult);
    result.reset(from, to);
    if (this._cannonRaycastResult.hasHit) {
      result.setHitData({
        x: this._cannonRaycastResult.hitNormalWorld.x,
        y: this._cannonRaycastResult.hitNormalWorld.y,
        z: this._cannonRaycastResult.hitNormalWorld.z
      }, {
        x: this._cannonRaycastResult.hitPointWorld.x,
        y: this._cannonRaycastResult.hitPointWorld.y,
        z: this._cannonRaycastResult.hitPointWorld.z
      });
      result.setHitDistance(this._cannonRaycastResult.distance);
    }
  }
}
PhysicsEngine.DefaultPluginFactory = () => {
  return new CannonJSPlugin;
};

// node_modules/@babylonjs/core/Physics/v1/Plugins/oimoJSPlugin.js
init_math_vector();
init_logger();
init_math_constants();

class OimoJSPlugin {
  constructor(_useDeltaForWorldStep = true, iterations, oimoInjection = OIMO) {
    this._useDeltaForWorldStep = _useDeltaForWorldStep;
    this.name = "OimoJSPlugin";
    this._fixedTimeStep = 1 / 60;
    this._tmpImpostorsArray = [];
    this._tmpPositionVector = Vector3.Zero();
    this.BJSOIMO = oimoInjection;
    this.world = new this.BJSOIMO.World({
      iterations
    });
    this.world.clear();
    this._raycastResult = new PhysicsRaycastResult;
  }
  getPluginVersion() {
    return 1;
  }
  setGravity(gravity) {
    this.world.gravity.set(gravity.x, gravity.y, gravity.z);
  }
  setTimeStep(timeStep) {
    this.world.timeStep = timeStep;
  }
  getTimeStep() {
    return this.world.timeStep;
  }
  executeStep(delta, impostors) {
    impostors.forEach(function(impostor) {
      impostor.beforeStep();
    });
    this.world.timeStep = this._useDeltaForWorldStep ? delta : this._fixedTimeStep;
    this.world.step();
    impostors.forEach((impostor) => {
      impostor.afterStep();
      this._tmpImpostorsArray[impostor.uniqueId] = impostor;
    });
    let contact = this.world.contacts;
    while (contact !== null) {
      if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
        contact = contact.next;
        continue;
      }
      const mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
      const collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
      if (!mainImpostor || !collidingImpostor) {
        contact = contact.next;
        continue;
      }
      mainImpostor.onCollide({ body: collidingImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });
      collidingImpostor.onCollide({ body: mainImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });
      contact = contact.next;
    }
  }
  applyImpulse(impostor, force, contactPoint) {
    const mass = impostor.physicsBody.mass;
    impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  }
  applyForce(impostor, force, contactPoint) {
    Logger.Warn("Oimo doesn't support applying force. Using impulse instead.");
    this.applyImpulse(impostor, force, contactPoint);
  }
  generatePhysicsBody(impostor) {
    if (impostor.parent) {
      if (impostor.physicsBody) {
        this.removePhysicsBody(impostor);
        impostor.forceUpdate();
      }
      return;
    }
    if (impostor.isBodyInitRequired()) {
      const bodyConfig = {
        name: impostor.uniqueId,
        config: [impostor.getParam("mass") || 0.001, impostor.getParam("friction"), impostor.getParam("restitution")],
        size: [],
        type: [],
        pos: [],
        posShape: [],
        rot: [],
        rotShape: [],
        move: impostor.getParam("mass") !== 0,
        density: impostor.getParam("mass"),
        friction: impostor.getParam("friction"),
        restitution: impostor.getParam("restitution"),
        world: this.world
      };
      const impostors = [impostor];
      const addToArray = (parent) => {
        if (!parent.getChildMeshes) {
          return;
        }
        parent.getChildMeshes().forEach(function(m) {
          if (m.physicsImpostor) {
            impostors.push(m.physicsImpostor);
          }
        });
      };
      addToArray(impostor.object);
      const checkWithEpsilon = (value) => {
        return Math.max(value, Epsilon);
      };
      const globalQuaternion = new Quaternion;
      impostors.forEach((i) => {
        if (!i.object.rotationQuaternion) {
          return;
        }
        const oldQuaternion = i.object.rotationQuaternion;
        globalQuaternion.copyFrom(oldQuaternion);
        i.object.rotationQuaternion.set(0, 0, 0, 1);
        i.object.computeWorldMatrix(true);
        const rot = globalQuaternion.toEulerAngles();
        const impostorExtents = i.getObjectExtents();
        const radToDeg = 57.29577951308232;
        if (i === impostor) {
          const center = impostor.getObjectCenter();
          impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector);
          this._tmpPositionVector.divideInPlace(impostor.object.scaling);
          bodyConfig.pos.push(center.x);
          bodyConfig.pos.push(center.y);
          bodyConfig.pos.push(center.z);
          bodyConfig.posShape.push(0, 0, 0);
          bodyConfig.rotShape.push(0, 0, 0);
        } else {
          const localPosition = i.object.position.clone();
          bodyConfig.posShape.push(localPosition.x);
          bodyConfig.posShape.push(localPosition.y);
          bodyConfig.posShape.push(localPosition.z);
          bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg);
        }
        i.object.rotationQuaternion.copyFrom(globalQuaternion);
        switch (i.type) {
          case PhysicsImpostor.ParticleImpostor:
            Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
          case PhysicsImpostor.SphereImpostor: {
            const radiusX = impostorExtents.x;
            const radiusY = impostorExtents.y;
            const radiusZ = impostorExtents.z;
            const size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
            bodyConfig.type.push("sphere");
            bodyConfig.size.push(size);
            bodyConfig.size.push(size);
            bodyConfig.size.push(size);
            break;
          }
          case PhysicsImpostor.CylinderImpostor: {
            const sizeX = checkWithEpsilon(impostorExtents.x) / 2;
            const sizeY = checkWithEpsilon(impostorExtents.y);
            bodyConfig.type.push("cylinder");
            bodyConfig.size.push(sizeX);
            bodyConfig.size.push(sizeY);
            bodyConfig.size.push(sizeY);
            break;
          }
          case PhysicsImpostor.PlaneImpostor:
          case PhysicsImpostor.BoxImpostor:
          default: {
            const sizeX = checkWithEpsilon(impostorExtents.x);
            const sizeY = checkWithEpsilon(impostorExtents.y);
            const sizeZ = checkWithEpsilon(impostorExtents.z);
            bodyConfig.type.push("box");
            bodyConfig.size.push(sizeX);
            bodyConfig.size.push(sizeY);
            bodyConfig.size.push(sizeZ);
            break;
          }
        }
        i.object.rotationQuaternion = oldQuaternion;
      });
      impostor.physicsBody = this.world.add(bodyConfig);
      impostor.physicsBody.resetQuaternion(globalQuaternion);
      impostor.physicsBody.updatePosition(0);
    } else {
      this._tmpPositionVector.copyFromFloats(0, 0, 0);
    }
    impostor.setDeltaPosition(this._tmpPositionVector);
  }
  removePhysicsBody(impostor) {
    this.world.removeRigidBody(impostor.physicsBody);
  }
  generateJoint(impostorJoint) {
    const mainBody = impostorJoint.mainImpostor.physicsBody;
    const connectedBody = impostorJoint.connectedImpostor.physicsBody;
    if (!mainBody || !connectedBody) {
      return;
    }
    const jointData = impostorJoint.joint.jointData;
    const options = jointData.nativeParams || {};
    let type;
    const nativeJointData = {
      body1: mainBody,
      body2: connectedBody,
      axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
      axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
      pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
      pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
      min: options.min,
      max: options.max,
      collision: options.collision || jointData.collision,
      spring: options.spring,
      world: this.world
    };
    switch (impostorJoint.joint.type) {
      case PhysicsJoint.BallAndSocketJoint:
        type = "jointBall";
        break;
      case PhysicsJoint.SpringJoint: {
        Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
        const springData = jointData;
        nativeJointData.min = springData.length || nativeJointData.min;
        nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
      }
      case PhysicsJoint.DistanceJoint:
        type = "jointDistance";
        nativeJointData.max = jointData.maxDistance;
        break;
      case PhysicsJoint.PrismaticJoint:
        type = "jointPrisme";
        break;
      case PhysicsJoint.SliderJoint:
        type = "jointSlide";
        break;
      case PhysicsJoint.WheelJoint:
        type = "jointWheel";
        break;
      case PhysicsJoint.HingeJoint:
      default:
        type = "jointHinge";
        break;
    }
    nativeJointData.type = type;
    impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  }
  removeJoint(impostorJoint) {
    try {
      this.world.removeJoint(impostorJoint.joint.physicsJoint);
    } catch (e) {
      Logger.Warn(e);
    }
  }
  isSupported() {
    return this.BJSOIMO !== undefined;
  }
  setTransformationFromPhysicsBody(impostor) {
    if (!impostor.physicsBody.sleeping) {
      if (impostor.physicsBody.shapes.next) {
        let parent = impostor.physicsBody.shapes;
        while (parent.next) {
          parent = parent.next;
        }
        impostor.object.position.set(parent.position.x, parent.position.y, parent.position.z);
      } else {
        const pos = impostor.physicsBody.getPosition();
        impostor.object.position.set(pos.x, pos.y, pos.z);
      }
      if (impostor.object.rotationQuaternion) {
        const quat = impostor.physicsBody.getQuaternion();
        impostor.object.rotationQuaternion.set(quat.x, quat.y, quat.z, quat.w);
      }
    }
  }
  setPhysicsBodyTransformation(impostor, newPosition, newRotation) {
    const body = impostor.physicsBody;
    if (impostor.physicsBody.shapes.next) {
      return;
    }
    body.position.set(newPosition.x, newPosition.y, newPosition.z);
    body.orientation.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
    body.syncShapes();
    body.awake();
  }
  setLinearVelocity(impostor, velocity) {
    impostor.physicsBody.linearVelocity.set(velocity.x, velocity.y, velocity.z);
  }
  setAngularVelocity(impostor, velocity) {
    impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);
  }
  getLinearVelocity(impostor) {
    const v = impostor.physicsBody.linearVelocity;
    if (!v) {
      return null;
    }
    return new Vector3(v.x, v.y, v.z);
  }
  getAngularVelocity(impostor) {
    const v = impostor.physicsBody.angularVelocity;
    if (!v) {
      return null;
    }
    return new Vector3(v.x, v.y, v.z);
  }
  setBodyMass(impostor, mass) {
    const staticBody = mass === 0;
    impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
    impostor.physicsBody.setupMass(staticBody ? 2 : 1);
  }
  getBodyMass(impostor) {
    return impostor.physicsBody.shapes.density;
  }
  getBodyFriction(impostor) {
    return impostor.physicsBody.shapes.friction;
  }
  setBodyFriction(impostor, friction) {
    impostor.physicsBody.shapes.friction = friction;
  }
  getBodyRestitution(impostor) {
    return impostor.physicsBody.shapes.restitution;
  }
  setBodyRestitution(impostor, restitution) {
    impostor.physicsBody.shapes.restitution = restitution;
  }
  sleepBody(impostor) {
    impostor.physicsBody.sleep();
  }
  wakeUpBody(impostor) {
    impostor.physicsBody.awake();
  }
  updateDistanceJoint(joint, maxDistance, minDistance) {
    joint.physicsJoint.limitMotor.upperLimit = maxDistance;
    if (minDistance !== undefined) {
      joint.physicsJoint.limitMotor.lowerLimit = minDistance;
    }
  }
  setMotor(joint, speed, force, motorIndex) {
    if (force !== undefined) {
      Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter");
    } else {
      force = 1e6;
    }
    speed *= -1;
    const motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
    if (motor) {
      motor.setMotor(speed, force);
    }
  }
  setLimit(joint, upperLimit, lowerLimit, motorIndex) {
    const motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
    if (motor) {
      motor.setLimit(upperLimit, lowerLimit === undefined ? -upperLimit : lowerLimit);
    }
  }
  syncMeshWithImpostor(mesh, impostor) {
    const body = impostor.physicsBody;
    mesh.position.x = body.position.x;
    mesh.position.y = body.position.y;
    mesh.position.z = body.position.z;
    if (mesh.rotationQuaternion) {
      mesh.rotationQuaternion.x = body.orientation.x;
      mesh.rotationQuaternion.y = body.orientation.y;
      mesh.rotationQuaternion.z = body.orientation.z;
      mesh.rotationQuaternion.w = body.orientation.w;
    }
  }
  getRadius(impostor) {
    return impostor.physicsBody.shapes.radius;
  }
  getBoxSizeToRef(impostor, result) {
    const shape = impostor.physicsBody.shapes;
    result.x = shape.halfWidth * 2;
    result.y = shape.halfHeight * 2;
    result.z = shape.halfDepth * 2;
  }
  dispose() {
    this.world.clear();
  }
  raycast(from, to) {
    Logger.Warn("raycast is not currently supported by the Oimo physics plugin");
    this._raycastResult.reset(from, to);
    return this._raycastResult;
  }
  raycastToRef(from, to, result) {
    Logger.Warn("raycast is not currently supported by the Oimo physics plugin");
    result.reset(from, to);
  }
}

// node_modules/@babylonjs/core/Physics/v1/Plugins/ammoJSPlugin.js
init_math_vector();
init_logger();
init_buffer();
init_math_constants();

class AmmoJSPlugin {
  constructor(_useDeltaForWorldStep = true, ammoInjection = Ammo, overlappingPairCache = null) {
    this._useDeltaForWorldStep = _useDeltaForWorldStep;
    this.bjsAMMO = {};
    this.name = "AmmoJSPlugin";
    this._timeStep = 1 / 60;
    this._fixedTimeStep = 1 / 60;
    this._maxSteps = 5;
    this._tmpQuaternion = new Quaternion;
    this._tmpContactCallbackResult = false;
    this._tmpContactPoint = new Vector3;
    this._tmpContactNormal = new Vector3;
    this._tmpVec3 = new Vector3;
    this._tmpMatrix = new Matrix;
    if (typeof ammoInjection === "function") {
      Logger.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");
      return;
    } else {
      this.bjsAMMO = ammoInjection;
    }
    if (!this.isSupported()) {
      Logger.Error("AmmoJS is not available. Please make sure you included the js file.");
      return;
    }
    this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration;
    this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);
    this._overlappingPairCache = overlappingPairCache || new this.bjsAMMO.btDbvtBroadphase;
    this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver;
    this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver;
    this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration, this._softBodySolver);
    this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback;
    this._tmpAmmoConcreteContactResultCallback.addSingleResult = (contactPoint) => {
      contactPoint = this.bjsAMMO.wrapPointer(contactPoint, this.bjsAMMO.btManifoldPoint);
      const worldPoint = contactPoint.getPositionWorldOnA();
      const worldNormal = contactPoint.m_normalWorldOnB;
      this._tmpContactPoint.x = worldPoint.x();
      this._tmpContactPoint.y = worldPoint.y();
      this._tmpContactPoint.z = worldPoint.z();
      this._tmpContactNormal.x = worldNormal.x();
      this._tmpContactNormal.y = worldNormal.y();
      this._tmpContactNormal.z = worldNormal.z();
      this._tmpContactImpulse = contactPoint.getAppliedImpulse();
      this._tmpContactDistance = contactPoint.getDistance();
      this._tmpContactCallbackResult = true;
    };
    this._raycastResult = new PhysicsRaycastResult;
    this._tmpAmmoTransform = new this.bjsAMMO.btTransform;
    this._tmpAmmoTransform.setIdentity();
    this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);
    this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);
    this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);
    this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);
    this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0, 0, 0);
  }
  getPluginVersion() {
    return 1;
  }
  setGravity(gravity) {
    this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);
    this.world.setGravity(this._tmpAmmoVectorA);
    this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA);
  }
  setTimeStep(timeStep) {
    this._timeStep = timeStep;
  }
  setFixedTimeStep(fixedTimeStep) {
    this._fixedTimeStep = fixedTimeStep;
  }
  setMaxSteps(maxSteps) {
    this._maxSteps = maxSteps;
  }
  getTimeStep() {
    return this._timeStep;
  }
  _isImpostorInContact(impostor) {
    this._tmpContactCallbackResult = false;
    this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);
    return this._tmpContactCallbackResult;
  }
  _isImpostorPairInContact(impostorA, impostorB) {
    this._tmpContactCallbackResult = false;
    this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);
    return this._tmpContactCallbackResult;
  }
  _stepSimulation(timeStep = 1 / 60, maxSteps = 10, fixedTimeStep = 1 / 60) {
    if (maxSteps == 0) {
      this.world.stepSimulation(timeStep, 0);
    } else {
      while (maxSteps > 0 && timeStep > 0) {
        if (timeStep - fixedTimeStep < fixedTimeStep) {
          this.world.stepSimulation(timeStep, 0);
          timeStep = 0;
        } else {
          timeStep -= fixedTimeStep;
          this.world.stepSimulation(fixedTimeStep, 0);
        }
        maxSteps--;
      }
    }
  }
  executeStep(delta, impostors) {
    for (const impostor of impostors) {
      if (!impostor.soft) {
        impostor.beforeStep();
      }
    }
    this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);
    for (const mainImpostor of impostors) {
      if (mainImpostor.soft) {
        this._afterSoftStep(mainImpostor);
      } else {
        mainImpostor.afterStep();
      }
      if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {
        if (this._isImpostorInContact(mainImpostor)) {
          for (const collideCallback of mainImpostor._onPhysicsCollideCallbacks) {
            for (const otherImpostor of collideCallback.otherImpostors) {
              if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {
                if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {
                  mainImpostor.onCollide({
                    body: otherImpostor.physicsBody,
                    point: this._tmpContactPoint,
                    distance: this._tmpContactDistance,
                    impulse: this._tmpContactImpulse,
                    normal: this._tmpContactNormal
                  });
                  otherImpostor.onCollide({
                    body: mainImpostor.physicsBody,
                    point: this._tmpContactPoint,
                    distance: this._tmpContactDistance,
                    impulse: this._tmpContactImpulse,
                    normal: this._tmpContactNormal
                  });
                }
              }
            }
          }
        }
      }
    }
  }
  _afterSoftStep(impostor) {
    if (impostor.type === PhysicsImpostor.RopeImpostor) {
      this._ropeStep(impostor);
    } else {
      this._softbodyOrClothStep(impostor);
    }
  }
  _ropeStep(impostor) {
    const bodyVertices = impostor.physicsBody.get_m_nodes();
    const nbVertices = bodyVertices.size();
    let node;
    let nodePositions;
    let x, y, z;
    const path = new Array;
    for (let n = 0;n < nbVertices; n++) {
      node = bodyVertices.at(n);
      nodePositions = node.get_m_x();
      x = nodePositions.x();
      y = nodePositions.y();
      z = nodePositions.z();
      path.push(new Vector3(x, y, z));
    }
    const object = impostor.object;
    const shape = impostor.getParam("shape");
    if (impostor._isFromLine) {
      impostor.object = CreateLines("lines", { points: path, instance: object });
    } else {
      impostor.object = ExtrudeShape("ext", { shape, path, instance: object });
    }
  }
  _softbodyOrClothStep(impostor) {
    const normalDirection = impostor.type === PhysicsImpostor.ClothImpostor ? 1 : -1;
    const object = impostor.object;
    let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
    if (!vertexPositions) {
      vertexPositions = [];
    }
    let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);
    if (!vertexNormals) {
      vertexNormals = [];
    }
    const nbVertices = vertexPositions.length / 3;
    const bodyVertices = impostor.physicsBody.get_m_nodes();
    let node;
    let nodePositions;
    let x, y, z;
    let nx, ny, nz;
    for (let n = 0;n < nbVertices; n++) {
      node = bodyVertices.at(n);
      nodePositions = node.get_m_x();
      x = nodePositions.x();
      y = nodePositions.y();
      z = nodePositions.z() * normalDirection;
      const nodeNormals = node.get_m_n();
      nx = nodeNormals.x();
      ny = nodeNormals.y();
      nz = nodeNormals.z() * normalDirection;
      vertexPositions[3 * n] = x;
      vertexPositions[3 * n + 1] = y;
      vertexPositions[3 * n + 2] = z;
      vertexNormals[3 * n] = nx;
      vertexNormals[3 * n + 1] = ny;
      vertexNormals[3 * n + 2] = nz;
    }
    const vertex_data = new VertexData;
    vertex_data.positions = vertexPositions;
    vertex_data.normals = vertexNormals;
    vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);
    vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);
    if (object && object.getIndices) {
      vertex_data.indices = object.getIndices();
    }
    vertex_data.applyToMesh(object);
  }
  applyImpulse(impostor, force, contactPoint) {
    if (!impostor.soft) {
      impostor.physicsBody.activate();
      const worldPoint = this._tmpAmmoVectorA;
      const impulse = this._tmpAmmoVectorB;
      if (impostor.object && impostor.object.getWorldMatrix) {
        contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation());
      }
      worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
      impulse.setValue(force.x, force.y, force.z);
      impostor.physicsBody.applyImpulse(impulse, worldPoint);
    } else {
      Logger.Warn("Cannot be applied to a soft body");
    }
  }
  applyForce(impostor, force, contactPoint) {
    if (!impostor.soft) {
      impostor.physicsBody.activate();
      const worldPoint = this._tmpAmmoVectorA;
      const impulse = this._tmpAmmoVectorB;
      if (impostor.object && impostor.object.getWorldMatrix) {
        const localTranslation = impostor.object.getWorldMatrix().getTranslation();
        worldPoint.setValue(contactPoint.x - localTranslation.x, contactPoint.y - localTranslation.y, contactPoint.z - localTranslation.z);
      } else {
        worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
      }
      impulse.setValue(force.x, force.y, force.z);
      impostor.physicsBody.applyForce(impulse, worldPoint);
    } else {
      Logger.Warn("Cannot be applied to a soft body");
    }
  }
  generatePhysicsBody(impostor) {
    impostor._pluginData.toDispose = [];
    if (impostor.parent) {
      if (impostor.physicsBody) {
        this.removePhysicsBody(impostor);
        impostor.forceUpdate();
      }
      return;
    }
    if (impostor.isBodyInitRequired()) {
      const colShape = this._createShape(impostor);
      const mass = impostor.getParam("mass");
      impostor._pluginData.mass = mass;
      if (impostor.soft) {
        colShape.get_m_cfg().set_collisions(17);
        colShape.get_m_cfg().set_kDP(impostor.getParam("damping"));
        this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam("margin"));
        colShape.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);
        this.world.addSoftBody(colShape, 1, -1);
        impostor.physicsBody = colShape;
        impostor._pluginData.toDispose.push(colShape);
        this.setBodyPressure(impostor, 0);
        if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {
          this.setBodyPressure(impostor, impostor.getParam("pressure"));
        }
        this.setBodyStiffness(impostor, impostor.getParam("stiffness"));
        this.setBodyVelocityIterations(impostor, impostor.getParam("velocityIterations"));
        this.setBodyPositionIterations(impostor, impostor.getParam("positionIterations"));
      } else {
        const localInertia = new this.bjsAMMO.btVector3(0, 0, 0);
        const startTransform = new this.bjsAMMO.btTransform;
        impostor.object.computeWorldMatrix(true);
        startTransform.setIdentity();
        if (mass !== 0) {
          colShape.calculateLocalInertia(mass, localInertia);
        }
        this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);
        this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w);
        startTransform.setOrigin(this._tmpAmmoVectorA);
        startTransform.setRotation(this._tmpAmmoQuaternion);
        const myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform);
        const rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
        const body = new this.bjsAMMO.btRigidBody(rbInfo);
        if (mass === 0) {
          body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._KINEMATIC_FLAG);
          body.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);
        }
        if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) {
          body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._DISABLE_COLLISION_FLAG);
        }
        if (impostor.type !== PhysicsImpostor.MeshImpostor && impostor.type !== PhysicsImpostor.NoImpostor) {
          const boundingInfo2 = impostor.object.getBoundingInfo();
          this._tmpVec3.copyFrom(impostor.object.getAbsolutePosition());
          this._tmpVec3.subtractInPlace(boundingInfo2.boundingBox.centerWorld);
          this._tmpVec3.x /= impostor.object.scaling.x;
          this._tmpVec3.y /= impostor.object.scaling.y;
          this._tmpVec3.z /= impostor.object.scaling.z;
          impostor.setDeltaPosition(this._tmpVec3);
        }
        const group = impostor.getParam("group");
        const mask = impostor.getParam("mask");
        if (group && mask) {
          this.world.addRigidBody(body, group, mask);
        } else {
          this.world.addRigidBody(body);
        }
        impostor.physicsBody = body;
        impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);
      }
      this.setBodyRestitution(impostor, impostor.getParam("restitution"));
      this.setBodyFriction(impostor, impostor.getParam("friction"));
    }
  }
  removePhysicsBody(impostor) {
    if (this.world) {
      if (impostor.soft) {
        this.world.removeSoftBody(impostor.physicsBody);
      } else {
        this.world.removeRigidBody(impostor.physicsBody);
      }
      if (impostor._pluginData) {
        impostor._pluginData.toDispose.forEach((d) => {
          this.bjsAMMO.destroy(d);
        });
        impostor._pluginData.toDispose = [];
      }
    }
  }
  generateJoint(impostorJoint) {
    const mainBody = impostorJoint.mainImpostor.physicsBody;
    const connectedBody = impostorJoint.connectedImpostor.physicsBody;
    if (!mainBody || !connectedBody) {
      return;
    }
    if (impostorJoint.joint.physicsJoint) {
      return;
    }
    const jointData = impostorJoint.joint.jointData;
    if (!jointData.mainPivot) {
      jointData.mainPivot = new Vector3(0, 0, 0);
    }
    if (!jointData.connectedPivot) {
      jointData.connectedPivot = new Vector3(0, 0, 0);
    }
    let joint;
    switch (impostorJoint.joint.type) {
      case PhysicsJoint.DistanceJoint: {
        const distance = jointData.maxDistance;
        if (distance) {
          jointData.mainPivot = new Vector3(0, -distance / 2, 0);
          jointData.connectedPivot = new Vector3(0, distance / 2, 0);
        }
        const mainPivot = this._tmpAmmoVectorA;
        mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z);
        const connectedPivot = this._tmpAmmoVectorB;
        connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z);
        joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot);
        break;
      }
      case PhysicsJoint.HingeJoint: {
        if (!jointData.mainAxis) {
          jointData.mainAxis = new Vector3(0, 0, 0);
        }
        if (!jointData.connectedAxis) {
          jointData.connectedAxis = new Vector3(0, 0, 0);
        }
        const mainPivot = this._tmpAmmoVectorA;
        mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z);
        const connectedPivot = this._tmpAmmoVectorB;
        connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z);
        const mainAxis = this._tmpAmmoVectorC;
        mainAxis.setValue(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);
        const connectedAxis = this._tmpAmmoVectorD;
        connectedAxis.setValue(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);
        joint = new this.bjsAMMO.btHingeConstraint(mainBody, connectedBody, mainPivot, connectedPivot, mainAxis, connectedAxis);
        break;
      }
      case PhysicsJoint.BallAndSocketJoint: {
        const mainPivot = this._tmpAmmoVectorA;
        mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z);
        const connectedPivot = this._tmpAmmoVectorB;
        connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z);
        joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot);
        break;
      }
      default: {
        Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");
        const mainPivot = this._tmpAmmoVectorA;
        mainPivot.setValue(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z);
        const connectedPivot = this._tmpAmmoVectorB;
        connectedPivot.setValue(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z);
        joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, mainPivot, connectedPivot);
        break;
      }
    }
    this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision);
    impostorJoint.joint.physicsJoint = joint;
  }
  removeJoint(impostorJoint) {
    if (this.world) {
      this.world.removeConstraint(impostorJoint.joint.physicsJoint);
    }
    this.bjsAMMO.destroy(impostorJoint.joint.physicsJoint);
  }
  _addMeshVerts(btTriangleMesh, topLevelObject, object) {
    let triangleCount = 0;
    if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
      let indices = object.getIndices();
      if (!indices) {
        indices = [];
      }
      let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
      if (!vertexPositions) {
        vertexPositions = [];
      }
      let localMatrix;
      if (topLevelObject && topLevelObject !== object) {
        let topLevelQuaternion;
        if (topLevelObject.rotationQuaternion) {
          topLevelQuaternion = topLevelObject.rotationQuaternion;
        } else if (topLevelObject.rotation) {
          topLevelQuaternion = Quaternion.FromEulerAngles(topLevelObject.rotation.x, topLevelObject.rotation.y, topLevelObject.rotation.z);
        } else {
          topLevelQuaternion = Quaternion.Identity();
        }
        const topLevelMatrix = Matrix.Compose(Vector3.One(), topLevelQuaternion, topLevelObject.position);
        topLevelMatrix.invertToRef(this._tmpMatrix);
        const wm = object.computeWorldMatrix(false);
        localMatrix = wm.multiply(this._tmpMatrix);
      } else {
        Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);
        localMatrix = this._tmpMatrix;
      }
      const faceCount = indices.length / 3;
      for (let i = 0;i < faceCount; i++) {
        const triPoints = [];
        for (let point = 0;point < 3; point++) {
          let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);
          v = Vector3.TransformCoordinates(v, localMatrix);
          let vec;
          if (point == 0) {
            vec = this._tmpAmmoVectorA;
          } else if (point == 1) {
            vec = this._tmpAmmoVectorB;
          } else {
            vec = this._tmpAmmoVectorC;
          }
          vec.setValue(v.x, v.y, v.z);
          triPoints.push(vec);
        }
        btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);
        triangleCount++;
      }
      object.getChildMeshes().forEach((m) => {
        triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);
      });
    }
    return triangleCount;
  }
  _softVertexData(impostor) {
    const object = impostor.object;
    if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
      let indices = object.getIndices();
      if (!indices) {
        indices = [];
      }
      let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
      if (!vertexPositions) {
        vertexPositions = [];
      }
      let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);
      if (!vertexNormals) {
        vertexNormals = [];
      }
      object.computeWorldMatrix(false);
      const newPoints = [];
      const newNorms = [];
      for (let i = 0;i < vertexPositions.length; i += 3) {
        let v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);
        let n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);
        v = Vector3.TransformCoordinates(v, object.getWorldMatrix());
        n = Vector3.TransformNormal(n, object.getWorldMatrix());
        newPoints.push(v.x, v.y, v.z);
        newNorms.push(n.x, n.y, n.z);
      }
      const vertex_data = new VertexData;
      vertex_data.positions = newPoints;
      vertex_data.normals = newNorms;
      vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);
      vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);
      if (object && object.getIndices) {
        vertex_data.indices = object.getIndices();
      }
      vertex_data.applyToMesh(object);
      object.position = Vector3.Zero();
      object.rotationQuaternion = null;
      object.rotation = Vector3.Zero();
      object.computeWorldMatrix(true);
      return vertex_data;
    }
    return VertexData.ExtractFromMesh(object);
  }
  _createSoftbody(impostor) {
    const object = impostor.object;
    if (object && object.getIndices) {
      let indices = object.getIndices();
      if (!indices) {
        indices = [];
      }
      const vertex_data = this._softVertexData(impostor);
      const vertexPositions = vertex_data.positions;
      const vertexNormals = vertex_data.normals;
      if (vertexPositions === null || vertexNormals === null) {
        return new this.bjsAMMO.btCompoundShape;
      } else {
        const triPoints = [];
        const triNorms = [];
        for (let i = 0;i < vertexPositions.length; i += 3) {
          const v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);
          const n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);
          triPoints.push(v.x, v.y, -v.z);
          triNorms.push(n.x, n.y, -n.z);
        }
        const softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), triPoints, object.getIndices(), indices.length / 3, true);
        const nbVertices = vertexPositions.length / 3;
        const bodyVertices = softBody.get_m_nodes();
        let node;
        let nodeNormals;
        for (let i = 0;i < nbVertices; i++) {
          node = bodyVertices.at(i);
          nodeNormals = node.get_m_n();
          nodeNormals.setX(triNorms[3 * i]);
          nodeNormals.setY(triNorms[3 * i + 1]);
          nodeNormals.setZ(triNorms[3 * i + 2]);
        }
        return softBody;
      }
    }
  }
  _createCloth(impostor) {
    const object = impostor.object;
    if (object && object.getIndices) {
      let indices = object.getIndices();
      if (!indices) {
        indices = [];
      }
      const vertex_data = this._softVertexData(impostor);
      const vertexPositions = vertex_data.positions;
      const vertexNormals = vertex_data.normals;
      if (vertexPositions === null || vertexNormals === null) {
        return new this.bjsAMMO.btCompoundShape;
      } else {
        const len = vertexPositions.length;
        const segments = Math.sqrt(len / 3);
        impostor.segments = segments;
        const segs = segments - 1;
        this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);
        this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]);
        this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);
        this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]);
        const clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, segments, segments, impostor.getParam("fixedPoints"), true);
        return clothBody;
      }
    }
  }
  _createRope(impostor) {
    let len;
    let segments;
    const vertex_data = this._softVertexData(impostor);
    const vertexPositions = vertex_data.positions;
    const vertexNormals = vertex_data.normals;
    if (vertexPositions === null || vertexNormals === null) {
      return new this.bjsAMMO.btCompoundShape;
    }
    vertex_data.applyToMesh(impostor.object, true);
    impostor._isFromLine = true;
    const vertexSquared = vertexNormals.map((x) => x * x);
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    const reduced = vertexSquared.reduce(reducer);
    if (reduced === 0) {
      len = vertexPositions.length;
      segments = len / 3 - 1;
      this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);
      this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);
    } else {
      impostor._isFromLine = false;
      const pathVectors = impostor.getParam("path");
      const shape = impostor.getParam("shape");
      if (shape === null) {
        Logger.Warn("No shape available for extruded mesh");
        return new this.bjsAMMO.btCompoundShape;
      }
      len = pathVectors.length;
      segments = len - 1;
      this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z);
      this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z);
    }
    impostor.segments = segments;
    let fixedPoints = impostor.getParam("fixedPoints");
    fixedPoints = fixedPoints > 3 ? 3 : fixedPoints;
    const ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, segments - 1, fixedPoints);
    ropeBody.get_m_cfg().set_collisions(17);
    return ropeBody;
  }
  _createCustom(impostor) {
    let returnValue = null;
    if (this.onCreateCustomShape) {
      returnValue = this.onCreateCustomShape(impostor);
    }
    if (returnValue == null) {
      returnValue = new this.bjsAMMO.btCompoundShape;
    }
    return returnValue;
  }
  _addHullVerts(btConvexHullShape, topLevelObject, object) {
    let triangleCount = 0;
    if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
      let indices = object.getIndices();
      if (!indices) {
        indices = [];
      }
      let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
      if (!vertexPositions) {
        vertexPositions = [];
      }
      object.computeWorldMatrix(false);
      const faceCount = indices.length / 3;
      for (let i = 0;i < faceCount; i++) {
        const triPoints = [];
        for (let point = 0;point < 3; point++) {
          let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);
          Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);
          v = Vector3.TransformCoordinates(v, this._tmpMatrix);
          let vec;
          if (point == 0) {
            vec = this._tmpAmmoVectorA;
          } else if (point == 1) {
            vec = this._tmpAmmoVectorB;
          } else {
            vec = this._tmpAmmoVectorC;
          }
          vec.setValue(v.x, v.y, v.z);
          triPoints.push(vec);
        }
        btConvexHullShape.addPoint(triPoints[0], true);
        btConvexHullShape.addPoint(triPoints[1], true);
        btConvexHullShape.addPoint(triPoints[2], true);
        triangleCount++;
      }
      object.getChildMeshes().forEach((m) => {
        triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m);
      });
    }
    return triangleCount;
  }
  _createShape(impostor, ignoreChildren = false) {
    const object = impostor.object;
    let returnValue;
    const impostorExtents = impostor.getObjectExtents();
    if (!ignoreChildren) {
      const meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];
      returnValue = new this.bjsAMMO.btCompoundShape;
      let childrenAdded = 0;
      meshChildren.forEach((childMesh) => {
        const childImpostor = childMesh.getPhysicsImpostor();
        if (childImpostor) {
          if (childImpostor.type == PhysicsImpostor.MeshImpostor) {
            throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";
          }
          const shape = this._createShape(childImpostor);
          const parentMat = childMesh.parent.getWorldMatrix().clone();
          const s = new Vector3;
          parentMat.decompose(s);
          this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);
          this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w);
          this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
          returnValue.addChildShape(this._tmpAmmoTransform, shape);
          childImpostor.dispose();
          childrenAdded++;
        }
      });
      if (childrenAdded > 0) {
        if (impostor.type != PhysicsImpostor.NoImpostor) {
          const shape = this._createShape(impostor, true);
          if (shape) {
            this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
            this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
            this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
            returnValue.addChildShape(this._tmpAmmoTransform, shape);
          }
        }
        return returnValue;
      } else {
        this.bjsAMMO.destroy(returnValue);
        returnValue = null;
      }
    }
    switch (impostor.type) {
      case PhysicsImpostor.SphereImpostor:
        if (WithinEpsilon(impostorExtents.x, impostorExtents.y, 0.0001) && WithinEpsilon(impostorExtents.x, impostorExtents.z, 0.0001)) {
          returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);
        } else {
          this._tmpAmmoVectorA.setValue(0, 0, 0);
          const positions = [this._tmpAmmoVectorA];
          const radii = [1];
          returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1);
          this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);
          returnValue.setLocalScaling(this._tmpAmmoVectorA);
        }
        break;
      case PhysicsImpostor.CapsuleImpostor:
        {
          const capRadius = impostorExtents.x / 2;
          returnValue = new this.bjsAMMO.btCapsuleShape(capRadius, impostorExtents.y - capRadius * 2);
        }
        break;
      case PhysicsImpostor.CylinderImpostor:
        this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);
        returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);
        break;
      case PhysicsImpostor.PlaneImpostor:
      case PhysicsImpostor.BoxImpostor:
        this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);
        returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);
        break;
      case PhysicsImpostor.MeshImpostor: {
        if (impostor.getParam("mass") == 0) {
          if (this.onCreateCustomMeshImpostor) {
            returnValue = this.onCreateCustomMeshImpostor(impostor);
          } else {
            const triMesh = new this.bjsAMMO.btTriangleMesh;
            impostor._pluginData.toDispose.push(triMesh);
            const triangleCount = this._addMeshVerts(triMesh, object, object);
            if (triangleCount == 0) {
              returnValue = new this.bjsAMMO.btCompoundShape;
            } else {
              returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(triMesh);
            }
          }
          break;
        }
      }
      case PhysicsImpostor.ConvexHullImpostor: {
        if (this.onCreateCustomConvexHullImpostor) {
          returnValue = this.onCreateCustomConvexHullImpostor(impostor);
        } else {
          const convexHull = new this.bjsAMMO.btConvexHullShape;
          const triangleCount = this._addHullVerts(convexHull, object, object);
          if (triangleCount == 0) {
            impostor._pluginData.toDispose.push(convexHull);
            returnValue = new this.bjsAMMO.btCompoundShape;
          } else {
            returnValue = convexHull;
          }
        }
        break;
      }
      case PhysicsImpostor.NoImpostor:
        returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);
        break;
      case PhysicsImpostor.CustomImpostor:
        returnValue = this._createCustom(impostor);
        break;
      case PhysicsImpostor.SoftbodyImpostor:
        returnValue = this._createSoftbody(impostor);
        break;
      case PhysicsImpostor.ClothImpostor:
        returnValue = this._createCloth(impostor);
        break;
      case PhysicsImpostor.RopeImpostor:
        returnValue = this._createRope(impostor);
        break;
      default:
        Logger.Warn("The impostor type is not currently supported by the ammo plugin.");
        break;
    }
    return returnValue;
  }
  setTransformationFromPhysicsBody(impostor) {
    impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
    impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
    if (!impostor.object.rotationQuaternion) {
      if (impostor.object.rotation) {
        this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
        this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
      }
    } else {
      impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
    }
  }
  setPhysicsBodyTransformation(impostor, newPosition, newRotation) {
    const trans = impostor.physicsBody.getWorldTransform();
    if (Math.abs(trans.getOrigin().x() - newPosition.x) > Epsilon || Math.abs(trans.getOrigin().y() - newPosition.y) > Epsilon || Math.abs(trans.getOrigin().z() - newPosition.z) > Epsilon || Math.abs(trans.getRotation().x() - newRotation.x) > Epsilon || Math.abs(trans.getRotation().y() - newRotation.y) > Epsilon || Math.abs(trans.getRotation().z() - newRotation.z) > Epsilon || Math.abs(trans.getRotation().w() - newRotation.w) > Epsilon) {
      this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
      trans.setOrigin(this._tmpAmmoVectorA);
      this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
      trans.setRotation(this._tmpAmmoQuaternion);
      impostor.physicsBody.setWorldTransform(trans);
      if (impostor.mass == 0) {
        const motionState = impostor.physicsBody.getMotionState();
        if (motionState) {
          motionState.setWorldTransform(trans);
        }
      } else {
        impostor.physicsBody.activate();
      }
    }
  }
  isSupported() {
    return this.bjsAMMO !== undefined;
  }
  setLinearVelocity(impostor, velocity) {
    this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
    if (impostor.soft) {
      impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA);
    } else {
      impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
    }
  }
  setAngularVelocity(impostor, velocity) {
    this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
    if (impostor.soft) {
      impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA);
    } else {
      impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
    }
  }
  getLinearVelocity(impostor) {
    let v;
    if (impostor.soft) {
      v = impostor.physicsBody.linearVelocity();
    } else {
      v = impostor.physicsBody.getLinearVelocity();
    }
    if (!v) {
      return null;
    }
    const result = new Vector3(v.x(), v.y(), v.z());
    this.bjsAMMO.destroy(v);
    return result;
  }
  getAngularVelocity(impostor) {
    let v;
    if (impostor.soft) {
      v = impostor.physicsBody.angularVelocity();
    } else {
      v = impostor.physicsBody.getAngularVelocity();
    }
    if (!v) {
      return null;
    }
    const result = new Vector3(v.x(), v.y(), v.z());
    this.bjsAMMO.destroy(v);
    return result;
  }
  setBodyMass(impostor, mass) {
    if (impostor.soft) {
      impostor.physicsBody.setTotalMass(mass, false);
    } else {
      impostor.physicsBody.setMassProps(mass);
    }
    impostor._pluginData.mass = mass;
  }
  getBodyMass(impostor) {
    return impostor._pluginData.mass || 0;
  }
  getBodyFriction(impostor) {
    return impostor._pluginData.friction || 0;
  }
  setBodyFriction(impostor, friction) {
    if (impostor.soft) {
      impostor.physicsBody.get_m_cfg().set_kDF(friction);
    } else {
      impostor.physicsBody.setFriction(friction);
    }
    impostor._pluginData.friction = friction;
  }
  getBodyRestitution(impostor) {
    return impostor._pluginData.restitution || 0;
  }
  setBodyRestitution(impostor, restitution) {
    impostor.physicsBody.setRestitution(restitution);
    impostor._pluginData.restitution = restitution;
  }
  getBodyPressure(impostor) {
    if (!impostor.soft) {
      Logger.Warn("Pressure is not a property of a rigid body");
      return 0;
    }
    return impostor._pluginData.pressure || 0;
  }
  setBodyPressure(impostor, pressure) {
    if (impostor.soft) {
      if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {
        impostor.physicsBody.get_m_cfg().set_kPR(pressure);
        impostor._pluginData.pressure = pressure;
      } else {
        impostor.physicsBody.get_m_cfg().set_kPR(0);
        impostor._pluginData.pressure = 0;
      }
    } else {
      Logger.Warn("Pressure can only be applied to a softbody");
    }
  }
  getBodyStiffness(impostor) {
    if (!impostor.soft) {
      Logger.Warn("Stiffness is not a property of a rigid body");
      return 0;
    }
    return impostor._pluginData.stiffness || 0;
  }
  setBodyStiffness(impostor, stiffness) {
    if (impostor.soft) {
      stiffness = stiffness < 0 ? 0 : stiffness;
      stiffness = stiffness > 1 ? 1 : stiffness;
      impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness);
      impostor._pluginData.stiffness = stiffness;
    } else {
      Logger.Warn("Stiffness cannot be applied to a rigid body");
    }
  }
  getBodyVelocityIterations(impostor) {
    if (!impostor.soft) {
      Logger.Warn("Velocity iterations is not a property of a rigid body");
      return 0;
    }
    return impostor._pluginData.velocityIterations || 0;
  }
  setBodyVelocityIterations(impostor, velocityIterations) {
    if (impostor.soft) {
      velocityIterations = velocityIterations < 0 ? 0 : velocityIterations;
      impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations);
      impostor._pluginData.velocityIterations = velocityIterations;
    } else {
      Logger.Warn("Velocity iterations cannot be applied to a rigid body");
    }
  }
  getBodyPositionIterations(impostor) {
    if (!impostor.soft) {
      Logger.Warn("Position iterations is not a property of a rigid body");
      return 0;
    }
    return impostor._pluginData.positionIterations || 0;
  }
  setBodyPositionIterations(impostor, positionIterations) {
    if (impostor.soft) {
      positionIterations = positionIterations < 0 ? 0 : positionIterations;
      impostor.physicsBody.get_m_cfg().set_piterations(positionIterations);
      impostor._pluginData.positionIterations = positionIterations;
    } else {
      Logger.Warn("Position iterations cannot be applied to a rigid body");
    }
  }
  appendAnchor(impostor, otherImpostor, width, height, influence = 1, noCollisionBetweenLinkedBodies = false) {
    const segs = impostor.segments;
    const nbAcross = Math.round((segs - 1) * width);
    const nbUp = Math.round((segs - 1) * height);
    const nbDown = segs - 1 - nbUp;
    const node = nbAcross + segs * nbDown;
    impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);
  }
  appendHook(impostor, otherImpostor, length, influence = 1, noCollisionBetweenLinkedBodies = false) {
    const node = Math.round(impostor.segments * length);
    impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);
  }
  sleepBody(impostor) {
    impostor.physicsBody.forceActivationState(0);
  }
  wakeUpBody(impostor) {
    impostor.physicsBody.activate();
  }
  updateDistanceJoint() {
    Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  }
  setMotor(joint, speed, maxForce) {
    joint.physicsJoint.enableAngularMotor(true, speed, maxForce);
  }
  setLimit() {
    Logger.Warn("setLimit is not currently supported by the Ammo physics plugin");
  }
  syncMeshWithImpostor(mesh, impostor) {
    const body = impostor.physicsBody;
    body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
    mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
    mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
    mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
    if (mesh.rotationQuaternion) {
      mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
      mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
      mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
      mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
    }
  }
  getRadius(impostor) {
    const extents = impostor.getObjectExtents();
    return extents.x / 2;
  }
  getBoxSizeToRef(impostor, result) {
    const extents = impostor.getObjectExtents();
    result.x = extents.x;
    result.y = extents.y;
    result.z = extents.z;
  }
  dispose() {
    this.bjsAMMO.destroy(this.world);
    this.bjsAMMO.destroy(this._softBodySolver);
    this.bjsAMMO.destroy(this._solver);
    this.bjsAMMO.destroy(this._overlappingPairCache);
    this.bjsAMMO.destroy(this._dispatcher);
    this.bjsAMMO.destroy(this._collisionConfiguration);
    this.bjsAMMO.destroy(this._tmpAmmoVectorA);
    this.bjsAMMO.destroy(this._tmpAmmoVectorB);
    this.bjsAMMO.destroy(this._tmpAmmoVectorC);
    this.bjsAMMO.destroy(this._tmpAmmoVectorD);
    this.bjsAMMO.destroy(this._tmpAmmoTransform);
    this.bjsAMMO.destroy(this._tmpAmmoQuaternion);
    this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback);
    this.world = null;
  }
  raycast(from, to) {
    this.raycastToRef(from, to, this._raycastResult);
    return this._raycastResult;
  }
  raycastToRef(from, to, result) {
    this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z);
    this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z);
    const rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB);
    this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback);
    result.reset(from, to);
    if (rayCallback.hasHit()) {
      result.setHitData({
        x: rayCallback.get_m_hitNormalWorld().x(),
        y: rayCallback.get_m_hitNormalWorld().y(),
        z: rayCallback.get_m_hitNormalWorld().z()
      }, {
        x: rayCallback.get_m_hitPointWorld().x(),
        y: rayCallback.get_m_hitPointWorld().y(),
        z: rayCallback.get_m_hitPointWorld().z()
      });
      result.calculateHitDistance();
    }
    this.bjsAMMO.destroy(rayCallback);
    this.bjsAMMO.destroy(this._tmpAmmoVectorRCA);
    this.bjsAMMO.destroy(this._tmpAmmoVectorRCB);
  }
}
AmmoJSPlugin._DISABLE_COLLISION_FLAG = 4;
AmmoJSPlugin._KINEMATIC_FLAG = 2;
AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG = 4;

// node_modules/@babylonjs/core/Probes/reflectionProbe.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_renderTargetTexture();
init_math_vector();
init_scene();
Scene.prototype.removeReflectionProbe = function(toRemove) {
  if (!this.reflectionProbes) {
    return -1;
  }
  const index = this.reflectionProbes.indexOf(toRemove);
  if (index !== -1) {
    this.reflectionProbes.splice(index, 1);
  }
  return index;
};
Scene.prototype.addReflectionProbe = function(newReflectionProbe) {
  if (!this.reflectionProbes) {
    this.reflectionProbes = [];
  }
  this.reflectionProbes.push(newReflectionProbe);
};

class ReflectionProbe {
  constructor(name353, size, scene, generateMipMaps = true, useFloat = false, linearSpace = false) {
    this.name = name353;
    this._viewMatrix = Matrix.Identity();
    this._target = Vector3.Zero();
    this._add = Vector3.Zero();
    this._invertYAxis = false;
    this.position = Vector3.Zero();
    this.metadata = null;
    this._parentContainer = null;
    this._scene = scene;
    if (scene.getEngine().supportsUniformBuffers) {
      this._sceneUBOs = [];
      for (let i = 0;i < 6; ++i) {
        this._sceneUBOs.push(scene.createSceneUniformBuffer(`Scene for Reflection Probe (name "${name353}") face #${i}`));
      }
    }
    if (!this._scene.reflectionProbes) {
      this._scene.reflectionProbes = [];
    }
    this._scene.reflectionProbes.push(this);
    let textureType = 0;
    if (useFloat) {
      const caps = this._scene.getEngine().getCaps();
      if (caps.textureHalfFloatRender) {
        textureType = 2;
      } else if (caps.textureFloatRender) {
        textureType = 1;
      }
    }
    this._renderTargetTexture = new RenderTargetTexture(name353, size, scene, generateMipMaps, true, textureType, true);
    this._renderTargetTexture.gammaSpace = !linearSpace;
    this._renderTargetTexture.invertZ = scene.useRightHandedSystem;
    const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;
    this._renderTargetTexture.onBeforeRenderObservable.add((faceIndex) => {
      if (this._sceneUBOs) {
        scene.setSceneUniformBuffer(this._sceneUBOs[faceIndex]);
        scene.getSceneUniformBuffer().unbindEffect();
      }
      switch (faceIndex) {
        case 0:
          this._add.copyFromFloats(1, 0, 0);
          break;
        case 1:
          this._add.copyFromFloats(-1, 0, 0);
          break;
        case 2:
          this._add.copyFromFloats(0, this._invertYAxis ? 1 : -1, 0);
          break;
        case 3:
          this._add.copyFromFloats(0, this._invertYAxis ? -1 : 1, 0);
          break;
        case 4:
          this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? -1 : 1);
          break;
        case 5:
          this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? 1 : -1);
          break;
      }
      if (this._attachedMesh) {
        this.position.copyFrom(this._attachedMesh.getAbsolutePosition());
      }
      this.position.addToRef(this._add, this._target);
      const lookAtFunction = scene.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef;
      const perspectiveFunction = scene.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH;
      lookAtFunction(this.position, this._target, Vector3.Up(), this._viewMatrix);
      if (scene.activeCamera) {
        this._projectionMatrix = perspectiveFunction(Math.PI / 2, 1, useReverseDepthBuffer ? scene.activeCamera.maxZ : scene.activeCamera.minZ, useReverseDepthBuffer ? scene.activeCamera.minZ : scene.activeCamera.maxZ, this._scene.getEngine().isNDCHalfZRange);
        scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);
        if (scene.activeCamera.isRigCamera && !this._renderTargetTexture.activeCamera) {
          this._renderTargetTexture.activeCamera = scene.activeCamera.rigParent || null;
        }
      }
      scene._forcedViewPosition = this.position;
    });
    let currentApplyByPostProcess;
    this._renderTargetTexture.onBeforeBindObservable.add(() => {
      this._currentSceneUBO = scene.getSceneUniformBuffer();
      scene.getEngine()._debugPushGroup?.(`reflection probe generation for ${name353}`, 1);
      currentApplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess;
      if (linearSpace) {
        scene.imageProcessingConfiguration.applyByPostProcess = true;
      }
    });
    this._renderTargetTexture.onAfterUnbindObservable.add(() => {
      scene.imageProcessingConfiguration.applyByPostProcess = currentApplyByPostProcess;
      scene._forcedViewPosition = null;
      if (this._sceneUBOs) {
        scene.setSceneUniformBuffer(this._currentSceneUBO);
      }
      scene.updateTransformMatrix(true);
      scene.getEngine()._debugPopGroup?.(1);
    });
  }
  get samples() {
    return this._renderTargetTexture.samples;
  }
  set samples(value) {
    this._renderTargetTexture.samples = value;
  }
  get refreshRate() {
    return this._renderTargetTexture.refreshRate;
  }
  set refreshRate(value) {
    this._renderTargetTexture.refreshRate = value;
  }
  getScene() {
    return this._scene;
  }
  get cubeTexture() {
    return this._renderTargetTexture;
  }
  get renderList() {
    return this._renderTargetTexture.renderList;
  }
  set renderList(value) {
    this._renderTargetTexture.renderList = value;
  }
  attachToMesh(mesh) {
    this._attachedMesh = mesh;
  }
  setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {
    this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  }
  dispose() {
    const index = this._scene.reflectionProbes.indexOf(this);
    if (index !== -1) {
      this._scene.reflectionProbes.splice(index, 1);
    }
    if (this._parentContainer) {
      const index2 = this._parentContainer.reflectionProbes.indexOf(this);
      if (index2 > -1) {
        this._parentContainer.reflectionProbes.splice(index2, 1);
      }
      this._parentContainer = null;
    }
    if (this._renderTargetTexture) {
      this._renderTargetTexture.dispose();
      this._renderTargetTexture = null;
    }
    if (this._sceneUBOs) {
      for (const ubo of this._sceneUBOs) {
        ubo.dispose();
      }
      this._sceneUBOs = [];
    }
  }
  toString(fullDetails) {
    let ret = "Name: " + this.name;
    if (fullDetails) {
      ret += ", position: " + this.position.toString();
      if (this._attachedMesh) {
        ret += ", attached mesh: " + this._attachedMesh.name;
      }
    }
    return ret;
  }
  getClassName() {
    return "ReflectionProbe";
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());
    serializationObject.isReflectionProbe = true;
    serializationObject.metadata = this.metadata;
    return serializationObject;
  }
  static Parse(parsedReflectionProbe, scene, rootUrl) {
    let reflectionProbe = null;
    if (scene.reflectionProbes) {
      for (let index = 0;index < scene.reflectionProbes.length; index++) {
        const rp = scene.reflectionProbes[index];
        if (rp.name === parsedReflectionProbe.name) {
          reflectionProbe = rp;
          break;
        }
      }
    }
    reflectionProbe = SerializationHelper.Parse(() => reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps), parsedReflectionProbe, scene, rootUrl);
    reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList;
    if (parsedReflectionProbe._attachedMesh) {
      reflectionProbe.attachToMesh(scene.getMeshById(parsedReflectionProbe._attachedMesh));
    }
    if (parsedReflectionProbe.metadata) {
      reflectionProbe.metadata = parsedReflectionProbe.metadata;
    }
    return reflectionProbe;
  }
}
__decorate([
  serializeAsMeshReference()
], ReflectionProbe.prototype, "_attachedMesh", undefined);
__decorate([
  serializeAsVector3()
], ReflectionProbe.prototype, "position", undefined);

// node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js
init_typeStore();
init_tools();
init_postProcess();

// node_modules/@babylonjs/core/Sprites/spriteManager.js
init_observable();
init_math_vector();

// node_modules/@babylonjs/core/Sprites/sprite.js
init_math_vector();
init_math_color();
init_observable();

// node_modules/@babylonjs/core/Sprites/thinSprite.js
class ThinSprite {
  get animationStarted() {
    return this._animationStarted;
  }
  get fromIndex() {
    return this._fromIndex;
  }
  get toIndex() {
    return this._toIndex;
  }
  get loopAnimation() {
    return this._loopAnimation;
  }
  get delay() {
    return Math.max(this._delay, 1);
  }
  constructor() {
    this.width = 1;
    this.height = 1;
    this.angle = 0;
    this.invertU = false;
    this.invertV = false;
    this.isVisible = true;
    this._animationStarted = false;
    this._loopAnimation = false;
    this._fromIndex = 0;
    this._toIndex = 0;
    this._delay = 0;
    this._direction = 1;
    this._time = 0;
    this._onBaseAnimationEnd = null;
    this.position = { x: 1, y: 1, z: 1 };
    this.color = { r: 1, g: 1, b: 1, a: 1 };
  }
  playAnimation(from, to, loop, delay, onAnimationEnd) {
    this._fromIndex = from;
    this._toIndex = to;
    this._loopAnimation = loop;
    this._delay = delay || 1;
    this._animationStarted = true;
    this._onBaseAnimationEnd = onAnimationEnd;
    if (from < to) {
      this._direction = 1;
    } else {
      this._direction = -1;
      this._toIndex = from;
      this._fromIndex = to;
    }
    this.cellIndex = from;
    this._time = 0;
  }
  stopAnimation() {
    this._animationStarted = false;
  }
  _animate(deltaTime) {
    if (!this._animationStarted) {
      return;
    }
    this._time += deltaTime;
    if (this._time > this._delay) {
      this._time = this._time % this._delay;
      this.cellIndex += this._direction;
      if (this._direction > 0 && this.cellIndex > this._toIndex || this._direction < 0 && this.cellIndex < this._fromIndex) {
        if (this._loopAnimation) {
          this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;
        } else {
          this.cellIndex = this._toIndex;
          this._animationStarted = false;
          if (this._onBaseAnimationEnd) {
            this._onBaseAnimationEnd();
          }
        }
      }
    }
  }
}

// node_modules/@babylonjs/core/Sprites/sprite.js
class Sprite extends ThinSprite {
  get size() {
    return this.width;
  }
  set size(value) {
    this.width = value;
    this.height = value;
  }
  get manager() {
    return this._manager;
  }
  constructor(name353, manager) {
    super();
    this.name = name353;
    this.animations = new Array;
    this.isPickable = false;
    this.useAlphaForPicking = false;
    this.onDisposeObservable = new Observable;
    this._onAnimationEnd = null;
    this._endAnimation = () => {
      if (this._onAnimationEnd) {
        this._onAnimationEnd();
      }
      if (this.disposeWhenFinishedAnimating) {
        this.dispose();
      }
    };
    this.color = new Color4(1, 1, 1, 1);
    this.position = Vector3.Zero();
    this._manager = manager;
    this._manager.sprites.push(this);
    this.uniqueId = this._manager.scene.getUniqueId();
  }
  getClassName() {
    return "Sprite";
  }
  get fromIndex() {
    return this._fromIndex;
  }
  set fromIndex(value) {
    this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd);
  }
  get toIndex() {
    return this._toIndex;
  }
  set toIndex(value) {
    this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd);
  }
  get loopAnimation() {
    return this._loopAnimation;
  }
  set loopAnimation(value) {
    this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd);
  }
  get delay() {
    return Math.max(this._delay, 1);
  }
  set delay(value) {
    this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd);
  }
  playAnimation(from, to, loop, delay, onAnimationEnd = null) {
    this._onAnimationEnd = onAnimationEnd;
    super.playAnimation(from, to, loop, delay, this._endAnimation);
  }
  dispose() {
    for (let i = 0;i < this._manager.sprites.length; i++) {
      if (this._manager.sprites[i] == this) {
        this._manager.sprites.splice(i, 1);
      }
    }
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
  }
  serialize() {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.position = this.position.asArray();
    serializationObject.color = this.color.asArray();
    serializationObject.width = this.width;
    serializationObject.height = this.height;
    serializationObject.angle = this.angle;
    serializationObject.cellIndex = this.cellIndex;
    serializationObject.cellRef = this.cellRef;
    serializationObject.invertU = this.invertU;
    serializationObject.invertV = this.invertV;
    serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating;
    serializationObject.isPickable = this.isPickable;
    serializationObject.isVisible = this.isVisible;
    serializationObject.useAlphaForPicking = this.useAlphaForPicking;
    serializationObject.animationStarted = this.animationStarted;
    serializationObject.fromIndex = this.fromIndex;
    serializationObject.toIndex = this.toIndex;
    serializationObject.loopAnimation = this.loopAnimation;
    serializationObject.delay = this.delay;
    return serializationObject;
  }
  static Parse(parsedSprite, manager) {
    const sprite = new Sprite(parsedSprite.name, manager);
    sprite.position = Vector3.FromArray(parsedSprite.position);
    sprite.color = Color4.FromArray(parsedSprite.color);
    sprite.width = parsedSprite.width;
    sprite.height = parsedSprite.height;
    sprite.angle = parsedSprite.angle;
    sprite.cellIndex = parsedSprite.cellIndex;
    sprite.cellRef = parsedSprite.cellRef;
    sprite.invertU = parsedSprite.invertU;
    sprite.invertV = parsedSprite.invertV;
    sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating;
    sprite.isPickable = parsedSprite.isPickable;
    sprite.isVisible = parsedSprite.isVisible;
    sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking;
    sprite._fromIndex = parsedSprite.fromIndex;
    sprite._toIndex = parsedSprite.toIndex;
    sprite._loopAnimation = parsedSprite.loopAnimation;
    sprite._delay = parsedSprite.delay;
    if (parsedSprite.animationStarted) {
      sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay);
    }
    return sprite;
  }
}

// node_modules/@babylonjs/core/Sprites/spriteSceneComponent.js
init_observable();
init_scene();
init_pickingInfo();
init_sceneComponent();
Scene.prototype._internalPickSprites = function(ray2, predicate, fastCheck, camera2) {
  if (!PickingInfo) {
    return null;
  }
  let pickingInfo2 = null;
  if (!camera2) {
    if (!this.activeCamera) {
      return null;
    }
    camera2 = this.activeCamera;
  }
  if (this.spriteManagers && this.spriteManagers.length > 0) {
    for (let spriteIndex = 0;spriteIndex < this.spriteManagers.length; spriteIndex++) {
      const spriteManager = this.spriteManagers[spriteIndex];
      if (!spriteManager.isPickable) {
        continue;
      }
      const result = spriteManager.intersects(ray2, camera2, predicate, fastCheck);
      if (!result || !result.hit) {
        continue;
      }
      if (!fastCheck && pickingInfo2 != null && result.distance >= pickingInfo2.distance) {
        continue;
      }
      pickingInfo2 = result;
      if (fastCheck) {
        break;
      }
    }
  }
  return pickingInfo2 || new PickingInfo;
};
Scene.prototype._internalMultiPickSprites = function(ray2, predicate, camera2) {
  if (!PickingInfo) {
    return null;
  }
  let pickingInfos = [];
  if (!camera2) {
    if (!this.activeCamera) {
      return null;
    }
    camera2 = this.activeCamera;
  }
  if (this.spriteManagers && this.spriteManagers.length > 0) {
    for (let spriteIndex = 0;spriteIndex < this.spriteManagers.length; spriteIndex++) {
      const spriteManager = this.spriteManagers[spriteIndex];
      if (!spriteManager.isPickable) {
        continue;
      }
      const results = spriteManager.multiIntersects(ray2, camera2, predicate);
      if (results !== null) {
        pickingInfos = pickingInfos.concat(results);
      }
    }
  }
  return pickingInfos;
};
Scene.prototype.pickSprite = function(x, y, predicate, fastCheck, camera2) {
  if (!this._tempSpritePickingRay) {
    return null;
  }
  CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera2);
  const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera2);
  if (result) {
    result.ray = CreatePickingRayInCameraSpace(this, x, y, camera2);
  }
  return result;
};
Scene.prototype.pickSpriteWithRay = function(ray2, predicate, fastCheck, camera2) {
  if (!this._tempSpritePickingRay) {
    return null;
  }
  if (!camera2) {
    if (!this.activeCamera) {
      return null;
    }
    camera2 = this.activeCamera;
  }
  Ray.TransformToRef(ray2, camera2.getViewMatrix(), this._tempSpritePickingRay);
  const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera2);
  if (result) {
    result.ray = ray2;
  }
  return result;
};
Scene.prototype.multiPickSprite = function(x, y, predicate, camera2) {
  CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera2);
  return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera2);
};
Scene.prototype.multiPickSpriteWithRay = function(ray2, predicate, camera2) {
  if (!this._tempSpritePickingRay) {
    return null;
  }
  if (!camera2) {
    if (!this.activeCamera) {
      return null;
    }
    camera2 = this.activeCamera;
  }
  Ray.TransformToRef(ray2, camera2.getViewMatrix(), this._tempSpritePickingRay);
  return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera2);
};
Scene.prototype.setPointerOverSprite = function(sprite) {
  if (this._pointerOverSprite === sprite) {
    return;
  }
  if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
    this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  }
  this._pointerOverSprite = sprite;
  if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
    this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  }
};
Scene.prototype.getPointerOverSprite = function() {
  return this._pointerOverSprite;
};

class SpriteSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_SPRITE;
    this.scene = scene;
    this.scene.spriteManagers = [];
    this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null;
    this.scene.onBeforeSpritesRenderingObservable = new Observable;
    this.scene.onAfterSpritesRenderingObservable = new Observable;
    this._spritePredicate = (sprite) => {
      if (!sprite.actionManager) {
        return false;
      }
      return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
    };
  }
  register() {
    this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
    this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
    this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  }
  rebuild() {}
  dispose() {
    this.scene.onBeforeSpritesRenderingObservable.clear();
    this.scene.onAfterSpritesRenderingObservable.clear();
    const spriteManagers = this.scene.spriteManagers;
    if (!spriteManagers) {
      return;
    }
    while (spriteManagers.length) {
      spriteManagers[0].dispose();
    }
  }
  _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera2) {
    const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera2);
    if (result) {
      result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
    }
    return result;
  }
  _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) {
    const scene = this.scene;
    if (isMeshPicked) {
      scene.setPointerOverSprite(null);
    } else {
      pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
      if (pickResult && pickResult.hit && pickResult.pickedSprite) {
        scene.setPointerOverSprite(pickResult.pickedSprite);
        if (!scene.doNotHandleCursors && element) {
          if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
            element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
          } else {
            element.style.cursor = scene.hoverCursor;
          }
        }
      } else {
        scene.setPointerOverSprite(null);
      }
    }
    return pickResult;
  }
  _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
    const scene = this.scene;
    scene._pickedDownSprite = null;
    if (scene.spriteManagers && scene.spriteManagers.length > 0) {
      pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
      if (pickResult && pickResult.hit && pickResult.pickedSprite) {
        if (pickResult.pickedSprite.actionManager) {
          scene._pickedDownSprite = pickResult.pickedSprite;
          switch (evt.button) {
            case 0:
              pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
              break;
            case 1:
              pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
              break;
            case 2:
              pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
              break;
          }
          if (pickResult.pickedSprite.actionManager) {
            pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
          }
        }
      }
    }
    return pickResult;
  }
  _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) {
    const scene = this.scene;
    if (scene.spriteManagers && scene.spriteManagers.length > 0) {
      const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
      if (spritePickResult) {
        if (spritePickResult.hit && spritePickResult.pickedSprite) {
          if (spritePickResult.pickedSprite.actionManager) {
            spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
            if (spritePickResult.pickedSprite.actionManager) {
              if (!this.scene._inputManager._isPointerSwiping()) {
                spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
              }
              if (doubleClick) {
                spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
              }
            }
          }
        }
        if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
          scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
        }
      }
    }
    return pickResult;
  }
}

// node_modules/@babylonjs/core/Sprites/spriteManager.js
init_pickingInfo();
init_texture();
init_sceneComponent();
init_logger();
init_tools();
init_webRequest();

// node_modules/@babylonjs/core/Sprites/spriteRenderer.js
init_buffer();
init_drawWrapper();
init_logger();
init_materialHelper_functions();

class SpriteRenderer {
  get fogEnabled() {
    return this._fogEnabled;
  }
  set fogEnabled(value) {
    if (this._fogEnabled === value) {
      return;
    }
    this._fogEnabled = value;
    this._createEffects();
  }
  get useLogarithmicDepth() {
    return this._useLogarithmicDepth;
  }
  set useLogarithmicDepth(value) {
    const fragmentDepthSupported = !!this._scene?.getEngine().getCaps().fragmentDepthSupported;
    if (value && !fragmentDepthSupported) {
      Logger.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it.");
    }
    this._useLogarithmicDepth = value && fragmentDepthSupported;
    this._createEffects();
  }
  get capacity() {
    return this._capacity;
  }
  get pixelPerfect() {
    return this._pixelPerfect;
  }
  set pixelPerfect(value) {
    if (this._pixelPerfect === value) {
      return;
    }
    this._pixelPerfect = value;
    this._createEffects();
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(engine2, capacity, epsilon = 0.01, scene = null, rendererOptions) {
    this.blendMode = 2;
    this.autoResetAlpha = true;
    this.disableDepthWrite = false;
    this._fogEnabled = true;
    this._pixelPerfect = false;
    this._shaderLanguage = 0;
    this._useVAO = false;
    this._useInstancing = false;
    this._vertexBuffers = {};
    this._isDisposed = false;
    this._shadersLoaded = false;
    this._pixelPerfect = rendererOptions?.pixelPerfect ?? false;
    this._capacity = capacity;
    this._epsilon = epsilon;
    this._engine = engine2;
    this._useInstancing = engine2.getCaps().instancedArrays && engine2._features.supportSpriteInstancing;
    this._useVAO = engine2.getCaps().vertexArrayObject && !engine2.disableVertexArrayObjects;
    this._scene = scene;
    if (!this._useInstancing) {
      this._buildIndexBuffer();
    }
    this._vertexBufferSize = this._useInstancing ? 16 : 18;
    this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
    this._buffer = new Buffer2(engine2, this._vertexData, true, this._vertexBufferSize);
    const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);
    const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing);
    let offset = 6;
    let offsets;
    if (this._useInstancing) {
      const spriteData = new Float32Array([
        this._epsilon,
        this._epsilon,
        1 - this._epsilon,
        this._epsilon,
        this._epsilon,
        1 - this._epsilon,
        1 - this._epsilon,
        1 - this._epsilon
      ]);
      this._spriteBuffer = new Buffer2(engine2, spriteData, false, 2);
      offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2);
    } else {
      offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing);
      offset += 2;
    }
    const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing);
    const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing);
    const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);
    this._vertexBuffers[VertexBuffer.PositionKind] = positions;
    this._vertexBuffers["options"] = options;
    this._vertexBuffers["offsets"] = offsets;
    this._vertexBuffers["inverts"] = inverts;
    this._vertexBuffers["cellInfo"] = cellInfo;
    this._vertexBuffers[VertexBuffer.ColorKind] = colors;
    this._initShaderSourceAsync();
  }
  async _initShaderSourceAsync() {
    const engine2 = this._engine;
    if (engine2.isWebGPU && !SpriteRenderer.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([Promise.resolve().then(() => (init_sprites_vertex(), exports_sprites_vertex)), Promise.resolve().then(() => (init_sprites_fragment(), exports_sprites_fragment))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_sprites_vertex2(), exports_sprites_vertex2)), Promise.resolve().then(() => (init_sprites_fragment2(), exports_sprites_fragment2))]);
    }
    this._shadersLoaded = true;
    this._createEffects();
  }
  _createEffects() {
    if (this._isDisposed || !this._shadersLoaded) {
      return;
    }
    this._drawWrapperBase?.dispose();
    this._drawWrapperDepth?.dispose();
    this._drawWrapperBase = new DrawWrapper(this._engine);
    this._drawWrapperDepth = new DrawWrapper(this._engine, false);
    if (this._drawWrapperBase.drawContext) {
      this._drawWrapperBase.drawContext.useInstancing = this._useInstancing;
    }
    if (this._drawWrapperDepth.drawContext) {
      this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing;
    }
    let defines = "";
    if (this._pixelPerfect) {
      defines += `#define PIXEL_PERFECT
`;
    }
    if (this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0 && this._fogEnabled) {
      defines += `#define FOG
`;
    }
    if (this._useLogarithmicDepth) {
      defines += `#define LOGARITHMICDEPTH
`;
    }
    this._drawWrapperBase.effect = this._engine.createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor", "logarithmicDepthConstant"], ["diffuseSampler"], defines, undefined, undefined, undefined, undefined, this._shaderLanguage);
    this._drawWrapperDepth.effect = this._drawWrapperBase.effect;
    this._drawWrapperBase.effect._refCount++;
    this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext;
  }
  render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) {
    if (!this._shadersLoaded || !this.texture || !this.texture.isReady() || !sprites.length) {
      return;
    }
    const drawWrapper = this._drawWrapperBase;
    const drawWrapperDepth = this._drawWrapperDepth;
    const shouldRenderFog = this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0;
    const effect = drawWrapper.effect;
    if (!effect.isReady()) {
      return;
    }
    const engine2 = this._engine;
    const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem);
    const max = Math.min(this._capacity, sprites.length);
    let offset = 0;
    let noSprite = true;
    for (let index = 0;index < max; index++) {
      const sprite = sprites[index];
      if (!sprite || !sprite.isVisible) {
        continue;
      }
      noSprite = false;
      sprite._animate(deltaTime);
      const baseSize = this.texture.getBaseSize();
      this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
      if (!this._useInstancing) {
        this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
        this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
        this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
      }
    }
    if (noSprite) {
      return;
    }
    this._buffer.update(this._vertexData);
    const culling = !!engine2.depthCullingState.cull;
    const zOffset = engine2.depthCullingState.zOffset;
    const zOffsetUnits = engine2.depthCullingState.zOffsetUnits;
    engine2.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits);
    engine2.enableEffect(drawWrapper);
    effect.setTexture("diffuseSampler", this.texture);
    effect.setMatrix("view", viewMatrix);
    effect.setMatrix("projection", projectionMatrix);
    if (shouldRenderFog) {
      const scene = this._scene;
      effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
      effect.setColor3("vFogColor", scene.fogColor);
    }
    if (this.useLogarithmicDepth && this._scene) {
      BindLogDepth(drawWrapper.defines, effect, this._scene);
    }
    if (this._useVAO) {
      if (!this._vertexArrayObject) {
        this._vertexArrayObject = engine2.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);
      }
      engine2.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);
    } else {
      engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
    }
    engine2.depthCullingState.depthFunc = engine2.useReverseDepthBuffer ? 518 : 515;
    if (!this.disableDepthWrite) {
      effect.setBool("alphaTest", true);
      engine2.setColorWrite(false);
      engine2.enableEffect(drawWrapperDepth);
      if (this._useInstancing) {
        engine2.drawArraysType(7, 0, 4, offset);
      } else {
        engine2.drawElementsType(0, 0, offset / 4 * 6);
      }
      engine2.enableEffect(drawWrapper);
      engine2.setColorWrite(true);
      effect.setBool("alphaTest", false);
    }
    engine2.setAlphaMode(this.blendMode);
    if (this._useInstancing) {
      engine2.drawArraysType(7, 0, 4, offset);
    } else {
      engine2.drawElementsType(0, 0, offset / 4 * 6);
    }
    if (this.autoResetAlpha) {
      engine2.setAlphaMode(0);
    }
    if (useRightHandedSystem) {
      this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits);
    }
    engine2.unbindInstanceAttributes();
  }
  _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) {
    let arrayOffset = index * this._vertexBufferSize;
    if (offsetX === 0) {
      offsetX = this._epsilon;
    } else if (offsetX === 1) {
      offsetX = 1 - this._epsilon;
    }
    if (offsetY === 0) {
      offsetY = this._epsilon;
    } else if (offsetY === 1) {
      offsetY = 1 - this._epsilon;
    }
    if (customSpriteUpdate) {
      customSpriteUpdate(sprite, baseSize);
    } else {
      if (!sprite.cellIndex) {
        sprite.cellIndex = 0;
      }
      const rowSize = baseSize.width / this.cellWidth;
      const offset = sprite.cellIndex / rowSize >> 0;
      sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width;
      sprite._yOffset = offset * this.cellHeight / baseSize.height;
      sprite._xSize = this.cellWidth;
      sprite._ySize = this.cellHeight;
    }
    this._vertexData[arrayOffset] = sprite.position.x;
    this._vertexData[arrayOffset + 1] = sprite.position.y;
    this._vertexData[arrayOffset + 2] = sprite.position.z;
    this._vertexData[arrayOffset + 3] = sprite.angle;
    this._vertexData[arrayOffset + 4] = sprite.width;
    this._vertexData[arrayOffset + 5] = sprite.height;
    if (!this._useInstancing) {
      this._vertexData[arrayOffset + 6] = offsetX;
      this._vertexData[arrayOffset + 7] = offsetY;
    } else {
      arrayOffset -= 2;
    }
    if (useRightHandedSystem) {
      this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;
    } else {
      this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
    }
    this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
    this._vertexData[arrayOffset + 10] = sprite._xOffset;
    this._vertexData[arrayOffset + 11] = sprite._yOffset;
    this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
    this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
    this._vertexData[arrayOffset + 14] = sprite.color.r;
    this._vertexData[arrayOffset + 15] = sprite.color.g;
    this._vertexData[arrayOffset + 16] = sprite.color.b;
    this._vertexData[arrayOffset + 17] = sprite.color.a;
  }
  _buildIndexBuffer() {
    const indices = [];
    let index = 0;
    for (let count = 0;count < this._capacity; count++) {
      indices.push(index);
      indices.push(index + 1);
      indices.push(index + 2);
      indices.push(index);
      indices.push(index + 2);
      indices.push(index + 3);
      index += 4;
    }
    this._indexBuffer = this._engine.createIndexBuffer(indices);
  }
  rebuild() {
    if (this._indexBuffer) {
      this._buildIndexBuffer();
    }
    if (this._useVAO) {
      this._vertexArrayObject = undefined;
    }
    this._buffer._rebuild();
    for (const key in this._vertexBuffers) {
      const vertexBuffer = this._vertexBuffers[key];
      vertexBuffer._rebuild();
    }
    this._spriteBuffer?._rebuild();
  }
  dispose() {
    if (this._buffer) {
      this._buffer.dispose();
      this._buffer = null;
    }
    if (this._spriteBuffer) {
      this._spriteBuffer.dispose();
      this._spriteBuffer = null;
    }
    if (this._indexBuffer) {
      this._engine._releaseBuffer(this._indexBuffer);
      this._indexBuffer = null;
    }
    if (this._vertexArrayObject) {
      this._engine.releaseVertexArrayObject(this._vertexArrayObject);
      this._vertexArrayObject = null;
    }
    if (this.texture) {
      this.texture.dispose();
      this.texture = null;
    }
    this._drawWrapperBase?.dispose();
    this._drawWrapperDepth?.dispose();
    this._isDisposed = true;
  }
}
SpriteRenderer.ForceGLSL = false;

// node_modules/@babylonjs/core/Sprites/spriteManager.js
init_engineStore();

class SpriteManager {
  set onDispose(callback) {
    if (this._onDisposeObserver) {
      this.onDisposeObservable.remove(this._onDisposeObserver);
    }
    this._onDisposeObserver = this.onDisposeObservable.add(callback);
  }
  get children() {
    return this.sprites;
  }
  get scene() {
    return this._scene;
  }
  get capacity() {
    return this._spriteRenderer.capacity;
  }
  get texture() {
    return this._spriteRenderer.texture;
  }
  set texture(value) {
    value.wrapU = Texture.CLAMP_ADDRESSMODE;
    value.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._spriteRenderer.texture = value;
    this._textureContent = null;
  }
  get cellWidth() {
    return this._spriteRenderer.cellWidth;
  }
  set cellWidth(value) {
    this._spriteRenderer.cellWidth = value;
  }
  get cellHeight() {
    return this._spriteRenderer.cellHeight;
  }
  set cellHeight(value) {
    this._spriteRenderer.cellHeight = value;
  }
  get fogEnabled() {
    return this._spriteRenderer.fogEnabled;
  }
  set fogEnabled(value) {
    this._spriteRenderer.fogEnabled = value;
  }
  get useLogarithmicDepth() {
    return this._spriteRenderer.useLogarithmicDepth;
  }
  set useLogarithmicDepth(value) {
    this._spriteRenderer.useLogarithmicDepth = value;
  }
  get blendMode() {
    return this._spriteRenderer.blendMode;
  }
  set blendMode(blendMode) {
    this._spriteRenderer.blendMode = blendMode;
  }
  get disableDepthWrite() {
    return this._disableDepthWrite;
  }
  set disableDepthWrite(value) {
    this._disableDepthWrite = value;
    this._spriteRenderer.disableDepthWrite = value;
  }
  get pixelPerfect() {
    return this._spriteRenderer.pixelPerfect;
  }
  set pixelPerfect(value) {
    this._spriteRenderer.pixelPerfect = value;
    if (value && this.texture.samplingMode !== 3) {
      this.texture.updateSamplingMode(3);
    }
  }
  constructor(name359, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null, options) {
    this.name = name359;
    this.sprites = [];
    this.renderingGroupId = 0;
    this.layerMask = 268435455;
    this.isPickable = false;
    this.metadata = null;
    this._wasDispatched = false;
    this.onDisposeObservable = new Observable;
    this._disableDepthWrite = false;
    this._packedAndReady = false;
    this._customUpdate = (sprite, baseSize) => {
      if (!sprite.cellRef) {
        sprite.cellIndex = 0;
      }
      const num = sprite.cellIndex;
      if (typeof num === "number" && isFinite(num) && Math.floor(num) === num) {
        sprite.cellRef = this._spriteMap[sprite.cellIndex];
      }
      sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;
      sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;
      sprite._xSize = this._cellData[sprite.cellRef].frame.w;
      sprite._ySize = this._cellData[sprite.cellRef].frame.h;
    };
    if (!scene) {
      scene = EngineStore.LastCreatedScene;
    }
    if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {
      scene._addComponent(new SpriteSceneComponent(scene));
    }
    this._fromPacked = fromPacked;
    this._scene = scene;
    const engine2 = this._scene.getEngine();
    this._spriteRenderer = new SpriteRenderer(engine2, capacity, epsilon, scene, options?.spriteRendererOptions);
    if (cellSize.width && cellSize.height) {
      this.cellWidth = cellSize.width;
      this.cellHeight = cellSize.height;
    } else if (cellSize !== undefined) {
      this.cellWidth = cellSize;
      this.cellHeight = cellSize;
    } else {
      this._spriteRenderer = null;
      return;
    }
    this._scene.spriteManagers && this._scene.spriteManagers.push(this);
    this.uniqueId = this.scene.getUniqueId();
    if (imgUrl) {
      this.texture = new Texture(imgUrl, scene, true, false, samplingMode);
    }
    if (this._fromPacked) {
      this._makePacked(imgUrl, spriteJSON);
    }
  }
  getClassName() {
    return "SpriteManager";
  }
  _makePacked(imgUrl, spriteJSON) {
    if (spriteJSON !== null) {
      try {
        let celldata;
        if (typeof spriteJSON === "string") {
          celldata = JSON.parse(spriteJSON);
        } else {
          celldata = spriteJSON;
        }
        if (celldata.frames.length) {
          const frametemp = {};
          for (let i = 0;i < celldata.frames.length; i++) {
            const _f = celldata.frames[i];
            if (typeof Object.keys(_f)[0] !== "string") {
              throw new Error("Invalid JSON Format.  Check the frame values and make sure the name is the first parameter.");
            }
            const name359 = _f[Object.keys(_f)[0]];
            frametemp[name359] = _f;
          }
          celldata.frames = frametemp;
        }
        const spritemap = Reflect.ownKeys(celldata.frames);
        this._spriteMap = spritemap;
        this._packedAndReady = true;
        this._cellData = celldata.frames;
      } catch (e) {
        this._fromPacked = false;
        this._packedAndReady = false;
        throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size.");
      }
    } else {
      const re = /\./g;
      let li;
      do {
        li = re.lastIndex;
        re.test(imgUrl);
      } while (re.lastIndex > 0);
      const jsonUrl = imgUrl.substring(0, li - 1) + ".json";
      const onerror = () => {
        Logger.Error("JSON ERROR: Unable to load JSON file.");
        this._fromPacked = false;
        this._packedAndReady = false;
      };
      const onload = (data) => {
        try {
          const celldata = JSON.parse(data);
          const spritemap = Reflect.ownKeys(celldata.frames);
          this._spriteMap = spritemap;
          this._packedAndReady = true;
          this._cellData = celldata.frames;
        } catch (e) {
          this._fromPacked = false;
          this._packedAndReady = false;
          throw new Error("Invalid JSON format. Please check documentation for format specifications.");
        }
      };
      Tools.LoadFile(jsonUrl, onload, undefined, undefined, false, onerror);
    }
  }
  _checkTextureAlpha(sprite, ray2, distance, min, max) {
    if (!sprite.useAlphaForPicking || !this.texture?.isReady()) {
      return true;
    }
    const textureSize = this.texture.getSize();
    if (!this._textureContent) {
      this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);
      this.texture.readPixels(0, 0, this._textureContent);
    }
    const contactPoint = TmpVectors.Vector3[0];
    contactPoint.copyFrom(ray2.direction);
    contactPoint.normalize();
    contactPoint.scaleInPlace(distance);
    contactPoint.addInPlace(ray2.origin);
    const contactPointU = (contactPoint.x - min.x) / (max.x - min.x);
    const contactPointV = 1 - (contactPoint.y - min.y) / (max.y - min.y);
    const u = sprite._xOffset * textureSize.width + contactPointU * sprite._xSize | 0;
    const v = sprite._yOffset * textureSize.height + contactPointV * sprite._ySize | 0;
    const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3];
    return alpha > 0.5;
  }
  intersects(ray2, camera2, predicate, fastCheck) {
    const count = Math.min(this.capacity, this.sprites.length);
    const min = Vector3.Zero();
    const max = Vector3.Zero();
    let distance = Number.MAX_VALUE;
    let currentSprite = null;
    const pickedPoint = TmpVectors.Vector3[0];
    const cameraSpacePosition = TmpVectors.Vector3[1];
    const cameraView = camera2.getViewMatrix();
    let activeRay = ray2;
    let pickedRay = ray2;
    for (let index = 0;index < count; index++) {
      const sprite = this.sprites[index];
      if (!sprite) {
        continue;
      }
      if (predicate) {
        if (!predicate(sprite)) {
          continue;
        }
      } else if (!sprite.isPickable) {
        continue;
      }
      Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
      if (sprite.angle) {
        Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, TmpVectors.Matrix[1]);
        Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, TmpVectors.Matrix[2]);
        Matrix.RotationZToRef(-sprite.angle, TmpVectors.Matrix[3]);
        TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]);
        TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]);
        activeRay = ray2.clone();
        Vector3.TransformCoordinatesToRef(ray2.origin, TmpVectors.Matrix[0], activeRay.origin);
        Vector3.TransformNormalToRef(ray2.direction, TmpVectors.Matrix[0], activeRay.direction);
      } else {
        activeRay = ray2;
      }
      min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
      max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
      if (activeRay.intersectsBoxMinMax(min, max)) {
        const currentDistance = Vector3.Distance(cameraSpacePosition, activeRay.origin);
        if (distance > currentDistance) {
          if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) {
            continue;
          }
          pickedRay = activeRay;
          distance = currentDistance;
          currentSprite = sprite;
          if (fastCheck) {
            break;
          }
        }
      }
    }
    if (currentSprite) {
      const result = new PickingInfo;
      cameraView.invertToRef(TmpVectors.Matrix[0]);
      result.hit = true;
      result.pickedSprite = currentSprite;
      result.distance = distance;
      const direction = TmpVectors.Vector3[2];
      direction.copyFrom(pickedRay.direction);
      direction.normalize();
      direction.scaleInPlace(distance);
      pickedRay.origin.addToRef(direction, pickedPoint);
      result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
      return result;
    }
    return null;
  }
  multiIntersects(ray2, camera2, predicate) {
    const count = Math.min(this.capacity, this.sprites.length);
    const min = Vector3.Zero();
    const max = Vector3.Zero();
    let distance;
    const results = [];
    const pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0);
    const cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0);
    const cameraView = camera2.getViewMatrix();
    for (let index = 0;index < count; index++) {
      const sprite = this.sprites[index];
      if (!sprite) {
        continue;
      }
      if (predicate) {
        if (!predicate(sprite)) {
          continue;
        }
      } else if (!sprite.isPickable) {
        continue;
      }
      Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
      min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
      max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
      if (ray2.intersectsBoxMinMax(min, max)) {
        distance = Vector3.Distance(cameraSpacePosition, ray2.origin);
        if (!this._checkTextureAlpha(sprite, ray2, distance, min, max)) {
          continue;
        }
        const result = new PickingInfo;
        results.push(result);
        cameraView.invertToRef(TmpVectors.Matrix[0]);
        result.hit = true;
        result.pickedSprite = sprite;
        result.distance = distance;
        const direction = TmpVectors.Vector3[2];
        direction.copyFrom(ray2.direction);
        direction.normalize();
        direction.scaleInPlace(distance);
        ray2.origin.addToRef(direction, pickedPoint);
        result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
      }
    }
    return results;
  }
  render() {
    if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {
      return;
    }
    const engine2 = this._scene.getEngine();
    const deltaTime = engine2.getDeltaTime();
    if (this._packedAndReady) {
      this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate);
    } else {
      this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix());
    }
  }
  rebuild() {
    this._spriteRenderer?.rebuild();
  }
  dispose() {
    if (this._spriteRenderer) {
      this._spriteRenderer.dispose();
      this._spriteRenderer = null;
    }
    this._textureContent = null;
    if (this._scene.spriteManagers) {
      const index = this._scene.spriteManagers.indexOf(this);
      this._scene.spriteManagers.splice(index, 1);
    }
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    this.metadata = null;
  }
  serialize(serializeTexture = false) {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.capacity = this.capacity;
    serializationObject.cellWidth = this.cellWidth;
    serializationObject.cellHeight = this.cellHeight;
    serializationObject.fogEnabled = this.fogEnabled;
    serializationObject.blendMode = this.blendMode;
    serializationObject.disableDepthWrite = this.disableDepthWrite;
    serializationObject.pixelPerfect = this.pixelPerfect;
    serializationObject.useLogarithmicDepth = this.useLogarithmicDepth;
    if (this.texture) {
      if (serializeTexture) {
        serializationObject.texture = this.texture.serialize();
      } else {
        serializationObject.textureUrl = this.texture.name;
        serializationObject.invertY = this.texture._invertY;
      }
    }
    serializationObject.sprites = [];
    for (const sprite of this.sprites) {
      serializationObject.sprites.push(sprite.serialize());
    }
    serializationObject.metadata = this.metadata;
    return serializationObject;
  }
  static Parse(parsedManager, scene, rootUrl) {
    const manager = new SpriteManager(parsedManager.name, "", parsedManager.capacity, {
      width: parsedManager.cellWidth,
      height: parsedManager.cellHeight
    }, scene);
    if (parsedManager.fogEnabled !== undefined) {
      manager.fogEnabled = parsedManager.fogEnabled;
    }
    if (parsedManager.blendMode !== undefined) {
      manager.blendMode = parsedManager.blendMode;
    }
    if (parsedManager.disableDepthWrite !== undefined) {
      manager.disableDepthWrite = parsedManager.disableDepthWrite;
    }
    if (parsedManager.pixelPerfect !== undefined) {
      manager.pixelPerfect = parsedManager.pixelPerfect;
    }
    if (parsedManager.useLogarithmicDepth !== undefined) {
      manager.useLogarithmicDepth = parsedManager.useLogarithmicDepth;
    }
    if (parsedManager.metadata !== undefined) {
      manager.metadata = parsedManager.metadata;
    }
    if (parsedManager.texture) {
      manager.texture = Texture.Parse(parsedManager.texture, scene, rootUrl);
    } else if (parsedManager.textureName) {
      manager.texture = new Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== undefined ? parsedManager.invertY : true);
    }
    for (const parsedSprite of parsedManager.sprites) {
      Sprite.Parse(parsedSprite, manager);
    }
    return manager;
  }
  static ParseFromFileAsync(name359, url, scene, rootUrl = "") {
    return new Promise((resolve3, reject) => {
      const request = new WebRequest;
      request.addEventListener("readystatechange", () => {
        if (request.readyState == 4) {
          if (request.status == 200) {
            const serializationObject = JSON.parse(request.responseText);
            const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
            if (name359) {
              output.name = name359;
            }
            resolve3(output);
          } else {
            reject("Unable to load the sprite manager");
          }
        }
      });
      request.open("GET", url);
      request.send();
    });
  }
  static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") {
    if (snippetId === "_BLANK") {
      return Promise.resolve(new SpriteManager("Default sprite manager", "//playground.babylonjs.com/textures/player.png", 500, 64, scene));
    }
    return new Promise((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);
            const serializationObject = JSON.parse(snippet.spriteManager);
            const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);
            output.snippetId = snippetId;
            resolve3(output);
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
}
SpriteManager.SnippetUrl = `https://snippet.babylonjs.com`;
SpriteManager.CreateFromSnippetAsync = SpriteManager.ParseFromSnippetAsync;

// node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js
class BabylonFileLoaderConfiguration {
}
BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined;
var tempIndexContainer = {};
var tempMaterialIndexContainer = {};
var tempMorphTargetManagerIndexContainer = {};
var parseMaterialByPredicate = (predicate, parsedData, scene, rootUrl) => {
  if (!parsedData.materials) {
    return null;
  }
  for (let index = 0, cache = parsedData.materials.length;index < cache; index++) {
    const parsedMaterial = parsedData.materials[index];
    if (predicate(parsedMaterial)) {
      return { parsedMaterial, material: Material.Parse(parsedMaterial, scene, rootUrl) };
    }
  }
  return null;
};
var isDescendantOf = (mesh, names, hierarchyIds) => {
  for (const i in names) {
    if (mesh.name === names[i]) {
      hierarchyIds.push(mesh.id);
      return true;
    }
  }
  if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) {
    hierarchyIds.push(mesh.id);
    return true;
  }
  return false;
};
var logOperation = (operation, producer) => {
  return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
};
var loadDetailLevels = (scene, mesh) => {
  const mastermesh = mesh;
  if (mesh._waitingData.lods) {
    if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {
      const lodmeshes = mesh._waitingData.lods.ids;
      const wasenabled = mastermesh.isEnabled(false);
      if (mesh._waitingData.lods.distances) {
        const distances = mesh._waitingData.lods.distances;
        if (distances.length >= lodmeshes.length) {
          const culling = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0;
          mastermesh.setEnabled(false);
          for (let index = 0;index < lodmeshes.length; index++) {
            const lodid = lodmeshes[index];
            const lodmesh = scene.getMeshById(lodid);
            if (lodmesh != null) {
              mastermesh.addLODLevel(distances[index], lodmesh);
            }
          }
          if (culling > 0) {
            mastermesh.addLODLevel(culling, null);
          }
          if (wasenabled === true) {
            mastermesh.setEnabled(true);
          }
        } else {
          Tools.Warn("Invalid level of detail distances for " + mesh.name);
        }
      }
    }
    mesh._waitingData.lods = null;
  }
};
var findParent = (parentId, parentInstanceIndex, scene) => {
  if (typeof parentId !== "number") {
    const parentEntry = scene.getLastEntryById(parentId);
    if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {
      const instance = parentEntry.instances[parseInt(parentInstanceIndex)];
      return instance;
    }
    return parentEntry;
  }
  const parent = tempIndexContainer[parentId];
  if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {
    const instance = parent.instances[parseInt(parentInstanceIndex)];
    return instance;
  }
  return parent;
};
var findMaterial = (materialId, scene) => {
  if (typeof materialId !== "number") {
    return scene.getLastMaterialById(materialId, true);
  }
  return tempMaterialIndexContainer[materialId];
};
var loadAssetContainer = (scene, data, rootUrl, onError, addToScene = false) => {
  const container = new AssetContainer(scene);
  let log = "importScene has failed JSON parse";
  try {
    var parsedData = JSON.parse(data);
    log = "";
    const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
    let index;
    let cache;
    if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
      const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
      if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
        const hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128;
        const hdrTexture = new HDRCubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR, undefined, parsedData.environmentTexturePrefilterOnLoad);
        if (parsedData.environmentTextureRotationY) {
          hdrTexture.rotationY = parsedData.environmentTextureRotationY;
        }
        scene.environmentTexture = hdrTexture;
      } else {
        if (typeof parsedData.environmentTexture === "object") {
          const environmentTexture = CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl);
          scene.environmentTexture = environmentTexture;
        } else if (parsedData.environmentTexture.endsWith(".env")) {
          const compressedTexture = new CubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);
          if (parsedData.environmentTextureRotationY) {
            compressedTexture.rotationY = parsedData.environmentTextureRotationY;
          }
          scene.environmentTexture = compressedTexture;
        } else {
          const cubeTexture = CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);
          if (parsedData.environmentTextureRotationY) {
            cubeTexture.rotationY = parsedData.environmentTextureRotationY;
          }
          scene.environmentTexture = cubeTexture;
        }
      }
      if (parsedData.createDefaultSkybox === true) {
        const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
        const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
        scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
      }
      container.environmentTexture = scene.environmentTexture;
    }
    if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {
      scene.environmentIntensity = parsedData.environmentIntensity;
    }
    if (parsedData.iblIntensity !== undefined && parsedData.iblIntensity !== null) {
      scene.iblIntensity = parsedData.iblIntensity;
    }
    if (parsedData.lights !== undefined && parsedData.lights !== null) {
      for (index = 0, cache = parsedData.lights.length;index < cache; index++) {
        const parsedLight = parsedData.lights[index];
        const light2 = Light.Parse(parsedLight, scene);
        if (light2) {
          tempIndexContainer[parsedLight.uniqueId] = light2;
          container.lights.push(light2);
          light2._parentContainer = container;
          log += index === 0 ? `
	Lights:` : "";
          log += `
		` + light2.toString(fullDetails);
        }
      }
    }
    if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {
      for (index = 0, cache = parsedData.reflectionProbes.length;index < cache; index++) {
        const parsedReflectionProbe = parsedData.reflectionProbes[index];
        const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);
        if (reflectionProbe) {
          container.reflectionProbes.push(reflectionProbe);
          reflectionProbe._parentContainer = container;
          log += index === 0 ? `
	Reflection Probes:` : "";
          log += `
		` + reflectionProbe.toString(fullDetails);
        }
      }
    }
    if (parsedData.animations !== undefined && parsedData.animations !== null) {
      for (index = 0, cache = parsedData.animations.length;index < cache; index++) {
        const parsedAnimation = parsedData.animations[index];
        const internalClass = GetClass("BABYLON.Animation");
        if (internalClass) {
          const animation2 = internalClass.Parse(parsedAnimation);
          scene.animations.push(animation2);
          container.animations.push(animation2);
          log += index === 0 ? `
	Animations:` : "";
          log += `
		` + animation2.toString(fullDetails);
        }
      }
    }
    if (parsedData.materials !== undefined && parsedData.materials !== null) {
      for (index = 0, cache = parsedData.materials.length;index < cache; index++) {
        const parsedMaterial = parsedData.materials[index];
        const mat = Material.Parse(parsedMaterial, scene, rootUrl);
        if (mat) {
          tempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat;
          container.materials.push(mat);
          mat._parentContainer = container;
          log += index === 0 ? `
	Materials:` : "";
          log += `
		` + mat.toString(fullDetails);
          const textures = mat.getActiveTextures();
          textures.forEach((t) => {
            if (container.textures.indexOf(t) == -1) {
              container.textures.push(t);
              t._parentContainer = container;
            }
          });
        }
      }
    }
    if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
      for (index = 0, cache = parsedData.multiMaterials.length;index < cache; index++) {
        const parsedMultiMaterial = parsedData.multiMaterials[index];
        const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
        tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;
        container.multiMaterials.push(mmat);
        mmat._parentContainer = container;
        log += index === 0 ? `
	MultiMaterials:` : "";
        log += `
		` + mmat.toString(fullDetails);
        const textures = mmat.getActiveTextures();
        textures.forEach((t) => {
          if (container.textures.indexOf(t) == -1) {
            container.textures.push(t);
            t._parentContainer = container;
          }
        });
      }
    }
    if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
      for (const parsedManager of parsedData.morphTargetManagers) {
        const manager = MorphTargetManager.Parse(parsedManager, scene);
        tempMorphTargetManagerIndexContainer[parsedManager.id] = manager;
        container.morphTargetManagers.push(manager);
        manager._parentContainer = container;
      }
    }
    if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
      for (index = 0, cache = parsedData.skeletons.length;index < cache; index++) {
        const parsedSkeleton = parsedData.skeletons[index];
        const skeleton2 = Skeleton.Parse(parsedSkeleton, scene);
        container.skeletons.push(skeleton2);
        skeleton2._parentContainer = container;
        log += index === 0 ? `
	Skeletons:` : "";
        log += `
		` + skeleton2.toString(fullDetails);
      }
    }
    const geometries = parsedData.geometries;
    if (geometries !== undefined && geometries !== null) {
      const addedGeometry = new Array;
      const vertexData = geometries.vertexData;
      if (vertexData !== undefined && vertexData !== null) {
        for (index = 0, cache = vertexData.length;index < cache; index++) {
          const parsedVertexData = vertexData[index];
          addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
        }
      }
      addedGeometry.forEach((g) => {
        if (g) {
          container.geometries.push(g);
          g._parentContainer = container;
        }
      });
    }
    if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
      for (index = 0, cache = parsedData.transformNodes.length;index < cache; index++) {
        const parsedTransformNode = parsedData.transformNodes[index];
        const node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
        tempIndexContainer[parsedTransformNode.uniqueId] = node;
        container.transformNodes.push(node);
        node._parentContainer = container;
      }
    }
    if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
      for (index = 0, cache = parsedData.meshes.length;index < cache; index++) {
        const parsedMesh = parsedData.meshes[index];
        const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
        tempIndexContainer[parsedMesh.uniqueId] = mesh;
        container.meshes.push(mesh);
        mesh._parentContainer = container;
        if (mesh.hasInstances) {
          for (const instance of mesh.instances) {
            container.meshes.push(instance);
            instance._parentContainer = container;
          }
        }
        log += index === 0 ? `
	Meshes:` : "";
        log += `
		` + mesh.toString(fullDetails);
      }
    }
    if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
      for (index = 0, cache = parsedData.cameras.length;index < cache; index++) {
        const parsedCamera = parsedData.cameras[index];
        const camera2 = Camera.Parse(parsedCamera, scene);
        tempIndexContainer[parsedCamera.uniqueId] = camera2;
        container.cameras.push(camera2);
        camera2._parentContainer = container;
        log += index === 0 ? `
	Cameras:` : "";
        log += `
		` + camera2.toString(fullDetails);
      }
    }
    if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) {
      for (index = 0, cache = parsedData.postProcesses.length;index < cache; index++) {
        const parsedPostProcess = parsedData.postProcesses[index];
        const postProcess = PostProcess.Parse(parsedPostProcess, scene, rootUrl);
        if (postProcess) {
          container.postProcesses.push(postProcess);
          postProcess._parentContainer = container;
          log += index === 0 ? `
Postprocesses:` : "";
          log += `
		` + postProcess.toString();
        }
      }
    }
    if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
      for (index = 0, cache = parsedData.animationGroups.length;index < cache; index++) {
        const parsedAnimationGroup = parsedData.animationGroups[index];
        const animationGroup2 = AnimationGroup.Parse(parsedAnimationGroup, scene);
        container.animationGroups.push(animationGroup2);
        animationGroup2._parentContainer = container;
        log += index === 0 ? `
	AnimationGroups:` : "";
        log += `
		` + animationGroup2.toString(fullDetails);
      }
    }
    if (parsedData.spriteManagers) {
      for (let index2 = 0, cache2 = parsedData.spriteManagers.length;index2 < cache2; index2++) {
        const parsedSpriteManager = parsedData.spriteManagers[index2];
        const spriteManager = SpriteManager.Parse(parsedSpriteManager, scene, rootUrl);
        log += `
		SpriteManager ` + spriteManager.name;
      }
    }
    for (index = 0, cache = scene.cameras.length;index < cache; index++) {
      const camera2 = scene.cameras[index];
      if (camera2._waitingParentId !== null) {
        camera2.parent = findParent(camera2._waitingParentId, camera2._waitingParentInstanceIndex, scene);
        camera2._waitingParentId = null;
        camera2._waitingParentInstanceIndex = null;
      }
    }
    for (index = 0, cache = scene.lights.length;index < cache; index++) {
      const light2 = scene.lights[index];
      if (light2 && light2._waitingParentId !== null) {
        light2.parent = findParent(light2._waitingParentId, light2._waitingParentInstanceIndex, scene);
        light2._waitingParentId = null;
        light2._waitingParentInstanceIndex = null;
      }
    }
    for (index = 0, cache = scene.transformNodes.length;index < cache; index++) {
      const transformNode = scene.transformNodes[index];
      if (transformNode._waitingParentId !== null) {
        transformNode.parent = findParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene);
        transformNode._waitingParentId = null;
        transformNode._waitingParentInstanceIndex = null;
      }
    }
    for (index = 0, cache = scene.meshes.length;index < cache; index++) {
      const mesh = scene.meshes[index];
      if (mesh._waitingParentId !== null) {
        mesh.parent = findParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene);
        mesh._waitingParentId = null;
        mesh._waitingParentInstanceIndex = null;
      }
      if (mesh._waitingData.lods) {
        loadDetailLevels(scene, mesh);
      }
    }
    scene.multiMaterials.forEach((multimat) => {
      multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {
        multimat.subMaterials.push(findMaterial(subMaterial, scene));
      });
      multimat._waitingSubMaterialsUniqueIds = [];
    });
    scene.meshes.forEach((mesh) => {
      if (mesh._waitingMaterialId !== null) {
        mesh.material = findMaterial(mesh._waitingMaterialId, scene);
        mesh._waitingMaterialId = null;
      }
    });
    scene.meshes.forEach((mesh) => {
      if (mesh._waitingMorphTargetManagerId !== null) {
        mesh.morphTargetManager = tempMorphTargetManagerIndexContainer[mesh._waitingMorphTargetManagerId];
        mesh._waitingMorphTargetManagerId = null;
      }
    });
    for (index = 0, cache = scene.skeletons.length;index < cache; index++) {
      const skeleton2 = scene.skeletons[index];
      if (skeleton2._hasWaitingData) {
        if (skeleton2.bones != null) {
          skeleton2.bones.forEach((bone2) => {
            if (bone2._waitingTransformNodeId) {
              const linkTransformNode = scene.getLastEntryById(bone2._waitingTransformNodeId);
              if (linkTransformNode) {
                bone2.linkTransformNode(linkTransformNode);
              }
              bone2._waitingTransformNodeId = null;
            }
          });
        }
        skeleton2._hasWaitingData = null;
      }
    }
    for (index = 0, cache = scene.meshes.length;index < cache; index++) {
      const currentMesh = scene.meshes[index];
      if (currentMesh._waitingData.freezeWorldMatrix) {
        currentMesh.freezeWorldMatrix();
        currentMesh._waitingData.freezeWorldMatrix = null;
      } else {
        currentMesh.computeWorldMatrix(true);
      }
    }
    for (index = 0, cache = scene.lights.length;index < cache; index++) {
      const light2 = scene.lights[index];
      if (light2._excludedMeshesIds.length > 0) {
        for (let excludedIndex = 0;excludedIndex < light2._excludedMeshesIds.length; excludedIndex++) {
          const excludedMesh = scene.getMeshById(light2._excludedMeshesIds[excludedIndex]);
          if (excludedMesh) {
            light2.excludedMeshes.push(excludedMesh);
          }
        }
        light2._excludedMeshesIds = [];
      }
      if (light2._includedOnlyMeshesIds.length > 0) {
        for (let includedOnlyIndex = 0;includedOnlyIndex < light2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
          const includedOnlyMesh = scene.getMeshById(light2._includedOnlyMeshesIds[includedOnlyIndex]);
          if (includedOnlyMesh) {
            light2.includedOnlyMeshes.push(includedOnlyMesh);
          }
        }
        light2._includedOnlyMeshesIds = [];
      }
    }
    scene.geometries.forEach((g) => {
      g._loadedUniqueId = "";
    });
    Parse(parsedData, scene, container, rootUrl);
    for (index = 0, cache = scene.meshes.length;index < cache; index++) {
      const mesh = scene.meshes[index];
      if (mesh._waitingData.actions) {
        ActionManager.Parse(mesh._waitingData.actions, mesh, scene);
        mesh._waitingData.actions = null;
      }
    }
    if (parsedData.actions !== undefined && parsedData.actions !== null) {
      ActionManager.Parse(parsedData.actions, null, scene);
    }
  } catch (err) {
    const msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
    if (onError) {
      onError(msg, err);
    } else {
      Logger.Log(msg);
      throw err;
    }
  } finally {
    tempIndexContainer = {};
    tempMaterialIndexContainer = {};
    tempMorphTargetManagerIndexContainer = {};
    if (!addToScene) {
      container.removeAllFromScene();
    }
    if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
      Logger.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
    }
  }
  return container;
};
SceneLoader.RegisterPlugin({
  name: "babylon.js",
  extensions: ".babylon",
  canDirectLoad: (data) => {
    if (data.indexOf("babylon") !== -1) {
      return true;
    }
    return false;
  },
  importMesh: (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) => {
    let log = "importMesh has failed JSON parse";
    try {
      var parsedData = JSON.parse(data);
      log = "";
      const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
      if (!meshesNames) {
        meshesNames = null;
      } else if (!Array.isArray(meshesNames)) {
        meshesNames = [meshesNames];
      }
      const hierarchyIds = [];
      const parsedIdToNodeMap = new Map;
      const loadedTransformNodes = [];
      if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
        for (let index = 0, cache = parsedData.transformNodes.length;index < cache; index++) {
          const parsedJSONTransformNode = parsedData.transformNodes[index];
          const parsedTransformNode = TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl);
          loadedTransformNodes.push(parsedTransformNode);
          parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId, parsedTransformNode);
          parsedTransformNode._waitingParsedUniqueId = null;
        }
      }
      if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
        const loadedSkeletonsIds = [];
        const loadedMaterialsIds = [];
        const loadedMaterialsUniqueIds = [];
        const loadedMorphTargetManagerIds = [];
        for (let index = 0, cache = parsedData.meshes.length;index < cache; index++) {
          const parsedMesh = parsedData.meshes[index];
          if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
            if (meshesNames !== null) {
              delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
            }
            if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
              if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
                let found = false;
                ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType) => {
                  if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) {
                    return;
                  } else {
                    parsedData.geometries[geometryType].forEach((parsedGeometryData) => {
                      if (parsedGeometryData.id === parsedMesh.geometryId) {
                        switch (geometryType) {
                          case "vertexData":
                            Geometry.Parse(parsedGeometryData, scene, rootUrl);
                            break;
                        }
                        found = true;
                      }
                    });
                  }
                });
                if (found === false) {
                  Logger.Warn("Geometry not found for mesh " + parsedMesh.id);
                }
              }
            }
            if (parsedMesh.materialUniqueId || parsedMesh.materialId) {
              const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds;
              let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1;
              if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
                const loadSubMaterial = (subMatId, predicate) => {
                  materialArray.push(subMatId);
                  const mat = parseMaterialByPredicate(predicate, parsedData, scene, rootUrl);
                  if (mat && mat.material) {
                    tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;
                    log += `
	Material ` + mat.material.toString(fullDetails);
                  }
                };
                for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length;multimatIndex < multimatCache; multimatIndex++) {
                  const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
                  if (parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId || parsedMultiMaterial.id === parsedMesh.materialId) {
                    if (parsedMultiMaterial.materialsUniqueIds) {
                      parsedMultiMaterial.materialsUniqueIds.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId));
                    } else {
                      parsedMultiMaterial.materials.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId));
                    }
                    materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id);
                    const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
                    tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;
                    if (mmat) {
                      materialFound = true;
                      log += `
	Multi-Material ` + mmat.toString(fullDetails);
                    }
                    break;
                  }
                }
              }
              if (materialFound === false) {
                materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId);
                const mat = parseMaterialByPredicate((parsedMaterial) => parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId || parsedMaterial.id === parsedMesh.materialId, parsedData, scene, rootUrl);
                if (!mat || !mat.material) {
                  Logger.Warn("Material not found for mesh " + parsedMesh.id);
                } else {
                  tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;
                  log += `
	Material ` + mat.material.toString(fullDetails);
                }
              }
            }
            if (parsedMesh.skeletonId !== null && parsedMesh.skeletonId !== undefined && parsedData.skeletonId !== -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
              const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1;
              if (!skeletonAlreadyLoaded) {
                for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length;skeletonIndex < skeletonCache; skeletonIndex++) {
                  const parsedSkeleton = parsedData.skeletons[skeletonIndex];
                  if (parsedSkeleton.id === parsedMesh.skeletonId) {
                    const skeleton2 = Skeleton.Parse(parsedSkeleton, scene);
                    skeletons.push(skeleton2);
                    loadedSkeletonsIds.push(parsedSkeleton.id);
                    log += `
	Skeleton ` + skeleton2.toString(fullDetails);
                  }
                }
              }
            }
            if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
              const morphTargetManagerAlreadyLoaded = loadedMorphTargetManagerIds.indexOf(parsedMesh.morphTargetManagerId) > -1;
              if (!morphTargetManagerAlreadyLoaded) {
                for (let morphTargetManagerIndex = 0;morphTargetManagerIndex < parsedData.morphTargetManagers.length; morphTargetManagerIndex++) {
                  const parsedManager = parsedData.morphTargetManagers[morphTargetManagerIndex];
                  if (parsedManager.id === parsedMesh.morphTargetManagerId) {
                    const morphTargetManager = MorphTargetManager.Parse(parsedManager, scene);
                    tempMorphTargetManagerIndexContainer[parsedManager.id] = morphTargetManager;
                    loadedMorphTargetManagerIds.push(parsedManager.id);
                    log += `
Morph target manager` + morphTargetManager.toString();
                  }
                }
              }
            }
            const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
            meshes.push(mesh);
            parsedIdToNodeMap.set(mesh._waitingParsedUniqueId, mesh);
            mesh._waitingParsedUniqueId = null;
            log += `
	Mesh ` + mesh.toString(fullDetails);
          }
        }
        scene.multiMaterials.forEach((multimat) => {
          multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {
            multimat.subMaterials.push(findMaterial(subMaterial, scene));
          });
          multimat._waitingSubMaterialsUniqueIds = [];
        });
        scene.meshes.forEach((mesh) => {
          if (mesh._waitingMaterialId !== null) {
            mesh.material = findMaterial(mesh._waitingMaterialId, scene);
            mesh._waitingMaterialId = null;
          }
        });
        scene.meshes.forEach((mesh) => {
          if (mesh._waitingMorphTargetManagerId !== null) {
            mesh.morphTargetManager = tempMorphTargetManagerIndexContainer[mesh._waitingMorphTargetManagerId];
            mesh._waitingMorphTargetManagerId = null;
          }
        });
        for (let index = 0, cache = scene.transformNodes.length;index < cache; index++) {
          const transformNode = scene.transformNodes[index];
          if (transformNode._waitingParentId !== null) {
            let parent = parsedIdToNodeMap.get(parseInt(transformNode._waitingParentId)) || null;
            if (parent === null) {
              parent = scene.getLastEntryById(transformNode._waitingParentId);
            }
            let parentNode = parent;
            if (transformNode._waitingParentInstanceIndex) {
              parentNode = parent.instances[parseInt(transformNode._waitingParentInstanceIndex)];
              transformNode._waitingParentInstanceIndex = null;
            }
            transformNode.parent = parentNode;
            transformNode._waitingParentId = null;
          }
        }
        let currentMesh;
        for (let index = 0, cache = scene.meshes.length;index < cache; index++) {
          currentMesh = scene.meshes[index];
          if (currentMesh._waitingParentId) {
            let parent = parsedIdToNodeMap.get(parseInt(currentMesh._waitingParentId)) || null;
            if (parent === null) {
              parent = scene.getLastEntryById(currentMesh._waitingParentId);
            }
            let parentNode = parent;
            if (currentMesh._waitingParentInstanceIndex) {
              parentNode = parent.instances[parseInt(currentMesh._waitingParentInstanceIndex)];
              currentMesh._waitingParentInstanceIndex = null;
            }
            currentMesh.parent = parentNode;
            currentMesh._waitingParentId = null;
          }
          if (currentMesh._waitingData.lods) {
            loadDetailLevels(scene, currentMesh);
          }
        }
        for (const transformNode of loadedTransformNodes) {
          const childMeshes = transformNode.getChildMeshes(false);
          if (!childMeshes.length) {
            transformNode.dispose();
          }
        }
        for (let index = 0, cache = scene.skeletons.length;index < cache; index++) {
          const skeleton2 = scene.skeletons[index];
          if (skeleton2._hasWaitingData) {
            if (skeleton2.bones != null) {
              skeleton2.bones.forEach((bone2) => {
                if (bone2._waitingTransformNodeId) {
                  const linkTransformNode = scene.getLastEntryById(bone2._waitingTransformNodeId);
                  if (linkTransformNode) {
                    bone2.linkTransformNode(linkTransformNode);
                  }
                  bone2._waitingTransformNodeId = null;
                }
              });
            }
            skeleton2._hasWaitingData = null;
          }
        }
        for (let index = 0, cache = scene.meshes.length;index < cache; index++) {
          currentMesh = scene.meshes[index];
          if (currentMesh._waitingData.freezeWorldMatrix) {
            currentMesh.freezeWorldMatrix();
            currentMesh._waitingData.freezeWorldMatrix = null;
          } else {
            currentMesh.computeWorldMatrix(true);
          }
        }
      }
      if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
        const parser = GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);
        if (parser) {
          for (let index = 0, cache = parsedData.particleSystems.length;index < cache; index++) {
            const parsedParticleSystem = parsedData.particleSystems[index];
            if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
              particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
            }
          }
        }
      }
      scene.geometries.forEach((g) => {
        g._loadedUniqueId = "";
      });
      return true;
    } catch (err) {
      const msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
      if (onError) {
        onError(msg, err);
      } else {
        Logger.Log(msg);
        throw err;
      }
    } finally {
      if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
        Logger.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
      }
      tempMaterialIndexContainer = {};
      tempMorphTargetManagerIndexContainer = {};
    }
    return false;
  },
  load: (scene, data, rootUrl, onError) => {
    let log = "importScene has failed JSON parse";
    try {
      var parsedData = JSON.parse(data);
      log = "";
      if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
        scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;
      }
      if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
        scene.autoClear = parsedData.autoClear;
      }
      if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
        scene.clearColor = Color4.FromArray(parsedData.clearColor);
      }
      if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
        scene.ambientColor = Color3.FromArray(parsedData.ambientColor);
      }
      if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
        scene.gravity = Vector3.FromArray(parsedData.gravity);
      }
      if (parsedData.useRightHandedSystem !== undefined) {
        scene.useRightHandedSystem = !!parsedData.useRightHandedSystem;
      }
      if (parsedData.fogMode !== undefined && parsedData.fogMode !== null) {
        scene.fogMode = parsedData.fogMode;
      }
      if (parsedData.fogColor !== undefined && parsedData.fogColor !== null) {
        scene.fogColor = Color3.FromArray(parsedData.fogColor);
      }
      if (parsedData.fogStart !== undefined && parsedData.fogStart !== null) {
        scene.fogStart = parsedData.fogStart;
      }
      if (parsedData.fogEnd !== undefined && parsedData.fogEnd !== null) {
        scene.fogEnd = parsedData.fogEnd;
      }
      if (parsedData.fogDensity !== undefined && parsedData.fogDensity !== null) {
        scene.fogDensity = parsedData.fogDensity;
      }
      log += "\tFog mode for scene:  ";
      switch (scene.fogMode) {
        case 0:
          log += `none
`;
          break;
        case 1:
          log += `exp
`;
          break;
        case 2:
          log += `exp2
`;
          break;
        case 3:
          log += `linear
`;
          break;
      }
      if (parsedData.physicsEnabled) {
        let physicsPlugin;
        if (parsedData.physicsEngine === "cannon" || parsedData.physicsEngine === CannonJSPlugin.name) {
          physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
        } else if (parsedData.physicsEngine === "oimo" || parsedData.physicsEngine === OimoJSPlugin.name) {
          physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
        } else if (parsedData.physicsEngine === "ammo" || parsedData.physicsEngine === AmmoJSPlugin.name) {
          physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined);
        }
        log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + ` enabled
`;
        const physicsGravity = parsedData.gravity ? Vector3.FromArray(parsedData.gravity) : parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;
        scene.enablePhysics(physicsGravity, physicsPlugin);
      }
      if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
        scene.metadata = parsedData.metadata;
      }
      if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
        scene.collisionsEnabled = parsedData.collisionsEnabled;
      }
      const container = loadAssetContainer(scene, data, rootUrl, onError, true);
      if (!container) {
        return false;
      }
      if (parsedData.autoAnimate) {
        scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1);
      }
      if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
        scene.setActiveCameraById(parsedData.activeCameraID);
      }
      return true;
    } catch (err) {
      const msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
      if (onError) {
        onError(msg, err);
      } else {
        Logger.Log(msg);
        throw err;
      }
    } finally {
      if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
        Logger.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
      }
    }
    return false;
  },
  loadAssetContainer: (scene, data, rootUrl, onError) => {
    const container = loadAssetContainer(scene, data, rootUrl, onError);
    return container;
  }
});
// node_modules/@babylonjs/core/Materials/Background/index.js
init_background_vertex();
init_background_fragment();
init_background_vertex2();
init_background_fragment2();

// node_modules/@babylonjs/core/Materials/index.js
init_colorCurves();
init_effect();

// node_modules/@babylonjs/core/Materials/fresnelParameters.js
init_deepCopier();
init_math_color();
init_decorators_serialization();
init_abstractEngine();

class FresnelParameters {
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    if (this._isEnabled === value) {
      return;
    }
    this._isEnabled = value;
    AbstractEngine.MarkAllMaterialsAsDirty(4 | 16);
  }
  constructor(options = {}) {
    this._isEnabled = true;
    this.bias = options.bias === undefined ? 0 : options.bias;
    this.power = options.power === undefined ? 1 : options.power;
    this.leftColor = options.leftColor || Color3.White();
    this.rightColor = options.rightColor || Color3.Black();
    if (options.isEnabled === false) {
      this.isEnabled = false;
    }
  }
  clone() {
    const newFresnelParameters = new FresnelParameters;
    DeepCopier.DeepCopy(this, newFresnelParameters);
    return newFresnelParameters;
  }
  equals(otherFresnelParameters) {
    return otherFresnelParameters && this.bias === otherFresnelParameters.bias && this.power === otherFresnelParameters.power && this.leftColor.equals(otherFresnelParameters.leftColor) && this.rightColor.equals(otherFresnelParameters.rightColor) && this.isEnabled === otherFresnelParameters.isEnabled;
  }
  serialize() {
    return {
      isEnabled: this.isEnabled,
      leftColor: this.leftColor.asArray(),
      rightColor: this.rightColor.asArray(),
      bias: this.bias,
      power: this.power
    };
  }
  static Parse(parsedFresnelParameters) {
    return new FresnelParameters({
      isEnabled: parsedFresnelParameters.isEnabled,
      leftColor: Color3.FromArray(parsedFresnelParameters.leftColor),
      rightColor: Color3.FromArray(parsedFresnelParameters.rightColor),
      bias: parsedFresnelParameters.bias,
      power: parsedFresnelParameters.power || 1
    });
  }
}
SerializationHelper._FresnelParametersParser = FresnelParameters.Parse;

// node_modules/@babylonjs/core/Materials/index.js
init_imageProcessingConfiguration();

// node_modules/@babylonjs/core/Materials/materialHelper.js
init_materialHelper_functions();

class MaterialHelper {
}
MaterialHelper.BindSceneUniformBuffer = BindSceneUniformBuffer;
MaterialHelper.PrepareDefinesForMergedUV = PrepareDefinesForMergedUV;
MaterialHelper.BindTextureMatrix = BindTextureMatrix;
MaterialHelper.GetFogState = GetFogState;
MaterialHelper.PrepareDefinesForMisc = PrepareDefinesForMisc;
MaterialHelper.PrepareDefinesForCamera = PrepareDefinesForCamera;
MaterialHelper.PrepareDefinesForFrameBoundValues = PrepareDefinesForFrameBoundValues;
MaterialHelper.PrepareDefinesForBones = PrepareDefinesForBones;
MaterialHelper.PrepareDefinesForMorphTargets = PrepareDefinesForMorphTargets;
MaterialHelper.PrepareDefinesForBakedVertexAnimation = PrepareDefinesForBakedVertexAnimation;
MaterialHelper.PrepareDefinesForAttributes = PrepareDefinesForAttributes;
MaterialHelper.PrepareDefinesForMultiview = PrepareDefinesForMultiview;
MaterialHelper.PrepareDefinesForOIT = PrepareDefinesForOIT;
MaterialHelper.PrepareDefinesForPrePass = PrepareDefinesForPrePass;
MaterialHelper.PrepareDefinesForLight = PrepareDefinesForLight;
MaterialHelper.PrepareDefinesForLights = PrepareDefinesForLights;
MaterialHelper.PrepareUniformsAndSamplersForLight = PrepareUniformsAndSamplersForLight;
MaterialHelper.PrepareUniformsAndSamplersList = PrepareUniformsAndSamplersList;
MaterialHelper.HandleFallbacksForShadows = HandleFallbacksForShadows;
MaterialHelper.PrepareAttributesForMorphTargetsInfluencers = PrepareAttributesForMorphTargetsInfluencers;
MaterialHelper.PrepareAttributesForMorphTargets = PrepareAttributesForMorphTargets;
MaterialHelper.PrepareAttributesForBakedVertexAnimation = PrepareAttributesForBakedVertexAnimation;
MaterialHelper.PrepareAttributesForBones = PrepareAttributesForBones;
MaterialHelper.PrepareAttributesForInstances = PrepareAttributesForInstances;
MaterialHelper.PushAttributesForInstances = PushAttributesForInstances;
MaterialHelper.BindLightProperties = BindLightProperties;
MaterialHelper.BindLight = BindLight;
MaterialHelper.BindLights = BindLights;
MaterialHelper.BindFogParameters = BindFogParameters;
MaterialHelper.BindBonesParameters = BindBonesParameters;
MaterialHelper.BindMorphTargetParameters = BindMorphTargetParameters;
MaterialHelper.BindLogDepth = BindLogDepth;
// node_modules/@babylonjs/core/Materials/Occlusion/occlusionMaterial.js
init_math_color();
init_color_fragment2();
init_color_vertex2();
// node_modules/@babylonjs/core/Materials/PBR/pbrBaseSimpleMaterial.js
init_tslib_es6();
init_decorators();
init_math_color();
class PBRBaseSimpleMaterial extends PBRBaseMaterial {
  get doubleSided() {
    return this._twoSidedLighting;
  }
  set doubleSided(value) {
    if (this._twoSidedLighting === value) {
      return;
    }
    this._twoSidedLighting = value;
    this.backFaceCulling = !value;
    this._markAllSubMeshesAsTexturesDirty();
  }
  constructor(name359, scene) {
    super(name359, scene);
    this.maxSimultaneousLights = 4;
    this.disableLighting = false;
    this.invertNormalMapX = false;
    this.invertNormalMapY = false;
    this.emissiveColor = new Color3(0, 0, 0);
    this.occlusionStrength = 1;
    this.useLightmapAsShadowmap = false;
    this._useAlphaFromAlbedoTexture = true;
    this._useAmbientInGrayScale = true;
  }
  getClassName() {
    return "PBRBaseSimpleMaterial";
  }
}
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "disableLighting", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
], PBRBaseSimpleMaterial.prototype, "environmentTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
], PBRBaseSimpleMaterial.prototype, "normalTexture", undefined);
__decorate([
  serializeAsColor3("emissive"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveColor", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
], PBRBaseSimpleMaterial.prototype, "occlusionStrength", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
], PBRBaseSimpleMaterial.prototype, "occlusionTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
], PBRBaseSimpleMaterial.prototype, "alphaCutOff", undefined);
__decorate([
  serialize()
], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRBaseSimpleMaterial.prototype, "lightmapTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", undefined);
// node_modules/@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_typeStore();

class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial {
  constructor(name359, scene) {
    super(name359, scene);
    this._useRoughnessFromMetallicTextureAlpha = false;
    this._useRoughnessFromMetallicTextureGreen = true;
    this._useMetallnessFromMetallicTextureBlue = true;
    this.metallic = 1;
    this.roughness = 1;
  }
  getClassName() {
    return "PBRMetallicRoughnessMaterial";
  }
  clone(name359) {
    const clone = SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name359, this.getScene()), this);
    clone.id = name359;
    clone.name = name359;
    this.clearCoat.copyTo(clone.clearCoat);
    this.anisotropy.copyTo(clone.anisotropy);
    this.brdf.copyTo(clone.brdf);
    this.sheen.copyTo(clone.sheen);
    this.subSurface.copyTo(clone.subSurface);
    return clone;
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
    if (!this.clearCoat.doNotSerialize) {
      serializationObject.clearCoat = this.clearCoat.serialize();
    }
    if (!this.anisotropy.doNotSerialize) {
      serializationObject.anisotropy = this.anisotropy.serialize();
    }
    if (!this.brdf.doNotSerialize) {
      serializationObject.brdf = this.brdf.serialize();
    }
    if (!this.sheen.doNotSerialize) {
      serializationObject.sheen = this.sheen.serialize();
    }
    if (!this.subSurface.doNotSerialize) {
      serializationObject.subSurface = this.subSurface.serialize();
    }
    if (!this.iridescence.doNotSerialize) {
      serializationObject.iridescence = this.iridescence.serialize();
    }
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const material = SerializationHelper.Parse(() => new PBRMetallicRoughnessMaterial(source.name, scene), source, scene, rootUrl);
    if (source.clearCoat) {
      material.clearCoat.parse(source.clearCoat, scene, rootUrl);
    }
    if (source.anisotropy) {
      material.anisotropy.parse(source.anisotropy, scene, rootUrl);
    }
    if (source.brdf) {
      material.brdf.parse(source.brdf, scene, rootUrl);
    }
    if (source.sheen) {
      material.sheen.parse(source.sheen, scene, rootUrl);
    }
    if (source.subSurface) {
      material.subSurface.parse(source.subSurface, scene, rootUrl);
    }
    if (source.iridescence) {
      material.iridescence.parse(source.iridescence, scene, rootUrl);
    }
    return material;
  }
}
__decorate([
  serializeAsColor3(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRMetallicRoughnessMaterial.prototype, "baseColor", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRMetallicRoughnessMaterial.prototype, "baseTexture", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "metallic", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "roughness", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", undefined);
RegisterClass("BABYLON.PBRMetallicRoughnessMaterial", PBRMetallicRoughnessMaterial);
// node_modules/@babylonjs/core/Materials/PBR/pbrSpecularGlossinessMaterial.js
init_tslib_es6();
init_decorators();
init_typeStore();
init_decorators_serialization();

class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial {
  get useMicroSurfaceFromReflectivityMapAlpha() {
    return this._useMicroSurfaceFromReflectivityMapAlpha;
  }
  constructor(name359, scene) {
    super(name359, scene);
    this._useMicroSurfaceFromReflectivityMapAlpha = true;
  }
  getClassName() {
    return "PBRSpecularGlossinessMaterial";
  }
  clone(name359) {
    const clone = SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name359, this.getScene()), this);
    clone.id = name359;
    clone.name = name359;
    this.clearCoat.copyTo(clone.clearCoat);
    this.anisotropy.copyTo(clone.anisotropy);
    this.brdf.copyTo(clone.brdf);
    this.sheen.copyTo(clone.sheen);
    this.subSurface.copyTo(clone.subSurface);
    return clone;
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
    if (!this.clearCoat.doNotSerialize) {
      serializationObject.clearCoat = this.clearCoat.serialize();
    }
    if (!this.anisotropy.doNotSerialize) {
      serializationObject.anisotropy = this.anisotropy.serialize();
    }
    if (!this.brdf.doNotSerialize) {
      serializationObject.brdf = this.brdf.serialize();
    }
    if (!this.sheen.doNotSerialize) {
      serializationObject.sheen = this.sheen.serialize();
    }
    if (!this.subSurface.doNotSerialize) {
      serializationObject.subSurface = this.subSurface.serialize();
    }
    if (!this.iridescence.doNotSerialize) {
      serializationObject.iridescence = this.iridescence.serialize();
    }
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const material = SerializationHelper.Parse(() => new PBRSpecularGlossinessMaterial(source.name, scene), source, scene, rootUrl);
    if (source.clearCoat) {
      material.clearCoat.parse(source.clearCoat, scene, rootUrl);
    }
    if (source.anisotropy) {
      material.anisotropy.parse(source.anisotropy, scene, rootUrl);
    }
    if (source.brdf) {
      material.brdf.parse(source.brdf, scene, rootUrl);
    }
    if (source.sheen) {
      material.sheen.parse(source.sheen, scene, rootUrl);
    }
    if (source.subSurface) {
      material.subSurface.parse(source.subSurface, scene, rootUrl);
    }
    if (source.iridescence) {
      material.iridescence.parse(source.iridescence, scene, rootUrl);
    }
    return material;
  }
}
__decorate([
  serializeAsColor3("diffuse"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", undefined);
__decorate([
  serializeAsColor3("specular"),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
], PBRSpecularGlossinessMaterial.prototype, "specularColor", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
], PBRSpecularGlossinessMaterial.prototype, "glossiness", undefined);
__decorate([
  serializeAsTexture(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", undefined);
RegisterClass("BABYLON.PBRSpecularGlossinessMaterial", PBRSpecularGlossinessMaterial);

// node_modules/@babylonjs/core/Materials/PBR/index.js
init_pbr_vertex();
init_pbr_fragment();
init_pbr_vertex2();
init_pbr_fragment2();
// node_modules/@babylonjs/core/Materials/shaderLanguage.js
var ShaderLanguage;
(function(ShaderLanguage2) {
  ShaderLanguage2[ShaderLanguage2["GLSL"] = 0] = "GLSL";
  ShaderLanguage2[ShaderLanguage2["WGSL"] = 1] = "WGSL";
})(ShaderLanguage || (ShaderLanguage = {}));
// node_modules/@babylonjs/core/Materials/Textures/index.js
init_baseTexture();
init_baseTexture_polynomial();

// node_modules/@babylonjs/core/Materials/Textures/colorGradingTexture.js
init_math_vector();
init_baseTexture();
init_typeStore();

class ColorGradingTexture extends BaseTexture {
  constructor(url, sceneOrEngine, onLoad = null) {
    super(sceneOrEngine);
    if (!url) {
      return;
    }
    this._textureMatrix = Matrix.Identity();
    this.name = url;
    this.url = url;
    this._onLoad = onLoad;
    this._texture = this._getFromCache(url, true);
    if (!this._texture) {
      const scene = this.getScene();
      if (scene) {
        if (!scene.useDelayedTextureLoading) {
          this._loadTexture();
        } else {
          this.delayLoadState = 4;
        }
      } else {
        this._loadTexture();
      }
    } else {
      this._triggerOnLoad();
    }
  }
  _triggerOnLoad() {
    if (this._onLoad) {
      this._onLoad();
    }
  }
  getTextureMatrix() {
    return this._textureMatrix;
  }
  _load3dlTexture() {
    const engine2 = this._getEngine();
    let texture;
    if (!engine2._features.support3DTextures) {
      texture = engine2.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0);
    } else {
      texture = engine2.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0);
    }
    this._texture = texture;
    this._texture.isReady = false;
    this.isCube = false;
    this.is3D = engine2._features.support3DTextures;
    this.wrapU = 0;
    this.wrapV = 0;
    this.wrapR = 0;
    this.anisotropicFilteringLevel = 1;
    const callback = (text) => {
      if (typeof text !== "string") {
        return;
      }
      let data = null;
      let tempData = null;
      let line;
      const lines = text.split(`
`);
      let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
      let maxColor = 0;
      for (let i = 0;i < lines.length; i++) {
        line = lines[i];
        if (!ColorGradingTexture._NoneEmptyLineRegex.test(line)) {
          continue;
        }
        if (line.indexOf("#") === 0) {
          continue;
        }
        const words = line.split(" ");
        if (size === 0) {
          size = words.length;
          data = new Uint8Array(size * size * size * 4);
          tempData = new Float32Array(size * size * size * 4);
          continue;
        }
        if (size != 0) {
          const r = Math.max(parseInt(words[0]), 0);
          const g = Math.max(parseInt(words[1]), 0);
          const b = Math.max(parseInt(words[2]), 0);
          maxColor = Math.max(r, maxColor);
          maxColor = Math.max(g, maxColor);
          maxColor = Math.max(b, maxColor);
          const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
          if (tempData) {
            tempData[pixelStorageIndex + 0] = r;
            tempData[pixelStorageIndex + 1] = g;
            tempData[pixelStorageIndex + 2] = b;
          }
          pixelIndexH++;
          if (pixelIndexH % size == 0) {
            pixelIndexSlice++;
            pixelIndexH = 0;
            if (pixelIndexSlice % size == 0) {
              pixelIndexW++;
              pixelIndexSlice = 0;
            }
          }
        }
      }
      if (tempData && data) {
        for (let i = 0;i < tempData.length; i++) {
          if (i > 0 && (i + 1) % 4 === 0) {
            data[i] = 255;
          } else {
            const value = tempData[i];
            data[i] = value / maxColor * 255;
          }
        }
      }
      if (texture.is3D) {
        texture.updateSize(size, size, size);
        engine2.updateRawTexture3D(texture, data, 5, false);
      } else {
        texture.updateSize(size * size, size);
        engine2.updateRawTexture(texture, data, 5, false);
      }
      texture.isReady = true;
      this._triggerOnLoad();
    };
    const scene = this.getScene();
    if (scene) {
      scene._loadFile(this.url, callback);
    } else {
      engine2._loadFile(this.url, callback);
    }
    return this._texture;
  }
  _loadTexture() {
    if (this.url) {
      const url = this.url.toLocaleLowerCase();
      if (url.endsWith(".3dl") || url.startsWith("blob:")) {
        this._load3dlTexture();
      }
    }
  }
  clone() {
    const newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine());
    newTexture.level = this.level;
    return newTexture;
  }
  delayLoad() {
    if (this.delayLoadState !== 4) {
      return;
    }
    this.delayLoadState = 1;
    this._texture = this._getFromCache(this.url, true);
    if (!this._texture) {
      this._loadTexture();
    }
  }
  static Parse(parsedTexture, scene) {
    let texture = null;
    if (parsedTexture.name && !parsedTexture.isRenderTarget) {
      texture = new ColorGradingTexture(parsedTexture.name, scene);
      texture.name = parsedTexture.name;
      texture.level = parsedTexture.level;
    }
    return texture;
  }
  serialize() {
    if (!this.name) {
      return null;
    }
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.level = this.level;
    serializationObject.customType = "BABYLON.ColorGradingTexture";
    return serializationObject;
  }
}
ColorGradingTexture._NoneEmptyLineRegex = /\S+/;
RegisterClass("BABYLON.ColorGradingTexture", ColorGradingTexture);
// node_modules/@babylonjs/core/Materials/Textures/equiRectangularCubeTexture.js
init_panoramaToCubemap();
init_baseTexture();
init_texture();
init_tools();
init_fileTools();
init_domManagement();

class EquiRectangularCubeTexture extends BaseTexture {
  constructor(url, scene, size, noMipmap = false, gammaSpace = true, onLoad = null, onError = null, supersample = false) {
    super(scene);
    this._onLoad = null;
    this._onError = null;
    if (!url) {
      throw new Error("Image url is not set");
    }
    this._coordinatesMode = Texture.CUBIC_MODE;
    this.name = url;
    this.url = url;
    this._size = size;
    this._supersample = supersample;
    this._noMipmap = noMipmap;
    this.gammaSpace = gammaSpace;
    this._onLoad = onLoad;
    this._onError = onError;
    this.hasAlpha = false;
    this.isCube = true;
    this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);
    if (!this._texture) {
      if (!scene.useDelayedTextureLoading) {
        this._loadImage(() => this._loadTexture(), this._onError);
      } else {
        this.delayLoadState = 4;
      }
    } else if (onLoad) {
      if (this._texture.isReady) {
        Tools.SetImmediate(() => onLoad());
      } else {
        this._texture.onLoadedObservable.add(onLoad);
      }
    }
  }
  _loadImage(loadTextureCallback, onError) {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    const texture = scene.getEngine().createRawCubeTexture(null, this._size, 4, scene.getEngine().getCaps().textureFloat ? 1 : 7, !this._noMipmap, false, 3);
    texture.generateMipMaps = !this._noMipmap;
    scene.addPendingData(texture);
    texture.url = this.url;
    texture.isReady = false;
    scene.getEngine()._internalTexturesCache.push(texture);
    this._texture = texture;
    LoadImage(this.url, (image) => {
      this._width = image.width;
      this._height = image.height;
      let canvas;
      if (IsDocumentAvailable()) {
        canvas = document.createElement("canvas");
        canvas.width = this._width;
        canvas.height = this._height;
      } else {
        canvas = new OffscreenCanvas(this._width, this._height);
      }
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0);
      const imageData = ctx.getImageData(0, 0, image.width, image.height);
      this._buffer = imageData.data.buffer;
      if (canvas.remove) {
        canvas.remove();
      }
      loadTextureCallback();
    }, (_, e) => {
      scene.removePendingData(texture);
      if (onError) {
        onError(`${this.getClassName()} could not be loaded`, e);
      }
    }, scene ? scene.offlineProvider : null);
  }
  _loadTexture() {
    const scene = this.getScene();
    const callback = () => {
      const imageData = this._getFloat32ArrayFromArrayBuffer(this._buffer);
      const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size, this._supersample);
      const results = [];
      for (let i = 0;i < 6; i++) {
        const dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]];
        results.push(dataFace);
      }
      return results;
    };
    if (!scene) {
      return;
    }
    const faceDataArrays = callback();
    const texture = this._texture;
    scene.getEngine().updateRawCubeTexture(texture, faceDataArrays, texture.format, texture.type, texture.invertY);
    texture.isReady = true;
    scene.removePendingData(texture);
    texture.onLoadedObservable.notifyObservers(texture);
    texture.onLoadedObservable.clear();
    if (this._onLoad) {
      this._onLoad();
    }
  }
  _getFloat32ArrayFromArrayBuffer(buffer2) {
    const dataView = new DataView(buffer2);
    const floatImageData = new Float32Array(buffer2.byteLength * 3 / 4);
    let k = 0;
    for (let i = 0;i < buffer2.byteLength; i++) {
      if ((i + 1) % 4 !== 0) {
        floatImageData[k++] = dataView.getUint8(i) / 255;
      }
    }
    return floatImageData;
  }
  getClassName() {
    return "EquiRectangularCubeTexture";
  }
  clone() {
    const scene = this.getScene();
    if (!scene) {
      return this;
    }
    const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace);
    newTexture.level = this.level;
    newTexture.wrapU = this.wrapU;
    newTexture.wrapV = this.wrapV;
    newTexture.coordinatesIndex = this.coordinatesIndex;
    newTexture.coordinatesMode = this.coordinatesMode;
    return newTexture;
  }
}
EquiRectangularCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"];
// node_modules/@babylonjs/core/Materials/Textures/htmlElementTexture.js
init_baseTexture();
init_math_vector();
init_observable();
class HtmlElementTexture extends BaseTexture {
  constructor(name359, element, options) {
    super(options.scene || options.engine);
    this.onLoadObservable = new Observable;
    if (!element || !options.engine && !options.scene) {
      return;
    }
    options = {
      ...HtmlElementTexture._DefaultOptions,
      ...options
    };
    this._generateMipMaps = options.generateMipMaps;
    this._samplingMode = options.samplingMode;
    this._textureMatrix = Matrix.Identity();
    this._format = options.format;
    this.name = name359;
    this.element = element;
    this._isVideo = !!element.getVideoPlaybackQuality;
    if (this._isVideo) {
      const engineWebGPU = this._engine;
      const createExternalTexture = engineWebGPU?.createExternalTexture;
      if (createExternalTexture) {
        this._externalTexture = createExternalTexture.call(engineWebGPU, element);
      }
    }
    this.anisotropicFilteringLevel = 1;
    this._createInternalTexture();
  }
  _createInternalTexture() {
    let width = 0;
    let height = 0;
    if (this._isVideo) {
      width = this.element.videoWidth;
      height = this.element.videoHeight;
    } else {
      width = this.element.width;
      height = this.element.height;
    }
    const engine2 = this._getEngine();
    if (engine2) {
      this._texture = engine2.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode);
      this._texture.format = this._format;
    }
    this.update();
  }
  getTextureMatrix() {
    return this._textureMatrix;
  }
  update(invertY = null) {
    const engine2 = this._getEngine();
    if (this._texture == null || engine2 == null) {
      return;
    }
    const wasReady = this.isReady();
    if (this._isVideo) {
      const videoElement = this.element;
      if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) {
        return;
      }
      engine2.updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : videoElement, invertY === null ? true : invertY);
    } else {
      const canvasElement = this.element;
      engine2.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false, this._format);
    }
    if (!wasReady && this.isReady()) {
      this.onLoadObservable.notifyObservers(this);
    }
  }
  dispose() {
    this.onLoadObservable.clear();
    super.dispose();
  }
}
HtmlElementTexture._DefaultOptions = {
  generateMipMaps: false,
  samplingMode: 2,
  format: 5,
  engine: null,
  scene: null
};

// node_modules/@babylonjs/core/Materials/Textures/index.js
init_internalTexture();

// node_modules/@babylonjs/core/Materials/Textures/Loaders/index.js
init_ddsTextureLoader();
init_envTextureLoader();
init_ktxTextureLoader();
init_tgaTextureLoader();
init_hdrTextureLoader();
init_basisTextureLoader();
init_exrTextureLoader();
init_iesTextureLoader();
init_textureLoaderManager();

// node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/index.js
init_exrLoader_compression();
init_exrLoader_compression_huf();
init_exrLoader_configuration();
init_exrLoader_core();
init_exrLoader_decoder();
init_exrLoader_header();
// node_modules/@babylonjs/core/Materials/Textures/multiRenderTarget.js
init_texture();
init_renderTargetTexture();
class MultiRenderTarget extends RenderTargetTexture {
  get isSupported() {
    return this._engine?.getCaps().drawBuffersExtension ?? false;
  }
  get textures() {
    return this._textures;
  }
  get count() {
    return this._count;
  }
  get depthTexture() {
    return this._textures[this._textures.length - 1];
  }
  set wrapU(wrap) {
    if (this._textures) {
      for (let i = 0;i < this._textures.length; i++) {
        this._textures[i].wrapU = wrap;
      }
    }
  }
  set wrapV(wrap) {
    if (this._textures) {
      for (let i = 0;i < this._textures.length; i++) {
        this._textures[i].wrapV = wrap;
      }
    }
  }
  constructor(name359, size, count, scene, options, textureNames) {
    const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
    const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
    const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15;
    const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
    const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false;
    super(name359, size, scene, generateMipMaps, doNotChangeAspectRatio, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
    if (!this.isSupported) {
      this.dispose();
      return;
    }
    this._textureNames = textureNames;
    const types = [];
    const samplingModes = [];
    const useSRGBBuffers = [];
    const formats = [];
    const targetTypes = [];
    const faceIndex = [];
    const layerIndex = [];
    const layerCounts = [];
    this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);
    const generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
    const generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
    const samples = options && options.samples ? options.samples : 1;
    this._multiRenderTargetOptions = {
      samplingModes,
      generateMipMaps,
      generateDepthBuffer,
      generateStencilBuffer,
      generateDepthTexture,
      depthTextureFormat,
      types,
      textureCount: count,
      useSRGBBuffers,
      samples,
      formats,
      targetTypes,
      faceIndex,
      layerIndex,
      layerCounts,
      labels: textureNames,
      label: name359
    };
    this._count = count;
    this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault;
    if (count > 0) {
      this._createInternalTextures();
      this._createTextures(textureNames);
    }
  }
  _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) {
    for (let i = 0;i < count; i++) {
      if (options && options.types && options.types[i] !== undefined) {
        types.push(options.types[i]);
      } else {
        types.push(options && options.defaultType ? options.defaultType : 0);
      }
      if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
        samplingModes.push(options.samplingModes[i]);
      } else {
        samplingModes.push(Texture.BILINEAR_SAMPLINGMODE);
      }
      if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== undefined) {
        useSRGBBuffers.push(options.useSRGBBuffers[i]);
      } else {
        useSRGBBuffers.push(false);
      }
      if (options && options.formats && options.formats[i] !== undefined) {
        formats.push(options.formats[i]);
      } else {
        formats.push(5);
      }
      if (options && options.targetTypes && options.targetTypes[i] !== undefined) {
        targets.push(options.targetTypes[i]);
      } else {
        targets.push(3553);
      }
      if (options && options.faceIndex && options.faceIndex[i] !== undefined) {
        faceIndex.push(options.faceIndex[i]);
      } else {
        faceIndex.push(0);
      }
      if (options && options.layerIndex && options.layerIndex[i] !== undefined) {
        layerIndex.push(options.layerIndex[i]);
      } else {
        layerIndex.push(0);
      }
      if (options && options.layerCounts && options.layerCounts[i] !== undefined) {
        layerCounts.push(options.layerCounts[i]);
      } else {
        layerCounts.push(1);
      }
    }
  }
  _createInternaTextureIndexMapping() {
    const mapMainInternalTexture2Index = {};
    const mapInternalTexture2MainIndex = [];
    if (!this._renderTarget) {
      return mapInternalTexture2MainIndex;
    }
    const internalTextures = this._renderTarget.textures;
    for (let i = 0;i < internalTextures.length; i++) {
      const texture = internalTextures[i];
      if (!texture) {
        continue;
      }
      const mainIndex = mapMainInternalTexture2Index[texture.uniqueId];
      if (mainIndex !== undefined) {
        mapInternalTexture2MainIndex[i] = mainIndex;
      } else {
        mapMainInternalTexture2Index[texture.uniqueId] = i;
      }
    }
    return mapInternalTexture2MainIndex;
  }
  _rebuild(fromContextLost = false, forceFullRebuild = false, textureNames) {
    if (this._count < 1 || fromContextLost) {
      return;
    }
    const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping();
    this.releaseInternalTextures();
    this._createInternalTextures();
    if (forceFullRebuild) {
      this._releaseTextures();
      this._createTextures(textureNames);
    }
    const internalTextures = this._renderTarget.textures;
    for (let i = 0;i < internalTextures.length; i++) {
      const texture = this._textures[i];
      if (mapInternalTexture2MainIndex[i] !== undefined) {
        this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i);
      }
      texture._texture = internalTextures[i];
      if (texture._texture) {
        texture._noMipmap = !texture._texture.useMipMaps;
        texture._useSRGBBuffer = texture._texture._useSRGBBuffer;
      }
    }
    if (this.samples !== 1) {
      this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true);
    }
  }
  _createInternalTextures() {
    this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault);
    this._texture = this._renderTarget.texture;
  }
  _releaseTextures() {
    if (this._textures) {
      for (let i = 0;i < this._textures.length; i++) {
        this._textures[i]._texture = null;
        this._textures[i].dispose();
      }
    }
  }
  _createTextures(textureNames) {
    const internalTextures = this._renderTarget.textures;
    this._textures = [];
    for (let i = 0;i < internalTextures.length; i++) {
      const texture = new Texture(null, this.getScene());
      if (textureNames?.[i]) {
        texture.name = textureNames[i];
      }
      texture._texture = internalTextures[i];
      if (texture._texture) {
        texture._noMipmap = !texture._texture.useMipMaps;
        texture._useSRGBBuffer = texture._texture._useSRGBBuffer;
      }
      this._textures.push(texture);
    }
  }
  setInternalTexture(texture, index, disposePrevious = true) {
    if (!this.renderTarget) {
      return;
    }
    if (index === 0) {
      this._texture = texture;
    }
    this.renderTarget.setTexture(texture, index, disposePrevious);
    if (!this.textures[index]) {
      this.textures[index] = new Texture(null, this.getScene());
      this.textures[index].name = this._textureNames?.[index] ?? this.textures[index].name;
    }
    this.textures[index]._texture = texture;
    this.textures[index]._noMipmap = !texture.useMipMaps;
    this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer;
    this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0;
    if (this._multiRenderTargetOptions.types) {
      this._multiRenderTargetOptions.types[index] = texture.type;
    }
    if (this._multiRenderTargetOptions.samplingModes) {
      this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode;
    }
    if (this._multiRenderTargetOptions.useSRGBBuffers) {
      this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer;
    }
    if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) {
      let target = 0;
      if (texture.is2DArray) {
        target = 35866;
      } else if (texture.isCube) {
        target = 34067;
      } else if (texture.is3D) {
        target = 32879;
      } else {
        target = 3553;
      }
      this._multiRenderTargetOptions.targetTypes[index] = target;
    }
  }
  setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) {
    if (!this.textures[index] || !this.renderTarget) {
      return;
    }
    if (this._multiRenderTargetOptions.layerIndex) {
      this._multiRenderTargetOptions.layerIndex[index] = layerIndex;
    }
    if (this._multiRenderTargetOptions.faceIndex) {
      this._multiRenderTargetOptions.faceIndex[index] = faceIndex;
    }
    this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex);
  }
  setLayerAndFaceIndices(layerIndices, faceIndices) {
    if (!this.renderTarget) {
      return;
    }
    this._multiRenderTargetOptions.layerIndex = layerIndices;
    this._multiRenderTargetOptions.faceIndex = faceIndices;
    this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices);
  }
  get samples() {
    return this._samples;
  }
  set samples(value) {
    if (this._renderTarget) {
      this._samples = this._renderTarget.setSamples(value);
    } else {
      this._samples = value;
    }
  }
  resize(size) {
    this._processSizeParameter(size);
    this._rebuild(false, undefined, this._textureNames);
  }
  updateCount(count, options, textureNames) {
    this._multiRenderTargetOptions.textureCount = count;
    this._count = count;
    const types = [];
    const samplingModes = [];
    const useSRGBBuffers = [];
    const formats = [];
    const targetTypes = [];
    const faceIndex = [];
    const layerIndex = [];
    const layerCounts = [];
    this._textureNames = textureNames;
    this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);
    this._multiRenderTargetOptions.types = types;
    this._multiRenderTargetOptions.samplingModes = samplingModes;
    this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers;
    this._multiRenderTargetOptions.formats = formats;
    this._multiRenderTargetOptions.targetTypes = targetTypes;
    this._multiRenderTargetOptions.faceIndex = faceIndex;
    this._multiRenderTargetOptions.layerIndex = layerIndex;
    this._multiRenderTargetOptions.layerCounts = layerCounts;
    this._multiRenderTargetOptions.labels = textureNames;
    this._rebuild(false, true, textureNames);
  }
  _unbindFrameBuffer(engine2, faceIndex) {
    if (this._renderTarget) {
      engine2.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => {
        this.onAfterRenderObservable.notifyObservers(faceIndex);
      });
    }
  }
  dispose(doNotDisposeInternalTextures = false) {
    this._releaseTextures();
    if (!doNotDisposeInternalTextures) {
      this.releaseInternalTextures();
    } else {
      this._texture = null;
    }
    super.dispose();
  }
  releaseInternalTextures() {
    const internalTextures = this._renderTarget?.textures;
    if (!internalTextures) {
      return;
    }
    for (let i = internalTextures.length - 1;i >= 0; i--) {
      this._textures[i]._texture = null;
    }
    this._renderTarget?.dispose();
    this._renderTarget = null;
  }
}
// node_modules/@babylonjs/core/Materials/Textures/Packer/packer.js
init_buffer();
init_texture();
init_math_vector();
init_math_color();

// node_modules/@babylonjs/core/Materials/Textures/Packer/frame.js
class TexturePackerFrame {
  constructor(id, scale, offset) {
    this.id = id;
    this.scale = scale;
    this.offset = offset;
  }
}

// node_modules/@babylonjs/core/Materials/Textures/Packer/packer.js
init_logger();
init_tools();

class TexturePacker {
  constructor(name359, meshes, options, scene) {
    this.name = name359;
    this.meshes = meshes;
    this.scene = scene;
    this.options = options;
    this.options.map = this.options.map ?? [
      "ambientTexture",
      "bumpTexture",
      "diffuseTexture",
      "emissiveTexture",
      "lightmapTexture",
      "opacityTexture",
      "reflectionTexture",
      "refractionTexture",
      "specularTexture"
    ];
    this.options.uvsIn = this.options.uvsIn ?? VertexBuffer.UVKind;
    this.options.uvsOut = this.options.uvsOut ?? VertexBuffer.UVKind;
    this.options.layout = this.options.layout ?? TexturePacker.LAYOUT_STRIP;
    if (this.options.layout === TexturePacker.LAYOUT_COLNUM) {
      this.options.colnum = this.options.colnum ?? 8;
    }
    this.options.updateInputMeshes = this.options.updateInputMeshes ?? true;
    this.options.disposeSources = this.options.disposeSources ?? true;
    this._expecting = 0;
    this.options.fillBlanks = this.options.fillBlanks ?? true;
    if (this.options.fillBlanks === true) {
      this.options.customFillColor = this.options.customFillColor ?? "black";
    }
    this.options.frameSize = this.options.frameSize ?? 256;
    this.options.paddingRatio = this.options.paddingRatio ?? 0.0115;
    this._paddingValue = Math.ceil(this.options.frameSize * this.options.paddingRatio);
    if (this._paddingValue % 2 !== 0) {
      this._paddingValue++;
    }
    this.options.paddingMode = this.options.paddingMode ?? TexturePacker.SUBUV_WRAP;
    if (this.options.paddingMode === TexturePacker.SUBUV_COLOR) {
      this.options.paddingColor = this.options.paddingColor ?? new Color4(0, 0, 0, 1);
    }
    this.sets = {};
    this.frames = [];
    return this;
  }
  _createFrames(resolve3) {
    const dtSize = this._calculateSize();
    const dtUnits = new Vector2(1, 1).divide(dtSize);
    let doneCount = 0;
    const expecting = this._expecting;
    const meshLength = this.meshes.length;
    const sKeys = Object.keys(this.sets);
    for (let i = 0;i < sKeys.length; i++) {
      const setName = sKeys[i];
      const dt = new DynamicTexture(this.name + ".TexturePack." + setName + "Set", { width: dtSize.x, height: dtSize.y }, this.scene, true, Texture.TRILINEAR_SAMPLINGMODE, 5);
      const dtx = dt.getContext();
      dtx.fillStyle = "rgba(0,0,0,0)";
      dtx.fillRect(0, 0, dtSize.x, dtSize.y);
      dt.update(false);
      this.sets[setName] = dt;
    }
    const baseSize = this.options.frameSize || 256;
    const padding = this._paddingValue;
    const tcs = baseSize + 2 * padding;
    const done = () => {
      this._calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, this.options.updateInputMeshes || false);
    };
    for (let i = 0;i < meshLength; i++) {
      const m = this.meshes[i];
      const mat = m.material;
      for (let j = 0;j < sKeys.length; j++) {
        const tempTexture = new DynamicTexture("temp", tcs, this.scene, true);
        const tcx = tempTexture.getContext();
        const offset = this._getFrameOffset(i);
        const updateDt = () => {
          doneCount++;
          tempTexture.update(false);
          const iDat = tcx.getImageData(0, 0, tcs, tcs);
          const dt = this.sets[setName];
          const dtx = dt.getContext();
          dtx.putImageData(iDat, dtSize.x * offset.x, dtSize.y * offset.y);
          tempTexture.dispose();
          dt.update(false);
          if (doneCount == expecting) {
            done();
            resolve3();
            return;
          }
        };
        const setName = sKeys[j] || "_blank";
        if (!mat || mat[setName] === null) {
          tcx.fillStyle = "rgba(0,0,0,0)";
          if (this.options.fillBlanks) {
            tcx.fillStyle = this.options.customFillColor;
          }
          tcx.fillRect(0, 0, tcs, tcs);
          updateDt();
        } else {
          const setTexture = mat[setName];
          const img = new Image;
          if (setTexture instanceof DynamicTexture) {
            img.src = setTexture.getContext().canvas.toDataURL("image/png");
          } else {
            img.src = setTexture.url;
          }
          Tools.SetCorsBehavior(img.src, img);
          img.onload = () => {
            tcx.fillStyle = "rgba(0,0,0,0)";
            tcx.fillRect(0, 0, tcs, tcs);
            tempTexture.update(false);
            tcx.setTransform(1, 0, 0, -1, 0, 0);
            const cellOffsets = [0, 0, 1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1 - 1, 0, -1, 1, -1];
            switch (this.options.paddingMode) {
              case 0:
                for (let i2 = 0;i2 < 9; i2++) {
                  tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[i2], padding + baseSize * cellOffsets[i2 + 1] - tcs, baseSize, baseSize);
                }
                break;
              case 1:
                for (let i2 = 0;i2 < padding; i2++) {
                  tcx.drawImage(img, 0, 0, img.width, img.height, i2 + baseSize * cellOffsets[0], padding - tcs, baseSize, baseSize);
                  tcx.drawImage(img, 0, 0, img.width, img.height, padding * 2 - i2, padding - tcs, baseSize, baseSize);
                  tcx.drawImage(img, 0, 0, img.width, img.height, padding, i2 - tcs, baseSize, baseSize);
                  tcx.drawImage(img, 0, 0, img.width, img.height, padding, padding * 2 - i2 - tcs, baseSize, baseSize);
                }
                tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);
                break;
              case 2:
                tcx.fillStyle = (this.options.paddingColor || Color3.Black()).toHexString();
                tcx.fillRect(0, 0, tcs, -tcs);
                tcx.clearRect(padding, padding, baseSize, baseSize);
                tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);
                break;
            }
            tcx.setTransform(1, 0, 0, 1, 0, 0);
            updateDt();
          };
        }
      }
    }
  }
  _calculateSize() {
    const meshLength = this.meshes.length || 0;
    const baseSize = this.options.frameSize || 0;
    const padding = this._paddingValue || 0;
    switch (this.options.layout) {
      case 0: {
        return new Vector2(baseSize * meshLength + 2 * padding * meshLength, baseSize + 2 * padding);
      }
      case 1: {
        const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));
        const size = baseSize * sqrtCount + 2 * padding * sqrtCount;
        return new Vector2(size, size);
      }
      case 2: {
        const cols = this.options.colnum || 1;
        const rowCnt = Math.max(1, Math.ceil(meshLength / cols));
        return new Vector2(baseSize * cols + 2 * padding * cols, baseSize * rowCnt + 2 * padding * rowCnt);
      }
    }
    return Vector2.Zero();
  }
  _calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, update) {
    const meshLength = this.meshes.length;
    for (let i = 0;i < meshLength; i++) {
      const m = this.meshes[i];
      const scale = new Vector2(baseSize / dtSize.x, baseSize / dtSize.y);
      const pOffset = dtUnits.clone().scale(padding);
      const frameOffset = this._getFrameOffset(i);
      const offset = frameOffset.add(pOffset);
      const frame = new TexturePackerFrame(i, scale, offset);
      this.frames.push(frame);
      if (update) {
        this._updateMeshUV(m, i);
        this._updateTextureReferences(m);
      }
    }
  }
  _getFrameOffset(index) {
    const meshLength = this.meshes.length;
    let uvStep, yStep, xStep;
    switch (this.options.layout) {
      case 0: {
        uvStep = 1 / meshLength;
        return new Vector2(index * uvStep, 0);
      }
      case 1: {
        const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));
        yStep = Math.floor(index / sqrtCount);
        xStep = index - yStep * sqrtCount;
        uvStep = 1 / sqrtCount;
        return new Vector2(xStep * uvStep, yStep * uvStep);
      }
      case 2: {
        const cols = this.options.colnum || 1;
        const rowCnt = Math.max(1, Math.ceil(meshLength / cols));
        xStep = Math.floor(index / rowCnt);
        yStep = index - xStep * rowCnt;
        uvStep = new Vector2(1 / cols, 1 / rowCnt);
        return new Vector2(xStep * uvStep.x, yStep * uvStep.y);
      }
    }
    return Vector2.Zero();
  }
  _updateMeshUV(mesh, frameID) {
    const frame = this.frames[frameID];
    const uvIn = mesh.getVerticesData(this.options.uvsIn || VertexBuffer.UVKind);
    const uvOut = [];
    let toCount = 0;
    if (uvIn.length) {
      toCount = uvIn.length || 0;
    }
    for (let i = 0;i < toCount; i += 2) {
      uvOut.push(uvIn[i] * frame.scale.x + frame.offset.x, uvIn[i + 1] * frame.scale.y + frame.offset.y);
    }
    mesh.setVerticesData(this.options.uvsOut || VertexBuffer.UVKind, uvOut);
  }
  _updateTextureReferences(m, force = false) {
    const mat = m.material;
    const sKeys = Object.keys(this.sets);
    const _dispose = (_t) => {
      if (_t.dispose) {
        _t.dispose();
      }
    };
    for (let i = 0;i < sKeys.length; i++) {
      const setName = sKeys[i];
      if (!force) {
        if (!mat) {
          return;
        }
        if (mat[setName] !== null) {
          _dispose(mat[setName]);
          mat[setName] = this.sets[setName];
        }
      } else {
        if (mat[setName] !== null) {
          _dispose(mat[setName]);
        }
        mat[setName] = this.sets[setName];
      }
    }
  }
  setMeshToFrame(m, frameID, updateMaterial = false) {
    this._updateMeshUV(m, frameID);
    if (updateMaterial) {
      this._updateTextureReferences(m, true);
    }
  }
  processAsync() {
    return new Promise((resolve3, reject) => {
      try {
        if (this.meshes.length === 0) {
          resolve3();
          return;
        }
        let done = 0;
        const doneCheck = (mat) => {
          done++;
          if (this.options.map) {
            for (let j = 0;j < this.options.map.length; j++) {
              const index = this.options.map[j];
              const t = mat[index];
              if (t !== null) {
                if (!this.sets[this.options.map[j]]) {
                  this.sets[this.options.map[j]] = true;
                }
                this._expecting++;
              }
            }
            if (done === this.meshes.length) {
              this._createFrames(resolve3);
            }
          }
        };
        for (let i = 0;i < this.meshes.length; i++) {
          const mesh = this.meshes[i];
          const material = mesh.material;
          if (!material) {
            done++;
            if (done === this.meshes.length) {
              return this._createFrames(resolve3);
            }
            continue;
          }
          material.forceCompilationAsync(mesh).then(() => {
            doneCheck(material);
          });
        }
      } catch (e) {
        return reject(e);
      }
    });
  }
  dispose() {
    const sKeys = Object.keys(this.sets);
    for (let i = 0;i < sKeys.length; i++) {
      const channel = sKeys[i];
      this.sets[channel].dispose();
    }
  }
  download(imageType = "png", quality = 1) {
    setTimeout(() => {
      const pack = {
        name: this.name,
        sets: {},
        options: {},
        frames: []
      };
      const sKeys = Object.keys(this.sets);
      const oKeys = Object.keys(this.options);
      try {
        for (let i = 0;i < sKeys.length; i++) {
          const channel = sKeys[i];
          const dt = this.sets[channel];
          pack.sets[channel] = dt.getContext().canvas.toDataURL("image/" + imageType, quality);
        }
        for (let i = 0;i < oKeys.length; i++) {
          const opt = oKeys[i];
          pack.options[opt] = this.options[opt];
        }
        for (let i = 0;i < this.frames.length; i++) {
          const _f = this.frames[i];
          pack.frames.push(_f.scale.x, _f.scale.y, _f.offset.x, _f.offset.y);
        }
      } catch (err) {
        Logger.Warn("Unable to download: " + err);
        return;
      }
      const data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(pack, null, 4));
      const _a = document.createElement("a");
      _a.setAttribute("href", data);
      _a.setAttribute("download", this.name + "_texurePackage.json");
      document.body.appendChild(_a);
      _a.click();
      _a.remove();
    }, 0);
  }
  updateFromJSON(data) {
    try {
      const parsedData = JSON.parse(data);
      this.name = parsedData.name;
      const _options = Object.keys(parsedData.options);
      for (let i = 0;i < _options.length; i++) {
        this.options[_options[i]] = parsedData.options[_options[i]];
      }
      for (let i = 0;i < parsedData.frames.length; i += 4) {
        const frame = new TexturePackerFrame(i / 4, new Vector2(parsedData.frames[i], parsedData.frames[i + 1]), new Vector2(parsedData.frames[i + 2], parsedData.frames[i + 3]));
        this.frames.push(frame);
      }
      const channels = Object.keys(parsedData.sets);
      for (let i = 0;i < channels.length; i++) {
        const _t = new Texture(parsedData.sets[channels[i]], this.scene, false, false);
        this.sets[channels[i]] = _t;
      }
    } catch (err) {
      Logger.Warn("Unable to update from JSON: " + err);
    }
  }
}
TexturePacker.LAYOUT_STRIP = 0;
TexturePacker.LAYOUT_POWER2 = 1;
TexturePacker.LAYOUT_COLNUM = 2;
TexturePacker.SUBUV_WRAP = 0;
TexturePacker.SUBUV_EXTEND = 1;
TexturePacker.SUBUV_COLOR = 2;
// node_modules/@babylonjs/core/Materials/Textures/Procedurals/customProceduralTexture.js
init_logger();
init_math_vector();
init_math_color();
init_texture();
init_webRequest();
// node_modules/@babylonjs/core/Materials/Textures/Procedurals/noiseProceduralTexture.js
init_engineStore();
init_typeStore();

// node_modules/@babylonjs/core/Shaders/noise.fragment.js
init_shaderStore();
var name359 = "noisePixelShader";
var shader358 = `uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p)
{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);}
float interpolationNoise(vec2 p)
{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); 
return ym;}
float perlinNoise2D(float x,float y)
{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++)
{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;}
return sum;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);}
`;
if (!ShaderStore.ShadersStore[name359]) {
  ShaderStore.ShadersStore[name359] = shader358;
}

// node_modules/@babylonjs/core/Materials/Textures/Procedurals/noiseProceduralTexture.js
class NoiseProceduralTexture extends ProceduralTexture {
  constructor(name360, size = 256, scene = EngineStore.LastCreatedScene, fallbackTexture, generateMipMaps) {
    super(name360, size, "noise", scene, fallbackTexture, generateMipMaps);
    this.time = 0;
    this.brightness = 0.2;
    this.octaves = 3;
    this.persistence = 0.8;
    this.animationSpeedFactor = 1;
    this.autoClear = false;
    this._updateShaderUniforms();
  }
  _updateShaderUniforms() {
    const scene = this.getScene();
    if (!scene) {
      return;
    }
    this.time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
    this.setFloat("brightness", this.brightness);
    this.setFloat("persistence", this.persistence);
    this.setFloat("timeScale", this.time);
  }
  _getDefines() {
    return "#define OCTAVES " + (this.octaves | 0);
  }
  render(useCameraPostProcess) {
    this._updateShaderUniforms();
    super.render(useCameraPostProcess);
  }
  serialize() {
    const serializationObject = {};
    serializationObject.customType = "BABYLON.NoiseProceduralTexture";
    serializationObject.brightness = this.brightness;
    serializationObject.octaves = this.octaves;
    serializationObject.persistence = this.persistence;
    serializationObject.animationSpeedFactor = this.animationSpeedFactor;
    serializationObject.size = this.getSize().width;
    serializationObject.generateMipMaps = this._generateMipMaps;
    serializationObject.time = this.time;
    return serializationObject;
  }
  clone() {
    const textureSize = this.getSize();
    const newTexture = new NoiseProceduralTexture(this.name, textureSize.width, this.getScene(), this._fallbackTexture ? this._fallbackTexture : undefined, this._generateMipMaps);
    newTexture.hasAlpha = this.hasAlpha;
    newTexture.level = this.level;
    newTexture.coordinatesMode = this.coordinatesMode;
    newTexture.brightness = this.brightness;
    newTexture.octaves = this.octaves;
    newTexture.persistence = this.persistence;
    newTexture.animationSpeedFactor = this.animationSpeedFactor;
    newTexture.time = this.time;
    return newTexture;
  }
  static Parse(parsedTexture, scene) {
    const texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
    texture.brightness = parsedTexture.brightness;
    texture.octaves = parsedTexture.octaves;
    texture.persistence = parsedTexture.persistence;
    texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
    texture.time = parsedTexture.time ?? 0;
    return texture;
  }
}
RegisterClass("BABYLON.NoiseProceduralTexture", NoiseProceduralTexture);
// node_modules/@babylonjs/core/Materials/Textures/rawCubeTexture.js
init_decorators_serialization();
init_environmentTextureTools();
// node_modules/@babylonjs/core/Materials/Textures/rawTexture3D.js
init_texture();
// node_modules/@babylonjs/core/Materials/Textures/refractionTexture.js
init_math_plane();
init_renderTargetTexture();

// node_modules/@babylonjs/core/Materials/Textures/index.js
init_renderTargetTexture();
init_texture();
init_thinTexture();

// node_modules/@babylonjs/core/Materials/Textures/thinRenderTargetTexture.js
init_thinTexture();

// node_modules/@babylonjs/core/Materials/Textures/index.js
init_ktx2decoderTypes();
init_procedural_vertex();
init_procedural_vertex2();
init_hdrFiltering_vertex2();
init_hdrFiltering_fragment2();
init_hdrFiltering_vertex();
init_hdrFiltering_fragment();
init_hdrIrradianceFiltering_vertex2();
init_hdrIrradianceFiltering_fragment2();
init_hdrIrradianceFiltering_vertex();
init_hdrIrradianceFiltering_fragment();

// node_modules/@babylonjs/core/Materials/index.js
init_uniformBuffer();
// node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.js
var NodeMaterialBlockConnectionPointMode;
(function(NodeMaterialBlockConnectionPointMode2) {
  NodeMaterialBlockConnectionPointMode2[NodeMaterialBlockConnectionPointMode2["Uniform"] = 0] = "Uniform";
  NodeMaterialBlockConnectionPointMode2[NodeMaterialBlockConnectionPointMode2["Attribute"] = 1] = "Attribute";
  NodeMaterialBlockConnectionPointMode2[NodeMaterialBlockConnectionPointMode2["Varying"] = 2] = "Varying";
  NodeMaterialBlockConnectionPointMode2[NodeMaterialBlockConnectionPointMode2["Undefined"] = 3] = "Undefined";
})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));
// node_modules/@babylonjs/core/Materials/Node/nodeMaterialConnectionPointCustomObject.js
class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint {
  constructor(name360, ownerBlock, direction, _blockType, _blockName) {
    super(name360, ownerBlock, direction);
    this._blockType = _blockType;
    this._blockName = _blockName;
    this.needDualDirectionValidation = true;
  }
  checkCompatibilityState(connectionPoint) {
    return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint._blockName === this._blockName ? 0 : 1;
  }
  createCustomInputBlock() {
    return [new this._blockType(this._blockName), this.name];
  }
}
// node_modules/@babylonjs/core/Materials/Node/Blocks/GaussianSplatting/gaussianSplattingBlock.js
init_typeStore();
class GaussianSplattingBlock extends NodeMaterialBlock {
  constructor(name360) {
    super(name360, NodeMaterialBlockTargets.Vertex);
    this._isUnique = true;
    this.registerInput("splatPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("splatScale", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Vertex);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("projection", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerOutput("splatVertex", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Vertex);
  }
  getClassName() {
    return "GaussianSplattingBlock";
  }
  get splatPosition() {
    return this._inputs[0];
  }
  get splatScale() {
    return this._inputs[1];
  }
  get world() {
    return this._inputs[2];
  }
  get view() {
    return this._inputs[3];
  }
  get projection() {
    return this._inputs[4];
  }
  get splatVertex() {
    return this._outputs[0];
  }
  initialize(state) {
    state._excludeVariableName("focal");
    state._excludeVariableName("invViewport");
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      return;
    }
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("gaussianSplattingVertexDeclaration", comments);
    state._emitFunctionFromInclude("gaussianSplatting", comments);
    state._emitUniformFromString("focal", NodeMaterialBlockConnectionPointTypes.Vector2);
    state._emitUniformFromString("invViewport", NodeMaterialBlockConnectionPointTypes.Vector2);
    state.attributes.push(VertexBuffer.PositionKind);
    state.sharedData.nodeMaterial.backFaceCulling = false;
    const splatPosition = this.splatPosition;
    const splatScale = this.splatScale;
    const world = this.world;
    const view = this.view;
    const projection = this.projection;
    const output = this.splatVertex;
    const addF = state.fSuffix;
    let splatScaleParameter = `vec2${addF}(1.,1.)`;
    if (splatScale.isConnected) {
      splatScaleParameter = splatScale.associatedVariableName;
    }
    let input = "position";
    let uniforms = "";
    if (state.shaderLanguage === 1) {
      input = "input.position";
      uniforms = ", uniforms.focal, uniforms.invViewport";
    }
    state.compilationString += `${state._declareOutput(output)} = gaussianSplatting(${input}, ${splatPosition.associatedVariableName}, ${splatScaleParameter}, covA, covB, ${world.associatedVariableName}, ${view.associatedVariableName}, ${projection.associatedVariableName}${uniforms});
`;
    return this;
  }
}
RegisterClass("BABYLON.GaussianSplattingBlock", GaussianSplattingBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/GaussianSplatting/gaussianBlock.js
init_typeStore();

class GaussianBlock extends NodeMaterialBlock {
  constructor(name360) {
    super(name360, NodeMaterialBlockTargets.Fragment);
    this._isUnique = false;
    this.registerInput("splatColor", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "GaussianBlock";
  }
  get splatColor() {
    return this._inputs[0];
  }
  get rgba() {
    return this._outputs[0];
  }
  initialize(state) {
    state._excludeVariableName("vPosition");
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      return;
    }
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("clipPlaneFragmentDeclaration", comments);
    state._emitFunctionFromInclude("logDepthDeclaration", comments);
    state._emitFunctionFromInclude("fogFragmentDeclaration", comments);
    state._emitFunctionFromInclude("gaussianSplattingFragmentDeclaration", comments);
    state._emitVaryingFromString("vPosition", NodeMaterialBlockConnectionPointTypes.Vector2);
    const color = this.splatColor;
    const output = this._outputs[0];
    if (state.shaderLanguage === 1) {
      state.compilationString += `${state._declareOutput(output)} = gaussianColor(${color.associatedVariableName}, input.vPosition);
`;
    } else {
      state.compilationString += `${state._declareOutput(output)} = gaussianColor(${color.associatedVariableName});
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.GaussianBlock", GaussianBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/GaussianSplatting/splatReaderBlock.js
init_typeStore();

// node_modules/@babylonjs/core/Materials/GaussianSplatting/gaussianSplattingMaterial.js
init_decorators_serialization();
init_buffer();
init_typeStore();
init_gaussianSplatting_fragment();
init_gaussianSplatting_vertex();
init_gaussianSplatting_fragment2();
init_gaussianSplatting_vertex2();
init_materialHelper_functions();

class GaussianSplattingMaterialDefines extends MaterialDefines {
  constructor() {
    super();
    this.FOG = false;
    this.THIN_INSTANCES = true;
    this.LOGARITHMICDEPTH = false;
    this.CLIPPLANE = false;
    this.CLIPPLANE2 = false;
    this.CLIPPLANE3 = false;
    this.CLIPPLANE4 = false;
    this.CLIPPLANE5 = false;
    this.CLIPPLANE6 = false;
    this.SH_DEGREE = 0;
    this.rebuild();
  }
}

class GaussianSplattingMaterial extends PushMaterial {
  constructor(name370, scene) {
    super(name370, scene);
    this.backFaceCulling = false;
  }
  get hasRenderTargetTextures() {
    return false;
  }
  needAlphaTesting() {
    return false;
  }
  needAlphaBlending() {
    return true;
  }
  isReadyForSubMesh(mesh, subMesh) {
    const useInstances = true;
    const drawWrapper = subMesh._drawWrapper;
    if (drawWrapper.effect && this.isFrozen) {
      if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) {
        return true;
      }
    }
    if (!subMesh.materialDefines) {
      subMesh.materialDefines = new GaussianSplattingMaterialDefines;
    }
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (this._isReadyForSubMesh(subMesh)) {
      return true;
    }
    const engine2 = scene.getEngine();
    PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, false, defines);
    PrepareDefinesForFrameBoundValues(scene, engine2, this, defines, useInstances, null, true);
    PrepareDefinesForAttributes(mesh, defines, false, false);
    if (engine2.version > 1 || engine2.isWebGPU) {
      defines["SH_DEGREE"] = mesh.shDegree;
    }
    if (defines.isDirty) {
      defines.markAsProcessed();
      scene.resetCachedMaterial();
      const attribs = [VertexBuffer.PositionKind, "splatIndex"];
      PrepareAttributesForInstances(attribs, defines);
      const uniforms = ["world", "view", "projection", "vFogInfos", "vFogColor", "logarithmicDepthConstant", "invViewport", "dataTextureSize", "focal", "vEyePosition"];
      const samplers = ["covariancesATexture", "covariancesBTexture", "centersTexture", "colorsTexture", "shTexture0", "shTexture1", "shTexture2"];
      const uniformBuffers = ["Scene", "Mesh"];
      PrepareUniformsAndSamplersList({
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines
      });
      addClipPlaneUniforms(uniforms);
      const join6 = defines.toString();
      const effect = scene.getEngine().createEffect("gaussianSplatting", {
        attributes: attribs,
        uniformsNames: uniforms,
        uniformBuffersNames: uniformBuffers,
        samplers,
        defines: join6,
        onCompiled: this.onCompiled,
        onError: this.onError,
        indexParameters: {},
        shaderLanguage: this._shaderLanguage,
        extraInitializationsAsync: async () => {
          if (this._shaderLanguage === 1) {
            await Promise.all([Promise.resolve().then(() => (init_gaussianSplatting_fragment2(), exports_gaussianSplatting_fragment2)), Promise.resolve().then(() => (init_gaussianSplatting_vertex2(), exports_gaussianSplatting_vertex2))]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_gaussianSplatting_fragment(), exports_gaussianSplatting_fragment)), Promise.resolve().then(() => (init_gaussianSplatting_vertex(), exports_gaussianSplatting_vertex))]);
          }
        }
      }, engine2);
      subMesh.setEffect(effect, defines, this._materialContext);
    }
    if (!subMesh.effect || !subMesh.effect.isReady()) {
      return false;
    }
    defines._renderId = scene.getRenderId();
    drawWrapper._wasPreviouslyReady = true;
    drawWrapper._wasPreviouslyUsingInstances = useInstances;
    return true;
  }
  static BindEffect(mesh, effect, scene) {
    const engine2 = scene.getEngine();
    const camera2 = scene.activeCamera;
    const renderWidth = engine2.getRenderWidth();
    const renderHeight = engine2.getRenderHeight();
    const numberOfRigs = camera2?.rigParent?.rigCameras.length || 1;
    effect.setFloat2("invViewport", 1 / (renderWidth / numberOfRigs), 1 / renderHeight);
    let focal = 1000;
    if (camera2) {
      const t = camera2.getProjectionMatrix().m[5];
      if (camera2.fovMode == Camera.FOVMODE_VERTICAL_FIXED) {
        focal = renderHeight * t / 2;
      } else {
        focal = renderWidth * t / 2;
      }
    }
    effect.setFloat2("focal", focal, focal);
    const gsMesh = mesh;
    if (gsMesh.covariancesATexture) {
      const textureSize = gsMesh.covariancesATexture.getSize();
      effect.setFloat2("dataTextureSize", textureSize.width, textureSize.height);
      effect.setTexture("covariancesATexture", gsMesh.covariancesATexture);
      effect.setTexture("covariancesBTexture", gsMesh.covariancesBTexture);
      effect.setTexture("centersTexture", gsMesh.centersTexture);
      effect.setTexture("colorsTexture", gsMesh.colorsTexture);
      if (gsMesh.shTextures) {
        for (let i = 0;i < gsMesh.shTextures?.length; i++) {
          effect.setTexture(`shTexture${i}`, gsMesh.shTextures[i]);
        }
      }
    }
  }
  bindForSubMesh(world, mesh, subMesh) {
    const scene = this.getScene();
    const defines = subMesh.materialDefines;
    if (!defines) {
      return;
    }
    const effect = subMesh.effect;
    if (!effect) {
      return;
    }
    this._activeEffect = effect;
    mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh");
    mesh.transferToEffect(world);
    const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility);
    if (mustRebind) {
      this.bindView(effect);
      this.bindViewProjection(effect);
      GaussianSplattingMaterial.BindEffect(mesh, this._activeEffect, scene);
      bindClipPlane(effect, this, scene);
    } else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {
      this._needToBindSceneUbo = true;
    }
    BindFogParameters(scene, mesh, effect);
    if (this.useLogarithmicDepth) {
      BindLogDepth(defines, effect, scene);
    }
    this._afterBind(mesh, this._activeEffect, subMesh);
  }
  clone(name370) {
    return SerializationHelper.Clone(() => new GaussianSplattingMaterial(name370, this.getScene()), this);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.customType = "BABYLON.GaussianSplattingMaterial";
    return serializationObject;
  }
  getClassName() {
    return "GaussianSplattingMaterial";
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new GaussianSplattingMaterial(source.name, scene), source, scene, rootUrl);
  }
}
RegisterClass("BABYLON.GaussianSplattingMaterial", GaussianSplattingMaterial);

// node_modules/@babylonjs/core/Materials/Node/Blocks/GaussianSplatting/splatReaderBlock.js
class SplatReaderBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Vertex);
    this._isUnique = true;
    this.registerInput("splatIndex", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Vertex);
    this.registerOutput("splatPosition", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Vertex);
    this.registerOutput("splatColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Vertex);
  }
  getClassName() {
    return "SplatReaderBlock";
  }
  get splatIndex() {
    return this._inputs[0];
  }
  get splatPosition() {
    return this._outputs[0];
  }
  get splatColor() {
    return this._outputs[1];
  }
  initialize(state) {
    state._excludeVariableName("covA");
    state._excludeVariableName("covB");
    state._excludeVariableName("vPosition");
    state._excludeVariableName("covariancesATexture");
    state._excludeVariableName("covariancesBTexture");
    state._excludeVariableName("centersTexture");
    state._excludeVariableName("colorsTexture");
    state._excludeVariableName("dataTextureSize");
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    const scene = mesh.getScene();
    GaussianSplattingMaterial.BindEffect(mesh, effect, scene);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      return;
    }
    state.sharedData.bindableBlocks.push(this);
    const comments = `//${this.name}`;
    state._emit2DSampler("covariancesATexture");
    state._emit2DSampler("covariancesBTexture");
    state._emit2DSampler("centersTexture");
    state._emit2DSampler("colorsTexture");
    state._emitFunctionFromInclude("gaussianSplattingVertexDeclaration", comments);
    state._emitFunctionFromInclude("gaussianSplatting", comments);
    state._emitVaryingFromString("vPosition", NodeMaterialBlockConnectionPointTypes.Vector2);
    state._emitUniformFromString("dataTextureSize", NodeMaterialBlockConnectionPointTypes.Vector2);
    const splatIndex = this.splatIndex;
    const splatPosition = this.splatPosition;
    const splatColor = this.splatColor;
    const splatVariablename = state._getFreeVariableName("splat");
    if (state.shaderLanguage === 1) {
      state.compilationString += `var ${splatVariablename}: Splat = readSplat(${splatIndex.associatedVariableName}, uniforms.dataTextureSize);
`;
      state.compilationString += `var covA: vec3f = splat.covA.xyz; var covB: vec3f = vec3f(splat.covA.w, splat.covB.xy);
`;
      state.compilationString += `vertexOutputs.vPosition = input.position;
`;
    } else {
      state.compilationString += `Splat ${splatVariablename} = readSplat(${splatIndex.associatedVariableName});
`;
      state.compilationString += `vec3 covA = splat.covA.xyz; vec3 covB = vec3(splat.covA.w, splat.covB.xy);
`;
      state.compilationString += `vPosition = position;
`;
    }
    state.compilationString += `${state._declareOutput(splatPosition)} = ${splatVariablename}.center.xyz;
`;
    state.compilationString += `${state._declareOutput(splatColor)} = ${splatVariablename}.color;
`;
    return this;
  }
}
RegisterClass("BABYLON.SplatReaderBlock", SplatReaderBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/bonesBlock.js
init_typeStore();
init_materialHelper_functions();

class BonesBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Vertex);
    this.registerInput("matricesIndices", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("matricesWeights", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("matricesIndicesExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("matricesWeightsExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  initialize(state) {
    state._excludeVariableName("boneSampler");
    state._excludeVariableName("boneTextureWidth");
    state._excludeVariableName("mBones");
    state._excludeVariableName("BonesPerMesh");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([Promise.resolve().then(() => (init_bonesDeclaration(), exports_bonesDeclaration)), Promise.resolve().then(() => (init_bonesVertex(), exports_bonesVertex))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_bonesDeclaration2(), exports_bonesDeclaration2)), Promise.resolve().then(() => (init_bonesVertex2(), exports_bonesVertex2))]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  getClassName() {
    return "BonesBlock";
  }
  get matricesIndices() {
    return this._inputs[0];
  }
  get matricesWeights() {
    return this._inputs[1];
  }
  get matricesIndicesExtra() {
    return this._inputs[2];
  }
  get matricesWeightsExtra() {
    return this._inputs[3];
  }
  get world() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.matricesIndices.isConnected) {
      let matricesIndicesInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesIndices" && additionalFilteringInfo(b));
      if (!matricesIndicesInput) {
        matricesIndicesInput = new InputBlock("matricesIndices");
        matricesIndicesInput.setAsAttribute("matricesIndices");
      }
      matricesIndicesInput.output.connectTo(this.matricesIndices);
    }
    if (!this.matricesWeights.isConnected) {
      let matricesWeightsInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesWeights" && additionalFilteringInfo(b));
      if (!matricesWeightsInput) {
        matricesWeightsInput = new InputBlock("matricesWeights");
        matricesWeightsInput.setAsAttribute("matricesWeights");
      }
      matricesWeightsInput.output.connectTo(this.matricesWeights);
    }
    if (!this.world.isConnected) {
      let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b));
      if (!worldInput) {
        worldInput = new InputBlock("world");
        worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
      }
      worldInput.output.connectTo(this.world);
    }
  }
  provideFallbacks(mesh, fallbacks) {
    if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
      fallbacks.addCPUSkinningFallback(0, mesh);
    }
  }
  bind(effect, nodeMaterial, mesh) {
    BindBonesParameters(mesh, effect);
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areAttributesDirty) {
      return;
    }
    PrepareDefinesForBones(mesh, defines);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    state.sharedData.blocksWithFallbacks.push(this);
    state.sharedData.forcedBindableBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    state.uniforms.push("boneTextureWidth");
    state.uniforms.push("mBones");
    state.samplers.push("boneSampler");
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("bonesDeclaration", comments, {
      removeAttributes: true,
      removeUniforms: false,
      removeVaryings: true,
      removeIfDef: false
    });
    const influenceVariablename = state._getFreeVariableName("influence");
    state.compilationString += state._emitCodeFromInclude("bonesVertex", comments, {
      replaceStrings: [
        {
          search: /finalWorld=finalWorld\*influence;/,
          replace: ""
        },
        {
          search: /influence/gm,
          replace: influenceVariablename
        }
      ]
    });
    const output = this._outputs[0];
    const worldInput = this.world;
    state.compilationString += `#if NUM_BONE_INFLUENCERS>0
`;
    state.compilationString += state._declareOutput(output) + ` = ${worldInput.associatedVariableName} * ${influenceVariablename};
`;
    state.compilationString += `#else
`;
    state.compilationString += state._declareOutput(output) + ` = ${worldInput.associatedVariableName};
`;
    state.compilationString += `#endif
`;
    return this;
  }
}
RegisterClass("BABYLON.BonesBlock", BonesBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/instancesBlock.js
init_typeStore();

class InstancesBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Vertex);
    this.registerInput("world0", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("world1", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("world2", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("world3", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("instanceID", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "InstancesBlock";
  }
  get world0() {
    return this._inputs[0];
  }
  get world1() {
    return this._inputs[1];
  }
  get world2() {
    return this._inputs[2];
  }
  get world3() {
    return this._inputs[3];
  }
  get world() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  get instanceID() {
    return this._outputs[1];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.world0.connectedPoint) {
      let world0Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world0" && additionalFilteringInfo(b));
      if (!world0Input) {
        world0Input = new InputBlock("world0");
        world0Input.setAsAttribute("world0");
      }
      world0Input.output.connectTo(this.world0);
    }
    if (!this.world1.connectedPoint) {
      let world1Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world1" && additionalFilteringInfo(b));
      if (!world1Input) {
        world1Input = new InputBlock("world1");
        world1Input.setAsAttribute("world1");
      }
      world1Input.output.connectTo(this.world1);
    }
    if (!this.world2.connectedPoint) {
      let world2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world2" && additionalFilteringInfo(b));
      if (!world2Input) {
        world2Input = new InputBlock("world2");
        world2Input.setAsAttribute("world2");
      }
      world2Input.output.connectTo(this.world2);
    }
    if (!this.world3.connectedPoint) {
      let world3Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world3" && additionalFilteringInfo(b));
      if (!world3Input) {
        world3Input = new InputBlock("world3");
        world3Input.setAsAttribute("world3");
      }
      world3Input.output.connectTo(this.world3);
    }
    if (!this.world.connectedPoint) {
      let worldInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world" && additionalFilteringInfo(b));
      if (!worldInput) {
        worldInput = new InputBlock("world");
        worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
      }
      worldInput.output.connectTo(this.world);
    }
    this.world.define = "!INSTANCES || THIN_INSTANCES";
  }
  prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {
    let changed = false;
    if (defines["INSTANCES"] !== useInstances) {
      defines.setValue("INSTANCES", useInstances);
      changed = true;
    }
    if (subMesh && defines["THIN_INSTANCES"] !== !!subMesh?.getRenderingMesh().hasThinInstances) {
      defines.setValue("THIN_INSTANCES", !!subMesh?.getRenderingMesh().hasThinInstances);
      changed = true;
    }
    if (changed) {
      defines.markAsUnprocessed();
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const engine2 = state.sharedData.scene.getEngine();
    state.sharedData.blocksWithDefines.push(this);
    const output = this._outputs[0];
    const instanceID = this._outputs[1];
    const world0 = this.world0;
    const world1 = this.world1;
    const world2 = this.world2;
    const world3 = this.world3;
    let mat4 = "mat4";
    let instance = "gl_InstanceID";
    let floatCast = "float";
    if (state.shaderLanguage === 1) {
      mat4 = "mat4x4f";
      instance = "vertexInputs.instanceIndex";
      floatCast = "f32";
    }
    state.compilationString += `#ifdef INSTANCES
`;
    state.compilationString += state._declareOutput(output) + ` = ${mat4}(${world0.associatedVariableName}, ${world1.associatedVariableName}, ${world2.associatedVariableName}, ${world3.associatedVariableName});
`;
    state.compilationString += `#ifdef THIN_INSTANCES
`;
    state.compilationString += `${output.associatedVariableName} = ${this.world.associatedVariableName} * ${output.associatedVariableName};
`;
    state.compilationString += `#endif
`;
    if (engine2._caps.canUseGLInstanceID) {
      state.compilationString += state._declareOutput(instanceID) + ` = ${floatCast}(${instance});
`;
    } else {
      state.compilationString += state._declareOutput(instanceID) + ` = 0.0;
`;
    }
    state.compilationString += `#else
`;
    state.compilationString += state._declareOutput(output) + ` = ${this.world.associatedVariableName};
`;
    state.compilationString += state._declareOutput(instanceID) + ` = 0.0;
`;
    state.compilationString += `#endif
`;
    return this;
  }
}
RegisterClass("BABYLON.InstancesBlock", InstancesBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/morphTargetsBlock.js
init_buffer();
init_typeStore();
init_materialHelper_functions();

class MorphTargetsBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Vertex);
    this.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.tangent.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("uv2", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4);
    this.registerOutput("positionOutput", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("normalOutput", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("tangentOutput", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("uvOutput", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("uv2Output", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("colorOutput", NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "MorphTargetsBlock";
  }
  get position() {
    return this._inputs[0];
  }
  get normal() {
    return this._inputs[1];
  }
  get tangent() {
    return this._inputs[2];
  }
  get uv() {
    return this._inputs[3];
  }
  get uv2() {
    return this._inputs[4];
  }
  get color() {
    return this._inputs[5];
  }
  get positionOutput() {
    return this._outputs[0];
  }
  get normalOutput() {
    return this._outputs[1];
  }
  get tangentOutput() {
    return this._outputs[2];
  }
  get uvOutput() {
    return this._outputs[3];
  }
  get uv2Output() {
    return this._outputs[4];
  }
  get colorOutput() {
    return this._outputs[5];
  }
  initialize(state) {
    state._excludeVariableName("morphTargetInfluences");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_morphTargetsVertex(), exports_morphTargetsVertex)),
        Promise.resolve().then(() => (init_morphTargetsVertexDeclaration(), exports_morphTargetsVertexDeclaration)),
        Promise.resolve().then(() => (init_morphTargetsVertexGlobal(), exports_morphTargetsVertexGlobal)),
        Promise.resolve().then(() => (init_morphTargetsVertexGlobalDeclaration(), exports_morphTargetsVertexGlobalDeclaration))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_morphTargetsVertex2(), exports_morphTargetsVertex2)),
        Promise.resolve().then(() => (init_morphTargetsVertexDeclaration2(), exports_morphTargetsVertexDeclaration2)),
        Promise.resolve().then(() => (init_morphTargetsVertexGlobal2(), exports_morphTargetsVertexGlobal2)),
        Promise.resolve().then(() => (init_morphTargetsVertexGlobalDeclaration2(), exports_morphTargetsVertexGlobalDeclaration2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.position.isConnected) {
      let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position" && additionalFilteringInfo(b));
      if (!positionInput) {
        positionInput = new InputBlock("position");
        positionInput.setAsAttribute();
      }
      positionInput.output.connectTo(this.position);
    }
    if (!this.normal.isConnected) {
      let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal" && additionalFilteringInfo(b));
      if (!normalInput) {
        normalInput = new InputBlock("normal");
        normalInput.setAsAttribute("normal");
      }
      normalInput.output.connectTo(this.normal);
    }
    if (!this.tangent.isConnected) {
      let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent" && additionalFilteringInfo(b));
      if (!tangentInput) {
        tangentInput = new InputBlock("tangent");
        tangentInput.setAsAttribute("tangent");
      }
      tangentInput.output.connectTo(this.tangent);
    }
    if (!this.uv.isConnected) {
      let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv" && additionalFilteringInfo(b));
      if (!uvInput) {
        uvInput = new InputBlock("uv");
        uvInput.setAsAttribute("uv");
      }
      uvInput.output.connectTo(this.uv);
    }
    if (!this.uv2.isConnected) {
      let uv2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv2" && additionalFilteringInfo(b));
      if (!uv2Input) {
        uv2Input = new InputBlock("uv2");
        uv2Input.setAsAttribute("uv2");
      }
      uv2Input.output.connectTo(this.uv2);
    }
    if (!this.color.isConnected) {
      let colorInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "color" && additionalFilteringInfo(b));
      if (!colorInput) {
        colorInput = new InputBlock("color");
        colorInput.setAsAttribute("color");
      }
      colorInput.output.connectTo(this.color);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (mesh.morphTargetManager) {
      const morphTargetManager = mesh.morphTargetManager;
      if (morphTargetManager?.isUsingTextureForTargets && (morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers) !== defines["NUM_MORPH_INFLUENCERS"]) {
        defines.markAsAttributesDirty();
      }
    }
    if (!defines._areAttributesDirty) {
      return;
    }
    PrepareDefinesForMorphTargets(mesh, defines);
  }
  bind(effect, nodeMaterial, mesh) {
    if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) {
      BindMorphTargetParameters(mesh, effect);
      if (mesh.morphTargetManager.isUsingTextureForTargets) {
        mesh.morphTargetManager._bind(effect);
      }
    }
  }
  replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {
    const position = this.position;
    const normal = this.normal;
    const tangent = this.tangent;
    const uv = this.uv;
    const uv2 = this.uv2;
    const color = this.color;
    const positionOutput = this.positionOutput;
    const normalOutput = this.normalOutput;
    const tangentOutput = this.tangentOutput;
    const uvOutput = this.uvOutput;
    const uv2Output = this.uv2Output;
    const colorOutput = this.colorOutput;
    const state = vertexShaderState;
    const repeatCount = defines.NUM_MORPH_INFLUENCERS;
    const manager = mesh.morphTargetManager;
    const supportPositions = manager && manager.supportsPositions;
    const supportNormals = manager && manager.supportsNormals;
    const supportTangents = manager && manager.supportsTangents;
    const supportUVs = manager && manager.supportsUVs;
    const supportUV2s = manager && manager.supportsUV2s;
    const supportColors = manager && manager.supportsColors;
    let injectionCode = "";
    if (manager?.isUsingTextureForTargets && repeatCount > 0) {
      injectionCode += `${state._declareLocalVar("vertexID", NodeMaterialBlockConnectionPointTypes.Float)};
`;
    }
    injectionCode += `#ifdef MORPHTARGETS
`;
    const isWebGPU = state.shaderLanguage === 1;
    const uniformsPrefix = isWebGPU ? "uniforms." : "";
    if (manager?.isUsingTextureForTargets) {
      injectionCode += `for (${isWebGPU ? "var" : "int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {
`;
      injectionCode += `if (i >= ${uniformsPrefix}morphTargetCount) { break; }
`;
      injectionCode += `vertexID = ${isWebGPU ? "f32(vertexInputs.vertexIndex" : "float(gl_VertexID"}) * ${uniformsPrefix}morphTargetTextureInfo.x;
`;
      if (supportPositions) {
        injectionCode += `#ifdef MORPHTARGETS_POSITION
`;
        injectionCode += `${positionOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${position.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];
`;
        injectionCode += `#endif
`;
      }
      injectionCode += `#ifdef MORPHTARGETTEXTURE_HASPOSITIONS
`;
      injectionCode += `vertexID += 1.0;
`;
      injectionCode += `#endif
`;
      if (supportNormals) {
        injectionCode += `#ifdef MORPHTARGETS_NORMAL
`;
        injectionCode += `${normalOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${normal.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];
`;
        injectionCode += `#endif
`;
      }
      injectionCode += `#ifdef MORPHTARGETTEXTURE_HASNORMALS
`;
      injectionCode += `vertexID += 1.0;
`;
      injectionCode += `#endif
`;
      if (supportUVs) {
        injectionCode += `#ifdef MORPHTARGETS_UV
`;
        injectionCode += `${uvOutput.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${uv.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];
`;
        injectionCode += `#endif
`;
      }
      injectionCode += `#ifdef MORPHTARGETTEXTURE_HASUVS
`;
      injectionCode += `vertexID += 1.0;
`;
      injectionCode += `#endif
`;
      if (supportTangents) {
        injectionCode += `#ifdef MORPHTARGETS_TANGENT
`;
        injectionCode += `${tangentOutput.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${tangent.associatedVariableName}.xyz) * ${uniformsPrefix}morphTargetInfluences[i];
`;
        if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) {
          injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;
`;
        } else {
          injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;
`;
        }
        injectionCode += `#endif
`;
      }
      injectionCode += `#ifdef MORPHTARGETTEXTURE_HASTANGENTS
`;
      injectionCode += `vertexID += 1.0;
`;
      injectionCode += `#endif
`;
      if (supportUV2s) {
        injectionCode += `#ifdef MORPHTARGETS_UV2
`;
        injectionCode += `${uv2Output.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${uv2.associatedVariableName}) * morphTargetInfluences[i];
`;
        injectionCode += `#endif
`;
      }
      injectionCode += `#ifdef MORPHTARGETTEXTURE_HASUV2S
`;
      injectionCode += `vertexID += 1.0;
`;
      injectionCode += `#endif
`;
      if (supportColors) {
        injectionCode += `#ifdef MORPHTARGETS_COLOR
`;
        injectionCode += `${colorOutput.associatedVariableName} += (readVector4FromRawSampler(i, vertexID) - ${color.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[i];
`;
        injectionCode += `#endif
`;
      }
      injectionCode += `}
`;
    } else {
      for (let index = 0;index < repeatCount; index++) {
        if (supportPositions) {
          injectionCode += `#ifdef MORPHTARGETS_POSITION
`;
          injectionCode += `${positionOutput.associatedVariableName} += (position${index} - ${position.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];
`;
          injectionCode += `#endif
`;
        }
        if (supportNormals && defines["NORMAL"]) {
          injectionCode += `#ifdef MORPHTARGETS_NORMAL
`;
          injectionCode += `${normalOutput.associatedVariableName} += (normal${index} - ${normal.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];
`;
          injectionCode += `#endif
`;
        }
        if (supportUVs && defines["UV1"]) {
          injectionCode += `#ifdef MORPHTARGETS_UV
`;
          injectionCode += `${uvOutput.associatedVariableName}.xy += (uv_${index} - ${uv.associatedVariableName}.xy) * ${uniformsPrefix}morphTargetInfluences[${index}];
`;
          injectionCode += `#endif
`;
        }
        if (supportTangents && defines["TANGENT"]) {
          injectionCode += `#ifdef MORPHTARGETS_TANGENT
`;
          injectionCode += `${tangentOutput.associatedVariableName}.xyz += (tangent${index} - ${tangent.associatedVariableName}.xyz) * ${uniformsPrefix}morphTargetInfluences[${index}];
`;
          if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) {
            injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;
`;
          } else {
            injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;
`;
          }
          injectionCode += `#endif
`;
        }
        if (supportUV2s && defines["UV2"]) {
          injectionCode += `#ifdef MORPHTARGETS_UV2
`;
          injectionCode += `${uv2Output.associatedVariableName}.xy += (uv2_${index} - ${uv2.associatedVariableName}.xy) * morphTargetInfluences[${index}];
`;
          injectionCode += `#endif
`;
        }
        if (supportColors && defines["VERTEXCOLOR_NME"]) {
          injectionCode += `#ifdef MORPHTARGETS_COLOR
`;
          injectionCode += `${colorOutput.associatedVariableName} += (color${index} - ${color.associatedVariableName}) * ${uniformsPrefix}morphTargetInfluences[${index}];
`;
          injectionCode += `#endif
`;
        }
      }
    }
    injectionCode += `#endif
`;
    state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode);
    if (repeatCount > 0) {
      for (let index = 0;index < repeatCount; index++) {
        if (supportPositions) {
          state.attributes.push(VertexBuffer.PositionKind + index);
        }
        if (supportNormals && defines["NORMAL"]) {
          state.attributes.push(VertexBuffer.NormalKind + index);
        }
        if (supportTangents && defines["TANGENT"]) {
          state.attributes.push(VertexBuffer.TangentKind + index);
        }
        if (supportUVs && defines["UV1"]) {
          state.attributes.push(VertexBuffer.UVKind + "_" + index);
        }
        if (supportUV2s && defines["UV2"]) {
          state.attributes.push(VertexBuffer.UV2Kind + "_" + index);
        }
        if (supportColors && defines["VERTEXCOLOR_NME"]) {
          state.attributes.push(VertexBuffer.ColorKind + index);
        }
      }
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.bindableBlocks.push(this);
    state.sharedData.repeatableContentBlocks.push(this);
    const position = this.position;
    const normal = this.normal;
    const tangent = this.tangent;
    const uv = this.uv;
    const uv2 = this.uv2;
    const color = this.color;
    const positionOutput = this.positionOutput;
    const normalOutput = this.normalOutput;
    const tangentOutput = this.tangentOutput;
    const uvOutput = this.uvOutput;
    const uv2Output = this.uv2Output;
    const colorOutput = this.colorOutput;
    const comments = `//${this.name}`;
    state.uniforms.push("morphTargetInfluences");
    state.uniforms.push("morphTargetCount");
    state.uniforms.push("morphTargetTextureInfo");
    state.uniforms.push("morphTargetTextureIndices");
    state.samplers.push("morphTargets");
    state._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", comments);
    state._emitFunctionFromInclude("morphTargetsVertexDeclaration", comments, {
      repeatKey: "maxSimultaneousMorphTargets"
    });
    state.compilationString += `${state._declareOutput(positionOutput)} = ${position.associatedVariableName};
`;
    state.compilationString += `#ifdef NORMAL
`;
    state.compilationString += `${state._declareOutput(normalOutput)} = ${normal.associatedVariableName};
`;
    state.compilationString += `#else
`;
    state.compilationString += `${state._declareOutput(normalOutput)} = vec3(0., 0., 0.);
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef TANGENT
`;
    state.compilationString += `${state._declareOutput(tangentOutput)} = ${tangent.associatedVariableName};
`;
    state.compilationString += `#else
`;
    state.compilationString += `${state._declareOutput(tangentOutput)} = vec4(0., 0., 0., 0.);
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef UV1
`;
    state.compilationString += `${state._declareOutput(uvOutput)} = ${uv.associatedVariableName};
`;
    state.compilationString += `#else
`;
    state.compilationString += `${state._declareOutput(uvOutput)} = vec2(0., 0.);
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef UV2
`;
    state.compilationString += `${state._declareOutput(uv2Output)} = ${uv2.associatedVariableName};
`;
    state.compilationString += `#else
`;
    state.compilationString += `${state._declareOutput(uv2Output)} = vec2(0., 0.);
`;
    state.compilationString += `#endif
`;
    state.compilationString += `#ifdef VERTEXCOLOR_NME
`;
    state.compilationString += `${state._declareOutput(colorOutput)} = ${color.associatedVariableName};
`;
    state.compilationString += `#else
`;
    state.compilationString += `${state._declareOutput(colorOutput)} = vec4(0., 0., 0., 0.);
`;
    state.compilationString += `#endif
`;
    this._repeatableContentAnchor = state._repeatableContentAnchor;
    state.compilationString += this._repeatableContentAnchor;
    return this;
  }
}
RegisterClass("BABYLON.MorphTargetsBlock", MorphTargetsBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/lightInformationBlock.js
init_typeStore();
class LightInformationBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Vertex);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerOutput("direction", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("color", NodeMaterialBlockConnectionPointTypes.Color3);
    this.registerOutput("intensity", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("shadowBias", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("shadowNormalBias", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("shadowDepthScale", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("shadowDepthRange", NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "LightInformationBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get direction() {
    return this._outputs[0];
  }
  get color() {
    return this._outputs[1];
  }
  get intensity() {
    return this._outputs[2];
  }
  get shadowBias() {
    return this._outputs[3];
  }
  get shadowNormalBias() {
    return this._outputs[4];
  }
  get shadowDepthScale() {
    return this._outputs[5];
  }
  get shadowDepthRange() {
    return this._outputs[6];
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    if (this.light && this.light.isDisposed()) {
      this.light = null;
    }
    let light2 = this.light;
    const scene = nodeMaterial.getScene();
    if (!light2 && scene.lights.length) {
      light2 = this.light = scene.lights[0];
      this._forcePrepareDefines = true;
    }
    if (!light2 || !light2.isEnabled) {
      effect.setFloat3(this._lightDataUniformName, 0, 0, 0);
      effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);
      return;
    }
    light2.transferToNodeMaterialEffect(effect, this._lightDataUniformName);
    effect.setColor4(this._lightColorUniformName, light2.diffuse, light2.intensity);
    const generator = light2.getShadowGenerator();
    if (this.shadowBias.hasEndpoints || this.shadowNormalBias.hasEndpoints || this.shadowDepthScale.hasEndpoints) {
      if (generator) {
        effect.setFloat3(this._lightShadowUniformName, generator.bias, generator.normalBias, generator.depthScale);
      } else {
        effect.setFloat3(this._lightShadowUniformName, 0, 0, 0);
      }
    }
    if (this.shadowDepthRange) {
      if (generator && scene.activeCamera) {
        const shadowLight2 = light2;
        effect.setFloat2(this._lightShadowExtraUniformName, shadowLight2.getDepthMinZ(scene.activeCamera), shadowLight2.getDepthMinZ(scene.activeCamera) + shadowLight2.getDepthMaxZ(scene.activeCamera));
      } else {
        effect.setFloat2(this._lightShadowExtraUniformName, 0, 0);
      }
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areLightsDirty && !this._forcePrepareDefines) {
      return;
    }
    this._forcePrepareDefines = false;
    const light2 = this.light;
    defines.setValue(this._lightTypeDefineName, light2 && light2 instanceof PointLight ? true : false, true);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    state.sharedData.bindableBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    const direction = this.direction;
    const color = this.color;
    const intensity = this.intensity;
    const shadowBias = this.shadowBias;
    const shadowNormalBias = this.shadowNormalBias;
    const shadowDepthScale = this.shadowDepthScale;
    const shadowDepthRange = this.shadowDepthRange;
    this._lightDataUniformName = state._getFreeVariableName("lightData");
    this._lightColorUniformName = state._getFreeVariableName("lightColor");
    this._lightShadowUniformName = state._getFreeVariableName("shadowData");
    this._lightShadowExtraUniformName = state._getFreeVariableName("shadowExtraData");
    this._lightTypeDefineName = state._getFreeDefineName("LIGHTPOINTTYPE");
    const uniformAdd = state.shaderLanguage === 1 ? "uniforms." : "";
    state._emitUniformFromString(this._lightDataUniformName, NodeMaterialBlockConnectionPointTypes.Vector3);
    state._emitUniformFromString(this._lightColorUniformName, NodeMaterialBlockConnectionPointTypes.Vector4);
    state.compilationString += `#ifdef ${this._lightTypeDefineName}
`;
    state.compilationString += state._declareOutput(direction) + ` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${uniformAdd}${this._lightDataUniformName});
`;
    state.compilationString += `#else
`;
    state.compilationString += state._declareOutput(direction) + ` = ${uniformAdd}${this._lightDataUniformName};
`;
    state.compilationString += `#endif
`;
    state.compilationString += state._declareOutput(color) + ` = ${uniformAdd}${this._lightColorUniformName}.rgb;
`;
    state.compilationString += state._declareOutput(intensity) + ` = ${uniformAdd}${this._lightColorUniformName}.a;
`;
    if (shadowBias.hasEndpoints || shadowNormalBias.hasEndpoints || shadowDepthScale.hasEndpoints) {
      state._emitUniformFromString(this._lightShadowUniformName, NodeMaterialBlockConnectionPointTypes.Vector3);
      if (shadowBias.hasEndpoints) {
        state.compilationString += state._declareOutput(shadowBias) + ` = ${uniformAdd}${this._lightShadowUniformName}.x;
`;
      }
      if (shadowNormalBias.hasEndpoints) {
        state.compilationString += state._declareOutput(shadowNormalBias) + ` = ${uniformAdd}${this._lightShadowUniformName}.y;
`;
      }
      if (shadowDepthScale.hasEndpoints) {
        state.compilationString += state._declareOutput(shadowDepthScale) + ` = ${uniformAdd}${this._lightShadowUniformName}.z;
`;
      }
    }
    if (shadowDepthRange.hasEndpoints) {
      state._emitUniformFromString(this._lightShadowExtraUniformName, NodeMaterialBlockConnectionPointTypes.Vector2);
      state.compilationString += state._declareOutput(shadowDepthRange) + ` = ${this._lightShadowUniformName};
`;
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    if (this.light) {
      serializationObject.lightId = this.light.id;
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    if (serializationObject.lightId) {
      this.light = scene.getLightById(serializationObject.lightId);
    }
  }
}
RegisterClass("BABYLON.LightInformationBlock", LightInformationBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/index.js
init_bonesDeclaration();
init_bonesVertex();
init_bonesDeclaration2();
init_bonesVertex2();
init_morphTargetsVertex();
init_morphTargetsVertexDeclaration();
init_morphTargetsVertexGlobal();
init_morphTargetsVertexGlobalDeclaration();
init_morphTargetsVertex2();
init_morphTargetsVertexDeclaration2();
init_morphTargetsVertexGlobal2();
init_morphTargetsVertexGlobalDeclaration2();
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/imageProcessingBlock.js
init_tslib_es6();
init_typeStore();
class ImageProcessingBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.convertInputToLinearSpace = true;
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color4);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ImageProcessingBlock";
  }
  get color() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  initialize(state) {
    state._excludeVariableName("exposureLinear");
    state._excludeVariableName("contrast");
    state._excludeVariableName("vInverseScreenSize");
    state._excludeVariableName("vignetteSettings1");
    state._excludeVariableName("vignetteSettings2");
    state._excludeVariableName("vCameraColorCurveNegative");
    state._excludeVariableName("vCameraColorCurveNeutral");
    state._excludeVariableName("vCameraColorCurvePositive");
    state._excludeVariableName("txColorTransform");
    state._excludeVariableName("colorTransformSettings");
    state._excludeVariableName("ditherIntensity");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_helperFunctions(), exports_helperFunctions)),
        Promise.resolve().then(() => (init_imageProcessingDeclaration(), exports_imageProcessingDeclaration)),
        Promise.resolve().then(() => (init_imageProcessingFunctions(), exports_imageProcessingFunctions))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_helperFunctions2(), exports_helperFunctions2)),
        Promise.resolve().then(() => (init_imageProcessingDeclaration2(), exports_imageProcessingDeclaration2)),
        Promise.resolve().then(() => (init_imageProcessingFunctions2(), exports_imageProcessingFunctions2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  isReady(mesh, nodeMaterial, defines) {
    if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
      if (!nodeMaterial.imageProcessingConfiguration.isReady()) {
        return false;
      }
    }
    return true;
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
      nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);
    }
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    if (!nodeMaterial.imageProcessingConfiguration) {
      return;
    }
    nodeMaterial.imageProcessingConfiguration.bind(effect);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.blockingBlocks.push(this);
    state.sharedData.bindableBlocks.push(this);
    state.uniforms.push("exposureLinear");
    state.uniforms.push("contrast");
    state.uniforms.push("vInverseScreenSize");
    state.uniforms.push("vignetteSettings1");
    state.uniforms.push("vignetteSettings2");
    state.uniforms.push("vCameraColorCurveNegative");
    state.uniforms.push("vCameraColorCurveNeutral");
    state.uniforms.push("vCameraColorCurvePositive");
    state.uniforms.push("txColorTransform");
    state.uniforms.push("colorTransformSettings");
    state.uniforms.push("ditherIntensity");
    const color = this.color;
    const output = this._outputs[0];
    const comments = `//${this.name}`;
    const overrideText = state.shaderLanguage === 1 ? "Vec3" : "";
    state._emitFunctionFromInclude("helperFunctions", comments);
    state._emitFunctionFromInclude("imageProcessingDeclaration", comments);
    state._emitFunctionFromInclude("imageProcessingFunctions", comments);
    if (color.connectedPoint?.isConnected) {
      if (color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4) {
        state.compilationString += `${state._declareOutput(output)} = ${color.associatedVariableName};
`;
      } else {
        state.compilationString += `${state._declareOutput(output)} = vec4${state.fSuffix}(${color.associatedVariableName}, 1.0);
`;
      }
      state.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS
`;
      if (this.convertInputToLinearSpace) {
        state.compilationString += `${output.associatedVariableName} = vec4${state.fSuffix}(toLinearSpace${overrideText}(${color.associatedVariableName}.rgb), ${color.associatedVariableName}.a);
`;
      }
      state.compilationString += `#else
`;
      state.compilationString += `#ifdef IMAGEPROCESSING
`;
      if (this.convertInputToLinearSpace) {
        state.compilationString += `${output.associatedVariableName} = vec4${state.fSuffix}(toLinearSpace${overrideText}(${color.associatedVariableName}.rgb), ${color.associatedVariableName}.a);
`;
      }
      state.compilationString += `${output.associatedVariableName} = applyImageProcessing(${output.associatedVariableName});
`;
      state.compilationString += `#endif
`;
      state.compilationString += `#endif
`;
      if (this.rgb.hasEndpoints) {
        state.compilationString += state._declareOutput(this.rgb) + ` = ${this.output.associatedVariableName}.xyz;
`;
      }
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertInputToLinearSpace = this.convertInputToLinearSpace;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertInputToLinearSpace = serializationObject.convertInputToLinearSpace ?? true;
  }
}
__decorate([
  editableInPropertyPage("Convert input to linear space", 0, "ADVANCED")
], ImageProcessingBlock.prototype, "convertInputToLinearSpace", undefined);
RegisterClass("BABYLON.ImageProcessingBlock", ImageProcessingBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/perturbNormalBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/TBNBlock.js
init_typeStore();
class TBNBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment, true);
    this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);
    this.normal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.Vector4, false);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false);
    this.registerOutput("TBN", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 1, TBNBlock, "TBNBlock"));
    this.registerOutput("row0", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("row1", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("row2", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "TBNBlock";
  }
  initialize(state) {
    state._excludeVariableName("tbnNormal");
    state._excludeVariableName("tbnTangent");
    state._excludeVariableName("tbnBitangent");
    state._excludeVariableName("TBN");
  }
  get normal() {
    return this._inputs[0];
  }
  get tangent() {
    return this._inputs[1];
  }
  get world() {
    return this._inputs[2];
  }
  get TBN() {
    return this._outputs[0];
  }
  get row0() {
    return this._outputs[1];
  }
  get row1() {
    return this._outputs[2];
  }
  get row2() {
    return this._outputs[3];
  }
  get target() {
    return NodeMaterialBlockTargets.Fragment;
  }
  set target(value) {}
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.world.isConnected) {
      let worldInput = material.getInputBlockByPredicate((b) => b.isSystemValue && b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b));
      if (!worldInput) {
        worldInput = new InputBlock("world");
        worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
      }
      worldInput.output.connectTo(this.world);
    }
    if (!this.normal.isConnected) {
      let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal" && additionalFilteringInfo(b));
      if (!normalInput) {
        normalInput = new InputBlock("normal");
        normalInput.setAsAttribute("normal");
      }
      normalInput.output.connectTo(this.normal);
    }
    if (!this.tangent.isConnected) {
      let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent" && b.type === NodeMaterialBlockConnectionPointTypes.Vector4 && additionalFilteringInfo(b));
      if (!tangentInput) {
        tangentInput = new InputBlock("tangent");
        tangentInput.setAsAttribute("tangent");
      }
      tangentInput.output.connectTo(this.tangent);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    const normal = this.normal;
    const tangent = this.tangent;
    let normalAvailable = normal.isConnected;
    if (normal.connectInputBlock?.isAttribute && !mesh.isVerticesDataPresent(normal.connectInputBlock?.name)) {
      normalAvailable = false;
    }
    let tangentAvailable = tangent.isConnected;
    if (tangent.connectInputBlock?.isAttribute && !mesh.isVerticesDataPresent(tangent.connectInputBlock?.name)) {
      tangentAvailable = false;
    }
    const useTBNBlock = normalAvailable && tangentAvailable;
    defines.setValue("TBNBLOCK", useTBNBlock, true);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const normal = this.normal;
    const tangent = this.tangent;
    const world = this.world;
    const TBN = this.TBN;
    const row0 = this.row0;
    const row1 = this.row1;
    const row2 = this.row2;
    const isWebGPU = state.shaderLanguage === 1;
    const mat3 = isWebGPU ? "mat3x3f" : "mat3";
    const fSuffix = isWebGPU ? "f" : "";
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `
                // ${this.name}
                ${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${normal.associatedVariableName}).xyz;
                ${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${tangent.associatedVariableName}.xyz);
                ${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${tangent.associatedVariableName}.w;
                ${isWebGPU ? "var" : "mat3"} ${TBN.associatedVariableName} = ${mat3}(${world.associatedVariableName}[0].xyz, ${world.associatedVariableName}[1].xyz, ${world.associatedVariableName}[2].xyz) * ${mat3}(tbnTangent, tbnBitangent, tbnNormal);
            `;
      if (row0.hasEndpoints) {
        state.compilationString += state._declareOutput(row0) + ` = vec3${fSuffix}(${TBN.associatedVariableName}[0][0], ${TBN.associatedVariableName}[0][1], ${TBN.associatedVariableName}[0][2]);
`;
      }
      if (row1.hasEndpoints) {
        state.compilationString += state._declareOutput(row1) + ` = vec3${fSuffix}(${TBN.associatedVariableName}[1[0], ${TBN.associatedVariableName}[1][1], ${TBN.associatedVariableName}[1][2]);
`;
      }
      if (row2.hasEndpoints) {
        state.compilationString += state._declareOutput(row2) + ` = vec3${fSuffix}(${TBN.associatedVariableName}[2][0], ${TBN.associatedVariableName}[2][1], ${TBN.associatedVariableName}[2][2]);
`;
      }
      state.sharedData.blocksWithDefines.push(this);
    }
    return this;
  }
}
RegisterClass("BABYLON.TBNBlock", TBNBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/perturbNormalBlock.js
class PerturbNormalBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this._tangentSpaceParameterName = "";
    this._tangentCorrectionFactorName = "";
    this._worldMatrixName = "";
    this.invertX = false;
    this.invertY = false;
    this.useParallaxOcclusion = false;
    this.useObjectSpaceNormalMap = false;
    this._isUnique = true;
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false);
    this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false);
    this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, false);
    this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float, false);
    this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3, true);
    this.registerInput("parallaxScale", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("parallaxHeight", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0, TBNBlock, "TBNBlock"));
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("uvOffset", NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "PerturbNormalBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get worldNormal() {
    return this._inputs[1];
  }
  get worldTangent() {
    return this._inputs[2];
  }
  get uv() {
    return this._inputs[3];
  }
  get normalMapColor() {
    return this._inputs[4];
  }
  get strength() {
    return this._inputs[5];
  }
  get viewDirection() {
    return this._inputs[6];
  }
  get parallaxScale() {
    return this._inputs[7];
  }
  get parallaxHeight() {
    return this._inputs[8];
  }
  get TBN() {
    return this._inputs[9];
  }
  get world() {
    return this._inputs[10];
  }
  get output() {
    return this._outputs[0];
  }
  get uvOffset() {
    return this._outputs[1];
  }
  initialize(state) {
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_bumpFragment(), exports_bumpFragment)),
        Promise.resolve().then(() => (init_bumpFragmentMainFunctions(), exports_bumpFragmentMainFunctions)),
        Promise.resolve().then(() => (init_bumpFragmentFunctions(), exports_bumpFragmentFunctions))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_bumpFragment2(), exports_bumpFragment2)),
        Promise.resolve().then(() => (init_bumpFragmentMainFunctions2(), exports_bumpFragmentMainFunctions2)),
        Promise.resolve().then(() => (init_bumpFragmentFunctions2(), exports_bumpFragmentFunctions2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    const normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;
    const useParallax = this.viewDirection.isConnected && (this.useParallaxOcclusion && normalSamplerName || !this.useParallaxOcclusion && this.parallaxHeight.isConnected);
    defines.setValue("BUMP", true);
    defines.setValue("PARALLAX", useParallax, true);
    defines.setValue("PARALLAX_RHS", nodeMaterial.getScene().useRightHandedSystem, true);
    defines.setValue("PARALLAXOCCLUSION", this.useParallaxOcclusion, true);
    defines.setValue("OBJECTSPACE_NORMALMAP", this.useObjectSpaceNormalMap, true);
  }
  bind(effect, nodeMaterial, mesh) {
    if (nodeMaterial.getScene()._mirroredCameraPosition) {
      effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1 : -1, this.invertY ? 1 : -1);
    } else {
      effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1 : 1, this.invertY ? -1 : 1);
    }
    if (mesh) {
      effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);
      if (this.useObjectSpaceNormalMap && !this.world.isConnected) {
        effect.setMatrix(this._worldMatrixName, mesh.getWorldMatrix());
      }
    }
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.uv.isConnected) {
      let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv" && additionalFilteringInfo(b));
      if (!uvInput) {
        uvInput = new InputBlock("uv");
        uvInput.setAsAttribute();
      }
      uvInput.output.connectTo(this.uv);
    }
    if (!this.strength.isConnected) {
      const strengthInput = new InputBlock("strength");
      strengthInput.value = 1;
      strengthInput.output.connectTo(this.strength);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const comments = `//${this.name}`;
    const uv = this.uv;
    const worldPosition = this.worldPosition;
    const worldNormal = this.worldNormal;
    const worldTangent = this.worldTangent;
    const isWebGPU = state.shaderLanguage === 1;
    const mat3 = isWebGPU ? "mat3x3f" : "mat3";
    const fSuffix = isWebGPU ? "f" : "";
    const uniformPrefix = isWebGPU ? "uniforms." : "";
    const fragmentInputsPrefix = isWebGPU ? "fragmentInputs." : "";
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.bindableBlocks.push(this);
    this._tangentSpaceParameterName = state._getFreeDefineName("tangentSpaceParameter");
    state._emitUniformFromString(this._tangentSpaceParameterName, NodeMaterialBlockConnectionPointTypes.Vector2);
    this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor");
    state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float);
    this._worldMatrixName = state._getFreeDefineName("perturbNormalWorldMatrix");
    state._emitUniformFromString(this._worldMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix);
    let normalSamplerName = null;
    if (this.normalMapColor.connectedPoint) {
      normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;
    }
    const useParallax = this.viewDirection.isConnected && (this.useParallaxOcclusion && normalSamplerName || !this.useParallaxOcclusion && this.parallaxHeight.isConnected);
    const replaceForParallaxInfos = !this.parallaxScale.isConnectedToInputBlock ? "0.05" : this.parallaxScale.connectInputBlock.isConstant ? state._emitFloat(this.parallaxScale.connectInputBlock.value) : this.parallaxScale.associatedVariableName;
    const replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant ? `
#if !defined(NORMALXYSCALE)
1.0/
#endif
${state._emitFloat(this.strength.connectInputBlock.value)}` : `
#if !defined(NORMALXYSCALE)
1.0/
#endif
${this.strength.associatedVariableName}`;
    if (!isWebGPU) {
      state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    }
    const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
    const tbnVarying = { search: /varying mat3 vTBN;/g, replace: "" };
    const normalMatrixReplaceString = { search: isWebGPU ? /uniform normalMatrix: mat4x4f;/g : /uniform mat4 normalMatrix;/g, replace: "" };
    const TBN = this.TBN;
    if (TBN.isConnected) {
      state.compilationString += `
            #ifdef TBNBLOCK
            ${isWebGPU ? "var" : "mat3"} vTBN = ${TBN.associatedVariableName};
            #endif
            `;
    } else if (worldTangent.isConnected) {
      state.compilationString += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormal.associatedVariableName}.xyz);
`;
      state.compilationString += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);
`;
      state.compilationString += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${uniformPrefix}${this._tangentCorrectionFactorName};
`;
      state.compilationString += `${isWebGPU ? "var" : "mat3"} vTBN = ${mat3}(tbnTangent, tbnBitangent, tbnNormal);
`;
    }
    let replaceStrings = [tangentReplaceString, tbnVarying, normalMatrixReplaceString];
    if (isWebGPU) {
      replaceStrings.push({ search: /varying vTBN0: vec3f;/g, replace: "" });
      replaceStrings.push({ search: /varying vTBN1: vec3f;/g, replace: "" });
      replaceStrings.push({ search: /varying vTBN2: vec3f;/g, replace: "" });
    }
    state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
      replaceStrings
    });
    const replaceString0 = isWebGPU ? "fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bumpSampler: texture_2d<f32>, bumpSamplerSampler: sampler)" : `#define inline
vec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)`;
    const searchExp0 = isWebGPU ? /fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g : /vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g;
    const replaceString1 = isWebGPU ? "fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)" : "vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)";
    const searchExp1 = isWebGPU ? /fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g : /vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;
    state._emitFunctionFromInclude("bumpFragmentFunctions", comments, {
      replaceStrings: [
        { search: /#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g, replace: "" },
        { search: /uniform sampler2D bumpSampler;/g, replace: "" },
        {
          search: searchExp0,
          replace: replaceString0
        },
        { search: searchExp1, replace: replaceString1 },
        { search: /texture.+?bumpSampler,.*?vBumpUV\)\.w/g, replace: "height_" }
      ]
    });
    const normalRead = isWebGPU ? `textureSample(${normalSamplerName}, ${normalSamplerName + `Sampler`}` : `texture2D(${normalSamplerName}`;
    const uvForPerturbNormal = !useParallax || !normalSamplerName ? this.normalMapColor.associatedVariableName : `${normalRead}, ${uv.associatedVariableName} + uvOffset).xyz`;
    const tempOutput = state._getFreeVariableName("tempOutput");
    state.compilationString += state._declareLocalVar(tempOutput, NodeMaterialBlockConnectionPointTypes.Vector3) + ` = vec3${fSuffix}(0.);
`;
    replaceStrings = [
      { search: new RegExp(`texture.+?bumpSampler${isWebGPU ? "Sampler,fragmentInputs." : ","}vBumpUV\\)`, "g"), replace: `${uvForPerturbNormal}` },
      {
        search: /#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,
        replace: `${state._declareLocalVar("normalMatrix", NodeMaterialBlockConnectionPointTypes.Matrix)} = toNormalMatrix(${this.world.isConnected ? this.world.associatedVariableName : uniformPrefix + this._worldMatrixName});`
      },
      {
        search: new RegExp(`perturbNormal\\(TBN,texture.+?bumpSampler${isWebGPU ? "Sampler,fragmentInputs." : ","}vBumpUV\\+uvOffset\\).xyz,${uniformPrefix}vBumpInfos.y\\)`, "g"),
        replace: `perturbNormal(TBN, ${uvForPerturbNormal}, ${uniformPrefix}vBumpInfos.y)`
      },
      {
        search: /parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,(fragmentInputs\.)?vBumpUV,(uniforms\.)?vBumpInfos.z\)/g,
        replace: `parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), ${fragmentInputsPrefix}vBumpUV, ${uniformPrefix}vBumpInfos.z, ${isWebGPU ? useParallax && this.useParallaxOcclusion ? `${normalSamplerName}, ${normalSamplerName + `Sampler`}` : "bump, bumpSampler" : useParallax && this.useParallaxOcclusion ? normalSamplerName : "bumpSampler"})`
      },
      {
        search: /parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,
        replace: `parallaxOffset(invTBN * viewDirectionW, ${uniformPrefix}vBumpInfos.z, ${useParallax ? this.parallaxHeight.associatedVariableName : "0."})`
      },
      { search: isWebGPU ? /uniforms.vBumpInfos.y/g : /vBumpInfos.y/g, replace: replaceForBumpInfos },
      { search: isWebGPU ? /uniforms.vBumpInfos.z/g : /vBumpInfos.z/g, replace: replaceForParallaxInfos },
      { search: /normalW=/g, replace: tempOutput + " = " },
      isWebGPU ? {
        search: /mat3x3f\(uniforms\.normalMatrix\[0\].xyz,uniforms\.normalMatrix\[1\]\.xyz,uniforms\.normalMatrix\[2\].xyz\)\*normalW/g,
        replace: `${mat3}(normalMatrix[0].xyz, normalMatrix[1].xyz, normalMatrix[2].xyz) * ` + tempOutput
      } : {
        search: /mat3\(normalMatrix\)\*normalW/g,
        replace: `${mat3}(normalMatrix) * ` + tempOutput
      },
      { search: /normalW/g, replace: worldNormal.associatedVariableName + ".xyz" },
      { search: /viewDirectionW/g, replace: useParallax ? this.viewDirection.associatedVariableName : `vec3${fSuffix}(0.)` },
      tangentReplaceString
    ];
    if (isWebGPU) {
      replaceStrings.push({ search: /fragmentInputs.vBumpUV/g, replace: uv.associatedVariableName });
      replaceStrings.push({ search: /input.vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" });
      replaceStrings.push({ search: /uniforms.vTangentSpaceParams/g, replace: uniformPrefix + this._tangentSpaceParameterName });
      replaceStrings.push({ search: /var TBN: mat3x3f=mat3x3<f32>\(input.vTBN0,input.vTBN1,input.vTBN2\);/g, replace: `var TBN = vTBN;` });
    } else {
      replaceStrings.push({ search: /vBumpUV/g, replace: uv.associatedVariableName });
      replaceStrings.push({ search: /vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" });
      replaceStrings.push({ search: /vTangentSpaceParams/g, replace: uniformPrefix + this._tangentSpaceParameterName });
    }
    state.compilationString += state._emitCodeFromInclude("bumpFragment", comments, {
      replaceStrings
    });
    state.compilationString += state._declareOutput(this.output) + ` = vec4${fSuffix}(${tempOutput}, 0.);
`;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.invertX = ${this.invertX};
`;
    codeString += `${this._codeVariableName}.invertY = ${this.invertY};
`;
    codeString += `${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};
`;
    codeString += `${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.invertX = this.invertX;
    serializationObject.invertY = this.invertY;
    serializationObject.useParallaxOcclusion = this.useParallaxOcclusion;
    serializationObject.useObjectSpaceNormalMap = this.useObjectSpaceNormalMap;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.invertX = serializationObject.invertX;
    this.invertY = serializationObject.invertY;
    this.useParallaxOcclusion = !!serializationObject.useParallaxOcclusion;
    this.useObjectSpaceNormalMap = !!serializationObject.useObjectSpaceNormalMap;
  }
}
__decorate([
  editableInPropertyPage("Invert X axis", 0, "PROPERTIES", { embedded: true, notifiers: { update: true } })
], PerturbNormalBlock.prototype, "invertX", undefined);
__decorate([
  editableInPropertyPage("Invert Y axis", 0, "PROPERTIES", { embedded: true, notifiers: { update: true } })
], PerturbNormalBlock.prototype, "invertY", undefined);
__decorate([
  editableInPropertyPage("Use parallax occlusion", 0, undefined, { embedded: true })
], PerturbNormalBlock.prototype, "useParallaxOcclusion", undefined);
__decorate([
  editableInPropertyPage("Object Space Mode", 0, "PROPERTIES", { embedded: true, notifiers: { update: true } })
], PerturbNormalBlock.prototype, "useObjectSpaceNormalMap", undefined);
RegisterClass("BABYLON.PerturbNormalBlock", PerturbNormalBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/discardBlock.js
init_typeStore();

class DiscardBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment, true);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("cutoff", NodeMaterialBlockConnectionPointTypes.Float, true);
  }
  getClassName() {
    return "DiscardBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get cutoff() {
    return this._inputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    state.sharedData.hints.needAlphaTesting = true;
    if (!this.cutoff.isConnected || !this.value.isConnected) {
      return;
    }
    state.compilationString += `if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }
`;
    return this;
  }
}
RegisterClass("BABYLON.DiscardBlock", DiscardBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/frontFacingBlock.js
init_typeStore();

class FrontFacingBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "FrontFacingBlock";
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      throw "FrontFacingBlock must only be used in a fragment shader";
    }
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary("1.0", "0.0", state.shaderLanguage === 0 ? "gl_FrontFacing" : "fragmentInputs.frontFacing")};
`;
    return this;
  }
}
RegisterClass("BABYLON.FrontFacingBlock", FrontFacingBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/derivativeBlock.js
init_typeStore();

class DerivativeBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);
    this.registerOutput("dx", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("dy", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._outputs[1]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "DerivativeBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get dx() {
    return this._outputs[0];
  }
  get dy() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const dx = this._outputs[0];
    const dy = this._outputs[1];
    state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    let dpdx = "dFdx";
    let dpdy = "dFdy";
    if (state.shaderLanguage === 1) {
      dpdx = "dpdx";
      dpdy = "dpdy";
    }
    if (dx.hasEndpoints) {
      state.compilationString += state._declareOutput(dx) + ` = ${dpdx}(${this.input.associatedVariableName});
`;
    }
    if (dy.hasEndpoints) {
      state.compilationString += state._declareOutput(dy) + ` = ${dpdy}(${this.input.associatedVariableName});
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.DerivativeBlock", DerivativeBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragCoordBlock.js
init_typeStore();

class FragCoordBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "FragCoordBlock";
  }
  get xy() {
    return this._outputs[0];
  }
  get xyz() {
    return this._outputs[1];
  }
  get xyzw() {
    return this._outputs[2];
  }
  get x() {
    return this._outputs[3];
  }
  get y() {
    return this._outputs[4];
  }
  get z() {
    return this._outputs[5];
  }
  get output() {
    return this._outputs[6];
  }
  writeOutputs(state) {
    let code = "";
    const coord = state.shaderLanguage === 1 ? "fragmentInputs.position" : "gl_FragCoord";
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        code += `${state._declareOutput(output)} = ${coord}.${output.name};
`;
      }
    }
    return code;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      throw "FragCoordBlock must only be used in a fragment shader";
    }
    state.compilationString += this.writeOutputs(state);
    return this;
  }
}
RegisterClass("BABYLON.FragCoordBlock", FragCoordBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSizeBlock.js
init_typeStore();

class ScreenSizeBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "ScreenSizeBlock";
  }
  get xy() {
    return this._outputs[0];
  }
  get x() {
    return this._outputs[1];
  }
  get y() {
    return this._outputs[2];
  }
  bind(effect) {
    const engine2 = this._scene.getEngine();
    effect.setFloat2(this._varName, engine2.getRenderWidth(), engine2.getRenderHeight());
  }
  writeOutputs(state, varName) {
    let code = "";
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        code += `${state._declareOutput(output)} = ${varName}.${output.name};
`;
      }
    }
    return code;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._scene = state.sharedData.scene;
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      throw "ScreenSizeBlock must only be used in a fragment shader";
    }
    state.sharedData.bindableBlocks.push(this);
    this._varName = state._getFreeVariableName("screenSize");
    state._emitUniformFromString(this._varName, NodeMaterialBlockConnectionPointTypes.Vector2);
    const prefix = state.shaderLanguage === 1 ? "uniforms." : "";
    state.compilationString += this.writeOutputs(state, prefix + this._varName);
    return this;
  }
}
RegisterClass("BABYLON.ScreenSizeBlock", ScreenSizeBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSpaceBlock.js
init_typeStore();
class ScreenSpaceBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("worldViewProjection", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float);
    this.inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ScreenSpaceBlock";
  }
  get vector() {
    return this._inputs[0];
  }
  get worldViewProjection() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  get x() {
    return this._outputs[1];
  }
  get y() {
    return this._outputs[2];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.worldViewProjection.isConnected) {
      let worldViewProjectionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.WorldViewProjection && additionalFilteringInfo(b));
      if (!worldViewProjectionInput) {
        worldViewProjectionInput = new InputBlock("worldViewProjection");
        worldViewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection);
      }
      worldViewProjectionInput.output.connectTo(this.worldViewProjection);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const vector = this.vector;
    const worldViewProjection = this.worldViewProjection;
    if (!vector.connectedPoint) {
      return;
    }
    const worldViewProjectionName = worldViewProjection.associatedVariableName;
    const tempVariableName = state._getFreeVariableName("screenSpaceTemp");
    switch (vector.connectedPoint.type) {
      case NodeMaterialBlockConnectionPointTypes.Vector3:
        state.compilationString += `${state._declareLocalVar(tempVariableName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldViewProjectionName} * vec4${state.fSuffix}(${vector.associatedVariableName}, 1.0);
`;
        break;
      case NodeMaterialBlockConnectionPointTypes.Vector4:
        state.compilationString += `${state._declareLocalVar(tempVariableName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldViewProjectionName} * ${vector.associatedVariableName};
`;
        break;
    }
    state.compilationString += `${tempVariableName} = vec4${state.fSuffix}(${tempVariableName}.xy / ${tempVariableName}.w, ${tempVariableName}.zw);`;
    state.compilationString += `${tempVariableName} = vec4${state.fSuffix}(${tempVariableName}.xy * 0.5 + vec2${state.fSuffix}(0.5, 0.5), ${tempVariableName}.zw);`;
    if (this.output.hasEndpoints) {
      state.compilationString += state._declareOutput(this.output) + ` = ${tempVariableName}.xy;
`;
    }
    if (this.x.hasEndpoints) {
      state.compilationString += state._declareOutput(this.x) + ` = ${tempVariableName}.x;
`;
    }
    if (this.y.hasEndpoints) {
      state.compilationString += state._declareOutput(this.y) + ` = ${tempVariableName}.y;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.ScreenSpaceBlock", ScreenSpaceBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/twirlBlock.js
init_typeStore();
init_math_vector();

class TwirlBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("center", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "TwirlBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get strength() {
    return this._inputs[1];
  }
  get center() {
    return this._inputs[2];
  }
  get offset() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  get x() {
    return this._outputs[1];
  }
  get y() {
    return this._outputs[2];
  }
  autoConfigure() {
    if (!this.center.isConnected) {
      const centerInput = new InputBlock("center");
      centerInput.value = new Vector2(0.5, 0.5);
      centerInput.output.connectTo(this.center);
    }
    if (!this.strength.isConnected) {
      const strengthInput = new InputBlock("strength");
      strengthInput.value = 1;
      strengthInput.output.connectTo(this.strength);
    }
    if (!this.offset.isConnected) {
      const offsetInput = new InputBlock("offset");
      offsetInput.value = new Vector2(0, 0);
      offsetInput.output.connectTo(this.offset);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const tempDelta = state._getFreeVariableName("delta");
    const tempAngle = state._getFreeVariableName("angle");
    const tempX = state._getFreeVariableName("x");
    const tempY = state._getFreeVariableName("y");
    const tempResult = state._getFreeVariableName("result");
    state.compilationString += `        
            ${state._declareLocalVar(tempDelta, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};
            ${state._declareLocalVar(tempAngle, NodeMaterialBlockConnectionPointTypes.Float)} = ${this.strength.associatedVariableName} * length(${tempDelta});
            ${state._declareLocalVar(tempX, NodeMaterialBlockConnectionPointTypes.Float)} = cos(${tempAngle}) * ${tempDelta}.x - sin(${tempAngle}) * ${tempDelta}.y;
            ${state._declareLocalVar(tempY, NodeMaterialBlockConnectionPointTypes.Float)} = sin(${tempAngle}) * ${tempDelta}.x + cos(${tempAngle}) * ${tempDelta}.y;
            ${state._declareLocalVar(tempResult, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2(${tempX} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${tempY} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);
        `;
    if (this.output.hasEndpoints) {
      state.compilationString += state._declareOutput(this.output) + ` = ${tempResult};
`;
    }
    if (this.x.hasEndpoints) {
      state.compilationString += state._declareOutput(this.x) + ` = ${tempResult}.x;
`;
    }
    if (this.y.hasEndpoints) {
      state.compilationString += state._declareOutput(this.y) + ` = ${tempResult}.y;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.TwirlBlock", TwirlBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/heightToNormalBlock.js
init_tslib_es6();
init_typeStore();
init_logger();

class HeightToNormalBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.generateInWorldSpace = false;
    this.automaticNormalizationNormal = true;
    this.automaticNormalizationTangent = true;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "HeightToNormalBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get worldPosition() {
    return this._inputs[1];
  }
  get worldNormal() {
    return this._inputs[2];
  }
  get worldTangent() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  get xyz() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const isWebGPU = state.shaderLanguage === 1;
    const fPrefix = state.fSuffix;
    if (!this.generateInWorldSpace && !this.worldTangent.isConnected) {
      Logger.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);
    }
    const startCode = this.generateInWorldSpace ? "" : `
            vec3 biTangent = cross(norm, tgt);
            mat3 TBN = mat3(tgt, biTangent, norm);
            `;
    const endCode = this.generateInWorldSpace ? "" : `
            result = TBN * result;
            result = result * vec3(0.5) + vec3(0.5);
            `;
    let heightToNormal = `
            vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {
                vec3 tgt = ${this.automaticNormalizationTangent ? "normalize(tangent);" : "tangent;"}
                vec3 norm = ${this.automaticNormalizationNormal ? "normalize(normal);" : "normal;"}
                ${startCode}
                vec3 worlddX = dFdx(position);
                vec3 worlddY = dFdy(position);
                vec3 crossX = cross(norm, worlddX);
                vec3 crossY = cross(worlddY, norm);
                float d = abs(dot(crossY, worlddX));
                vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));
                inToNormal.y *= -1.0;
                vec3 result = normalize((d * norm) - inToNormal);
                ${endCode}
                return vec4(result, 0.);
            }`;
    if (isWebGPU) {
      heightToNormal = state._babylonSLtoWGSL(heightToNormal);
    } else {
      state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    }
    state._emitFunction("heightToNormal", heightToNormal, "// heightToNormal");
    state.compilationString += state._declareOutput(output) + ` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected ? this.worldTangent.associatedVariableName : `vec3${fPrefix}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});
`;
    if (this.xyz.hasEndpoints) {
      state.compilationString += state._declareOutput(this.xyz) + ` = ${this.output.associatedVariableName}.xyz;
`;
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};
`;
    codeString += `${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};
`;
    codeString += `${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.generateInWorldSpace = this.generateInWorldSpace;
    serializationObject.automaticNormalizationNormal = this.automaticNormalizationNormal;
    serializationObject.automaticNormalizationTangent = this.automaticNormalizationTangent;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.generateInWorldSpace = serializationObject.generateInWorldSpace;
    this.automaticNormalizationNormal = serializationObject.automaticNormalizationNormal;
    this.automaticNormalizationTangent = serializationObject.automaticNormalizationTangent;
  }
}
__decorate([
  editableInPropertyPage("Generate in world space instead of tangent space", 0, "PROPERTIES", { notifiers: { update: true } })
], HeightToNormalBlock.prototype, "generateInWorldSpace", undefined);
__decorate([
  editableInPropertyPage("Force normalization for the worldNormal input", 0, "PROPERTIES", { notifiers: { update: true } })
], HeightToNormalBlock.prototype, "automaticNormalizationNormal", undefined);
__decorate([
  editableInPropertyPage("Force normalization for the worldTangent input", 0, "PROPERTIES", { notifiers: { update: true } })
], HeightToNormalBlock.prototype, "automaticNormalizationTangent", undefined);
RegisterClass("BABYLON.HeightToNormalBlock", HeightToNormalBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragDepthBlock.js
init_typeStore();
init_logger();

class FragDepthBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment, true);
    this.registerInput("depth", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, true);
  }
  getClassName() {
    return "FragDepthBlock";
  }
  get depth() {
    return this._inputs[0];
  }
  get worldPos() {
    return this._inputs[1];
  }
  get viewProjection() {
    return this._inputs[2];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const fragDepth = state.shaderLanguage === 0 ? "gl_FragDepth" : "fragmentOutputs.fragDepth";
    if (this.depth.isConnected) {
      state.compilationString += `${fragDepth} = ${this.depth.associatedVariableName};
`;
    } else if (this.worldPos.isConnected && this.viewProjection.isConnected) {
      state.compilationString += `
                ${state._declareLocalVar("p", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};
                ${state._declareLocalVar("v", NodeMaterialBlockConnectionPointTypes.Float)} = p.z / p.w;
                #ifndef IS_NDC_HALF_ZRANGE
                    v = v * 0.5 + 0.5;
                #endif
                ${fragDepth} = v;
    
            `;
    } else {
      Logger.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!");
    }
    return this;
  }
}
RegisterClass("BABYLON.FragDepthBlock", FragDepthBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/shadowMapBlock.js
init_typeStore();

class ShadowMapBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false);
    this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, false);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ShadowMapBlock";
  }
  initialize(state) {
    state._excludeVariableName("vPositionWSM");
    state._excludeVariableName("lightDataSM");
    state._excludeVariableName("biasAndScaleSM");
    state._excludeVariableName("depthValuesSM");
    state._excludeVariableName("clipPos");
    state._excludeVariableName("worldPos");
    state._excludeVariableName("zSM");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_shadowMapVertexMetric(), exports_shadowMapVertexMetric)),
        Promise.resolve().then(() => (init_packingFunctions(), exports_packingFunctions)),
        Promise.resolve().then(() => (init_shadowMapFragment(), exports_shadowMapFragment))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_shadowMapVertexMetric2(), exports_shadowMapVertexMetric2)),
        Promise.resolve().then(() => (init_packingFunctions2(), exports_packingFunctions2)),
        Promise.resolve().then(() => (init_shadowMapFragment2(), exports_shadowMapFragment2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get viewProjection() {
    return this._inputs[1];
  }
  get worldNormal() {
    return this._inputs[2];
  }
  get depth() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const comments = `//${this.name}`;
    const isWebGPU = state.shaderLanguage === 1;
    state._emitUniformFromString("biasAndScaleSM", NodeMaterialBlockConnectionPointTypes.Vector3);
    state._emitUniformFromString("lightDataSM", NodeMaterialBlockConnectionPointTypes.Vector3);
    state._emitUniformFromString("depthValuesSM", NodeMaterialBlockConnectionPointTypes.Vector2);
    state._emitFunctionFromInclude("packingFunctions", comments);
    state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.worldPosition.associatedVariableName};
`;
    state.compilationString += `${state._declareLocalVar("vPositionWSM", NodeMaterialBlockConnectionPointTypes.Vector3)};
`;
    state.compilationString += `${state._declareLocalVar("vDepthMetricSM", NodeMaterialBlockConnectionPointTypes.Float)} = 0.0;
`;
    state.compilationString += `${state._declareLocalVar("zSM", NodeMaterialBlockConnectionPointTypes.Float)};
`;
    if (this.worldNormal.isConnected) {
      state.compilationString += `${state._declareLocalVar("vNormalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;
`;
      state.compilationString += state._emitCodeFromInclude("shadowMapVertexNormalBias", comments);
    }
    state.compilationString += `${state._declareLocalVar("clipPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.viewProjection.associatedVariableName} * worldPos;
`;
    state.compilationString += state._emitCodeFromInclude("shadowMapVertexMetric", comments, {
      replaceStrings: [
        {
          search: /gl_Position/g,
          replace: "clipPos"
        },
        {
          search: /vertexOutputs.position/g,
          replace: "clipPos"
        },
        {
          search: /vertexOutputs\.vDepthMetricSM/g,
          replace: "vDepthMetricSM"
        }
      ]
    });
    state.compilationString += state._emitCodeFromInclude("shadowMapFragment", comments, {
      replaceStrings: [
        {
          search: /return;/g,
          replace: ""
        },
        {
          search: /fragmentInputs\.vDepthMetricSM/g,
          replace: "vDepthMetricSM"
        }
      ]
    });
    const output = isWebGPU ? "fragmentOutputs.fragDepth" : "gl_FragDepth";
    state.compilationString += `
            #if SM_DEPTHTEXTURE == 1
                #ifdef IS_NDC_HALF_ZRANGE
                    ${output} = (clipPos.z / clipPos.w);
                #else
                    ${output} = (clipPos.z / clipPos.w) * 0.5 + 0.5;
                #endif
            #endif
        `;
    state.compilationString += `${state._declareOutput(this.depth)} = vec3${state.fSuffix}(depthSM, 1., 1.);
`;
    return this;
  }
}
RegisterClass("BABYLON.ShadowMapBlock", ShadowMapBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/prePassOutputBlock.js
init_typeStore();

class PrePassOutputBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment, true);
    this.registerInput("viewDepth", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("screenDepth", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("localPosition", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("viewNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("reflectivity", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("velocity", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("velocityLinear", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.inputs[2].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this.inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this.inputs[4].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this.inputs[5].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this.inputs[6].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
    this.inputs[7].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this.inputs[8].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "PrePassOutputBlock";
  }
  get viewDepth() {
    return this._inputs[0];
  }
  get screenDepth() {
    return this._inputs[1];
  }
  get worldPosition() {
    return this._inputs[2];
  }
  get localPosition() {
    return this._inputs[3];
  }
  get viewNormal() {
    return this._inputs[4];
  }
  get worldNormal() {
    return this._inputs[5];
  }
  get reflectivity() {
    return this._inputs[6];
  }
  get velocity() {
    return this._inputs[7];
  }
  get velocityLinear() {
    return this._inputs[8];
  }
  _getFragData(isWebGPU, index) {
    return isWebGPU ? `fragmentOutputs.fragData${index}` : `gl_FragData[${index}]`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const worldPosition = this.worldPosition;
    const localPosition = this.localPosition;
    const viewNormal = this.viewNormal;
    const worldNormal = this.worldNormal;
    const viewDepth = this.viewDepth;
    const reflectivity = this.reflectivity;
    const screenDepth = this.screenDepth;
    const velocity = this.velocity;
    const velocityLinear = this.velocityLinear;
    state.sharedData.blocksWithDefines.push(this);
    const comments = `//${this.name}`;
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    const isWebGPU = state.shaderLanguage === 1;
    state._emitFunctionFromInclude("helperFunctions", comments);
    state.compilationString += `#if defined(PREPASS)\r
`;
    state.compilationString += isWebGPU ? `var fragData: array<vec4<f32>, SCENE_MRT_COUNT>;\r
` : `vec4 fragData[SCENE_MRT_COUNT];\r
`;
    state.compilationString += `#ifdef PREPASS_DEPTH\r
`;
    if (viewDepth.connectedPoint) {
      state.compilationString += ` fragData[PREPASS_DEPTH_INDEX] = ${vec4}(${viewDepth.associatedVariableName}, 0.0, 0.0, 1.0);\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_DEPTH_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_SCREENSPACE_DEPTH\r
`;
    if (screenDepth.connectedPoint) {
      state.compilationString += ` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(${screenDepth.associatedVariableName}, 0.0, 0.0, 1.0);\r
`;
    } else {
      state.compilationString += ` gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_POSITION\r
`;
    if (worldPosition.connectedPoint) {
      state.compilationString += `fragData[PREPASS_POSITION_INDEX] = ${vec4}(${worldPosition.associatedVariableName}.rgb, ${worldPosition.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? worldPosition.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_POSITION_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_LOCAL_POSITION\r
`;
    if (localPosition.connectedPoint) {
      state.compilationString += ` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(${localPosition.associatedVariableName}.rgb, ${localPosition.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? localPosition.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` gl_FragData[PREPASS_LOCAL_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_NORMAL\r
`;
    if (viewNormal.connectedPoint) {
      state.compilationString += ` fragData[PREPASS_NORMAL_INDEX] = ${vec4}(${viewNormal.associatedVariableName}.rgb, ${viewNormal.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? viewNormal.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_NORMAL_INDEX] = ${vec4}(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_WORLD_NORMAL\r
`;
    if (worldNormal.connectedPoint) {
      state.compilationString += ` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(${worldNormal.associatedVariableName}.rgb, ${worldNormal.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? worldNormal.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` gl_FragData[PREPASS_WORLD_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_REFLECTIVITY\r
`;
    if (reflectivity.connectedPoint) {
      state.compilationString += ` fragData[PREPASS_REFLECTIVITY_INDEX] = ${vec4}(${reflectivity.associatedVariableName}.rgb, ${reflectivity.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? reflectivity.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_REFLECTIVITY_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_VELOCITY\r
`;
    if (velocity.connectedPoint) {
      state.compilationString += ` fragData[PREPASS_VELOCITY_INDEX] = ${vec4}(${velocity.associatedVariableName}.rgb, ${velocity.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? velocity.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_VELOCITY_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#ifdef PREPASS_VELOCITY_LINEAR\r
`;
    if (velocityLinear.connectedPoint) {
      state.compilationString += ` fragData[PREPASS_VELOCITY_LINEAR_INDEX] = ${vec4}(${velocityLinear.associatedVariableName}.rgb, ${velocityLinear.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? velocityLinear.associatedVariableName + ".a" : "1.0"});\r
`;
    } else {
      state.compilationString += ` fragData[PREPASS_VELOCITY_LINEAR_INDEX] = ${vec4}(0.0, 0.0, 0.0, 1.0);\r
`;
    }
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 1\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 1)} = fragData[1];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 2\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 2)} = fragData[2];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 3\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 3)} = fragData[3];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 4\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 4)} = fragData[4];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 5\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 5)} = fragData[5];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 6\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 6)} = fragData[6];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#if SCENE_MRT_COUNT > 7\r
`;
    state.compilationString += `${this._getFragData(isWebGPU, 7)} = fragData[7];\r
`;
    state.compilationString += `#endif\r
`;
    state.compilationString += `#endif\r
`;
    return this;
  }
}
RegisterClass("BABYLON.PrePassOutputBlock", PrePassOutputBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/index.js
init_helperFunctions();
init_imageProcessingDeclaration();
init_imageProcessingFunctions();
init_helperFunctions2();
init_imageProcessingDeclaration2();
init_imageProcessingFunctions2();
init_bumpFragment();
init_bumpFragmentMainFunctions();
init_bumpFragmentFunctions();
init_bumpFragment2();
init_bumpFragmentMainFunctions2();
init_bumpFragmentFunctions2();
init_shadowMapVertexMetric();
init_packingFunctions();
init_shadowMapFragment();
init_shadowMapVertexMetric2();
init_packingFunctions2();
init_shadowMapFragment2();
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/fogBlock.js
init_typeStore();
init_materialHelper_functions();

class FogBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment, false);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("fogColor", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.input.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);
    this.fogColor.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "FogBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get view() {
    return this._inputs[1];
  }
  get input() {
    return this._inputs[2];
  }
  get fogColor() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  initialize(state) {
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.resolve().then(() => (init_fogFragmentDeclaration(), exports_fogFragmentDeclaration));
    } else {
      await Promise.resolve().then(() => (init_fogFragmentDeclaration2(), exports_fogFragmentDeclaration2));
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.view.isConnected) {
      let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b));
      if (!viewInput) {
        viewInput = new InputBlock("view");
        viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
      }
      viewInput.output.connectTo(this.view);
    }
    if (!this.fogColor.isConnected) {
      let fogColorInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.FogColor && additionalFilteringInfo(b));
      if (!fogColorInput) {
        fogColorInput = new InputBlock("fogColor", undefined, NodeMaterialBlockConnectionPointTypes.Color3);
        fogColorInput.setAsSystemValue(NodeMaterialSystemValues.FogColor);
      }
      fogColorInput.output.connectTo(this.fogColor);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    const scene = mesh.getScene();
    defines.setValue("FOG", nodeMaterial.fogEnabled && GetFogState(mesh, scene));
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    const scene = mesh.getScene();
    effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.blocksWithDefines.push(this);
      state.sharedData.bindableBlocks.push(this);
      let replaceStrings = [];
      let prefix1 = "";
      let prefix2 = "";
      if (state.shaderLanguage === 1) {
        replaceStrings = [
          { search: /fn CalcFogFactor\(\)/, replace: "fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)" },
          { search: /uniforms.vFogInfos/g, replace: "vFogInfos" },
          { search: /fragmentInputs.vFogDistance/g, replace: "vFogDistance" }
        ];
        prefix1 = "fragmentInputs.";
        prefix2 = "uniforms.";
      } else {
        replaceStrings = [{ search: /float CalcFogFactor\(\)/, replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)" }];
      }
      state._emitFunctionFromInclude("fogFragmentDeclaration", `//${this.name}`, {
        removeUniforms: true,
        removeVaryings: true,
        removeIfDef: false,
        replaceStrings
      });
      const tempFogVariablename = state._getFreeVariableName("fog");
      const color = this.input;
      const fogColor = this.fogColor;
      this._fogParameters = state._getFreeVariableName("fogParameters");
      const output = this._outputs[0];
      state._emitUniformFromString(this._fogParameters, NodeMaterialBlockConnectionPointTypes.Vector4);
      state.compilationString += `#ifdef FOG
`;
      state.compilationString += `${state._declareLocalVar(tempFogVariablename, NodeMaterialBlockConnectionPointTypes.Float)} = CalcFogFactor(${prefix1}${this._fogDistanceName}, ${prefix2}${this._fogParameters});
`;
      state.compilationString += state._declareOutput(output) + ` = ${tempFogVariablename} * ${color.associatedVariableName}.rgb + (1.0 - ${tempFogVariablename}) * ${fogColor.associatedVariableName}.rgb;
`;
      state.compilationString += `#else
${state._declareOutput(output)} =  ${color.associatedVariableName}.rgb;
`;
      state.compilationString += `#endif
`;
    } else {
      const worldPos = this.worldPosition;
      const view = this.view;
      this._fogDistanceName = state._getFreeVariableName("vFogDistance");
      state._emitVaryingFromString(this._fogDistanceName, NodeMaterialBlockConnectionPointTypes.Vector3);
      const prefix = state.shaderLanguage === 1 ? "vertexOutputs." : "";
      state.compilationString += `${prefix}${this._fogDistanceName} = (${view.associatedVariableName} * ${worldPos.associatedVariableName}).xyz;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.FogBlock", FogBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/lightBlock.js
init_tslib_es6();
init_typeStore();
init_logger();
init_materialHelper_functions();

class LightBlock extends NodeMaterialBlock {
  static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {
    const that = block;
    if (that.worldPosition.isConnected) {
      that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;
      Logger.Error("The worldPosition input must not be connected to be able to switch!");
      return false;
    }
    that._setTarget();
    return true;
  }
  _setTarget() {
    this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);
    this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment);
    this._lightId = 0;
    this.generateOnlyFragmentCode = false;
    this._isUnique = true;
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("glossiness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("glossPower", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("specularColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, true);
    this.registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  }
  getClassName() {
    return "LightBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get worldNormal() {
    return this._inputs[1];
  }
  get cameraPosition() {
    return this._inputs[2];
  }
  get glossiness() {
    return this._inputs[3];
  }
  get glossPower() {
    return this._inputs[4];
  }
  get diffuseColor() {
    return this._inputs[5];
  }
  get specularColor() {
    return this._inputs[6];
  }
  get view() {
    return this._inputs[7];
  }
  get diffuseOutput() {
    return this._outputs[0];
  }
  get specularOutput() {
    return this._outputs[1];
  }
  get shadow() {
    return this._outputs[2];
  }
  initialize(state) {
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_lightFragment(), exports_lightFragment)),
        Promise.resolve().then(() => (init_lightUboDeclaration(), exports_lightUboDeclaration)),
        Promise.resolve().then(() => (init_lightVxUboDeclaration(), exports_lightVxUboDeclaration)),
        Promise.resolve().then(() => (init_helperFunctions(), exports_helperFunctions)),
        Promise.resolve().then(() => (init_lightsFragmentFunctions(), exports_lightsFragmentFunctions)),
        Promise.resolve().then(() => (init_shadowsFragmentFunctions(), exports_shadowsFragmentFunctions)),
        Promise.resolve().then(() => (init_shadowsVertex(), exports_shadowsVertex))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_lightFragmentDeclaration(), exports_lightFragmentDeclaration)),
        Promise.resolve().then(() => (init_lightFragment2(), exports_lightFragment2)),
        Promise.resolve().then(() => (init_lightUboDeclaration2(), exports_lightUboDeclaration2)),
        Promise.resolve().then(() => (init_lightVxUboDeclaration2(), exports_lightVxUboDeclaration2)),
        Promise.resolve().then(() => (init_lightVxFragmentDeclaration2(), exports_lightVxFragmentDeclaration)),
        Promise.resolve().then(() => (init_helperFunctions2(), exports_helperFunctions2)),
        Promise.resolve().then(() => (init_lightsFragmentFunctions2(), exports_lightsFragmentFunctions2)),
        Promise.resolve().then(() => (init_shadowsFragmentFunctions2(), exports_shadowsFragmentFunctions2)),
        Promise.resolve().then(() => (init_shadowsVertex2(), exports_shadowsVertex2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.cameraPosition.isConnected) {
      let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b));
      if (!cameraPositionInput) {
        cameraPositionInput = new InputBlock("cameraPosition");
        cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);
      }
      cameraPositionInput.output.connectTo(this.cameraPosition);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areLightsDirty) {
      return;
    }
    const scene = mesh.getScene();
    if (!this.light) {
      PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);
    } else {
      const state = {
        needNormals: false,
        needRebuild: false,
        lightmapMode: false,
        shadowEnabled: false,
        specularEnabled: false
      };
      PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);
      if (state.needRebuild) {
        defines.rebuild();
      }
    }
  }
  updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {
    state.samplers.push("areaLightsLTC1Sampler");
    state.samplers.push("areaLightsLTC2Sampler");
    for (let lightIndex = 0;lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {
      if (!defines["LIGHT" + lightIndex]) {
        break;
      }
      const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0;
      PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList, defines["IESLIGHTTEXTURE" + lightIndex]);
    }
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    const scene = mesh.getScene();
    if (!this.light) {
      BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);
    } else {
      BindLight(this.light, this._lightId, scene, effect, true);
    }
  }
  _injectVertexCode(state) {
    const worldPos = this.worldPosition;
    const comments = `//${this.name}`;
    if (!this.light) {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, {
        repeatKey: "maxSimultaneousLights"
      });
      this._lightId = 0;
      state.sharedData.dynamicUniformBlocks.push(this);
    } else {
      this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1;
      state.counters["lightCounter"] = this._lightId;
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, {
        replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
      }, this._lightId.toString());
    }
    const worldPosVaryingName = "v_" + worldPos.associatedVariableName;
    if (state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) {
      state.compilationString += (state.shaderLanguage === 1 ? "vertexOutputs." : "") + `${worldPosVaryingName} = ${worldPos.associatedVariableName};
`;
    }
    if (this.light) {
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        replaceStrings: [
          { search: /{X}/g, replace: this._lightId.toString() },
          { search: /worldPos/g, replace: worldPos.associatedVariableName }
        ]
      });
    } else {
      state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldPos.associatedVariableName};
`;
      if (this.view.isConnected) {
        state.compilationString += `${state._declareLocalVar("view", NodeMaterialBlockConnectionPointTypes.Matrix)} = ${this.view.associatedVariableName};
`;
      }
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        repeatKey: "maxSimultaneousLights"
      });
    }
  }
  _injectUBODeclaration(state) {
    const comments = `//${this.name}`;
    if (!this.light) {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined
      });
    } else {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
        replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
      }, this._lightId.toString());
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const isWGSL = state.shaderLanguage === 1;
    const addF = isWGSL ? "f" : "";
    const comments = `//${this.name}`;
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      this._injectVertexCode(state);
      return;
    }
    if (this.generateOnlyFragmentCode) {
      state.sharedData.dynamicUniformBlocks.push(this);
    }
    const accessor = isWGSL ? "fragmentInputs." : "";
    state.sharedData.forcedBindableBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    const worldPos = this.worldPosition;
    let worldPosVariableName = worldPos.associatedVariableName;
    if (this.generateOnlyFragmentCode) {
      worldPosVariableName = state._getFreeVariableName("globalWorldPos");
      state._emitFunction("light_globalworldpos", `${state._declareLocalVar(worldPosVariableName, NodeMaterialBlockConnectionPointTypes.Vector3)};
`, comments);
      state.compilationString += `${worldPosVariableName} = ${worldPos.associatedVariableName}.xyz;
`;
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${worldPos.associatedVariableName}` : undefined
      });
    } else {
      worldPosVariableName = accessor + "v_" + worldPosVariableName + ".xyz";
    }
    state._emitFunctionFromInclude("helperFunctions", comments);
    let replaceString = { search: /vPositionW/g, replace: worldPosVariableName };
    if (isWGSL) {
      replaceString = { search: /fragmentInputs\.vPositionW/g, replace: worldPosVariableName };
    }
    state._emitFunctionFromInclude("lightsFragmentFunctions", comments, {
      replaceStrings: [replaceString]
    });
    state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, {
      replaceStrings: [replaceString]
    });
    this._injectUBODeclaration(state);
    if (this._lightId === 0) {
      if (state._registerTempVariable("viewDirectionW")) {
        state.compilationString += `${state._declareLocalVar("viewDirectionW", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVariableName});
`;
      }
      state.compilationString += isWGSL ? `var info: lightingInfo;
` : `lightingInfo info;
`;
      state.compilationString += `${state._declareLocalVar("shadow", NodeMaterialBlockConnectionPointTypes.Float)} = 1.;
`;
      state.compilationString += `${state._declareLocalVar("aggShadow", NodeMaterialBlockConnectionPointTypes.Float)} = 0.;
`;
      state.compilationString += `${state._declareLocalVar("numLights", NodeMaterialBlockConnectionPointTypes.Float)} = 0.;
`;
      state.compilationString += `${state._declareLocalVar("glossiness", NodeMaterialBlockConnectionPointTypes.Float)} = ${this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0"} * ${this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0"};
`;
      state.compilationString += `${state._declareLocalVar("diffuseBase", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3${addF}(0., 0., 0.);
`;
      state.compilationString += `${state._declareLocalVar("specularBase", NodeMaterialBlockConnectionPointTypes.Vector3)}  = vec3${addF}(0., 0., 0.);
`;
      state.compilationString += `${state._declareLocalVar("normalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;
`;
    }
    if (this.light) {
      let replaceString2 = { search: /vPositionW/g, replace: worldPosVariableName + ".xyz" };
      if (isWGSL) {
        replaceString2 = { search: /fragmentInputs\.vPositionW/g, replace: worldPosVariableName + ".xyz" };
      }
      state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
        replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }, replaceString2]
      });
    } else {
      let substitutionVars = `vPositionW,${worldPosVariableName}.xyz`;
      if (isWGSL) {
        substitutionVars = `fragmentInputs.vPositionW,${worldPosVariableName}.xyz`;
      }
      state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars
      });
    }
    if (this._lightId === 0) {
      state.compilationString += `aggShadow = aggShadow / numLights;
`;
    }
    const diffuseOutput = this.diffuseOutput;
    const specularOutput = this.specularOutput;
    state.compilationString += state._declareOutput(diffuseOutput) + ` = diffuseBase${this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : ""};
`;
    if (specularOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(specularOutput) + ` = specularBase${this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : ""};
`;
    }
    if (this.shadow.hasEndpoints) {
      state.compilationString += state._declareOutput(this.shadow) + ` = aggShadow;
`;
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;
    if (this.light) {
      serializationObject.lightId = this.light.id;
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    if (serializationObject.lightId) {
      this.light = scene.getLightById(serializationObject.lightId);
    }
    this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;
    this._setTarget();
  }
}
__decorate([
  editableInPropertyPage("Generate only fragment code", 0, "ADVANCED", {
    notifiers: { rebuild: true, update: true, onValidation: LightBlock._OnGenerateOnlyFragmentCodeChanged }
  })
], LightBlock.prototype, "generateOnlyFragmentCode", undefined);
RegisterClass("BABYLON.LightBlock", LightBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/textureBlock.js
init_typeStore();
init_texture();
init_helperFunctions2();

// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/imageSourceBlock.js
init_typeStore();
init_texture();
init_engineStore();

class ImageSourceBlock extends NodeMaterialBlock {
  get texture() {
    return this._texture;
  }
  set texture(texture2) {
    if (this._texture === texture2) {
      return;
    }
    const scene = texture2?.getScene() ?? EngineStore.LastCreatedScene;
    if (!texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this._texture);
      });
    }
    this._texture = texture2;
    if (texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(texture2);
      });
    }
  }
  get samplerName() {
    return this._samplerName;
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment);
    this.registerOutput("source", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("dimensions", NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  bind(effect) {
    if (!this.texture) {
      return;
    }
    effect.setTexture(this._samplerName, this.texture);
  }
  isReady() {
    if (this.texture && !this.texture.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  getClassName() {
    return "ImageSourceBlock";
  }
  get source() {
    return this._outputs[0];
  }
  get dimensions() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      this._samplerName = state._getFreeVariableName(this.name + "Texture");
      state.sharedData.blockingBlocks.push(this);
      state.sharedData.textureBlocks.push(this);
      state.sharedData.bindableBlocks.push(this);
    }
    if (this.dimensions.isConnected) {
      let affect = "";
      if (state.shaderLanguage === 1) {
        affect = `vec2f(textureDimensions(${this._samplerName}, 0).xy)`;
      } else {
        affect = `vec2(textureSize(${this._samplerName}, 0).xy)`;
      }
      state.compilationString += `${state._declareOutput(this.dimensions)} = ${affect};
`;
    }
    state._emit2DSampler(this._samplerName);
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (!this.texture) {
      return codeString;
    }
    codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`;
    codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`;
    codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`;
    codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`;
    codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`;
    codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`;
    codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`;
    codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`;
    codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`;
    codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`;
    codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    if (this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") {
      serializationObject.texture = this.texture.serialize();
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl, urlRewriter) {
    super._deserialize(serializationObject, scene, rootUrl, urlRewriter);
    if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {
      if (serializationObject.texture.url.indexOf("data:") === 0) {
        rootUrl = "";
      } else if (urlRewriter) {
        serializationObject.texture.url = urlRewriter(serializationObject.texture.url);
        serializationObject.texture.name = serializationObject.texture.url;
      }
      this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
    }
  }
}
RegisterClass("BABYLON.ImageSourceBlock", ImageSourceBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/textureBlock.js
init_engineStore();

class TextureBlock extends NodeMaterialBlock {
  get texture() {
    if (this.source.isConnected) {
      return (this.source.connectedPoint?.ownerBlock).texture;
    }
    return this._texture;
  }
  set texture(texture2) {
    if (this._texture === texture2) {
      return;
    }
    const scene = texture2?.getScene() ?? EngineStore.LastCreatedScene;
    if (!texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this._texture);
      });
    }
    this._texture = texture2;
    if (texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(texture2);
      });
    }
  }
  static _IsPrePassTextureBlock(block) {
    return block?.getClassName() === "PrePassTextureBlock";
  }
  get _isSourcePrePass() {
    return TextureBlock._IsPrePassTextureBlock(this._imageSource);
  }
  get samplerName() {
    if (this._imageSource) {
      if (!TextureBlock._IsPrePassTextureBlock(this._imageSource)) {
        return this._imageSource.samplerName;
      }
      if (this.source.connectedPoint) {
        return this._imageSource.getSamplerName(this.source.connectedPoint);
      }
    }
    return this._samplerName;
  }
  get hasImageSource() {
    return this.source.isConnected;
  }
  set convertToGammaSpace(value) {
    if (value === this._convertToGammaSpace) {
      return;
    }
    this._convertToGammaSpace = value;
    if (this.texture) {
      const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene;
      scene?.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this.texture);
      });
    }
  }
  get convertToGammaSpace() {
    return this._convertToGammaSpace;
  }
  set convertToLinearSpace(value) {
    if (value === this._convertToLinearSpace) {
      return;
    }
    this._convertToLinearSpace = value;
    if (this.texture) {
      const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene;
      scene?.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this.texture);
      });
    }
  }
  get convertToLinearSpace() {
    return this._convertToLinearSpace;
  }
  constructor(name370, fragmentOnly = false) {
    super(name370, fragmentOnly ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);
    this._convertToGammaSpace = false;
    this._convertToLinearSpace = false;
    this.disableLevelMultiplication = false;
    this._fragmentOnly = fragmentOnly;
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);
    this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 0, ImageSourceBlock, "ImageSourceBlock"));
    this.registerInput("layer", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("lod", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this._inputs[0]._prioritizeVertex = !fragmentOnly;
  }
  getClassName() {
    return "TextureBlock";
  }
  get uv() {
    return this._inputs[0];
  }
  get source() {
    return this._inputs[1];
  }
  get layer() {
    return this._inputs[2];
  }
  get lod() {
    return this._inputs[3];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  get level() {
    return this._outputs[6];
  }
  _isTiedToFragment(input) {
    if (input.target === NodeMaterialBlockTargets.Fragment) {
      return true;
    }
    if (input.target === NodeMaterialBlockTargets.Vertex) {
      return false;
    }
    if (input.target === NodeMaterialBlockTargets.Neutral || input.target === NodeMaterialBlockTargets.VertexAndFragment) {
      const parentBlock = input.ownerBlock;
      if (parentBlock.target === NodeMaterialBlockTargets.Fragment) {
        return true;
      }
      for (const input2 of parentBlock.inputs) {
        if (!input2.isConnected) {
          continue;
        }
        if (this._isTiedToFragment(input2.connectedPoint)) {
          return true;
        }
      }
    }
    return false;
  }
  _getEffectiveTarget() {
    if (this._fragmentOnly) {
      return NodeMaterialBlockTargets.Fragment;
    }
    if (!this.uv.isConnected) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    if (this.uv.sourceBlock.isInput) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    if (this._isTiedToFragment(this.uv.connectedPoint)) {
      return NodeMaterialBlockTargets.Fragment;
    }
    return NodeMaterialBlockTargets.VertexAndFragment;
  }
  get target() {
    return this._getEffectiveTarget();
  }
  set target(value) {}
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.uv.isConnected) {
      if (material.mode === NodeMaterialModes.PostProcess) {
        const uvInput = material.getBlockByPredicate((b) => b.name === "uv" && additionalFilteringInfo(b));
        if (uvInput) {
          uvInput.connectTo(this);
        }
      } else if (material.mode !== NodeMaterialModes.ProceduralTexture) {
        const attributeName = material.mode === NodeMaterialModes.Particle ? "particle_uv" : "uv";
        let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === attributeName && additionalFilteringInfo(b));
        if (!uvInput) {
          uvInput = new InputBlock("uv");
          uvInput.setAsAttribute(attributeName);
        }
        uvInput.output.connectTo(this.uv);
      }
    }
  }
  initializeDefines(mesh, nodeMaterial, defines) {
    if (!defines._areTexturesDirty) {
      return;
    }
    if (this._mainUVDefineName !== undefined) {
      defines.setValue(this._mainUVDefineName, false, true);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areTexturesDirty) {
      return;
    }
    if (!this.texture || !this.texture.getTextureMatrix) {
      if (this._isMixed) {
        defines.setValue(this._defineName, false, true);
        defines.setValue(this._mainUVDefineName, true, true);
      }
      return;
    }
    const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;
    const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;
    defines.setValue(this._linearDefineName, toGamma, true);
    defines.setValue(this._gammaDefineName, toLinear, true);
    if (this._isMixed) {
      if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {
        defines.setValue(this._defineName, true);
        if (defines[this._mainUVDefineName] == undefined) {
          defines.setValue(this._mainUVDefineName, false, true);
        }
      } else {
        defines.setValue(this._defineName, false, true);
        defines.setValue(this._mainUVDefineName, true, true);
      }
    }
  }
  isReady() {
    if (this._isSourcePrePass) {
      return true;
    }
    if (this.texture && !this.texture.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  bind(effect) {
    if (this._isSourcePrePass) {
      effect.setFloat(this._textureInfoName, 1);
    }
    if (!this.texture) {
      return;
    }
    if (this._isMixed) {
      effect.setFloat(this._textureInfoName, this.texture.level);
      effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());
    }
    if (!this._imageSource) {
      effect.setTexture(this._samplerName, this.texture);
    }
  }
  get _isMixed() {
    return this.target !== NodeMaterialBlockTargets.Fragment;
  }
  _injectVertexCode(state) {
    const uvInput = this.uv;
    this._defineName = state._getFreeDefineName("UVTRANSFORM");
    this._mainUVDefineName = "VMAIN" + uvInput.declarationVariableName.toUpperCase();
    this._mainUVName = "vMain" + uvInput.declarationVariableName;
    this._transformedUVName = state._getFreeVariableName("transformedUV");
    this._textureTransformName = state._getFreeVariableName("textureTransform");
    this._textureInfoName = state._getFreeVariableName("textureInfoName");
    this.level.associatedVariableName = this._textureInfoName;
    state._emitVaryingFromString(this._transformedUVName, NodeMaterialBlockConnectionPointTypes.Vector2, this._defineName);
    state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2, this._mainUVDefineName);
    state._emitUniformFromString(this._textureTransformName, NodeMaterialBlockConnectionPointTypes.Matrix, this._defineName);
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    const vec2 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector2);
    state.compilationString += `#ifdef ${this._defineName}
`;
    state.compilationString += `${state._getVaryingName(this._transformedUVName)} = ${vec2}(${this._textureTransformName} * ${vec4}(${uvInput.associatedVariableName}.xy, 1.0, 0.0));
`;
    state.compilationString += `#elif defined(${this._mainUVDefineName})
`;
    let automaticPrefix = "";
    if (state.shaderLanguage === 1) {
      if (uvInput.isConnectedToInputBlock && uvInput.associatedVariableName.indexOf("vertexInputs.") === -1) {
        automaticPrefix = "vertexInputs.";
      }
    }
    state.compilationString += `${state._getVaryingName(this._mainUVName)} = ${automaticPrefix}${uvInput.associatedVariableName}.xy;
`;
    state.compilationString += `#endif
`;
    if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
      return;
    }
    this._writeTextureRead(state, true);
    for (const output of this._outputs) {
      if (output.hasEndpoints && output.name !== "level") {
        this._writeOutput(state, output, output.name, true);
      }
    }
  }
  _getUVW(uvName) {
    let coords = uvName;
    const is2DArrayTexture = this._texture?._texture?.is2DArray ?? false;
    const is3D = this._texture?._texture?.is3D ?? false;
    if (is2DArrayTexture) {
      const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : "0";
      coords = `vec3(${uvName}, ${layerValue})`;
    } else if (is3D) {
      const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : "0";
      coords = `vec3(${uvName}, ${layerValue})`;
    }
    return coords;
  }
  _samplerFunc(state) {
    if (state.shaderLanguage === 1) {
      return state.target === NodeMaterialBlockTargets.Vertex ? "textureSampleLevel" : "textureSample";
    }
    return this.lod.isConnected ? "texture2DLodEXT" : "texture2D";
  }
  get _samplerLodSuffix() {
    return this.lod.isConnected ? `, ${this.lod.associatedVariableName}` : "";
  }
  _generateTextureSample(uv, state) {
    if (state.shaderLanguage === 1) {
      const isVertex = state.target === NodeMaterialBlockTargets.Vertex;
      return `${this._samplerFunc(state)}(${this.samplerName},${this.samplerName + `Sampler`}, ${this._getUVW(uv)}${this._samplerLodSuffix}${isVertex ? ", 0" : ""})`;
    }
    return `${this._samplerFunc(state)}(${this.samplerName}, ${this._getUVW(uv)}${this._samplerLodSuffix})`;
  }
  _generateTextureLookup(state) {
    state.compilationString += `#ifdef ${this._defineName}
`;
    state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(state._getVaryingName(this._transformedUVName), state)};
`;
    state.compilationString += `#elif defined(${this._mainUVDefineName})
`;
    state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(this._mainUVName ? state._getVaryingName(this._mainUVName) : this.uv.associatedVariableName, state)}${this._samplerLodSuffix};
`;
    state.compilationString += `#endif
`;
  }
  _writeTextureRead(state, vertexMode = false) {
    const uvInput = this.uv;
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      this._generateTextureLookup(state);
      return;
    }
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(uvInput.associatedVariableName, state)}${this._samplerLodSuffix};
`;
      return;
    }
    this._generateTextureLookup(state);
  }
  _generateConversionCode(state, output, swizzle) {
    if (swizzle !== "a") {
      if (!this.texture || !this.texture.gammaSpace) {
        state.compilationString += `#ifdef ${this._linearDefineName}
                    ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});
                    #endif
                `;
      }
      state.compilationString += `#ifdef ${this._gammaDefineName}
                ${output.associatedVariableName} = ${state._toLinearSpace(output)};
                #endif
            `;
    }
  }
  _writeOutput(state, output, swizzle, vertexMode = false) {
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      this._generateConversionCode(state, output, swizzle);
      return;
    }
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      this._generateConversionCode(state, output, swizzle);
      return;
    }
    let complement = "";
    if (!this.disableLevelMultiplication) {
      complement = ` * ${(state.shaderLanguage === 1 ? "uniforms." : "") + this._textureInfoName}`;
    }
    state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle}${complement};
`;
    this._generateConversionCode(state, output, swizzle);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.source.isConnected) {
      this._imageSource = this.source.connectedPoint.ownerBlock;
    } else {
      this._imageSource = null;
    }
    if (state.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || state.target === NodeMaterialBlockTargets.Fragment) {
      this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
      this._linearDefineName = state._getFreeDefineName("ISLINEAR");
      this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
    }
    if (!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment || this._isMixed && state.target === NodeMaterialBlockTargets.Vertex) {
      if (!this._imageSource) {
        const varName = state._getFreeVariableName(this.name);
        this._samplerName = varName + "Texture";
        if (this._texture?._texture?.is2DArray) {
          state._emit2DArraySampler(this._samplerName);
        } else {
          state._emit2DSampler(this._samplerName);
        }
      }
      state.sharedData.blockingBlocks.push(this);
      state.sharedData.textureBlocks.push(this);
      state.sharedData.blocksWithDefines.push(this);
      state.sharedData.bindableBlocks.push(this);
    }
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      this._injectVertexCode(state);
      return;
    }
    if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {
      return;
    }
    if (this._isMixed && !this._imageSource) {
      if (this._texture?._texture?.is2DArray) {
        state._emit2DArraySampler(this._samplerName);
      } else {
        state._emit2DSampler(this._samplerName);
      }
    }
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    if (this._isMixed) {
      state._emitUniformFromString(this._textureInfoName, NodeMaterialBlockConnectionPointTypes.Float);
    }
    this._writeTextureRead(state);
    for (const output of this._outputs) {
      if (output.hasEndpoints && output.name !== "level") {
        this._writeOutput(state, output, output.name);
      }
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`;
    codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`;
    codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};
`;
    if (!this.texture) {
      return codeString;
    }
    codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`;
    codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`;
    codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`;
    codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`;
    codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`;
    codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`;
    codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`;
    codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`;
    codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`;
    codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`;
    codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    serializationObject.fragmentOnly = this._fragmentOnly;
    serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;
    if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") {
      serializationObject.texture = this.texture.serialize();
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl, urlRewriter) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertToGammaSpace = serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    this._fragmentOnly = !!serializationObject.fragmentOnly;
    this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;
    if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {
      if (serializationObject.texture.url.indexOf("data:") === 0) {
        rootUrl = "";
      } else if (urlRewriter) {
        serializationObject.texture.url = urlRewriter(serializationObject.texture.url);
        serializationObject.texture.name = serializationObject.texture.url;
      }
      this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
    }
  }
}
RegisterClass("BABYLON.TextureBlock", TextureBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.js
init_tslib_es6();
init_typeStore();
init_texture();
init_engineStore();
class ReflectionTextureBaseBlock extends NodeMaterialBlock {
  get texture() {
    return this._texture;
  }
  set texture(texture2) {
    if (this._texture === texture2) {
      return;
    }
    const scene = texture2?.getScene() ?? EngineStore.LastCreatedScene;
    if (!texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this._texture);
      });
    }
    this._texture = texture2;
    if (texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(texture2);
      });
    }
  }
  static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {
    const that = block;
    return that._onGenerateOnlyFragmentCodeChanged();
  }
  _onGenerateOnlyFragmentCodeChanged() {
    this._setTarget();
    return true;
  }
  _setTarget() {
    this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment);
    this.generateOnlyFragmentCode = false;
  }
  getClassName() {
    return "ReflectionTextureBaseBlock";
  }
  _getTexture() {
    return this.texture;
  }
  initialize(state) {
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.resolve().then(() => (init_reflectionFunction(), exports_reflectionFunction));
    } else {
      await Promise.resolve().then(() => (init_reflectionFunction2(), exports_reflectionFunction2));
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.position.isConnected) {
      let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position" && additionalFilteringInfo(b));
      if (!positionInput) {
        positionInput = new InputBlock("position");
        positionInput.setAsAttribute();
      }
      positionInput.output.connectTo(this.position);
    }
    if (!this.world.isConnected) {
      let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World && additionalFilteringInfo(b));
      if (!worldInput) {
        worldInput = new InputBlock("world");
        worldInput.setAsSystemValue(NodeMaterialSystemValues.World);
      }
      worldInput.output.connectTo(this.world);
    }
    if (this.view && !this.view.isConnected) {
      let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b));
      if (!viewInput) {
        viewInput = new InputBlock("view");
        viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
      }
      viewInput.output.connectTo(this.view);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areTexturesDirty) {
      return;
    }
    const texture2 = this._getTexture();
    if (!texture2 || !texture2.getTextureMatrix) {
      return;
    }
    defines.setValue(this._define3DName, texture2.isCube, true);
    defines.setValue(this._defineLocalCubicName, texture2.boundingBoxSize ? true : false, true);
    defines.setValue(this._defineExplicitName, texture2.coordinatesMode === 0, true);
    defines.setValue(this._defineSkyboxName, texture2.coordinatesMode === 5, true);
    defines.setValue(this._defineCubicName, texture2.coordinatesMode === 3 || texture2.coordinatesMode === 6, true);
    defines.setValue("INVERTCUBICMAP", texture2.coordinatesMode === 6, true);
    defines.setValue(this._defineSphericalName, texture2.coordinatesMode === 1, true);
    defines.setValue(this._definePlanarName, texture2.coordinatesMode === 2, true);
    defines.setValue(this._defineProjectionName, texture2.coordinatesMode === 4, true);
    defines.setValue(this._defineEquirectangularName, texture2.coordinatesMode === 7, true);
    defines.setValue(this._defineEquirectangularFixedName, texture2.coordinatesMode === 8, true);
    defines.setValue(this._defineMirroredEquirectangularFixedName, texture2.coordinatesMode === 9, true);
  }
  isReady() {
    const texture2 = this._getTexture();
    if (texture2 && !texture2.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  bind(effect, nodeMaterial, mesh, _subMesh) {
    const texture2 = this._getTexture();
    if (!mesh || !texture2) {
      return;
    }
    effect.setMatrix(this._reflectionMatrixName, texture2.getReflectionTextureMatrix());
    if (texture2.isCube) {
      effect.setTexture(this._cubeSamplerName, texture2);
    } else {
      effect.setTexture(this._2DSamplerName, texture2);
    }
    if (texture2.boundingBoxSize) {
      const cubeTexture2 = texture2;
      effect.setVector3(this._reflectionPositionName, cubeTexture2.boundingBoxPosition);
      effect.setVector3(this._reflectionSizeName, cubeTexture2.boundingBoxSize);
    }
  }
  handleVertexSide(state) {
    if (this.generateOnlyFragmentCode && state.target === NodeMaterialBlockTargets.Vertex) {
      return "";
    }
    const isWebGPU = state.shaderLanguage === 1;
    this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D");
    this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC");
    this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL");
    this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR");
    this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION");
    this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT");
    this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR");
    this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC");
    this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
    this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
    this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX");
    this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ");
    this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix");
    state._emitUniformFromString(this._reflectionMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix);
    let code = "";
    this._worldPositionNameInFragmentOnlyMode = state._getFreeVariableName("worldPosition");
    const worldPosVaryingName = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : "v_" + this.worldPosition.associatedVariableName;
    if (this.generateOnlyFragmentCode || state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) {
      if (this.generateOnlyFragmentCode) {
        code += `${state._declareLocalVar(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this.worldPosition.associatedVariableName};
`;
      } else {
        code += `${isWebGPU ? "vertexOutputs." : ""}${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};
`;
      }
    }
    this._positionUVWName = state._getFreeVariableName("positionUVW");
    this._directionWName = state._getFreeVariableName("directionW");
    if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._positionUVWName, NodeMaterialBlockConnectionPointTypes.Vector3, this._defineSkyboxName)) {
      code += `#ifdef ${this._defineSkyboxName}
`;
      if (this.generateOnlyFragmentCode) {
        code += `${state._declareLocalVar(this._positionUVWName, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.position.associatedVariableName}.xyz;
`;
      } else {
        code += `${isWebGPU ? "vertexOutputs." : ""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;
`;
      }
      code += `#endif
`;
    }
    if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._directionWName, NodeMaterialBlockConnectionPointTypes.Vector3, `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {
      code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})
`;
      if (this.generateOnlyFragmentCode) {
        code += `${state._declareLocalVar(this._directionWName, NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(vec3${state.fSuffix}(${this.world.associatedVariableName} * vec4${state.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));
`;
      } else {
        code += `${isWebGPU ? "vertexOutputs." : ""}${this._directionWName} = normalize(vec3${state.fSuffix}(${this.world.associatedVariableName} * vec4${state.fSuffix}(${this.position.associatedVariableName}.xyz, 0.0)));
`;
      }
      code += `#endif
`;
    }
    return code;
  }
  handleFragmentSideInits(state) {
    state.sharedData.blockingBlocks.push(this);
    state.sharedData.textureBlocks.push(this);
    this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
    state.samplers.push(this._cubeSamplerName);
    this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
    state.samplers.push(this._2DSamplerName);
    state._samplerDeclaration += `#ifdef ${this._define3DName}
`;
    state._emitCubeSampler(this._cubeSamplerName, "", true);
    state._samplerDeclaration += `#else
`;
    state._emit2DSampler(this._2DSamplerName, "", true);
    state._samplerDeclaration += `#endif
`;
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.bindableBlocks.push(this);
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    state._emitFunctionFromInclude("reflectionFunction", comments, {
      replaceStrings: [
        { search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" },
        { search: /fn computeReflectionCoords\(worldPos: vec4f,worldNormal: vec3f\)->vec3f/g, replace: "fn DUMMYFUNC()" }
      ]
    });
    this._reflectionColorName = state._getFreeVariableName("reflectionColor");
    this._reflectionVectorName = state._getFreeVariableName("reflectionUVW");
    this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords");
    this._reflectionPositionName = state._getFreeVariableName("vReflectionPosition");
    state._emitUniformFromString(this._reflectionPositionName, NodeMaterialBlockConnectionPointTypes.Vector3);
    this._reflectionSizeName = state._getFreeVariableName("vReflectionPosition");
    state._emitUniformFromString(this._reflectionSizeName, NodeMaterialBlockConnectionPointTypes.Vector3);
  }
  handleFragmentSideCodeReflectionCoords(state, worldNormalVarName, worldPos, onlyReflectionVector = false, doNotEmitInvertZ = false) {
    const isWebGPU = state.shaderLanguage === 1;
    const reflectionMatrix = (isWebGPU ? "uniforms." : "") + this._reflectionMatrixName;
    const direction = `normalize(${this._directionWName})`;
    const positionUVW = `${this._positionUVWName}`;
    const vEyePosition = `${this.cameraPosition.associatedVariableName}`;
    const view = `${this.view.associatedVariableName}`;
    const fragmentInputsPrefix = isWebGPU ? "fragmentInputs." : "";
    if (!worldPos) {
      worldPos = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : `${fragmentInputsPrefix}v_${this.worldPosition.associatedVariableName}`;
    }
    worldNormalVarName += ".xyz";
    let code = `
            #ifdef ${this._defineMirroredEquirectangularFixedName}
               ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
            #endif

            #ifdef ${this._defineEquirectangularFixedName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});
            #endif

            #ifdef ${this._defineEquirectangularName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
            #endif

            #ifdef ${this._defineSphericalName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix});
            #endif

            #ifdef ${this._definePlanarName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
            #endif

            #ifdef ${this._defineCubicName}
                #ifdef ${this._defineLocalCubicName}
                    ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, ${this._reflectionSizeName}, ${this._reflectionPositionName});
                #else
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});
                #endif
            #endif

            #ifdef ${this._defineProjectionName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});
            #endif

            #ifdef ${this._defineSkyboxName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});
            #endif

            #ifdef ${this._defineExplicitName}
                ${state._declareLocalVar(this._reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3(0, 0, 0);
            #endif
`;
    if (!doNotEmitInvertZ) {
      code += `#ifdef ${this._defineOppositeZ}
                ${this._reflectionVectorName}.z *= -1.0;
            #endif
`;
    }
    if (!onlyReflectionVector) {
      code += `
                #ifdef ${this._define3DName}
                    ${state._declareLocalVar(this._reflectionCoordsName, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._reflectionVectorName};
                #else
                    ${state._declareLocalVar(this._reflectionCoordsName, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this._reflectionVectorName}.xy;
                    #ifdef ${this._defineProjectionName}
                        ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;
                    #endif
                    ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;
                #endif
`;
    }
    return code;
  }
  handleFragmentSideCodeReflectionColor(state, lodVarName, swizzleLookupTexture = ".rgb") {
    let colorType = NodeMaterialBlockConnectionPointTypes.Vector4;
    if (swizzleLookupTexture.length === 3) {
      colorType = NodeMaterialBlockConnectionPointTypes.Vector3;
    }
    let code = `${state._declareLocalVar(this._reflectionColorName, colorType)};
            #ifdef ${this._define3DName}
`;
    if (lodVarName) {
      code += `${this._reflectionColorName} = ${state._generateTextureSampleCubeLOD(this._reflectionVectorName, this._cubeSamplerName, lodVarName)}${swizzleLookupTexture};
`;
    } else {
      code += `${this._reflectionColorName} = ${state._generateTextureSampleCube(this._reflectionVectorName, this._cubeSamplerName)}${swizzleLookupTexture};
`;
    }
    code += `
            #else
`;
    if (lodVarName) {
      code += `${this._reflectionColorName} =${state._generateTextureSampleLOD(this._reflectionCoordsName, this._2DSamplerName, lodVarName)}${swizzleLookupTexture};
`;
    } else {
      code += `${this._reflectionColorName} = ${state._generateTextureSample(this._reflectionCoordsName, this._2DSamplerName)}${swizzleLookupTexture};
`;
    }
    code += `#endif
`;
    return code;
  }
  writeOutputs(state, varName) {
    let code = "";
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      for (const output of this._outputs) {
        if (output.hasEndpoints) {
          code += `${state._declareOutput(output)} = ${varName}.${output.name};
`;
        }
      }
    }
    return code;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (!this.texture) {
      return codeString;
    }
    if (this.texture.isCube) {
      const forcedExtension = this.texture.forcedExtension;
      codeString += `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${forcedExtension ? '"' + forcedExtension + '"' : "null"});
`;
    } else {
      codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);
`;
    }
    codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    if (this.texture && !this.texture.isRenderTarget) {
      serializationObject.texture = this.texture.serialize();
    }
    serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) {
      rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
      if (serializationObject.texture.isCube) {
        this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);
      } else {
        this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
      }
    }
    this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;
    this._setTarget();
  }
}
__decorate([
  editableInPropertyPage("Generate only fragment code", 0, "ADVANCED", {
    notifiers: { rebuild: true, update: true, onValidation: ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged }
  })
], ReflectionTextureBaseBlock.prototype, "generateOnlyFragmentCode", undefined);
RegisterClass("BABYLON.ReflectionTextureBaseBlock", ReflectionTextureBaseBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBlock.js
init_typeStore();
init_logger();

class ReflectionTextureBlock extends ReflectionTextureBaseBlock {
  _onGenerateOnlyFragmentCodeChanged() {
    if (this.position.isConnected) {
      this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;
      Logger.Error("The position input must not be connected to be able to switch!");
      return false;
    }
    if (this.worldPosition.isConnected) {
      this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;
      Logger.Error("The worldPosition input must not be connected to be able to switch!");
      return false;
    }
    this._setTarget();
    return true;
  }
  _setTarget() {
    super._setTarget();
    this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
    this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
  }
  constructor(name370) {
    super(name370);
    this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ReflectionTextureBlock";
  }
  get position() {
    return this._inputs[0];
  }
  get worldPosition() {
    return this._inputs[1];
  }
  get worldNormal() {
    return this._inputs[2];
  }
  get world() {
    return this._inputs[3];
  }
  get cameraPosition() {
    return this._inputs[4];
  }
  get view() {
    return this._inputs[5];
  }
  get rgb() {
    return this._outputs[0];
  }
  get rgba() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    super.autoConfigure(material);
    if (!this.cameraPosition.isConnected) {
      let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b));
      if (!cameraPositionInput) {
        cameraPositionInput = new InputBlock("cameraPosition");
        cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);
      }
      cameraPositionInput.output.connectTo(this.cameraPosition);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this.texture) {
      state.compilationString += this.writeOutputs(state, `vec4${state.fSuffix}(0.)`);
      return this;
    }
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      state.compilationString += this.handleVertexSide(state);
      return this;
    }
    if (this.generateOnlyFragmentCode) {
      state.compilationString += this.handleVertexSide(state);
    }
    this.handleFragmentSideInits(state);
    const normalWUnit = state._getFreeVariableName("normalWUnit");
    state.compilationString += `${state._declareLocalVar(normalWUnit, NodeMaterialBlockConnectionPointTypes.Vector4)} = normalize(${this.worldNormal.associatedVariableName});
`;
    state.compilationString += this.handleFragmentSideCodeReflectionCoords(state, normalWUnit);
    state.compilationString += this.handleFragmentSideCodeReflectionColor(state, undefined, "");
    state.compilationString += this.writeOutputs(state, this._reflectionColorName);
    return this;
  }
}
RegisterClass("BABYLON.ReflectionTextureBlock", ReflectionTextureBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/sceneDepthBlock.js
init_tslib_es6();
init_typeStore();
class SceneDepthBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment);
    this.useNonLinearDepth = false;
    this.storeCameraSpaceZ = false;
    this.force32itsFloat = false;
    this._isUnique = true;
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);
    this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this._inputs[0]._prioritizeVertex = false;
  }
  getClassName() {
    return "SceneDepthBlock";
  }
  get uv() {
    return this._inputs[0];
  }
  get depth() {
    return this._outputs[0];
  }
  initialize(state) {
    state._excludeVariableName("textureSampler");
  }
  get target() {
    if (!this.uv.isConnected) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    if (this.uv.sourceBlock.isInput) {
      return NodeMaterialBlockTargets.VertexAndFragment;
    }
    return NodeMaterialBlockTargets.Fragment;
  }
  _getTexture(scene) {
    const depthRenderer = scene.enableDepthRenderer(undefined, this.useNonLinearDepth, this.force32itsFloat, undefined, this.storeCameraSpaceZ);
    return depthRenderer.getDepthMap();
  }
  bind(effect, nodeMaterial) {
    const texture2 = this._getTexture(nodeMaterial.getScene());
    effect.setTexture(this._samplerName, texture2);
  }
  _injectVertexCode(state) {
    const uvInput = this.uv;
    if (uvInput.connectedPoint.ownerBlock.isInput) {
      const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;
      if (!uvInputOwnerBlock.isAttribute) {
        state._emitUniformFromString(uvInput.associatedVariableName, uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? NodeMaterialBlockConnectionPointTypes.Vector3 : uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? NodeMaterialBlockConnectionPointTypes.Vector4 : NodeMaterialBlockConnectionPointTypes.Vector2);
      }
    }
    this._mainUVName = "vMain" + uvInput.associatedVariableName;
    state._emitVaryingFromString(this._mainUVName, NodeMaterialBlockConnectionPointTypes.Vector2);
    state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;
`;
    if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {
      return;
    }
    this._writeTextureRead(state, true);
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        this._writeOutput(state, output, "r", true);
      }
    }
  }
  _writeTextureRead(state, vertexMode = false) {
    const uvInput = this.uv;
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      const textureReadFunc2 = state.shaderLanguage === 0 ? `texture2D(${this._samplerName},` : `textureSampleLevel(${this._samplerName}, ${this._samplerName + `Sampler`},`;
      const complement = state.shaderLanguage === 0 ? "" : ", 0";
      state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)}=  ${textureReadFunc2} ${uvInput.associatedVariableName}.xy${complement});
`;
      return;
    }
    const textureReadFunc = state.shaderLanguage === 0 ? `texture2D(${this._samplerName},` : `textureSample(${this._samplerName}, ${this._samplerName + `Sampler`},`;
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${uvInput.associatedVariableName}.xy);
`;
      return;
    }
    state.compilationString += `${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${textureReadFunc} ${this._mainUVName});
`;
  }
  _writeOutput(state, output, swizzle, vertexMode = false) {
    if (vertexMode) {
      if (state.target === NodeMaterialBlockTargets.Fragment) {
        return;
      }
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      return;
    }
    if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {
      state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
      return;
    }
    state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle};
`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._samplerName = state._getFreeVariableName(this.name + "Sampler");
    this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
    if (state.sharedData.bindableBlocks.indexOf(this) < 0) {
      state.sharedData.bindableBlocks.push(this);
    }
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      state._emit2DSampler(this._samplerName);
      this._injectVertexCode(state);
      return;
    }
    if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {
      return;
    }
    state._emit2DSampler(this._samplerName);
    this._writeTextureRead(state);
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        this._writeOutput(state, output, "r");
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.useNonLinearDepth = this.useNonLinearDepth;
    serializationObject.storeCameraSpaceZ = this.storeCameraSpaceZ;
    serializationObject.force32itsFloat = this.force32itsFloat;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.useNonLinearDepth = serializationObject.useNonLinearDepth;
    this.storeCameraSpaceZ = !!serializationObject.storeCameraSpaceZ;
    this.force32itsFloat = serializationObject.force32itsFloat;
  }
}
__decorate([
  editableInPropertyPage("Use non linear depth", 0, "ADVANCED", {
    embedded: true,
    notifiers: {
      activatePreviewCommand: true,
      callback: (scene, block) => {
        const sceneDepthBlock = block;
        let retVal = false;
        if (sceneDepthBlock.useNonLinearDepth) {
          sceneDepthBlock.storeCameraSpaceZ = false;
          retVal = true;
        }
        if (scene) {
          scene.disableDepthRenderer();
        }
        return retVal;
      }
    }
  })
], SceneDepthBlock.prototype, "useNonLinearDepth", undefined);
__decorate([
  editableInPropertyPage("Store Camera space Z", 0, "ADVANCED", {
    notifiers: {
      activatePreviewCommand: true,
      callback: (scene, block) => {
        const sceneDepthBlock = block;
        let retVal = false;
        if (sceneDepthBlock.storeCameraSpaceZ) {
          sceneDepthBlock.useNonLinearDepth = false;
          retVal = true;
        }
        if (scene) {
          scene.disableDepthRenderer();
        }
        return retVal;
      }
    }
  })
], SceneDepthBlock.prototype, "storeCameraSpaceZ", undefined);
__decorate([
  editableInPropertyPage("Force 32 bits float", 0, "ADVANCED", {
    notifiers: { activatePreviewCommand: true, callback: (scene) => scene?.disableDepthRenderer() }
  })
], SceneDepthBlock.prototype, "force32itsFloat", undefined);
RegisterClass("BABYLON.SceneDepthBlock", SceneDepthBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/clipPlanesBlock.js
init_typeStore();

class ClipPlanesBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment, true);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false);
  }
  getClassName() {
    return "ClipPlanesBlock";
  }
  initialize(state) {
    state._excludeVariableName("vClipPlane");
    state._excludeVariableName("fClipDistance");
    state._excludeVariableName("vClipPlane2");
    state._excludeVariableName("fClipDistance2");
    state._excludeVariableName("vClipPlane3");
    state._excludeVariableName("fClipDistance3");
    state._excludeVariableName("vClipPlane4");
    state._excludeVariableName("fClipDistance4");
    state._excludeVariableName("vClipPlane5");
    state._excludeVariableName("fClipDistance5");
    state._excludeVariableName("vClipPlane6");
    state._excludeVariableName("fClipDistance6");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([
        Promise.resolve().then(() => (init_clipPlaneFragment(), exports_clipPlaneFragment)),
        Promise.resolve().then(() => (init_clipPlaneFragmentDeclaration(), exports_clipPlaneFragmentDeclaration)),
        Promise.resolve().then(() => (init_clipPlaneVertex(), exports_clipPlaneVertex)),
        Promise.resolve().then(() => (init_clipPlaneVertexDeclaration(), exports_clipPlaneVertexDeclaration))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_clipPlaneFragment2(), exports_clipPlaneFragment2)),
        Promise.resolve().then(() => (init_clipPlaneFragmentDeclaration2(), exports_clipPlaneFragmentDeclaration2)),
        Promise.resolve().then(() => (init_clipPlaneVertex2(), exports_clipPlaneVertex2)),
        Promise.resolve().then(() => (init_clipPlaneVertexDeclaration2(), exports_clipPlaneVertexDeclaration2))
      ]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get target() {
    return NodeMaterialBlockTargets.VertexAndFragment;
  }
  set target(value) {}
  prepareDefines(mesh, nodeMaterial, defines) {
    const scene = mesh.getScene();
    const useClipPlane1 = nodeMaterial.clipPlane ?? scene.clipPlane ? true : false;
    const useClipPlane2 = nodeMaterial.clipPlane2 ?? scene.clipPlane2 ? true : false;
    const useClipPlane3 = nodeMaterial.clipPlane3 ?? scene.clipPlane3 ? true : false;
    const useClipPlane4 = nodeMaterial.clipPlane4 ?? scene.clipPlane4 ? true : false;
    const useClipPlane5 = nodeMaterial.clipPlane5 ?? scene.clipPlane5 ? true : false;
    const useClipPlane6 = nodeMaterial.clipPlane6 ?? scene.clipPlane6 ? true : false;
    defines.setValue("CLIPPLANE", useClipPlane1, true);
    defines.setValue("CLIPPLANE2", useClipPlane2, true);
    defines.setValue("CLIPPLANE3", useClipPlane3, true);
    defines.setValue("CLIPPLANE4", useClipPlane4, true);
    defines.setValue("CLIPPLANE5", useClipPlane5, true);
    defines.setValue("CLIPPLANE6", useClipPlane6, true);
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    const scene = mesh.getScene();
    bindClipPlane(effect, nodeMaterial, scene);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const comments = `//${this.name}`;
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      const worldPos = this.worldPosition;
      state._emitFunctionFromInclude("clipPlaneVertexDeclaration", comments, {
        replaceStrings: [{ search: /uniform vec4 vClipPlane\d*;/g, replace: "" }]
      });
      state.compilationString += state._emitCodeFromInclude("clipPlaneVertex", comments, {
        replaceStrings: [{ search: /worldPos/g, replace: worldPos.associatedVariableName }]
      });
      state._emitUniformFromString("vClipPlane", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClipPlane2", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClipPlane3", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClipPlane4", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClipPlane5", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClipPlane6", NodeMaterialBlockConnectionPointTypes.Vector4);
      return;
    }
    state.sharedData.bindableBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    state._emitFunctionFromInclude("clipPlaneFragmentDeclaration", comments);
    state.compilationString += state._emitCodeFromInclude("clipPlaneFragment", comments);
    return this;
  }
}
RegisterClass("BABYLON.ClipPlanesBlock", ClipPlanesBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/index.js
init_clipPlaneFragment();
init_clipPlaneFragmentDeclaration();
init_clipPlaneVertex();
init_clipPlaneVertexDeclaration();
init_clipPlaneFragment2();
init_clipPlaneFragmentDeclaration2();
init_clipPlaneVertex2();
init_clipPlaneVertexDeclaration2();
init_fogFragmentDeclaration();
init_fogFragmentDeclaration2();
init_lightFragment();
init_lightUboDeclaration();
init_lightVxUboDeclaration();
init_helperFunctions();
init_lightsFragmentFunctions();
init_shadowsFragmentFunctions();
init_shadowsVertex();
init_lightFragmentDeclaration();
init_lightFragment2();
init_lightUboDeclaration2();
init_lightVxUboDeclaration2();
init_lightVxFragmentDeclaration2();
init_helperFunctions2();
init_lightsFragmentFunctions2();
init_shadowsFragmentFunctions2();
init_shadowsVertex2();
init_reflectionFunction();
init_reflectionFunction2();
// node_modules/@babylonjs/core/Materials/Node/Blocks/Input/prePassTextureBlock.js
init_typeStore();
class PrePassTextureBlock extends NodeMaterialBlock {
  get texture() {
    return null;
  }
  set texture(value) {
    return;
  }
  constructor(name370, target = NodeMaterialBlockTargets.VertexAndFragment) {
    super(name370, target, false);
    this.registerOutput("position", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("position", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("localPosition", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("localPosition", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("depth", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("screenDepth", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("screenDepth", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("normal", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("normal", this, 1, ImageSourceBlock, "ImageSourceBlock"));
    this.registerOutput("worldNormal", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("worldNormal", this, 1, ImageSourceBlock, "ImageSourceBlock"));
  }
  getSamplerName(output) {
    if (output === this._outputs[0]) {
      return this._positionSamplerName;
    }
    if (output === this._outputs[1]) {
      return this._localPositionSamplerName;
    }
    if (output === this._outputs[2]) {
      return this._depthSamplerName;
    }
    if (output === this._outputs[3]) {
      return this._screenSpaceDepthSamplerName;
    }
    if (output === this._outputs[4]) {
      return this._normalSamplerName;
    }
    if (output === this._outputs[5]) {
      return this._worldNormalSamplerName;
    }
    return "";
  }
  get position() {
    return this._outputs[0];
  }
  get localPosition() {
    return this._outputs[1];
  }
  get depth() {
    return this._outputs[2];
  }
  get screenDepth() {
    return this._outputs[3];
  }
  get normal() {
    return this._outputs[4];
  }
  get worldNormal() {
    return this._outputs[5];
  }
  get positionSamplerName() {
    return this._positionSamplerName;
  }
  get localPositionSamplerName() {
    return this._localPositionSamplerName;
  }
  get normalSamplerName() {
    return this._normalSamplerName;
  }
  get worldNormalSamplerName() {
    return this._worldNormalSamplerName;
  }
  get depthSamplerName() {
    return this._depthSamplerName;
  }
  get linearDepthSamplerName() {
    return this._screenSpaceDepthSamplerName;
  }
  getClassName() {
    return "PrePassTextureBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (state.target === NodeMaterialBlockTargets.Vertex) {
      return;
    }
    this._positionSamplerName = "prepassPositionSampler";
    this._depthSamplerName = "prepassDepthSampler";
    this._normalSamplerName = "prepassNormalSampler";
    this._worldNormalSamplerName = "prepassWorldNormalSampler";
    this._localPositionSamplerName = "prepassLocalPositionSampler";
    this._screenSpaceDepthSamplerName = "prepassScreenSpaceDepthSampler";
    state.sharedData.variableNames.prepassPositionSampler = 0;
    state.sharedData.variableNames.prepassDepthSampler = 0;
    state.sharedData.variableNames.prepassNormalSampler = 0;
    state.sharedData.variableNames.prepassWorldNormalSampler = 0;
    state.sharedData.variableNames.prepassLocalPositionSampler = 0;
    state.sharedData.variableNames.prepassScreenSpaceDepthSampler = 0;
    state.sharedData.textureBlocks.push(this);
    state.sharedData.bindableBlocks.push(this);
    if (this.position.isConnected) {
      state._emit2DSampler(this._positionSamplerName);
    }
    if (this.depth.isConnected) {
      state._emit2DSampler(this._depthSamplerName);
    }
    if (this.normal.isConnected) {
      state._emit2DSampler(this._normalSamplerName);
    }
    if (this.worldNormal.isConnected) {
      state._emit2DSampler(this._worldNormalSamplerName);
    }
    if (this.localPosition.isConnected) {
      state._emit2DSampler(this._localPositionSamplerName);
    }
    if (this.screenDepth.isConnected) {
      state._emit2DSampler(this._screenSpaceDepthSamplerName);
    }
    return this;
  }
  bind(effect, nodeMaterial) {
    const scene = nodeMaterial.getScene();
    const prePassRenderer = scene.enablePrePassRenderer();
    if (!prePassRenderer) {
      return;
    }
    const sceneRT = prePassRenderer.defaultRT;
    if (!sceneRT.textures) {
      return;
    }
    if (this.position.isConnected) {
      effect.setTexture(this._positionSamplerName, sceneRT.textures[prePassRenderer.getIndex(1)]);
    }
    if (this.localPosition.isConnected) {
      effect.setTexture(this._localPositionSamplerName, sceneRT.textures[prePassRenderer.getIndex(9)]);
    }
    if (this.depth.isConnected) {
      effect.setTexture(this._depthSamplerName, sceneRT.textures[prePassRenderer.getIndex(5)]);
    }
    if (this.screenDepth.isConnected) {
      effect.setTexture(this._screenSpaceDepthSamplerName, sceneRT.textures[prePassRenderer.getIndex(10)]);
    }
    if (this.normal.isConnected) {
      effect.setTexture(this._normalSamplerName, sceneRT.textures[prePassRenderer.getIndex(6)]);
    }
    if (this.worldNormal.isConnected) {
      effect.setTexture(this._worldNormalSamplerName, sceneRT.textures[prePassRenderer.getIndex(8)]);
    }
  }
}
RegisterClass("BABYLON.PrePassTextureBlock", PrePassTextureBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Teleport/teleportInBlock.js
init_typeStore();
class NodeMaterialTeleportInBlock extends NodeMaterialBlock {
  get endpoints() {
    return this._endpoints;
  }
  get target() {
    const input = this._inputs[0];
    if (input.isConnected) {
      const block = input.connectedPoint.ownerBlock;
      if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) {
        return block.target;
      }
      if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) {
        return input.connectedPoint.target;
      }
    }
    return this._target;
  }
  set target(value) {
    if ((this._target & value) !== 0) {
      return;
    }
    this._target = value;
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this._endpoints = [];
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
  }
  getClassName() {
    return "NodeMaterialTeleportInBlock";
  }
  get input() {
    return this._inputs[0];
  }
  isConnectedInFragmentShader() {
    return this.endpoints.some((e) => e.output.isConnectedInFragmentShader);
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = super._dumpCode(uniqueNames, alreadyDumped);
    for (const endpoint of this.endpoints) {
      if (alreadyDumped.indexOf(endpoint) === -1) {
        codeString += endpoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString;
  }
  isAnAncestorOf(block) {
    for (const endpoint of this.endpoints) {
      if (endpoint === block) {
        return true;
      }
      if (endpoint.isAnAncestorOf(block)) {
        return true;
      }
    }
    return false;
  }
  attachToEndpoint(endpoint) {
    endpoint.detach();
    this._endpoints.push(endpoint);
    endpoint._entryPoint = this;
    endpoint._outputs[0]._typeConnectionSource = this._inputs[0];
    endpoint._tempEntryPointUniqueId = null;
    endpoint.name = "> " + this.name;
    this._outputs = this._endpoints.map((e) => e.output);
  }
  detachFromEndpoint(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index !== -1) {
      this._endpoints.splice(index, 1);
      endpoint._outputs[0]._typeConnectionSource = null;
      endpoint._entryPoint = null;
      this._outputs = this._endpoints.map((e) => e.output);
    }
  }
  dispose() {
    super.dispose();
    for (const endpoint of this._endpoints) {
      this.detachFromEndpoint(endpoint);
    }
    this._endpoints = [];
  }
}
RegisterClass("BABYLON.NodeMaterialTeleportInBlock", NodeMaterialTeleportInBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/Teleport/teleportOutBlock.js
init_typeStore();
class NodeMaterialTeleportOutBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this._entryPoint = null;
    this._tempEntryPointUniqueId = null;
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
  }
  get entryPoint() {
    return this._entryPoint;
  }
  getClassName() {
    return "NodeMaterialTeleportOutBlock";
  }
  get output() {
    return this._outputs[0];
  }
  get target() {
    return this._entryPoint ? this._entryPoint.target : this._target;
  }
  set target(value) {
    if ((this._target & value) !== 0) {
      return;
    }
    this._target = value;
  }
  detach() {
    if (!this._entryPoint) {
      return;
    }
    this._entryPoint.detachFromEndpoint(this);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.entryPoint) {
      state.compilationString += state._declareOutput(this.output) + ` = ${this.entryPoint.input.associatedVariableName};
`;
    }
  }
  clone(scene, rootUrl = "") {
    const clone = super.clone(scene, rootUrl);
    if (this.entryPoint) {
      this.entryPoint.attachToEndpoint(clone);
    }
    return clone;
  }
  _customBuildStep(state, activeBlocks) {
    if (this.entryPoint) {
      this.entryPoint.build(state, activeBlocks);
    }
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = "";
    if (this.entryPoint) {
      if (alreadyDumped.indexOf(this.entryPoint) === -1) {
        codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString + super._dumpCode(uniqueNames, alreadyDumped);
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = super._dumpCodeForOutputConnections(alreadyDumped);
    if (this.entryPoint) {
      codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped);
    }
    return codeString;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (this.entryPoint) {
      codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});
`;
    }
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.entryPoint = this.entryPoint?.uniqueId ?? "";
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this._tempEntryPointUniqueId = serializationObject.entryPoint;
  }
}
RegisterClass("BABYLON.NodeMaterialTeleportOutBlock", NodeMaterialTeleportOutBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/addBlock.js
init_typeStore();
class AddBlock extends BaseMathBlock {
  constructor(name370) {
    super(name370);
  }
  getClassName() {
    return "AddBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.AddBlock", AddBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/scaleBlock.js
init_typeStore();

class ScaleBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("factor", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "ScaleBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get factor() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.ScaleBlock", ScaleBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/clampBlock.js
init_tslib_es6();
init_typeStore();
class ClampBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.minimum = 0;
    this.maximum = 1;
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "ClampBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const cast = state.shaderLanguage === 1 ? state._getShaderType(this.value.type) : "";
    state.compilationString += state._declareOutput(output) + ` = clamp(${this.value.associatedVariableName}, ${cast}(${this._writeFloat(this.minimum)}), ${cast}(${this._writeFloat(this.maximum)}));
`;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.minimum = ${this.minimum};
`;
    codeString += `${this._codeVariableName}.maximum = ${this.maximum};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.minimum = this.minimum;
    serializationObject.maximum = this.maximum;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.minimum = serializationObject.minimum;
    this.maximum = serializationObject.maximum;
  }
}
__decorate([
  editableInPropertyPage("Minimum", 1, undefined, { embedded: true })
], ClampBlock.prototype, "minimum", undefined);
__decorate([
  editableInPropertyPage("Maximum", 1, undefined, { embedded: true })
], ClampBlock.prototype, "maximum", undefined);
RegisterClass("BABYLON.ClampBlock", ClampBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/crossBlock.js
init_typeStore();

class CrossBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "CrossBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);
`;
    return this;
  }
}
RegisterClass("BABYLON.CrossBlock", CrossBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/customBlock.js
init_typeStore();
class CustomBlock extends NodeMaterialBlock {
  get options() {
    return this._options;
  }
  set options(options) {
    this._deserializeOptions(options);
  }
  constructor(name370) {
    super(name370);
  }
  getClassName() {
    return "CustomBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    let code = this._code;
    let functionName = this._options.functionName;
    this._inputs.forEach((input) => {
      const rexp = new RegExp("\\{TYPE_" + input.name + "\\}", "gm");
      const type = state._getGLType(input.type);
      code = code.replace(rexp, type);
      functionName = functionName.replace(rexp, type);
    });
    this._outputs.forEach((output) => {
      const rexp = new RegExp("\\{TYPE_" + output.name + "\\}", "gm");
      const type = state._getGLType(output.type);
      code = code.replace(rexp, type);
      functionName = functionName.replace(rexp, type);
    });
    state._emitFunction(functionName, code, "");
    this._outputs.forEach((output) => {
      state.compilationString += state._declareOutput(output) + `;
`;
    });
    state.compilationString += functionName + "(";
    let hasInput = false;
    this._inputs.forEach((input, index) => {
      if (index > 0) {
        state.compilationString += ", ";
      }
      if (this._inputSamplers && this._inputSamplers.indexOf(input.name) !== -1) {
        state.compilationString += input.connectedPoint?.ownerBlock?.samplerName ?? input.associatedVariableName;
      } else {
        state.compilationString += input.associatedVariableName;
      }
      hasInput = true;
    });
    this._outputs.forEach((output, index) => {
      if (index > 0 || hasInput) {
        state.compilationString += ", ";
      }
      state.compilationString += output.associatedVariableName;
    });
    state.compilationString += `);
`;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.options = ${JSON.stringify(this._options)};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.options = this._options;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    this._deserializeOptions(serializationObject.options);
    super._deserialize(serializationObject, scene, rootUrl);
  }
  _deserializeOptions(options) {
    this._options = options;
    this._code = options.code.join(`
`) + `
`;
    this.name = this.name || options.name;
    this.target = NodeMaterialBlockTargets[options.target];
    options.inParameters?.forEach((input, index) => {
      const type = NodeMaterialBlockConnectionPointTypes[input.type];
      if (input.type === "sampler2D" || input.type === "samplerCube") {
        this._inputSamplers = this._inputSamplers || [];
        this._inputSamplers.push(input.name);
        this.registerInput(input.name, NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(input.name, this, 0, ImageSourceBlock, "ImageSourceBlock"));
      } else {
        this.registerInput(input.name, type);
      }
      Object.defineProperty(this, input.name, {
        get: function() {
          return this._inputs[index];
        },
        enumerable: true,
        configurable: true
      });
    });
    options.outParameters?.forEach((output, index) => {
      this.registerOutput(output.name, NodeMaterialBlockConnectionPointTypes[output.type]);
      Object.defineProperty(this, output.name, {
        get: function() {
          return this._outputs[index];
        },
        enumerable: true,
        configurable: true
      });
      if (output.type === "BasedOnInput") {
        this._outputs[index]._typeConnectionSource = this._findInputByName(output.typeFromInput)[0];
      }
    });
    options.inLinkedConnectionTypes?.forEach((connection) => {
      this._linkConnectionTypes(this._findInputByName(connection.input1)[1], this._findInputByName(connection.input2)[1]);
    });
  }
  _findInputByName(name370) {
    if (!name370) {
      return null;
    }
    for (let i = 0;i < this._inputs.length; i++) {
      if (this._inputs[i].name === name370) {
        return [this._inputs[i], i];
      }
    }
    return null;
  }
}
RegisterClass("BABYLON.CustomBlock", CustomBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/dotBlock.js
init_typeStore();

class DotBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "DotBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.DotBlock", DotBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/normalizeBlock.js
init_typeStore();

class NormalizeBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "NormalizeBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input = this._inputs[0];
    state.compilationString += state._declareOutput(output) + ` = normalize(${input.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.NormalizeBlock", NormalizeBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/colorMergerBlock.js
init_typeStore();

class ColorMergerBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.rSwizzle = "r";
    this.gSwizzle = "g";
    this.bSwizzle = "b";
    this.aSwizzle = "a";
    this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.registerInput("r", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("g", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3);
  }
  getClassName() {
    return "ColorMergerBlock";
  }
  get rgbIn() {
    return this._inputs[0];
  }
  get r() {
    return this._inputs[1];
  }
  get g() {
    return this._inputs[2];
  }
  get b() {
    return this._inputs[3];
  }
  get a() {
    return this._inputs[4];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgbOut() {
    return this._outputs[1];
  }
  get rgb() {
    return this.rgbOut;
  }
  _inputRename(name370) {
    if (name370 === "rgb ") {
      return "rgbIn";
    }
    return name370;
  }
  _buildSwizzle(len) {
    const swizzle = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle;
    return "." + swizzle.substring(0, len);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const rInput = this.r;
    const gInput = this.g;
    const bInput = this.b;
    const aInput = this.a;
    const rgbInput = this.rgbIn;
    const color4Output = this._outputs[0];
    const color3Output = this._outputs[1];
    const vec4 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector4);
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    if (rgbInput.isConnected) {
      if (color4Output.hasEndpoints) {
        state.compilationString += state._declareOutput(color4Output) + ` = ${vec4}(${rgbInput.associatedVariableName}, ${aInput.isConnected ? this._writeVariable(aInput) : "0.0"})${this._buildSwizzle(4)};
`;
      }
      if (color3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(color3Output) + ` = ${rgbInput.associatedVariableName}${this._buildSwizzle(3)};
`;
      }
    } else {
      if (color4Output.hasEndpoints) {
        state.compilationString += state._declareOutput(color4Output) + ` = ${vec4}(${rInput.isConnected ? this._writeVariable(rInput) : "0.0"}, ${gInput.isConnected ? this._writeVariable(gInput) : "0.0"}, ${bInput.isConnected ? this._writeVariable(bInput) : "0.0"}, ${aInput.isConnected ? this._writeVariable(aInput) : "0.0"})${this._buildSwizzle(4)};
`;
      }
      if (color3Output.hasEndpoints) {
        state.compilationString += state._declareOutput(color3Output) + ` = ${vec3}(${rInput.isConnected ? this._writeVariable(rInput) : "0.0"}, ${gInput.isConnected ? this._writeVariable(gInput) : "0.0"}, ${bInput.isConnected ? this._writeVariable(bInput) : "0.0"})${this._buildSwizzle(3)};
`;
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.rSwizzle = this.rSwizzle;
    serializationObject.gSwizzle = this.gSwizzle;
    serializationObject.bSwizzle = this.bSwizzle;
    serializationObject.aSwizzle = this.aSwizzle;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.rSwizzle = serializationObject.rSwizzle ?? "r";
    this.gSwizzle = serializationObject.gSwizzle ?? "g";
    this.bSwizzle = serializationObject.bSwizzle ?? "b";
    this.aSwizzle = serializationObject.aSwizzle ?? "a";
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.rSwizzle = "${this.rSwizzle}";
`;
    codeString += `${this._codeVariableName}.gSwizzle = "${this.gSwizzle}";
`;
    codeString += `${this._codeVariableName}.bSwizzle = "${this.bSwizzle}";
`;
    codeString += `${this._codeVariableName}.aSwizzle = "${this.aSwizzle}";
`;
    return codeString;
  }
}
RegisterClass("BABYLON.ColorMergerBlock", ColorMergerBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/vectorSplitterBlock.js
init_typeStore();

class VectorSplitterBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true);
    this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true);
    this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float);
    this.inputsAreExclusive = true;
  }
  getClassName() {
    return "VectorSplitterBlock";
  }
  get xyzw() {
    return this._inputs[0];
  }
  get xyzIn() {
    return this._inputs[1];
  }
  get xyIn() {
    return this._inputs[2];
  }
  get xyzOut() {
    return this._outputs[0];
  }
  get xyOut() {
    return this._outputs[1];
  }
  get zw() {
    return this._outputs[2];
  }
  get x() {
    return this._outputs[3];
  }
  get y() {
    return this._outputs[4];
  }
  get z() {
    return this._outputs[5];
  }
  get w() {
    return this._outputs[6];
  }
  _inputRename(name370) {
    switch (name370) {
      case "xy ":
        return "xyIn";
      case "xyz ":
        return "xyzIn";
      default:
        return name370;
    }
  }
  _outputRename(name370) {
    switch (name370) {
      case "xy":
        return "xyOut";
      case "xyz":
        return "xyzOut";
      default:
        return name370;
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn;
    const xyzOutput = this._outputs[0];
    const xyOutput = this._outputs[1];
    const zwOutput = this._outputs[2];
    const xOutput = this._outputs[3];
    const yOutput = this._outputs[4];
    const zOutput = this._outputs[5];
    const wOutput = this._outputs[6];
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    if (xyzOutput.hasEndpoints) {
      if (input === this.xyIn) {
        state.compilationString += state._declareOutput(xyzOutput) + ` = ${vec3}(${input.associatedVariableName}, 0.0);
`;
      } else {
        state.compilationString += state._declareOutput(xyzOutput) + ` = ${input.associatedVariableName}.xyz;
`;
      }
    }
    if (zwOutput.hasEndpoints && this.xyzw.isConnected) {
      state.compilationString += state._declareOutput(zwOutput) + ` = ${this.xyzw.associatedVariableName}.zw;
`;
    }
    if (xyOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(xyOutput) + ` = ${input.associatedVariableName}.xy;
`;
    }
    if (xOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(xOutput) + ` = ${input.associatedVariableName}.x;
`;
    }
    if (yOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(yOutput) + ` = ${input.associatedVariableName}.y;
`;
    }
    if (zOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(zOutput) + ` = ${input.associatedVariableName}.z;
`;
    }
    if (wOutput.hasEndpoints) {
      state.compilationString += state._declareOutput(wOutput) + ` = ${input.associatedVariableName}.w;
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.VectorSplitterBlock", VectorSplitterBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/lerpBlock.js
init_typeStore();

class LerpBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._linkConnectionTypes(1, 2, true);
    this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "LerpBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get gradient() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.LerpBlock", LerpBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/divideBlock.js
init_typeStore();
class DivideBlock extends BaseMathBlock {
  constructor(name370) {
    super(name370);
  }
  getClassName() {
    return "DivideBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.DivideBlock", DivideBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/subtractBlock.js
init_typeStore();
class SubtractBlock extends BaseMathBlock {
  constructor(name370) {
    super(name370);
  }
  getClassName() {
    return "SubtractBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.SubtractBlock", SubtractBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/stepBlock.js
init_typeStore();

class StepBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("edge", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "StepBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get edge() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.StepBlock", StepBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/oneMinusBlock.js
init_typeStore();

class OneMinusBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "OneMinusBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = 1. - ${this.input.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.OneMinusBlock", OneMinusBlock);
RegisterClass("BABYLON.OppositeBlock", OneMinusBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/viewDirectionBlock.js
init_typeStore();
class ViewDirectionBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3);
  }
  getClassName() {
    return "ViewDirectionBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get cameraPosition() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.cameraPosition.isConnected) {
      let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b));
      if (!cameraPositionInput) {
        cameraPositionInput = new InputBlock("cameraPosition");
        cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);
      }
      cameraPositionInput.output.connectTo(this.cameraPosition);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);
`;
    return this;
  }
}
RegisterClass("BABYLON.ViewDirectionBlock", ViewDirectionBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/fresnelBlock.js
init_typeStore();
init_fresnelFunction2();
class FresnelBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("bias", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("power", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("fresnel", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "FresnelBlock";
  }
  get worldNormal() {
    return this._inputs[0];
  }
  get viewDirection() {
    return this._inputs[1];
  }
  get bias() {
    return this._inputs[2];
  }
  get power() {
    return this._inputs[3];
  }
  get fresnel() {
    return this._outputs[0];
  }
  autoConfigure(material) {
    if (!this.viewDirection.isConnected) {
      const viewDirectionInput = new ViewDirectionBlock("View direction");
      viewDirectionInput.output.connectTo(this.viewDirection);
      viewDirectionInput.autoConfigure(material);
    }
    if (!this.bias.isConnected) {
      const biasInput = new InputBlock("bias");
      biasInput.value = 0;
      biasInput.output.connectTo(this.bias);
    }
    if (!this.power.isConnected) {
      const powerInput = new InputBlock("power");
      powerInput.value = 1;
      powerInput.output.connectTo(this.power);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("fresnelFunction", comments, { removeIfDef: true });
    state.compilationString += state._declareOutput(this.fresnel) + ` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.FresnelBlock", FresnelBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/maxBlock.js
init_typeStore();

class MaxBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "MaxBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.MaxBlock", MaxBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/minBlock.js
init_typeStore();

class MinBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "MinBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.MinBlock", MinBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/distanceBlock.js
init_typeStore();

class DistanceBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "DistanceBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.DistanceBlock", DistanceBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/lengthBlock.js
init_typeStore();

class LengthBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "LengthBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = length(${this.value.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.LengthBlock", LengthBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/negateBlock.js
init_typeStore();

class NegateBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "NegateBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = -1.0 * ${this.value.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.NegateBlock", NegateBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/powBlock.js
init_typeStore();

class PowBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("power", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "PowBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get power() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = pow(max(${this.value.associatedVariableName}, 0.), ${this.power.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.PowBlock", PowBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/randomNumberBlock.js
init_typeStore();
init_helperFunctions2();

class RandomNumberBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "RandomNumberBlock";
  }
  get seed() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    state.compilationString += state._declareOutput(output) + ` = getRand(${this.seed.associatedVariableName}.xy);
`;
    return this;
  }
}
RegisterClass("BABYLON.RandomNumberBlock", RandomNumberBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/arcTan2Block.js
init_typeStore();

class ArcTan2Block extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "ArcTan2Block";
  }
  get x() {
    return this._inputs[0];
  }
  get y() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const func = state.shaderLanguage === 1 ? "atan2" : "atan";
    state.compilationString += state._declareOutput(output) + ` = ${func}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.ArcTan2Block", ArcTan2Block);
// node_modules/@babylonjs/core/Materials/Node/Blocks/smoothStepBlock.js
init_typeStore();

class SmoothStepBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("edge0", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("edge1", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "SmoothStepBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get edge0() {
    return this._inputs[1];
  }
  get edge1() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const cast = state._getShaderType(this.value.type);
    state.compilationString += state._declareOutput(output) + ` = smoothstep(${cast}(${this.edge0.associatedVariableName}), ${cast}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.SmoothStepBlock", SmoothStepBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/reciprocalBlock.js
init_typeStore();

class ReciprocalBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "ReciprocalBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    if (this.input.type === NodeMaterialBlockConnectionPointTypes.Matrix) {
      state.compilationString += state._declareOutput(output) + ` = inverse(${this.input.associatedVariableName});
`;
    } else {
      state.compilationString += state._declareOutput(output) + ` = 1. / ${this.input.associatedVariableName};
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.ReciprocalBlock", ReciprocalBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/replaceColorBlock.js
init_typeStore();

class ReplaceColorBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("reference", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("distance", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("replacement", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._linkConnectionTypes(0, 3);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "ReplaceColorBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get reference() {
    return this._inputs[1];
  }
  get distance() {
    return this._inputs[2];
  }
  get replacement() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + `;
`;
    state.compilationString += `if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {
`;
    state.compilationString += `${output.associatedVariableName} = ${this.replacement.associatedVariableName};
`;
    state.compilationString += `} else {
`;
    state.compilationString += `${output.associatedVariableName} = ${this.value.associatedVariableName};
`;
    state.compilationString += `}
`;
    return this;
  }
}
RegisterClass("BABYLON.ReplaceColorBlock", ReplaceColorBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/posterizeBlock.js
init_typeStore();

class PosterizeBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("steps", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "PosterizeBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get steps() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.PosterizeBlock", PosterizeBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/waveBlock.js
init_tslib_es6();
init_typeStore();
var WaveBlockKind;
(function(WaveBlockKind2) {
  WaveBlockKind2[WaveBlockKind2["SawTooth"] = 0] = "SawTooth";
  WaveBlockKind2[WaveBlockKind2["Square"] = 1] = "Square";
  WaveBlockKind2[WaveBlockKind2["Triangle"] = 2] = "Triangle";
})(WaveBlockKind || (WaveBlockKind = {}));

class WaveBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.kind = 0;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "WaveBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    switch (this.kind) {
      case 0: {
        state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});
`;
        break;
      }
      case 1: {
        state.compilationString += state._declareOutput(output) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));
`;
        break;
      }
      case 2: {
        state.compilationString += state._declareOutput(output) + ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;
`;
        break;
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.kind = this.kind;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.kind = serializationObject.kind;
  }
}
__decorate([
  editableInPropertyPage("Kind", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "SawTooth", value: 0 },
      { label: "Square", value: 1 },
      { label: "Triangle", value: 2 }
    ]
  })
], WaveBlock.prototype, "kind", undefined);
RegisterClass("BABYLON.WaveBlock", WaveBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/gradientBlock.js
init_typeStore();
init_math_color();
init_observable();

class GradientBlockColorStep {
  get step() {
    return this._step;
  }
  set step(val) {
    this._step = val;
  }
  get color() {
    return this._color;
  }
  set color(val) {
    this._color = val;
  }
  constructor(step, color) {
    this.step = step;
    this.color = color;
  }
}

class GradientBlock extends NodeMaterialBlock {
  colorStepsUpdated() {
    this.onValueChangedObservable.notifyObservers(this);
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.colorSteps = [new GradientBlockColorStep(0, Color3.Black()), new GradientBlockColorStep(1, Color3.White())];
    this.onValueChangedObservable = new Observable;
    this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Float | NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "GradientBlock";
  }
  get gradient() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _writeColorConstant(index, vec3) {
    const step = this.colorSteps[index];
    return `${vec3}(${step.color.r}, ${step.color.g}, ${step.color.b})`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    if (!this.colorSteps.length || !this.gradient.connectedPoint) {
      state.compilationString += state._declareOutput(output) + ` = ${vec3}(0., 0., 0.);
`;
      return;
    }
    const tempColor = state._getFreeVariableName("gradientTempColor");
    const tempPosition = state._getFreeVariableName("gradientTempPosition");
    state.compilationString += `${state._declareLocalVar(tempColor, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._writeColorConstant(0, vec3)};
`;
    state.compilationString += `${state._declareLocalVar(tempPosition, NodeMaterialBlockConnectionPointTypes.Float)};
`;
    let gradientSource = this.gradient.associatedVariableName;
    if (this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float) {
      gradientSource += ".x";
    }
    for (let index = 1;index < this.colorSteps.length; index++) {
      const step = this.colorSteps[index];
      const previousStep = this.colorSteps[index - 1];
      state.compilationString += `${tempPosition} = clamp((${gradientSource} - ${state._emitFloat(previousStep.step)}) / (${state._emitFloat(step.step)} -  ${state._emitFloat(previousStep.step)}), 0.0, 1.0) * step(${state._emitFloat(index)}, ${state._emitFloat(this.colorSteps.length - 1)});
`;
      state.compilationString += `${tempColor} = mix(${tempColor}, ${this._writeColorConstant(index, vec3)}, ${tempPosition});
`;
    }
    state.compilationString += state._declareOutput(output) + ` = ${tempColor};
`;
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.colorSteps = [];
    for (const step of this.colorSteps) {
      serializationObject.colorSteps.push({
        step: step.step,
        color: {
          r: step.color.r,
          g: step.color.g,
          b: step.color.b
        }
      });
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.colorSteps.length = 0;
    for (const step of serializationObject.colorSteps) {
      this.colorSteps.push(new GradientBlockColorStep(step.step, new Color3(step.color.r, step.color.g, step.color.b)));
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.colorSteps = [];
`;
    for (const colorStep of this.colorSteps) {
      codeString += `${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${colorStep.step}, new BABYLON.Color3(${colorStep.color.r}, ${colorStep.color.g}, ${colorStep.color.b})));
`;
    }
    return codeString;
  }
}
RegisterClass("BABYLON.GradientBlock", GradientBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/nLerpBlock.js
init_typeStore();

class NLerpBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._linkConnectionTypes(1, 2, true);
    this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "NLerpBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get gradient() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));
`;
    return this;
  }
}
RegisterClass("BABYLON.NLerpBlock", NLerpBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/worleyNoise3DBlock.js
init_tslib_es6();
init_typeStore();
class WorleyNoise3DBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.manhattanDistance = false;
    this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("jitter", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "WorleyNoise3DBlock";
  }
  get seed() {
    return this._inputs[0];
  }
  get jitter() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  get x() {
    return this._outputs[1];
  }
  get y() {
    return this._outputs[2];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this.seed.isConnected) {
      return;
    }
    if (!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints) {
      return;
    }
    let functionString = `vec3 permute(vec3 x){
`;
    functionString += `    return mod((34.0 * x + 1.0) * x, 289.0);
`;
    functionString += `}

`;
    functionString += `vec3 dist(vec3 x, vec3 y, vec3 z,  bool manhattanDistance){
`;
    functionString += `    return [manhattanDistance ?  abs(x) + abs(y) + abs(z) :  (x * x + y * y + z * z)];
`;
    functionString += `}

`;
    functionString += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){
`;
    functionString += `    float K = 0.142857142857; // 1/7
`;
    functionString += `    float Ko = 0.428571428571; // 1/2-K/2
`;
    functionString += `    float  K2 = 0.020408163265306; // 1/(7*7)
`;
    functionString += `    float Kz = 0.166666666667; // 1/6
`;
    functionString += `    float Kzo = 0.416666666667; // 1/2-1/6*2
`;
    functionString += `
`;
    functionString += `    vec3 Pi = mod(floor(P), 289.0);
`;
    functionString += `    vec3 Pf = fract(P) - 0.5;
`;
    functionString += `
`;
    functionString += `    vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);
`;
    functionString += `    vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);
`;
    functionString += `    vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);
`;
    functionString += `
`;
    functionString += `    vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));
`;
    functionString += `    vec3 p1 = permute(p + Pi.y - 1.0);
`;
    functionString += `    vec3 p2 = permute(p + Pi.y);
`;
    functionString += `    vec3 p3 = permute(p + Pi.y + 1.0);
`;
    functionString += `
`;
    functionString += `    vec3 p11 = permute(p1 + Pi.z - 1.0);
`;
    functionString += `    vec3 p12 = permute(p1 + Pi.z);
`;
    functionString += `    vec3 p13 = permute(p1 + Pi.z + 1.0);
`;
    functionString += `
`;
    functionString += `    vec3 p21 = permute(p2 + Pi.z - 1.0);
`;
    functionString += `    vec3 p22 = permute(p2 + Pi.z);
`;
    functionString += `    vec3 p23 = permute(p2 + Pi.z + 1.0);
`;
    functionString += `
`;
    functionString += `    vec3 p31 = permute(p3 + Pi.z - 1.0);
`;
    functionString += `    vec3 p32 = permute(p3 + Pi.z);
`;
    functionString += `    vec3 p33 = permute(p3 + Pi.z + 1.0);
`;
    functionString += `
`;
    functionString += `    vec3 ox11 = fract(p11*K) - Ko;
`;
    functionString += `    vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed
`;
    functionString += `
`;
    functionString += `    vec3 ox12 = fract(p12*K) - Ko;
`;
    functionString += `    vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz12 = floor(p12*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox13 = fract(p13*K) - Ko;
`;
    functionString += `    vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz13 = floor(p13*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox21 = fract(p21*K) - Ko;
`;
    functionString += `    vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz21 = floor(p21*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox22 = fract(p22*K) - Ko;
`;
    functionString += `    vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz22 = floor(p22*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox23 = fract(p23*K) - Ko;
`;
    functionString += `    vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz23 = floor(p23*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox31 = fract(p31*K) - Ko;
`;
    functionString += `    vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz31 = floor(p31*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox32 = fract(p32*K) - Ko;
`;
    functionString += `    vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz32 = floor(p32*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 ox33 = fract(p33*K) - Ko;
`;
    functionString += `    vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;
`;
    functionString += `    vec3 oz33 = floor(p33*K2)*Kz - Kzo;
`;
    functionString += `
`;
    functionString += `    vec3 dx11 = Pfx + jitter*ox11;
`;
    functionString += `    vec3 dy11 = Pfy.x + jitter*oy11;
`;
    functionString += `    vec3 dz11 = Pfz.x + jitter*oz11;
`;
    functionString += `
`;
    functionString += `    vec3 dx12 = Pfx + jitter*ox12;
`;
    functionString += `    vec3 dy12 = Pfy.x + jitter*oy12;
`;
    functionString += `    vec3 dz12 = Pfz.y + jitter*oz12;
`;
    functionString += `
`;
    functionString += `    vec3 dx13 = Pfx + jitter*ox13;
`;
    functionString += `    vec3 dy13 = Pfy.x + jitter*oy13;
`;
    functionString += `    vec3 dz13 = Pfz.z + jitter*oz13;
`;
    functionString += `
`;
    functionString += `    vec3 dx21 = Pfx + jitter*ox21;
`;
    functionString += `    vec3 dy21 = Pfy.y + jitter*oy21;
`;
    functionString += `    vec3 dz21 = Pfz.x + jitter*oz21;
`;
    functionString += `
`;
    functionString += `    vec3 dx22 = Pfx + jitter*ox22;
`;
    functionString += `    vec3 dy22 = Pfy.y + jitter*oy22;
`;
    functionString += `    vec3 dz22 = Pfz.y + jitter*oz22;
`;
    functionString += `
`;
    functionString += `    vec3 dx23 = Pfx + jitter*ox23;
`;
    functionString += `    vec3 dy23 = Pfy.y + jitter*oy23;
`;
    functionString += `    vec3 dz23 = Pfz.z + jitter*oz23;
`;
    functionString += `
`;
    functionString += `    vec3 dx31 = Pfx + jitter*ox31;
`;
    functionString += `    vec3 dy31 = Pfy.z + jitter*oy31;
`;
    functionString += `    vec3 dz31 = Pfz.x + jitter*oz31;
`;
    functionString += `
`;
    functionString += `    vec3 dx32 = Pfx + jitter*ox32;
`;
    functionString += `    vec3 dy32 = Pfy.z + jitter*oy32;
`;
    functionString += `    vec3 dz32 = Pfz.y + jitter*oz32;
`;
    functionString += `
`;
    functionString += `    vec3 dx33 = Pfx + jitter*ox33;
`;
    functionString += `    vec3 dy33 = Pfy.z + jitter*oy33;
`;
    functionString += `    vec3 dz33 = Pfz.z + jitter*oz33;
`;
    functionString += `
`;
    functionString += `    vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);
`;
    functionString += `    vec3 d12 = dist(dx12, dy12, dz12, manhattanDistance);
`;
    functionString += `    vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);
`;
    functionString += `    vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);
`;
    functionString += `    vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);
`;
    functionString += `    vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);
`;
    functionString += `    vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);
`;
    functionString += `    vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);
`;
    functionString += `    vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);
`;
    functionString += `
`;
    functionString += `    vec3 d1a = min(d11, d12);
`;
    functionString += `    d12 = max(d11, d12);
`;
    functionString += `    d11 = min(d1a, d13); // Smallest now not in d12 or d13
`;
    functionString += `    d13 = max(d1a, d13);
`;
    functionString += `    d12 = min(d12, d13); // 2nd smallest now not in d13
`;
    functionString += `    vec3 d2a = min(d21, d22);
`;
    functionString += `    d22 = max(d21, d22);
`;
    functionString += `    d21 = min(d2a, d23); // Smallest now not in d22 or d23
`;
    functionString += `    d23 = max(d2a, d23);
`;
    functionString += `    d22 = min(d22, d23); // 2nd smallest now not in d23
`;
    functionString += `    vec3 d3a = min(d31, d32);
`;
    functionString += `    d32 = max(d31, d32);
`;
    functionString += `    d31 = min(d3a, d33); // Smallest now not in d32 or d33
`;
    functionString += `    d33 = max(d3a, d33);
`;
    functionString += `    d32 = min(d32, d33); // 2nd smallest now not in d33
`;
    functionString += `    vec3 da = min(d11, d21);
`;
    functionString += `    d21 = max(d11, d21);
`;
    functionString += `    d11 = min(da, d31); // Smallest now in d11
`;
    functionString += `    d31 = max(da, d31); // 2nd smallest now not in d31
`;
    functionString += `    if (d11.x >= d11.y) { vec2 temp = d11.yx; d11.x = temp.x; d11.y = temp.y; }
`;
    functionString += `    if (d11.x >= d11.z) { vec2 temp = d11.zx; d11.x = temp.x; d11.z = temp.y; }
`;
    functionString += `    d12 = min(d12, d21); // 2nd smallest now not in d21
`;
    functionString += `    d12 = min(d12, d22); // nor in d22
`;
    functionString += `    d12 = min(d12, d31); // nor in d31
`;
    functionString += `    d12 = min(d12, d32); // nor in d32
`;
    functionString += `    vec2 temp2 = min(d11.yz, d12.xy); // nor in d12.yz
`;
    functionString += `    d11.y = temp2.x;
`;
    functionString += `    d11.z = temp2.y;
`;
    functionString += `    d11.y = min(d11.y, d12.z); // Only two more to go
`;
    functionString += `    d11.y = min(d11.y, d11.z); // Done! (Phew!)
`;
    functionString += `    return sqrt(d11.xy); // F1, F2
`;
    functionString += `}

`;
    if (state.shaderLanguage === 1) {
      functionString = state._babylonSLtoWGSL(functionString);
    } else {
      functionString = state._babylonSLtoGLSL(functionString);
    }
    state._emitFunction("worley3D", functionString, "// Worley3D");
    const tempVariable = state._getFreeVariableName("worleyTemp");
    state.compilationString += `${state._declareLocalVar(tempVariable, NodeMaterialBlockConnectionPointTypes.Vector2)} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});
`;
    if (this.output.hasEndpoints) {
      state.compilationString += state._declareOutput(this.output) + ` = ${tempVariable};
`;
    }
    if (this.x.hasEndpoints) {
      state.compilationString += state._declareOutput(this.x) + ` = ${tempVariable}.x;
`;
    }
    if (this.y.hasEndpoints) {
      state.compilationString += state._declareOutput(this.y) + ` = ${tempVariable}.y;
`;
    }
    return this;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.manhattanDistance = this.manhattanDistance;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.manhattanDistance = serializationObject.manhattanDistance;
  }
}
__decorate([
  editableInPropertyPage("Use Manhattan Distance", 0, "PROPERTIES", { embedded: true, notifiers: { update: false } })
], WorleyNoise3DBlock.prototype, "manhattanDistance", undefined);
RegisterClass("BABYLON.WorleyNoise3DBlock", WorleyNoise3DBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/simplexPerlin3DBlock.js
init_typeStore();

class SimplexPerlin3DBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "SimplexPerlin3DBlock";
  }
  get seed() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this.seed.isConnected) {
      return;
    }
    if (!this._outputs[0].hasEndpoints) {
      return;
    }
    let functionString = `const float SKEWFACTOR = 1.0/3.0;
`;
    functionString += `const float UNSKEWFACTOR = 1.0/6.0;
`;
    functionString += `const float SIMPLEX_CORNER_POS = 0.5;
`;
    functionString += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;
`;
    functionString += `float SimplexPerlin3D( vec3 source ){
`;
    functionString += `    vec3 P = source;
`;
    functionString += `    P.x = [P.x == 0. && P.y == 0. && P.z == 0. ? 0.00001 : P.x];
`;
    functionString += `    P *= SIMPLEX_TETRAHADRON_HEIGHT;
`;
    functionString += `    vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );`;
    functionString += `    vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );
`;
    functionString += `    vec3 g = step(x0.yzx, x0.xyz);
`;
    functionString += `    vec3 l = 1.0 - g;
`;
    functionString += `    vec3 Pi_1 = min( g.xyz, l.zxy );
`;
    functionString += `    vec3 Pi_2 = max( g.xyz, l.zxy );
`;
    functionString += `    vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;
`;
    functionString += `    vec3 x2 = x0 - Pi_2 + SKEWFACTOR;
`;
    functionString += `    vec3 x3 = x0 - SIMPLEX_CORNER_POS;
`;
    functionString += `    vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );
`;
    functionString += `    vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );
`;
    functionString += `    vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );
`;
    functionString += `    Pi = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;
`;
    functionString += `    vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );
`;
    functionString += `    vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;
`;
    functionString += `    Pt *= Pt;
`;
    functionString += `    vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );
`;
    functionString += `    Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );
`;
    functionString += `    const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );
`;
    functionString += `    const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );
`;
    functionString += `    vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );
`;
    functionString += `    vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );
`;
    functionString += `    Pi_1 = [( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods];
`;
    functionString += `    Pi_2 = [( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods];
`;
    functionString += `    vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;
`;
    functionString += `    vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;
`;
    functionString += `    vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;
`;
    functionString += `    vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );
`;
    functionString += `    const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;
`;
    functionString += `    vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;
`;
    functionString += `    kernel_weights = max(0.5 - kernel_weights, vec4(0.));
`;
    functionString += `    kernel_weights = kernel_weights*kernel_weights*kernel_weights;
`;
    functionString += `    return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;
`;
    functionString += `}
`;
    if (state.shaderLanguage === 1) {
      functionString = state._babylonSLtoWGSL(functionString);
    } else {
      functionString = state._babylonSLtoGLSL(functionString);
    }
    state._emitFunction("SimplexPerlin3D", functionString, "// SimplexPerlin3D");
    state.compilationString += state._declareOutput(this._outputs[0]) + ` = SimplexPerlin3D(${this.seed.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.SimplexPerlin3DBlock", SimplexPerlin3DBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/normalBlendBlock.js
init_typeStore();

class NormalBlendBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("normalMap0", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("normalMap1", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "NormalBlendBlock";
  }
  get normalMap0() {
    return this._inputs[0];
  }
  get normalMap1() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input0 = this._inputs[0];
    const input1 = this._inputs[1];
    const stepR = state._getFreeVariableName("stepR");
    const stepG = state._getFreeVariableName("stepG");
    state.compilationString += `${state._declareLocalVar(stepR, NodeMaterialBlockConnectionPointTypes.Float)} = step(0.5, ${input0.associatedVariableName}.r);
`;
    state.compilationString += `${state._declareLocalVar(stepG, NodeMaterialBlockConnectionPointTypes.Float)} = step(0.5, ${input0.associatedVariableName}.g);
`;
    state.compilationString += state._declareOutput(output) + `;
`;
    state.compilationString += `${output.associatedVariableName}.r = (1.0 - ${stepR}) * ${input0.associatedVariableName}.r * ${input1.associatedVariableName}.r * 2.0 + ${stepR} * (1.0 - (1.0 - ${input0.associatedVariableName}.r) * (1.0 - ${input1.associatedVariableName}.r) * 2.0);
`;
    state.compilationString += `${output.associatedVariableName}.g = (1.0 - ${stepG}) * ${input0.associatedVariableName}.g * ${input1.associatedVariableName}.g * 2.0 + ${stepG} * (1.0 - (1.0 - ${input0.associatedVariableName}.g) * (1.0 - ${input1.associatedVariableName}.g) * 2.0);
`;
    state.compilationString += `${output.associatedVariableName}.b = ${input0.associatedVariableName}.b * ${input1.associatedVariableName}.b;
`;
    return this;
  }
}
RegisterClass("BABYLON.NormalBlendBlock", NormalBlendBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/rotate2dBlock.js
init_typeStore();
class Rotate2dBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("angle", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "Rotate2dBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get angle() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.angle.isConnected) {
      const angleInput = new InputBlock("angle");
      angleInput.value = 0;
      angleInput.output.connectTo(this.angle);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const angle = this.angle;
    const input = this.input;
    state.compilationString += state._declareOutput(output) + ` = vec2(cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.x - sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.y, sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.x + cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.y);
`;
    return this;
  }
}
RegisterClass("BABYLON.Rotate2dBlock", Rotate2dBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/reflectBlock.js
init_typeStore();

class ReflectBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
    this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "ReflectBlock";
  }
  get incident() {
    return this._inputs[0];
  }
  get normal() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);
`;
    return this;
  }
}
RegisterClass("BABYLON.ReflectBlock", ReflectBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/refractBlock.js
init_typeStore();

class RefractBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("ior", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
    this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Color4);
  }
  getClassName() {
    return "RefractBlock";
  }
  get incident() {
    return this._inputs[0];
  }
  get normal() {
    return this._inputs[1];
  }
  get ior() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    state.compilationString += state._declareOutput(output) + ` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.RefractBlock", RefractBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/desaturateBlock.js
init_typeStore();

class DesaturateBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3);
    this.registerInput("level", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3);
  }
  getClassName() {
    return "DesaturateBlock";
  }
  get color() {
    return this._inputs[0];
  }
  get level() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const color = this.color;
    const colorName = color.associatedVariableName;
    const tempMin = state._getFreeVariableName("colorMin");
    const tempMax = state._getFreeVariableName("colorMax");
    const tempMerge = state._getFreeVariableName("colorMerge");
    state.compilationString += `${state._declareLocalVar(tempMin, NodeMaterialBlockConnectionPointTypes.Float)} = min(min(${colorName}.x, ${colorName}.y), ${colorName}.z);
`;
    state.compilationString += `${state._declareLocalVar(tempMax, NodeMaterialBlockConnectionPointTypes.Float)} = max(max(${colorName}.x, ${colorName}.y), ${colorName}.z);
`;
    state.compilationString += `${state._declareLocalVar(tempMerge, NodeMaterialBlockConnectionPointTypes.Float)} = 0.5 * (${tempMin} + ${tempMax});
`;
    state.compilationString += state._declareOutput(output) + ` = mix(${colorName}, ${state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3)}(${tempMerge}, ${tempMerge}, ${tempMerge}), ${this.level.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.DesaturateBlock", DesaturateBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.js
init_tslib_es6();
init_typeStore();

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/sheenBlock.js
init_tslib_es6();
init_typeStore();
class SheenBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.albedoScaling = false;
    this.linkSheenWithAlbedo = false;
    this._isUnique = true;
    this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("sheen", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, 1, SheenBlock, "SheenBlock"));
  }
  initialize(state) {
    state._excludeVariableName("sheenOut");
    state._excludeVariableName("sheenMapData");
    state._excludeVariableName("vSheenColor");
    state._excludeVariableName("vSheenRoughness");
  }
  getClassName() {
    return "SheenBlock";
  }
  get intensity() {
    return this._inputs[0];
  }
  get color() {
    return this._inputs[1];
  }
  get roughness() {
    return this._inputs[2];
  }
  get sheen() {
    return this._outputs[0];
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    defines.setValue("SHEEN", true);
    defines.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true);
    defines.setValue("SHEEN_LINKWITHALBEDO", this.linkSheenWithAlbedo, true);
    defines.setValue("SHEEN_ROUGHNESS", this.roughness.isConnected, true);
    defines.setValue("SHEEN_ALBEDOSCALING", this.albedoScaling, true);
  }
  getCode(reflectionBlock, state) {
    let code = "";
    const color = this.color.isConnected ? this.color.associatedVariableName : `vec3${state.fSuffix}(1.)`;
    const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.";
    const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0.";
    const texture2 = `vec4${state.fSuffix}(0.)`;
    const isWebGPU = state.shaderLanguage === 1;
    code = `#ifdef SHEEN
            ${isWebGPU ? "var sheenOut: sheenOutParams" : "sheenOutParams sheenOut"};

            ${state._declareLocalVar("vSheenColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${color}, ${intensity});

            sheenOut = sheenBlock(
                vSheenColor
            #ifdef SHEEN_ROUGHNESS
                , ${roughness}
            #endif
                , roughness
            #ifdef SHEEN_TEXTURE
                , ${texture2}
                ${isWebGPU ? `, ${texture2}Sampler` : ""}
                , 1.0
            #endif
                , reflectance
            #ifdef SHEEN_LINKWITHALBEDO
                , baseColor
                , surfaceAlbedo
            #endif
            #ifdef ENVIRONMENTBRDF
                , NdotV
                , environmentBrdf
            #endif
            #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)
                , AARoughnessFactors
                , ${isWebGPU ? "uniforms." : ""}${reflectionBlock?._vReflectionMicrosurfaceInfosName}
                , ${reflectionBlock?._vReflectionInfosName}
                , ${reflectionBlock?.reflectionColor}
                , ${isWebGPU ? "uniforms." : ""}vLightingIntensity
                #ifdef ${reflectionBlock?._define3DName}
                    , ${reflectionBlock?._cubeSamplerName}                                      
                    ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                #else
                    , ${reflectionBlock?._2DSamplerName}
                    ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}
                #endif
                , reflectionOut.reflectionCoords
                , NdotVUnclamped
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${reflectionBlock?._define3DName}
                        , ${reflectionBlock?._cubeSamplerName}                        
                        ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                        , ${reflectionBlock?._cubeSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                    #else
                        , ${reflectionBlock?._2DSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}
                        , ${reflectionBlock?._2DSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}
                    #endif
                #endif
                #if !defined(${reflectionBlock?._defineSkyboxName}) && defined(RADIANCEOCCLUSION)
                    , seo
                #endif
                #if !defined(${reflectionBlock?._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${reflectionBlock?._define3DName})
                    , eho
                #endif
            #endif
            );

            #ifdef SHEEN_LINKWITHALBEDO
                surfaceAlbedo = sheenOut.surfaceAlbedo;
            #endif
        #endif
`;
    return code;
  }
  _buildBlock(state) {
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.blocksWithDefines.push(this);
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.albedoScaling = ${this.albedoScaling};
`;
    codeString += `${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.albedoScaling = this.albedoScaling;
    serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.albedoScaling = serializationObject.albedoScaling;
    this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo;
  }
}
__decorate([
  editableInPropertyPage("Albedo scaling", 0, "PROPERTIES", { embedded: true, notifiers: { update: true } })
], SheenBlock.prototype, "albedoScaling", undefined);
__decorate([
  editableInPropertyPage("Link sheen with albedo", 0, "PROPERTIES", { embedded: true, notifiers: { update: true } })
], SheenBlock.prototype, "linkSheenWithAlbedo", undefined);
RegisterClass("BABYLON.SheenBlock", SheenBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/anisotropyBlock.js
init_typeStore();
init_logger();

class AnisotropyBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this._tangentCorrectionFactorName = "";
    this._isUnique = true;
    this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("direction", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, true);
    this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0, TBNBlock, "TBNBlock"));
    this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, 1, AnisotropyBlock, "AnisotropyBlock"));
  }
  initialize(state) {
    state._excludeVariableName("anisotropicOut");
    state._excludeVariableName("TBN");
  }
  getClassName() {
    return "AnisotropyBlock";
  }
  get intensity() {
    return this._inputs[0];
  }
  get direction() {
    return this._inputs[1];
  }
  get uv() {
    return this._inputs[2];
  }
  get worldTangent() {
    return this._inputs[3];
  }
  get TBN() {
    return this._inputs[4];
  }
  get roughness() {
    return this._inputs[5];
  }
  get anisotropy() {
    return this._outputs[0];
  }
  _generateTBNSpace(state) {
    let code = "";
    const comments = `//${this.name}`;
    const uv = this.uv;
    const worldPosition = this.worldPositionConnectionPoint;
    const worldNormal = this.worldNormalConnectionPoint;
    const worldTangent = this.worldTangent;
    const isWebGPU = state.shaderLanguage === 1;
    if (!uv.isConnected) {
      Logger.Error("You must connect the 'uv' input of the Anisotropy block!");
    }
    state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
    const TBN = this.TBN;
    if (TBN.isConnected) {
      state.compilationString += `
            #ifdef TBNBLOCK
            ${isWebGPU ? "var TBN" : "mat3 TBN"} = ${TBN.associatedVariableName};
            #endif
            `;
    } else if (worldTangent.isConnected) {
      code += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormal.associatedVariableName}.xyz);
`;
      code += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);
`;
      code += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};
`;
      code += `${isWebGPU ? "var vTBN" : "mat3 vTBN"} = ${isWebGPU ? "mat3x3f" : "mat3"}(tbnTangent, tbnBitangent, tbnNormal);
`;
    }
    code += `
            #if defined(${worldTangent.isConnected ? "TANGENT" : "IGNORE"}) && defined(NORMAL)
                ${isWebGPU ? "var TBN" : "mat3 TBN"} = vTBN;
            #else
                ${isWebGPU ? "var TBN" : "mat3 TBN"} = cotangent_frame(${worldNormal.associatedVariableName + ".xyz"}, ${"v_" + worldPosition.associatedVariableName + ".xyz"}, ${uv.isConnected ? uv.associatedVariableName : "vec2(0.)"}, vec2${state.fSuffix}(1., 1.));
            #endif
`;
    state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
      replaceStrings: [tangentReplaceString]
    });
    return code;
  }
  getCode(state, generateTBNSpace = false) {
    let code = "";
    if (generateTBNSpace) {
      code += this._generateTBNSpace(state);
    }
    const isWebGPU = state.shaderLanguage === 1;
    const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.0";
    const direction = this.direction.isConnected ? this.direction.associatedVariableName : "vec2(1., 0.)";
    const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0.";
    code += `${isWebGPU ? "var anisotropicOut: anisotropicOutParams" : "anisotropicOutParams anisotropicOut"};
            anisotropicOut = anisotropicBlock(
                vec3(${direction}, ${intensity}),
                ${roughness},
            #ifdef ANISOTROPIC_TEXTURE
                vec3(0.),
            #endif
                TBN,
                normalW,
                viewDirectionW
            );
`;
    return code;
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    defines.setValue("ANISOTROPIC", true);
    defines.setValue("ANISOTROPIC_TEXTURE", false, true);
    defines.setValue("ANISOTROPIC_LEGACY", !this.roughness.isConnected);
  }
  bind(effect, nodeMaterial, mesh) {
    super.bind(effect, nodeMaterial, mesh);
    if (mesh) {
      effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);
    }
  }
  _buildBlock(state) {
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.blocksWithDefines.push(this);
      state.sharedData.bindableBlocks.push(this);
      this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor");
      state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float);
    }
    return this;
  }
}
RegisterClass("BABYLON.AnisotropyBlock", AnisotropyBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/reflectionBlock.js
init_tslib_es6();
init_typeStore();
init_texture();
init_logger();

class ReflectionBlock extends ReflectionTextureBaseBlock {
  _onGenerateOnlyFragmentCodeChanged() {
    if (this.position.isConnected) {
      this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;
      Logger.Error("The position input must not be connected to be able to switch!");
      return false;
    }
    this._setTarget();
    return true;
  }
  _setTarget() {
    super._setTarget();
    this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
    if (this.generateOnlyFragmentCode) {
      this.forceIrradianceInFragment = true;
    }
  }
  constructor(name370) {
    super(name370);
    this.useSphericalHarmonics = true;
    this.forceIrradianceInFragment = false;
    this._isUnique = true;
    this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("reflection", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, 1, ReflectionBlock, "ReflectionBlock"));
    this.position.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "ReflectionBlock";
  }
  get position() {
    return this._inputs[0];
  }
  get worldPosition() {
    return this.worldPositionConnectionPoint;
  }
  get worldNormal() {
    return this.worldNormalConnectionPoint;
  }
  get world() {
    return this._inputs[1];
  }
  get cameraPosition() {
    return this.cameraPositionConnectionPoint;
  }
  get view() {
    return this.viewConnectionPoint;
  }
  get color() {
    return this._inputs[2];
  }
  get reflection() {
    return this._outputs[0];
  }
  get hasTexture() {
    return !!this._getTexture();
  }
  get reflectionColor() {
    return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)";
  }
  _getTexture() {
    if (this.texture) {
      return this.texture;
    }
    return this._scene.environmentTexture;
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    const reflectionTexture = this._getTexture();
    const reflection = reflectionTexture && reflectionTexture.getTextureMatrix;
    defines.setValue("REFLECTION", reflection, true);
    if (!reflection) {
      return;
    }
    defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true);
    defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true);
    defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true);
    defines.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, true);
    defines.setValue("GAMMAREFLECTION", reflectionTexture.gammaSpace, true);
    defines.setValue("RGBDREFLECTION", reflectionTexture.isRGBD, true);
    if (reflectionTexture && reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {
      if (reflectionTexture.isCube) {
        defines.setValue("USESPHERICALFROMREFLECTIONMAP", true);
        defines.setValue("USEIRRADIANCEMAP", false);
        if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) {
          defines.setValue("USESPHERICALINVERTEX", false);
        } else {
          defines.setValue("USESPHERICALINVERTEX", true);
        }
      }
    }
  }
  bind(effect, nodeMaterial, mesh, subMesh) {
    super.bind(effect, nodeMaterial, mesh);
    const reflectionTexture = this._getTexture();
    if (!reflectionTexture || !subMesh) {
      return;
    }
    if (reflectionTexture.isCube) {
      effect.setTexture(this._cubeSamplerName, reflectionTexture);
    } else {
      effect.setTexture(this._2DSamplerName, reflectionTexture);
    }
    const width = reflectionTexture.getSize().width;
    effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
    effect.setFloat2(this._vReflectionFilteringInfoName, width, Math.log2(width));
    const defines = subMesh.materialDefines;
    const polynomials = reflectionTexture.sphericalPolynomial;
    if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
      if (defines.SPHERICAL_HARMONICS) {
        const preScaledHarmonics = polynomials.preScaledHarmonics;
        effect.setVector3("vSphericalL00", preScaledHarmonics.l00);
        effect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
        effect.setVector3("vSphericalL10", preScaledHarmonics.l10);
        effect.setVector3("vSphericalL11", preScaledHarmonics.l11);
        effect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
        effect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
        effect.setVector3("vSphericalL20", preScaledHarmonics.l20);
        effect.setVector3("vSphericalL21", preScaledHarmonics.l21);
        effect.setVector3("vSphericalL22", preScaledHarmonics.l22);
      } else {
        effect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
        effect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
        effect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
        effect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
        effect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
        effect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
        effect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
        effect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
        effect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
      }
    }
  }
  handleVertexSide(state) {
    let code = super.handleVertexSide(state);
    const isWebGPU = state.shaderLanguage === 1;
    state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, {
      replaceStrings: [
        { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
        { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }
      ]
    });
    const reflectionVectorName = state._getFreeVariableName("reflectionVector");
    this._vEnvironmentIrradianceName = state._getFreeVariableName("vEnvironmentIrradiance");
    state._emitVaryingFromString(this._vEnvironmentIrradianceName, NodeMaterialBlockConnectionPointTypes.Vector3, "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)");
    state._emitUniformFromString("vSphericalL00", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL1_1", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL10", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL11", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL2_2", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL2_1", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL20", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL21", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalL22", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS");
    state._emitUniformFromString("vSphericalX", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalY", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalXX_ZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalYY_ZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalZZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalXY", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalYZ", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    state._emitUniformFromString("vSphericalZX", NodeMaterialBlockConnectionPointTypes.Vector3, "SPHERICAL_HARMONICS", true);
    code += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)
                ${state._declareLocalVar(reflectionVectorName, NodeMaterialBlockConnectionPointTypes.Vector3)} = (${(isWebGPU ? "uniforms." : "") + this._reflectionMatrixName} * vec4${state.fSuffix}(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;
                #ifdef ${this._defineOppositeZ}
                    ${reflectionVectorName}.z *= -1.0;
                #endif
                ${isWebGPU ? "vertexOutputs." : ""}${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName});
            #endif
`;
    return code;
  }
  getCode(state, normalVarName) {
    let code = "";
    this.handleFragmentSideInits(state);
    const isWebGPU = state.shaderLanguage === 1;
    state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, {
      replaceStrings: [
        { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
        { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }
      ]
    });
    if (!isWebGPU) {
      state._emitFunction("sampleReflection", `
                #ifdef ${this._define3DName}
                    #define sampleReflection(s, c) textureCube(s, c)
                #else
                    #define sampleReflection(s, c) texture2D(s, c)
                #endif
`, `//${this.name}`);
      state._emitFunction("sampleReflectionLod", `
                #ifdef ${this._define3DName}
                    #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)
                #else
                    #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)
                #endif
`, `//${this.name}`);
    }
    const computeReflectionCoordsFunc = isWebGPU ? `
            fn computeReflectionCoordsPBR(worldPos: vec4f, worldNormal: vec3f) -> vec3f {
                ${this.handleFragmentSideCodeReflectionCoords(state, "worldNormal", "worldPos", true, true)}
                return ${this._reflectionVectorName};
            }
` : `
            vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {
                ${this.handleFragmentSideCodeReflectionCoords(state, "worldNormal", "worldPos", true, true)}
                return ${this._reflectionVectorName};
            }
`;
    state._emitFunction("computeReflectionCoordsPBR", computeReflectionCoordsFunc, `//${this.name}`);
    this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName("vReflectionMicrosurfaceInfos");
    state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, NodeMaterialBlockConnectionPointTypes.Vector3);
    this._vReflectionInfosName = state._getFreeVariableName("vReflectionInfos");
    this._vReflectionFilteringInfoName = state._getFreeVariableName("vReflectionFilteringInfo");
    state._emitUniformFromString(this._vReflectionFilteringInfoName, NodeMaterialBlockConnectionPointTypes.Vector2);
    code += `#ifdef REFLECTION
            ${state._declareLocalVar(this._vReflectionInfosName, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(1., 0.);

            ${isWebGPU ? "var reflectionOut: reflectionOutParams" : "reflectionOutParams reflectionOut"};

            reflectionOut = reflectionBlock(
                ${this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : (isWebGPU ? "input." : "") + "v_" + this.worldPosition.associatedVariableName}.xyz
                , ${normalVarName}
                , alphaG
                , ${(isWebGPU ? "uniforms." : "") + this._vReflectionMicrosurfaceInfosName}
                , ${this._vReflectionInfosName}
                , ${this.reflectionColor}
            #ifdef ANISOTROPIC
                ,anisotropicOut
            #endif
            #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})
                ,NdotVUnclamped
            #endif
            #ifdef ${this._defineLinearSpecularReflection}
                , roughness
            #endif
            #ifdef ${this._define3DName}
                , ${this._cubeSamplerName}
                ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""}
            #else
                , ${this._2DSamplerName}
                ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""}
            #endif
            #if defined(NORMAL) && defined(USESPHERICALINVERTEX)
                , ${isWebGPU ? "input." : ""}${this._vEnvironmentIrradianceName}
            #endif
            #if (defined(USESPHERICALFROMREFLECTIONMAP) && (!defined(NORMAL) || !defined(USESPHERICALINVERTEX))) || (defined(USEIRRADIANCEMAP) && defined(REFLECTIONMAP_3D))
                    , ${this._reflectionMatrixName}
            #endif
            #ifdef USEIRRADIANCEMAP
                , irradianceSampler         // ** not handled **
                ${isWebGPU ? `, irradianceSamplerSampler` : ""}
            #endif
            #ifndef LODBASEDMICROSFURACE
                #ifdef ${this._define3DName}
                    , ${this._cubeSamplerName}
                    ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""}
                    , ${this._cubeSamplerName}
                    ${isWebGPU ? `, ${this._cubeSamplerName}Sampler` : ""}
                #else
                    , ${this._2DSamplerName}
                    ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""}
                    , ${this._2DSamplerName}                    
                    ${isWebGPU ? `, ${this._2DSamplerName}Sampler` : ""}
                #endif
            #endif
            #ifdef REALTIME_FILTERING
                , ${this._vReflectionFilteringInfoName}
                #ifdef IBL_CDF_FILTERING
                    , icdfSampler         // ** not handled **
                    ${isWebGPU ? `, icdfSamplerSampler` : ""}
                #endif
            #endif
            );
        #endif
`;
    return code;
  }
  _buildBlock(state) {
    this._scene = state.sharedData.scene;
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      this._defineLODReflectionAlpha = state._getFreeDefineName("LODINREFLECTIONALPHA");
      this._defineLinearSpecularReflection = state._getFreeDefineName("LINEARSPECULARREFLECTION");
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (this.texture) {
      codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};
`;
    }
    codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};
`;
    codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.useSphericalHarmonics = this.useSphericalHarmonics;
    serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment;
    serializationObject.gammaSpace = this.texture?.gammaSpace ?? true;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.useSphericalHarmonics = serializationObject.useSphericalHarmonics;
    this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment;
    if (this.texture) {
      this.texture.gammaSpace = serializationObject.gammaSpace;
    }
  }
}
__decorate([
  editableInPropertyPage("Spherical Harmonics", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], ReflectionBlock.prototype, "useSphericalHarmonics", undefined);
__decorate([
  editableInPropertyPage("Force irradiance in fragment", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], ReflectionBlock.prototype, "forceIrradianceInFragment", undefined);
RegisterClass("BABYLON.ReflectionBlock", ReflectionBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/clearCoatBlock.js
init_tslib_es6();
init_typeStore();
class ClearCoatBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this._tangentCorrectionFactorName = "";
    this.remapF0OnInterfaceChange = true;
    this._isUnique = true;
    this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("tintThickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);
    this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, 0, TBNBlock, "TBNBlock"));
    this.registerOutput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, 1, ClearCoatBlock, "ClearCoatBlock"));
  }
  initialize(state) {
    state._excludeVariableName("clearcoatOut");
    state._excludeVariableName("vClearCoatParams");
    state._excludeVariableName("vClearCoatTintParams");
    state._excludeVariableName("vClearCoatRefractionParams");
    state._excludeVariableName("vClearCoatTangentSpaceParams");
    state._excludeVariableName("vGeometricNormaClearCoatW");
  }
  getClassName() {
    return "ClearCoatBlock";
  }
  get intensity() {
    return this._inputs[0];
  }
  get roughness() {
    return this._inputs[1];
  }
  get indexOfRefraction() {
    return this._inputs[2];
  }
  get normalMapColor() {
    return this._inputs[3];
  }
  get uv() {
    return this._inputs[4];
  }
  get tintColor() {
    return this._inputs[5];
  }
  get tintAtDistance() {
    return this._inputs[6];
  }
  get tintThickness() {
    return this._inputs[7];
  }
  get worldTangent() {
    return this._inputs[8];
  }
  get worldNormal() {
    return this._inputs[9];
  }
  get TBN() {
    return this._inputs[10];
  }
  get clearcoat() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.intensity.isConnected) {
      const intensityInput = new InputBlock("ClearCoat intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      intensityInput.value = 1;
      intensityInput.output.connectTo(this.intensity);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    defines.setValue("CLEARCOAT", true);
    defines.setValue("CLEARCOAT_TEXTURE", false, true);
    defines.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true);
    defines.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true);
    defines.setValue("CLEARCOAT_BUMP", this.normalMapColor.isConnected, true);
    defines.setValue("CLEARCOAT_DEFAULTIOR", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : true, true);
    defines.setValue("CLEARCOAT_REMAP_F0", this.remapF0OnInterfaceChange, true);
  }
  bind(effect, nodeMaterial, mesh) {
    super.bind(effect, nodeMaterial, mesh);
    const indexOfRefraction = this.indexOfRefraction.connectInputBlock?.value ?? PBRClearCoatConfiguration._DefaultIndexOfRefraction;
    const a = 1 - indexOfRefraction;
    const b = 1 + indexOfRefraction;
    const f0 = Math.pow(-a / b, 2);
    const eta = 1 / indexOfRefraction;
    effect.setFloat4("vClearCoatRefractionParams", f0, eta, a, b);
    const mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null;
    const perturbedNormalBlock = mainPBRBlock?.perturbedNormal.isConnected ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null;
    if (this._scene._mirroredCameraPosition) {
      effect.setFloat2("vClearCoatTangentSpaceParams", perturbedNormalBlock?.invertX ? 1 : -1, perturbedNormalBlock?.invertY ? 1 : -1);
    } else {
      effect.setFloat2("vClearCoatTangentSpaceParams", perturbedNormalBlock?.invertX ? -1 : 1, perturbedNormalBlock?.invertY ? -1 : 1);
    }
    if (mesh) {
      effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);
    }
  }
  _generateTBNSpace(state, worldPositionVarName, worldNormalVarName) {
    let code = "";
    const comments = `//${this.name}`;
    const worldTangent = this.worldTangent;
    const isWebGPU = state.shaderLanguage === 1;
    if (!isWebGPU) {
      state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    }
    const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
    const TBN = this.TBN;
    if (TBN.isConnected) {
      state.compilationString += `
            #ifdef TBNBLOCK
                ${isWebGPU ? "var TBN" : "mat3 TBN"} = ${TBN.associatedVariableName};
            #endif
            `;
    } else if (worldTangent.isConnected) {
      code += `${state._declareLocalVar("tbnNormal", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldNormalVarName}.xyz);
`;
      code += `${state._declareLocalVar("tbnTangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${worldTangent.associatedVariableName}.xyz);
`;
      code += `${state._declareLocalVar("tbnBitangent", NodeMaterialBlockConnectionPointTypes.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};
`;
      code += `${isWebGPU ? "var vTBN" : "mat3 vTBN"} = ${isWebGPU ? "mat3x3f" : "mat3"}(tbnTangent, tbnBitangent, tbnNormal);
`;
    }
    state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
      replaceStrings: [tangentReplaceString]
    });
    return code;
  }
  static _GetInitializationCode(state, ccBlock) {
    let code = "";
    const intensity = ccBlock?.intensity.isConnected ? ccBlock.intensity.associatedVariableName : "1.";
    const roughness = ccBlock?.roughness.isConnected ? ccBlock.roughness.associatedVariableName : "0.";
    const tintColor = ccBlock?.tintColor.isConnected ? ccBlock.tintColor.associatedVariableName : `vec3${state.fSuffix}(1.)`;
    const tintThickness = ccBlock?.tintThickness.isConnected ? ccBlock.tintThickness.associatedVariableName : "1.";
    code += `
            #ifdef CLEARCOAT
                ${state._declareLocalVar("vClearCoatParams", NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(${intensity}, ${roughness});
                ${state._declareLocalVar("vClearCoatTintParams", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${tintColor}, ${tintThickness});
            #endif
`;
    return code;
  }
  static GetCode(state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) {
    let code = "";
    const normalMapColor = ccBlock?.normalMapColor.isConnected ? ccBlock.normalMapColor.associatedVariableName : `vec3${state.fSuffix}(0.)`;
    const uv = ccBlock?.uv.isConnected ? ccBlock.uv.associatedVariableName : `vec2${state.fSuffix}(0.)`;
    const tintAtDistance = ccBlock?.tintAtDistance.isConnected ? ccBlock.tintAtDistance.associatedVariableName : "1.";
    const tintTexture = `vec4${state.fSuffix}(0.)`;
    if (ccBlock) {
      state._emitUniformFromString("vClearCoatRefractionParams", NodeMaterialBlockConnectionPointTypes.Vector4);
      state._emitUniformFromString("vClearCoatTangentSpaceParams", NodeMaterialBlockConnectionPointTypes.Vector2);
      const normalShading = ccBlock.worldNormal;
      code += `${state._declareLocalVar("vGeometricNormaClearCoatW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};
`;
    } else {
      code += `${state._declareLocalVar("vGeometricNormaClearCoatW", NodeMaterialBlockConnectionPointTypes.Vector3)} = geometricNormalW;
`;
    }
    if (generateTBNSpace && ccBlock) {
      code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName);
      vTBNAvailable = ccBlock.worldTangent.isConnected;
    }
    const isWebGPU = state.shaderLanguage === 1;
    code += `${isWebGPU ? "var clearcoatOut: clearcoatOutParams" : "clearcoatOutParams clearcoatOut"};

        #ifdef CLEARCOAT
            clearcoatOut = clearcoatBlock(
                ${worldPosVarName}.xyz
                , vGeometricNormaClearCoatW
                , viewDirectionW
                , vClearCoatParams
                , specularEnvironmentR0
            #ifdef CLEARCOAT_TEXTURE
                , vec2${state.fSuffix}(0.)
            #endif
            #ifdef CLEARCOAT_TINT
                , vClearCoatTintParams
                , ${tintAtDistance}
                , ${isWebGPU ? "uniforms." : ""}vClearCoatRefractionParams
                #ifdef CLEARCOAT_TINT_TEXTURE
                    , ${tintTexture}
                #endif
            #endif
            #ifdef CLEARCOAT_BUMP
                , vec2${state.fSuffix}(0., 1.)
                , vec4${state.fSuffix}(${normalMapColor}, 0.)
                , ${uv}
                #if defined(${vTBNAvailable ? "TANGENT" : "IGNORE"}) && defined(NORMAL)
                    , vTBN
                #else
                    , ${isWebGPU ? "uniforms." : ""}vClearCoatTangentSpaceParams
                #endif
                #ifdef OBJECTSPACE_NORMALMAP
                    , normalMatrix
                #endif
            #endif
            #if defined(FORCENORMALFORWARD) && defined(NORMAL)
                , faceNormal
            #endif
            #ifdef REFLECTION
                , ${isWebGPU ? "uniforms." : ""}${reflectionBlock?._vReflectionMicrosurfaceInfosName}
                , ${reflectionBlock?._vReflectionInfosName}
                , ${reflectionBlock?.reflectionColor}
                , ${isWebGPU ? "uniforms." : ""}vLightingIntensity
                #ifdef ${reflectionBlock?._define3DName}
                    , ${reflectionBlock?._cubeSamplerName}       
                    ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                #else
                    , ${reflectionBlock?._2DSamplerName}       
                    ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${reflectionBlock?._define3DName}
                        , ${reflectionBlock?._cubeSamplerName}       
                        ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                        , ${reflectionBlock?._cubeSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                    #else
                        , ${reflectionBlock?._2DSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}
                        , ${reflectionBlock?._2DSamplerName}
                        ${isWebGPU ? `, ${reflectionBlock?._2DSamplerName}Sampler` : ""}                        
                    #endif
                #endif
            #endif
            #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)
                , (${state._generateTernary("1.", "-1.", isWebGPU ? "fragmentInputs.frontFacing" : "gl_FrontFacing")})
            #endif
            );
        #else
            clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;
        #endif
`;
    return code;
  }
  _buildBlock(state) {
    this._scene = state.sharedData.scene;
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.bindableBlocks.push(this);
      state.sharedData.blocksWithDefines.push(this);
      this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor");
      state._emitUniformFromString(this._tangentCorrectionFactorName, NodeMaterialBlockConnectionPointTypes.Float);
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.remapF0OnInterfaceChange = serializationObject.remapF0OnInterfaceChange ?? true;
  }
}
__decorate([
  editableInPropertyPage("Remap F0 on interface change", 0, "ADVANCED", { embedded: true })
], ClearCoatBlock.prototype, "remapF0OnInterfaceChange", undefined);
RegisterClass("BABYLON.ClearCoatBlock", ClearCoatBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/iridescenceBlock.js
init_typeStore();
class IridescenceBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this._isUnique = true;
    this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, 1, IridescenceBlock, "IridescenceBlock"));
  }
  initialize(state) {
    state._excludeVariableName("iridescenceOut");
    state._excludeVariableName("vIridescenceParams");
  }
  getClassName() {
    return "IridescenceBlock";
  }
  get intensity() {
    return this._inputs[0];
  }
  get indexOfRefraction() {
    return this._inputs[1];
  }
  get thickness() {
    return this._inputs[2];
  }
  get iridescence() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.intensity.isConnected) {
      const intensityInput = new InputBlock("Iridescence intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      intensityInput.value = 1;
      intensityInput.output.connectTo(this.intensity);
      const indexOfRefractionInput = new InputBlock("Iridescence ior", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      indexOfRefractionInput.value = 1.3;
      indexOfRefractionInput.output.connectTo(this.indexOfRefraction);
      const thicknessInput = new InputBlock("Iridescence thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      thicknessInput.value = 400;
      thicknessInput.output.connectTo(this.thickness);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    defines.setValue("IRIDESCENCE", true, true);
    defines.setValue("IRIDESCENCE_TEXTURE", false, true);
    defines.setValue("IRIDESCENCE_THICKNESS_TEXTURE", false, true);
  }
  static GetCode(iridescenceBlock, state) {
    let code = "";
    const intensityName = iridescenceBlock?.intensity.isConnected ? iridescenceBlock.intensity.associatedVariableName : "1.";
    const indexOfRefraction = iridescenceBlock?.indexOfRefraction.isConnected ? iridescenceBlock.indexOfRefraction.associatedVariableName : PBRIridescenceConfiguration._DefaultIndexOfRefraction;
    const thickness = iridescenceBlock?.thickness.isConnected ? iridescenceBlock.thickness.associatedVariableName : PBRIridescenceConfiguration._DefaultMaximumThickness;
    const isWebGPU = state.shaderLanguage === 1;
    code += `${isWebGPU ? "var iridescenceOut: iridescenceOutParams" : "iridescenceOutParams iridescenceOut"};

        #ifdef IRIDESCENCE
            iridescenceOut = iridescenceBlock(
                vec4(${intensityName}, ${indexOfRefraction}, 1., ${thickness})
                , NdotV
                , specularEnvironmentR0
                #ifdef CLEARCOAT
                    , NdotVUnclamped
                    , vClearCoatParams
                #endif                
            );

            ${isWebGPU ? "let" : "float"} iridescenceIntensity = iridescenceOut.iridescenceIntensity;
            specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;
        #endif
`;
    return code;
  }
  _buildBlock(state) {
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.bindableBlocks.push(this);
      state.sharedData.blocksWithDefines.push(this);
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
  }
}
RegisterClass("BABYLON.IridescenceBlock", IridescenceBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/subSurfaceBlock.js
init_typeStore();

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/refractionBlock.js
init_tslib_es6();
init_typeStore();
init_texture();
class RefractionBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this.linkRefractionWithTransparency = false;
    this.invertRefractionY = false;
    this.useThicknessAsDepth = false;
    this._isUnique = true;
    this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("volumeIndexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, 1, RefractionBlock, "RefractionBlock"));
  }
  initialize(state) {
    state._excludeVariableName("vRefractionPosition");
    state._excludeVariableName("vRefractionSize");
  }
  getClassName() {
    return "RefractionBlock";
  }
  get intensity() {
    return this._inputs[0];
  }
  get tintAtDistance() {
    return this._inputs[1];
  }
  get volumeIndexOfRefraction() {
    return this._inputs[2];
  }
  get view() {
    return this.viewConnectionPoint;
  }
  get refraction() {
    return this._outputs[0];
  }
  get hasTexture() {
    return !!this._getTexture();
  }
  _getTexture() {
    if (this.texture) {
      return this.texture;
    }
    return this._scene.environmentTexture;
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.intensity.isConnected) {
      const intensityInput = new InputBlock("Refraction intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      intensityInput.value = 1;
      intensityInput.output.connectTo(this.intensity);
    }
    if (this.view && !this.view.isConnected) {
      let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b));
      if (!viewInput) {
        viewInput = new InputBlock("view");
        viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
      }
      viewInput.output.connectTo(this.view);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    const refractionTexture2 = this._getTexture();
    const refraction = refractionTexture2 && refractionTexture2.getTextureMatrix;
    defines.setValue("SS_REFRACTION", refraction, true);
    if (!refraction) {
      return;
    }
    defines.setValue(this._define3DName, refractionTexture2.isCube, true);
    defines.setValue(this._defineLODRefractionAlpha, refractionTexture2.lodLevelInAlpha, true);
    defines.setValue(this._defineLinearSpecularRefraction, refractionTexture2.linearSpecularLOD, true);
    defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem && refractionTexture2.isCube ? !refractionTexture2.invertZ : refractionTexture2.invertZ, true);
    defines.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, true);
    defines.setValue("SS_GAMMAREFRACTION", refractionTexture2.gammaSpace, true);
    defines.setValue("SS_RGBDREFRACTION", refractionTexture2.isRGBD, true);
    defines.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC", refractionTexture2.boundingBoxSize ? true : false, true);
    defines.setValue("SS_USE_THICKNESS_AS_DEPTH", this.useThicknessAsDepth, true);
  }
  isReady() {
    const texture2 = this._getTexture();
    if (texture2 && !texture2.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  bind(effect, nodeMaterial, mesh) {
    super.bind(effect, nodeMaterial, mesh);
    const refractionTexture2 = this._getTexture();
    if (!refractionTexture2) {
      return;
    }
    if (refractionTexture2.isCube) {
      effect.setTexture(this._cubeSamplerName, refractionTexture2);
    } else {
      effect.setTexture(this._2DSamplerName, refractionTexture2);
    }
    effect.setMatrix(this._refractionMatrixName, refractionTexture2.getRefractionTextureMatrix());
    let depth = 1;
    if (!refractionTexture2.isCube) {
      if (refractionTexture2.depth) {
        depth = refractionTexture2.depth;
      }
    }
    const indexOfRefraction = this.volumeIndexOfRefraction.connectInputBlock?.value ?? this.indexOfRefractionConnectionPoint.connectInputBlock?.value ?? 1.5;
    effect.setFloat4(this._vRefractionInfosName, refractionTexture2.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
    effect.setFloat4(this._vRefractionMicrosurfaceInfosName, refractionTexture2.getSize().width, refractionTexture2.lodGenerationScale, refractionTexture2.lodGenerationOffset, 1 / indexOfRefraction);
    const width = refractionTexture2.getSize().width;
    effect.setFloat2(this._vRefractionFilteringInfoName, width, Math.log2(width));
    if (refractionTexture2.boundingBoxSize) {
      const cubeTexture2 = refractionTexture2;
      effect.setVector3("vRefractionPosition", cubeTexture2.boundingBoxPosition);
      effect.setVector3("vRefractionSize", cubeTexture2.boundingBoxSize);
    }
  }
  getCode(state) {
    const code = "";
    state.sharedData.blockingBlocks.push(this);
    state.sharedData.textureBlocks.push(this);
    this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
    state.samplers.push(this._cubeSamplerName);
    this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
    state.samplers.push(this._2DSamplerName);
    this._define3DName = state._getFreeDefineName("SS_REFRACTIONMAP_3D");
    const refractionTexture2 = this._getTexture();
    if (refractionTexture2) {
      state._samplerDeclaration += `#ifdef ${this._define3DName}
`;
      state._emitCubeSampler(this._cubeSamplerName, undefined, true);
      state._samplerDeclaration += `#else
`;
      state._emit2DSampler(this._2DSamplerName, undefined, true);
      state._samplerDeclaration += `#endif
`;
    }
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.bindableBlocks.push(this);
    this._defineLODRefractionAlpha = state._getFreeDefineName("SS_LODINREFRACTIONALPHA");
    this._defineLinearSpecularRefraction = state._getFreeDefineName("SS_LINEARSPECULARREFRACTION");
    this._defineOppositeZ = state._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ");
    this._refractionMatrixName = state._getFreeVariableName("refractionMatrix");
    state._emitUniformFromString(this._refractionMatrixName, NodeMaterialBlockConnectionPointTypes.Matrix);
    if (state.shaderLanguage !== 1) {
      state._emitFunction("sampleRefraction", `
                #ifdef ${this._define3DName}
                    #define sampleRefraction(s, c) textureCube(s, c)
                #else
                    #define sampleRefraction(s, c) texture2D(s, c)
                #endif
`, `//${this.name}`);
      state._emitFunction("sampleRefractionLod", `
                #ifdef ${this._define3DName}
                    #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)
                #else
                    #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)
                #endif
`, `//${this.name}`);
    }
    this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName("vRefractionMicrosurfaceInfos");
    state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, NodeMaterialBlockConnectionPointTypes.Vector4);
    this._vRefractionInfosName = state._getFreeVariableName("vRefractionInfos");
    state._emitUniformFromString(this._vRefractionInfosName, NodeMaterialBlockConnectionPointTypes.Vector4);
    this._vRefractionFilteringInfoName = state._getFreeVariableName("vRefractionFilteringInfo");
    state._emitUniformFromString(this._vRefractionFilteringInfoName, NodeMaterialBlockConnectionPointTypes.Vector2);
    state._emitUniformFromString("vRefractionPosition", NodeMaterialBlockConnectionPointTypes.Vector3);
    state._emitUniformFromString("vRefractionSize", NodeMaterialBlockConnectionPointTypes.Vector3);
    return code;
  }
  _buildBlock(state) {
    this._scene = state.sharedData.scene;
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (this.texture) {
      if (this.texture.isCube) {
        codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");
`;
      } else {
        codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");
`;
      }
      codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`;
    }
    codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};
`;
    codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};
`;
    codeString += `${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    if (this.texture && !this.texture.isRenderTarget) {
      serializationObject.texture = this.texture.serialize();
    }
    serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;
    serializationObject.invertRefractionY = this.invertRefractionY;
    serializationObject.useThicknessAsDepth = this.useThicknessAsDepth;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    if (serializationObject.texture) {
      rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
      if (serializationObject.texture.isCube) {
        this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);
      } else {
        this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
      }
    }
    this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency;
    this.invertRefractionY = serializationObject.invertRefractionY;
    this.useThicknessAsDepth = !!serializationObject.useThicknessAsDepth;
  }
}
__decorate([
  editableInPropertyPage("Link refraction to transparency", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], RefractionBlock.prototype, "linkRefractionWithTransparency", undefined);
__decorate([
  editableInPropertyPage("Invert refraction Y", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], RefractionBlock.prototype, "invertRefractionY", undefined);
__decorate([
  editableInPropertyPage("Use thickness as depth", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], RefractionBlock.prototype, "useThicknessAsDepth", undefined);
RegisterClass("BABYLON.RefractionBlock", RefractionBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/subSurfaceBlock.js
class SubSurfaceBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Fragment);
    this._isUnique = true;
    this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("translucencyIntensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("translucencyDiffusionDist", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("refraction", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, 0, RefractionBlock, "RefractionBlock"));
    this.registerInput("dispersion", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, 1, SubSurfaceBlock, "SubSurfaceBlock"));
  }
  initialize(state) {
    state._excludeVariableName("subSurfaceOut");
    state._excludeVariableName("vThicknessParam");
    state._excludeVariableName("vTintColor");
    state._excludeVariableName("vTranslucencyColor");
    state._excludeVariableName("vSubSurfaceIntensity");
    state._excludeVariableName("dispersion");
  }
  getClassName() {
    return "SubSurfaceBlock";
  }
  get thickness() {
    return this._inputs[0];
  }
  get tintColor() {
    return this._inputs[1];
  }
  get translucencyIntensity() {
    return this._inputs[2];
  }
  get translucencyDiffusionDist() {
    return this._inputs[3];
  }
  get refraction() {
    return this._inputs[4];
  }
  get dispersion() {
    return this._inputs[5];
  }
  get subsurface() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.thickness.isConnected) {
      const thicknessInput = new InputBlock("SubSurface thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);
      thicknessInput.value = 0;
      thicknessInput.output.connectTo(this.thickness);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    super.prepareDefines(mesh, nodeMaterial, defines);
    const translucencyEnabled = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected;
    defines.setValue("SUBSURFACE", translucencyEnabled || this.refraction.isConnected, true);
    defines.setValue("SS_TRANSLUCENCY", translucencyEnabled, true);
    defines.setValue("SS_THICKNESSANDMASK_TEXTURE", false, true);
    defines.setValue("SS_REFRACTIONINTENSITY_TEXTURE", false, true);
    defines.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE", false, true);
    defines.setValue("SS_USE_GLTF_TEXTURES", false, true);
    defines.setValue("SS_DISPERSION", this.dispersion.isConnected, true);
  }
  static GetCode(state, ssBlock, reflectionBlock, worldPosVarName) {
    let code = "";
    const thickness = ssBlock?.thickness.isConnected ? ssBlock.thickness.associatedVariableName : "0.";
    const tintColor = ssBlock?.tintColor.isConnected ? ssBlock.tintColor.associatedVariableName : "vec3(1.)";
    const translucencyIntensity = ssBlock?.translucencyIntensity.isConnected ? ssBlock?.translucencyIntensity.associatedVariableName : "1.";
    const translucencyDiffusionDistance = ssBlock?.translucencyDiffusionDist.isConnected ? ssBlock?.translucencyDiffusionDist.associatedVariableName : "vec3(1.)";
    const refractionBlock = ssBlock?.refraction.isConnected ? ssBlock?.refraction.connectedPoint?.ownerBlock : null;
    const refractionTintAtDistance = refractionBlock?.tintAtDistance.isConnected ? refractionBlock.tintAtDistance.associatedVariableName : "1.";
    const refractionIntensity = refractionBlock?.intensity.isConnected ? refractionBlock.intensity.associatedVariableName : "1.";
    const refractionView = refractionBlock?.view.isConnected ? refractionBlock.view.associatedVariableName : "";
    const dispersion = ssBlock?.dispersion.isConnected ? ssBlock?.dispersion.associatedVariableName : "0.0";
    const isWebGPU = state.shaderLanguage === 1;
    code += refractionBlock?.getCode(state) ?? "";
    code += `${isWebGPU ? "var subSurfaceOut: subSurfaceOutParams" : "subSurfaceOutParams subSurfaceOut"};

        #ifdef SUBSURFACE
            ${state._declareLocalVar("vThicknessParam", NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${state.fSuffix}(0., ${thickness});
            ${state._declareLocalVar("vTintColor", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}(${tintColor}, ${refractionTintAtDistance});
            ${state._declareLocalVar("vSubSurfaceIntensity", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3(${refractionIntensity}, ${translucencyIntensity}, 0.);
            ${state._declareLocalVar("dispersion", NodeMaterialBlockConnectionPointTypes.Float)} = ${dispersion};
            subSurfaceOut = subSurfaceBlock(
                vSubSurfaceIntensity
                , vThicknessParam
                , vTintColor
                , normalW
                , specularEnvironmentReflectance
            #ifdef SS_THICKNESSANDMASK_TEXTURE
                , vec4${state.fSuffix}(0.)
            #endif
            #ifdef REFLECTION
                #ifdef SS_TRANSLUCENCY
                    , ${(isWebGPU ? "uniforms." : "") + reflectionBlock?._reflectionMatrixName}
                    #ifdef USESPHERICALFROMREFLECTIONMAP
                        #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)
                            , reflectionOut.irradianceVector
                        #endif
                        #if defined(REALTIME_FILTERING)
                            , ${reflectionBlock?._cubeSamplerName}
                            ${isWebGPU ? `, ${reflectionBlock?._cubeSamplerName}Sampler` : ""}
                            , ${reflectionBlock?._vReflectionFilteringInfoName}
                        #endif
                        #endif
                    #ifdef USEIRRADIANCEMAP
                        , irradianceSampler
                        ${isWebGPU ? `, irradianceSamplerSampler` : ""}
                    #endif
                #endif
            #endif
            #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)
                , surfaceAlbedo
            #endif
            #ifdef SS_REFRACTION
                , ${worldPosVarName}.xyz
                , viewDirectionW
                , ${refractionView}
                , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._vRefractionInfosName ?? "")}
                , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._refractionMatrixName ?? "")}
                , ${(isWebGPU ? "uniforms." : "") + (refractionBlock?._vRefractionMicrosurfaceInfosName ?? "")}
                , ${isWebGPU ? "uniforms." : ""}vLightingIntensity
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    , alpha
                #endif
                #ifdef ${refractionBlock?._defineLODRefractionAlpha ?? "IGNORE"}
                    , NdotVUnclamped
                #endif
                #ifdef ${refractionBlock?._defineLinearSpecularRefraction ?? "IGNORE"}
                    , roughness
                #endif
                , alphaG
                #ifdef ${refractionBlock?._define3DName ?? "IGNORE"}
                    , ${refractionBlock?._cubeSamplerName ?? ""}
                    ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""}
                #else
                    , ${refractionBlock?._2DSamplerName ?? ""}
                    ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""}
                #endif
                #ifndef LODBASEDMICROSFURACE
                    #ifdef ${refractionBlock?._define3DName ?? "IGNORE"}
                        , ${refractionBlock?._cubeSamplerName ?? ""}                        
                        ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""}
                        , ${refractionBlock?._cubeSamplerName ?? ""}                        
                        ${isWebGPU ? `, ${refractionBlock?._cubeSamplerName}Sampler` : ""}
                    #else
                        , ${refractionBlock?._2DSamplerName ?? ""}
                        ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""}
                        , ${refractionBlock?._2DSamplerName ?? ""}
                        ${isWebGPU ? `, ${refractionBlock?._2DSamplerName}Sampler` : ""}
                    #endif
                #endif
                #ifdef ANISOTROPIC
                    , anisotropicOut
                #endif
                #ifdef REALTIME_FILTERING
                    , ${refractionBlock?._vRefractionFilteringInfoName ?? ""}
                #endif
                #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC
                    , vRefractionPosition
                    , vRefractionSize
                #endif
                #ifdef SS_DISPERSION
                    , dispersion
                #endif
            #endif
            #ifdef SS_TRANSLUCENCY
                , ${translucencyDiffusionDistance}
                , vTintColor
                #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE
                    , vec4${state.fSuffix}(0.)
                #endif
            #endif                
            );

            #ifdef SS_REFRACTION
                surfaceAlbedo = subSurfaceOut.surfaceAlbedo;
                #ifdef SS_LINKREFRACTIONTOTRANSPARENCY
                    alpha = subSurfaceOut.alpha;
                #endif
            #endif
        #else
            subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;
        #endif
`;
    return code;
  }
  _buildBlock(state) {
    if (state.target === NodeMaterialBlockTargets.Fragment) {
      state.sharedData.blocksWithDefines.push(this);
    }
    return this;
  }
}
RegisterClass("BABYLON.SubSurfaceBlock", SubSurfaceBlock);

// node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.js
init_math_color();
init_logger();
init_materialHelper_functions();
var mapOutputToVariable = {
  ambientClr: ["finalAmbient", ""],
  diffuseDir: ["finalDiffuse", ""],
  specularDir: ["finalSpecularScaled", "!defined(UNLIT) && defined(SPECULARTERM)"],
  clearcoatDir: ["finalClearCoatScaled", "!defined(UNLIT) && defined(CLEARCOAT)"],
  sheenDir: ["finalSheenScaled", "!defined(UNLIT) && defined(SHEEN)"],
  diffuseInd: ["finalIrradiance", "!defined(UNLIT) && defined(REFLECTION)"],
  specularInd: ["finalRadianceScaled", "!defined(UNLIT) && defined(REFLECTION)"],
  clearcoatInd: ["clearcoatOut.finalClearCoatRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],
  sheenInd: ["sheenOut.finalSheenRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],
  refraction: ["subSurfaceOut.finalRefraction", "!defined(UNLIT) && defined(SS_REFRACTION)"],
  lighting: ["finalColor.rgb", ""],
  shadow: ["aggShadow", ""],
  alpha: ["alpha", ""]
};

class PBRMetallicRoughnessBlock extends NodeMaterialBlock {
  static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {
    const that = block;
    if (that.worldPosition.isConnected || that.worldNormal.isConnected) {
      that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;
      Logger.Error("The worldPosition and worldNormal inputs must not be connected to be able to switch!");
      return false;
    }
    that._setTarget();
    return true;
  }
  _setTarget() {
    this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);
    this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
    this.getInputByName("worldNormal").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;
  }
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.VertexAndFragment);
    this._environmentBRDFTexture = null;
    this._metallicReflectanceColor = Color3.White();
    this._metallicF0Factor = 1;
    this.directIntensity = 1;
    this.environmentIntensity = 1;
    this.specularIntensity = 1;
    this.lightFalloff = 0;
    this.useAlphaTest = false;
    this.alphaTestCutoff = 0.5;
    this.useAlphaBlending = false;
    this.useRadianceOverAlpha = true;
    this.useSpecularOverAlpha = true;
    this.enableSpecularAntiAliasing = false;
    this.realTimeFiltering = false;
    this.realTimeFilteringQuality = 8;
    this.useEnergyConservation = true;
    this.useRadianceOcclusion = true;
    this.useHorizonOcclusion = true;
    this.unlit = false;
    this.forceNormalForward = false;
    this.generateOnlyFragmentCode = false;
    this.debugMode = 0;
    this.debugLimit = 0;
    this.debugFactor = 1;
    this._isUnique = true;
    this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);
    this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false);
    this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("perturbedNormal", NodeMaterialBlockConnectionPointTypes.Vector4, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("baseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("metallic", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);
    this.registerInput("ambientOcc", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("opacity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("ambientColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);
    this.registerInput("reflection", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, 0, ReflectionBlock, "ReflectionBlock"));
    this.registerInput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, 0, ClearCoatBlock, "ClearCoatBlock"));
    this.registerInput("sheen", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, 0, SheenBlock, "SheenBlock"));
    this.registerInput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, 0, SubSurfaceBlock, "SubSurfaceBlock"));
    this.registerInput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, 0, AnisotropyBlock, "AnisotropyBlock"));
    this.registerInput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, 0, IridescenceBlock, "IridescenceBlock"));
    this.registerOutput("ambientClr", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("diffuseDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("specularDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("clearcoatDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("sheenDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("diffuseInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("specularInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("clearcoatInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("sheenInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("lighting", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("alpha", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
  }
  initialize(state) {
    state._excludeVariableName("vLightingIntensity");
    state._excludeVariableName("geometricNormalW");
    state._excludeVariableName("normalW");
    state._excludeVariableName("faceNormal");
    state._excludeVariableName("albedoOpacityOut");
    state._excludeVariableName("surfaceAlbedo");
    state._excludeVariableName("alpha");
    state._excludeVariableName("aoOut");
    state._excludeVariableName("baseColor");
    state._excludeVariableName("reflectivityOut");
    state._excludeVariableName("microSurface");
    state._excludeVariableName("roughness");
    state._excludeVariableName("NdotVUnclamped");
    state._excludeVariableName("NdotV");
    state._excludeVariableName("alphaG");
    state._excludeVariableName("AARoughnessFactors");
    state._excludeVariableName("environmentBrdf");
    state._excludeVariableName("ambientMonochrome");
    state._excludeVariableName("seo");
    state._excludeVariableName("eho");
    state._excludeVariableName("environmentRadiance");
    state._excludeVariableName("irradianceVector");
    state._excludeVariableName("environmentIrradiance");
    state._excludeVariableName("diffuseBase");
    state._excludeVariableName("specularBase");
    state._excludeVariableName("preInfo");
    state._excludeVariableName("info");
    state._excludeVariableName("shadow");
    state._excludeVariableName("finalDiffuse");
    state._excludeVariableName("finalAmbient");
    state._excludeVariableName("ambientOcclusionForDirectDiffuse");
    state._excludeVariableName("finalColor");
    state._excludeVariableName("vClipSpacePosition");
    state._excludeVariableName("vDebugMode");
    this._initShaderSourceAsync(state.shaderLanguage);
  }
  async _initShaderSourceAsync(shaderLanguage) {
    this._codeIsReady = false;
    if (shaderLanguage === 1) {
      await Promise.all([Promise.resolve().then(() => (init_pbr_vertex(), exports_pbr_vertex)), Promise.resolve().then(() => (init_pbr_fragment(), exports_pbr_fragment))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_pbr_vertex2(), exports_pbr_vertex2)), Promise.resolve().then(() => (init_pbr_fragment2(), exports_pbr_fragment2))]);
    }
    this._codeIsReady = true;
    this.onCodeIsReadyObservable.notifyObservers(this);
  }
  getClassName() {
    return "PBRMetallicRoughnessBlock";
  }
  get worldPosition() {
    return this._inputs[0];
  }
  get worldNormal() {
    return this._inputs[1];
  }
  get view() {
    return this._inputs[2];
  }
  get cameraPosition() {
    return this._inputs[3];
  }
  get perturbedNormal() {
    return this._inputs[4];
  }
  get baseColor() {
    return this._inputs[5];
  }
  get metallic() {
    return this._inputs[6];
  }
  get roughness() {
    return this._inputs[7];
  }
  get ambientOcc() {
    return this._inputs[8];
  }
  get opacity() {
    return this._inputs[9];
  }
  get indexOfRefraction() {
    return this._inputs[10];
  }
  get ambientColor() {
    return this._inputs[11];
  }
  get reflection() {
    return this._inputs[12];
  }
  get clearcoat() {
    return this._inputs[13];
  }
  get sheen() {
    return this._inputs[14];
  }
  get subsurface() {
    return this._inputs[15];
  }
  get anisotropy() {
    return this._inputs[16];
  }
  get iridescence() {
    return this._inputs[17];
  }
  get ambientClr() {
    return this._outputs[0];
  }
  get diffuseDir() {
    return this._outputs[1];
  }
  get specularDir() {
    return this._outputs[2];
  }
  get clearcoatDir() {
    return this._outputs[3];
  }
  get sheenDir() {
    return this._outputs[4];
  }
  get diffuseInd() {
    return this._outputs[5];
  }
  get specularInd() {
    return this._outputs[6];
  }
  get clearcoatInd() {
    return this._outputs[7];
  }
  get sheenInd() {
    return this._outputs[8];
  }
  get refraction() {
    return this._outputs[9];
  }
  get lighting() {
    return this._outputs[10];
  }
  get shadow() {
    return this._outputs[11];
  }
  get alpha() {
    return this._outputs[12];
  }
  autoConfigure(material, additionalFilteringInfo = () => true) {
    if (!this.cameraPosition.isConnected) {
      let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition && additionalFilteringInfo(b));
      if (!cameraPositionInput) {
        cameraPositionInput = new InputBlock("cameraPosition");
        cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);
      }
      cameraPositionInput.output.connectTo(this.cameraPosition);
    }
    if (!this.view.isConnected) {
      let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View && additionalFilteringInfo(b));
      if (!viewInput) {
        viewInput = new InputBlock("view");
        viewInput.setAsSystemValue(NodeMaterialSystemValues.View);
      }
      viewInput.output.connectTo(this.view);
    }
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    defines.setValue("PBR", true);
    defines.setValue("METALLICWORKFLOW", true);
    defines.setValue("DEBUGMODE", this.debugMode, true);
    defines.setValue("DEBUGMODE_FORCERETURN", true);
    defines.setValue("NORMALXYSCALE", true);
    defines.setValue("BUMP", this.perturbedNormal.isConnected, true);
    defines.setValue("LODBASEDMICROSFURACE", this._scene.getEngine().getCaps().textureLOD);
    defines.setValue("ALBEDO", false, true);
    defines.setValue("OPACITY", this.opacity.isConnected, true);
    defines.setValue("AMBIENT", true, true);
    defines.setValue("AMBIENTINGRAYSCALE", false, true);
    defines.setValue("REFLECTIVITY", false, true);
    defines.setValue("AOSTOREINMETALMAPRED", false, true);
    defines.setValue("METALLNESSSTOREINMETALMAPBLUE", false, true);
    defines.setValue("ROUGHNESSSTOREINMETALMAPALPHA", false, true);
    defines.setValue("ROUGHNESSSTOREINMETALMAPGREEN", false, true);
    if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
      defines.setValue("USEPHYSICALLIGHTFALLOFF", false);
      defines.setValue("USEGLTFLIGHTFALLOFF", false);
    } else if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
      defines.setValue("USEPHYSICALLIGHTFALLOFF", false);
      defines.setValue("USEGLTFLIGHTFALLOFF", true);
    } else {
      defines.setValue("USEPHYSICALLIGHTFALLOFF", true);
      defines.setValue("USEGLTFLIGHTFALLOFF", false);
    }
    const alphaTestCutOffString = this.alphaTestCutoff.toString();
    defines.setValue("ALPHABLEND", this.useAlphaBlending, true);
    defines.setValue("ALPHAFROMALBEDO", false, true);
    defines.setValue("ALPHATEST", this.useAlphaTest, true);
    defines.setValue("ALPHATESTVALUE", alphaTestCutOffString.indexOf(".") < 0 ? alphaTestCutOffString + "." : alphaTestCutOffString, true);
    defines.setValue("OPACITYRGB", false, true);
    defines.setValue("RADIANCEOVERALPHA", this.useRadianceOverAlpha, true);
    defines.setValue("SPECULAROVERALPHA", this.useSpecularOverAlpha, true);
    defines.setValue("SPECULARAA", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true);
    defines.setValue("REALTIME_FILTERING", this.realTimeFiltering, true);
    const scene = mesh.getScene();
    const engine2 = scene.getEngine();
    if (engine2._features.needTypeSuffixInShaderConstants) {
      defines.setValue("NUM_SAMPLES", this.realTimeFilteringQuality + "u", true);
    } else {
      defines.setValue("NUM_SAMPLES", "" + this.realTimeFilteringQuality, true);
    }
    defines.setValue("BRDF_V_HEIGHT_CORRELATED", true);
    defines.setValue("MS_BRDF_ENERGY_CONSERVATION", this.useEnergyConservation, true);
    defines.setValue("RADIANCEOCCLUSION", this.useRadianceOcclusion, true);
    defines.setValue("HORIZONOCCLUSION", this.useHorizonOcclusion, true);
    defines.setValue("UNLIT", this.unlit, true);
    defines.setValue("FORCENORMALFORWARD", this.forceNormalForward, true);
    if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {
      defines.setValue("ENVIRONMENTBRDF", true);
      defines.setValue("ENVIRONMENTBRDF_RGBD", this._environmentBRDFTexture.isRGBD, true);
    } else {
      defines.setValue("ENVIRONMENTBRDF", false);
      defines.setValue("ENVIRONMENTBRDF_RGBD", false);
    }
    if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
      nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);
    }
    if (!defines._areLightsDirty) {
      return;
    }
    if (!this.light) {
      PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);
      defines._needNormals = true;
      PrepareDefinesForMultiview(scene, defines);
    } else {
      const state = {
        needNormals: false,
        needRebuild: false,
        lightmapMode: false,
        shadowEnabled: false,
        specularEnabled: false
      };
      PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);
      if (state.needRebuild) {
        defines.rebuild();
      }
    }
  }
  updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {
    for (let lightIndex = 0;lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {
      if (!defines["LIGHT" + lightIndex]) {
        break;
      }
      const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0;
      PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList, defines["IESLIGHTTEXTURE" + lightIndex]);
    }
  }
  isReady(mesh, nodeMaterial, defines) {
    if (this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady()) {
      return false;
    }
    if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
      if (!nodeMaterial.imageProcessingConfiguration.isReady()) {
        return false;
      }
    }
    return true;
  }
  bind(effect, nodeMaterial, mesh) {
    if (!mesh) {
      return;
    }
    const scene = mesh.getScene();
    if (!this.light) {
      BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);
    } else {
      BindLight(this.light, this._lightId, scene, effect, true);
    }
    effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture);
    effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor);
    const ambientScene = this._scene.ambientColor;
    if (ambientScene) {
      effect.setColor3("ambientFromScene", ambientScene);
    }
    const invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null);
    effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1);
    effect.setFloat4("vLightingIntensity", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity);
    const outsideIOR = 1;
    const ior = this.indexOfRefraction.connectInputBlock?.value ?? 1.5;
    const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);
    this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);
    const metallicF90 = this._metallicF0Factor;
    effect.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], metallicF90);
    if (nodeMaterial.imageProcessingConfiguration) {
      nodeMaterial.imageProcessingConfiguration.bind(effect);
    }
  }
  _injectVertexCode(state) {
    const worldPos = this.worldPosition;
    const worldNormal = this.worldNormal;
    const comments = `//${this.name}`;
    const isWebGPU = state.shaderLanguage === 1;
    if (!this.light) {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, {
        repeatKey: "maxSimultaneousLights"
      });
      this._lightId = 0;
      state.sharedData.dynamicUniformBlocks.push(this);
    } else {
      this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1;
      state.counters["lightCounter"] = this._lightId;
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, {
        replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
      }, this._lightId.toString());
    }
    const worldPosVaryingName = "v_" + worldPos.associatedVariableName;
    if (state._emitVaryingFromString(worldPosVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) {
      state.compilationString += (isWebGPU ? "vertexOutputs." : "") + `${worldPosVaryingName} = ${worldPos.associatedVariableName};
`;
    }
    const worldNormalVaryingName = "v_" + worldNormal.associatedVariableName;
    if (state._emitVaryingFromString(worldNormalVaryingName, NodeMaterialBlockConnectionPointTypes.Vector4)) {
      state.compilationString += (isWebGPU ? "vertexOutputs." : "") + `${worldNormalVaryingName} = ${worldNormal.associatedVariableName};
`;
    }
    const reflectionBlock = this.reflection.isConnected ? this.reflection.connectedPoint?.ownerBlock : null;
    if (reflectionBlock) {
      reflectionBlock.viewConnectionPoint = this.view;
    }
    state.compilationString += reflectionBlock?.handleVertexSide(state) ?? "";
    if (state._emitVaryingFromString("vClipSpacePosition", NodeMaterialBlockConnectionPointTypes.Vector4, "defined(IGNORE) || DEBUGMODE > 0")) {
      state._injectAtEnd += `#if DEBUGMODE > 0
`;
      state._injectAtEnd += (isWebGPU ? "vertexOutputs." : "") + `vClipSpacePosition = ${isWebGPU ? "vertexOutputs.position" : "gl_Position"};
`;
      state._injectAtEnd += `#endif
`;
    }
    if (this.light) {
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        replaceStrings: [
          { search: /{X}/g, replace: this._lightId.toString() },
          { search: /worldPos/g, replace: worldPos.associatedVariableName }
        ]
      });
    } else {
      state.compilationString += `${state._declareLocalVar("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4)} = ${worldPos.associatedVariableName};
`;
      if (this.view.isConnected) {
        state.compilationString += `${state._declareLocalVar("view", NodeMaterialBlockConnectionPointTypes.Matrix)} = ${this.view.associatedVariableName};
`;
      }
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        repeatKey: "maxSimultaneousLights"
      });
    }
  }
  _getAlbedoOpacityCode(state) {
    const isWebGPU = state.shaderLanguage === 1;
    let code = isWebGPU ? `var albedoOpacityOut: albedoOpacityOutParams;
` : `albedoOpacityOutParams albedoOpacityOut;
`;
    const albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : "vec3(1.)";
    const opacity = this.opacity.isConnected ? this.opacity.associatedVariableName : "1.";
    code += `albedoOpacityOut = albedoOpacityBlock(
                vec4${state.fSuffix}(${albedoColor}, 1.)
            #ifdef ALBEDO
                ,vec4${state.fSuffix}(1.)
                ,vec2${state.fSuffix}(1., 1.)
            #endif
                ,1. /* Base Weight */
            #ifdef OPACITY
                ,vec4${state.fSuffix}(${opacity})
                ,vec2${state.fSuffix}(1., 1.)
            #endif
            );

            ${state._declareLocalVar("surfaceAlbedo", NodeMaterialBlockConnectionPointTypes.Vector3)} = albedoOpacityOut.surfaceAlbedo;
            ${state._declareLocalVar("alpha", NodeMaterialBlockConnectionPointTypes.Float)} = albedoOpacityOut.alpha;
`;
    return code;
  }
  _getAmbientOcclusionCode(state) {
    const isWebGPU = state.shaderLanguage === 1;
    let code = isWebGPU ? `var aoOut: ambientOcclusionOutParams;
` : `ambientOcclusionOutParams aoOut;
`;
    const ao = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : "1.";
    code += `aoOut = ambientOcclusionBlock(
            #ifdef AMBIENT
                vec3${state.fSuffix}(${ao}),
                vec4${state.fSuffix}(0., 1.0, 1.0, 0.)
            #endif
            );
`;
    return code;
  }
  _getReflectivityCode(state) {
    const isWebGPU = state.shaderLanguage === 1;
    let code = isWebGPU ? `var reflectivityOut: reflectivityOutParams;
` : `reflectivityOutParams reflectivityOut;
`;
    const aoIntensity = "1.";
    this._vMetallicReflectanceFactorsName = state._getFreeVariableName("vMetallicReflectanceFactors");
    state._emitUniformFromString(this._vMetallicReflectanceFactorsName, NodeMaterialBlockConnectionPointTypes.Vector4);
    code += `${state._declareLocalVar("baseColor", NodeMaterialBlockConnectionPointTypes.Vector3)} = surfaceAlbedo;

            reflectivityOut = reflectivityBlock(
                vec4${state.fSuffix}(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.)
            #ifdef METALLICWORKFLOW
                , surfaceAlbedo
                , ${(isWebGPU ? "uniforms." : "") + this._vMetallicReflectanceFactorsName}
            #endif
            #ifdef REFLECTIVITY
                , vec3${state.fSuffix}(0., 0., ${aoIntensity})
                , vec4${state.fSuffix}(1.)
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY)  && defined(AOSTOREINMETALMAPRED)
                , aoOut.ambientOcclusionColor
            #endif
            #ifdef MICROSURFACEMAP
                , microSurfaceTexel <== not handled!
            #endif
            );

            ${state._declareLocalVar("microSurface", NodeMaterialBlockConnectionPointTypes.Float)} = reflectivityOut.microSurface;
            ${state._declareLocalVar("roughness", NodeMaterialBlockConnectionPointTypes.Float)} = reflectivityOut.roughness;

            #ifdef METALLICWORKFLOW
                surfaceAlbedo = reflectivityOut.surfaceAlbedo;
            #endif
            #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)
                aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;
            #endif
`;
    return code;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this._scene = state.sharedData.scene;
    const isWebGPU = state.shaderLanguage === 1;
    if (!this._environmentBRDFTexture) {
      this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene);
    }
    const reflectionBlock = this.reflection.isConnected ? this.reflection.connectedPoint?.ownerBlock : null;
    if (reflectionBlock) {
      reflectionBlock.worldPositionConnectionPoint = this.worldPosition;
      reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition;
      reflectionBlock.worldNormalConnectionPoint = this.worldNormal;
      reflectionBlock.viewConnectionPoint = this.view;
    }
    if (state.target !== NodeMaterialBlockTargets.Fragment) {
      this._injectVertexCode(state);
      return this;
    }
    state.sharedData.forcedBindableBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.blockingBlocks.push(this);
    if (this.generateOnlyFragmentCode) {
      state.sharedData.dynamicUniformBlocks.push(this);
    }
    const comments = `//${this.name}`;
    const normalShading = this.perturbedNormal;
    let worldPosVarName = this.worldPosition.associatedVariableName;
    let worldNormalVarName = this.worldNormal.associatedVariableName;
    if (this.generateOnlyFragmentCode) {
      worldPosVarName = state._getFreeVariableName("globalWorldPos");
      state._emitFunction("pbr_globalworldpos", isWebGPU ? `var<private> ${worldPosVarName}:vec3${state.fSuffix};
` : `vec3${state.fSuffix} ${worldPosVarName};
`, comments);
      state.compilationString += `${worldPosVarName} = ${this.worldPosition.associatedVariableName}.xyz;
`;
      worldNormalVarName = state._getFreeVariableName("globalWorldNormal");
      state._emitFunction("pbr_globalworldnorm", isWebGPU ? `var<private> ${worldNormalVarName}:vec4${state.fSuffix};
` : `vec4${state.fSuffix} ${worldNormalVarName};
`, comments);
      state.compilationString += `${worldNormalVarName} = ${this.worldNormal.associatedVariableName};
`;
      state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${this.worldPosition.associatedVariableName}` : undefined
      });
      state.compilationString += `#if DEBUGMODE > 0
`;
      state.compilationString += `${state._declareLocalVar("vClipSpacePosition", NodeMaterialBlockConnectionPointTypes.Vector4)} = vec4${state.fSuffix}((vec2${state.fSuffix}(${isWebGPU ? "fragmentInputs.position" : "gl_FragCoord.xy"}) / vec2${state.fSuffix}(1.0)) * 2.0 - 1.0, 0.0, 1.0);
`;
      state.compilationString += `#endif
`;
    } else {
      worldPosVarName = (isWebGPU ? "input." : "") + "v_" + worldPosVarName;
      worldNormalVarName = (isWebGPU ? "input." : "") + "v_" + worldNormalVarName;
    }
    this._environmentBrdfSamplerName = state._getFreeVariableName("environmentBrdfSampler");
    state._emit2DSampler(this._environmentBrdfSamplerName);
    state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending;
    state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest;
    state._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)");
    state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
    state._emitUniformFromString("vDebugMode", NodeMaterialBlockConnectionPointTypes.Vector2, "defined(IGNORE) || DEBUGMODE > 0");
    state._emitUniformFromString("ambientFromScene", NodeMaterialBlockConnectionPointTypes.Vector3);
    state.uniforms.push("exposureLinear");
    state.uniforms.push("contrast");
    state.uniforms.push("vInverseScreenSize");
    state.uniforms.push("vignetteSettings1");
    state.uniforms.push("vignetteSettings2");
    state.uniforms.push("vCameraColorCurveNegative");
    state.uniforms.push("vCameraColorCurveNeutral");
    state.uniforms.push("vCameraColorCurvePositive");
    state.uniforms.push("txColorTransform");
    state.uniforms.push("colorTransformSettings");
    state.uniforms.push("ditherIntensity");
    if (!this.light) {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined
      });
    } else {
      state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
        replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
      }, this._lightId.toString());
    }
    state._emitFunctionFromInclude("helperFunctions", comments);
    state._emitFunctionFromInclude("importanceSampling", comments);
    state._emitFunctionFromInclude("pbrHelperFunctions", comments);
    state._emitFunctionFromInclude("imageProcessingDeclaration", comments);
    state._emitFunctionFromInclude("imageProcessingFunctions", comments);
    state._emitFunctionFromInclude("shadowsFragmentFunctions", comments);
    state._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", comments);
    state._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", comments);
    state._emitFunctionFromInclude("pbrBRDFFunctions", comments, {
      replaceStrings: [{ search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" }]
    });
    state._emitFunctionFromInclude("hdrFilteringFunctions", comments);
    state._emitFunctionFromInclude("pbrDirectLightingFunctions", comments);
    state._emitFunctionFromInclude("pbrIBLFunctions", comments);
    state._emitFunctionFromInclude("pbrBlockAlbedoOpacity", comments);
    state._emitFunctionFromInclude("pbrBlockReflectivity", comments);
    state._emitFunctionFromInclude("pbrBlockAmbientOcclusion", comments);
    state._emitFunctionFromInclude("pbrBlockAlphaFresnel", comments);
    state._emitFunctionFromInclude("pbrBlockAnisotropic", comments);
    state._emitUniformFromString("vLightingIntensity", NodeMaterialBlockConnectionPointTypes.Vector4);
    if (reflectionBlock?.generateOnlyFragmentCode) {
      state.compilationString += reflectionBlock.handleVertexSide(state);
    }
    this._vNormalWName = state._getFreeVariableName("vNormalW");
    state.compilationString += `${state._declareLocalVar(this._vNormalWName, NodeMaterialBlockConnectionPointTypes.Vector4)} = normalize(${worldNormalVarName});
`;
    if (state._registerTempVariable("viewDirectionW")) {
      state.compilationString += `${state._declareLocalVar("viewDirectionW", NodeMaterialBlockConnectionPointTypes.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVarName}.xyz);
`;
    }
    state.compilationString += `${state._declareLocalVar("geometricNormalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this._vNormalWName}.xyz;
`;
    state.compilationString += `${state._declareLocalVar("normalW", NodeMaterialBlockConnectionPointTypes.Vector3)} = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};
`;
    this._invertNormalName = state._getFreeVariableName("invertNormal");
    state._emitUniformFromString(this._invertNormalName, NodeMaterialBlockConnectionPointTypes.Float);
    state.compilationString += state._emitCodeFromInclude("pbrBlockNormalFinal", comments, {
      replaceStrings: [
        { search: /vPositionW/g, replace: worldPosVarName + ".xyz" },
        { search: /vEyePosition.w/g, replace: this._invertNormalName }
      ]
    });
    state.compilationString += this._getAlbedoOpacityCode(state);
    state.compilationString += state._emitCodeFromInclude("depthPrePass", comments);
    state.compilationString += this._getAmbientOcclusionCode(state);
    state.compilationString += state._emitCodeFromInclude("pbrBlockLightmapInit", comments);
    state.compilationString += `#ifdef UNLIT
                ${state._declareLocalVar("diffuseBase", NodeMaterialBlockConnectionPointTypes.Vector3)} = vec3${state.fSuffix}(1., 1., 1.);
            #else
`;
    state.compilationString += this._getReflectivityCode(state);
    state.compilationString += state._emitCodeFromInclude("pbrBlockGeometryInfo", comments, {
      replaceStrings: [
        { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" },
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }
      ]
    });
    const anisotropyBlock = this.anisotropy.isConnected ? this.anisotropy.connectedPoint?.ownerBlock : null;
    if (anisotropyBlock) {
      anisotropyBlock.worldPositionConnectionPoint = this.worldPosition;
      anisotropyBlock.worldNormalConnectionPoint = this.worldNormal;
      state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected);
    }
    if (reflectionBlock && reflectionBlock.hasTexture) {
      state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? "anisotropicOut.anisotropicNormal" : "normalW");
    }
    state._emitFunctionFromInclude("pbrBlockReflection", comments, {
      replaceStrings: [
        { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" },
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" },
        { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" },
        { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" },
        { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" },
        { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" },
        { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" },
        { search: /vReflectionFilteringInfo/g, replace: reflectionBlock?._vReflectionFilteringInfoName ?? "vReflectionFilteringInfo" }
      ]
    });
    state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance0", comments, {
      replaceStrings: [{ search: /metallicReflectanceFactors/g, replace: (isWebGPU ? "uniforms." : "") + this._vMetallicReflectanceFactorsName }]
    });
    const sheenBlock = this.sheen.isConnected ? this.sheen.connectedPoint?.ownerBlock : null;
    if (sheenBlock) {
      state.compilationString += sheenBlock.getCode(reflectionBlock, state);
    }
    state._emitFunctionFromInclude("pbrBlockSheen", comments, {
      replaceStrings: [
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" },
        { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" },
        { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" },
        { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" }
      ]
    });
    const clearcoatBlock = this.clearcoat.isConnected ? this.clearcoat.connectedPoint?.ownerBlock : null;
    state.compilationString += ClearCoatBlock._GetInitializationCode(state, clearcoatBlock);
    const iridescenceBlock = this.iridescence.isConnected ? this.iridescence.connectedPoint?.ownerBlock : null;
    state.compilationString += IridescenceBlock.GetCode(iridescenceBlock, state);
    state._emitFunctionFromInclude("pbrBlockIridescence", comments, {
      replaceStrings: []
    });
    const generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected;
    const isTangentConnectedToPerturbNormal = this.perturbedNormal.isConnected && (this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected;
    const isTangentConnectedToAnisotropy = this.anisotropy.isConnected && (this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;
    let vTBNAvailable = isTangentConnectedToPerturbNormal || !this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy;
    state.compilationString += ClearCoatBlock.GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName);
    if (generateTBNSpace) {
      vTBNAvailable = clearcoatBlock?.worldTangent.isConnected ?? false;
    }
    state._emitFunctionFromInclude("pbrBlockClearcoat", comments, {
      replaceStrings: [
        { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" },
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" },
        { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" },
        { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" },
        { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" },
        { search: /LODINREFLECTIONALPHA/g, replace: reflectionBlock?._defineLODReflectionAlpha ?? "LODINREFLECTIONALPHA" },
        { search: /LINEARSPECULARREFLECTION/g, replace: reflectionBlock?._defineLinearSpecularReflection ?? "LINEARSPECULARREFLECTION" },
        { search: /defined\(TANGENT\)/g, replace: vTBNAvailable ? "defined(TANGENT)" : "defined(IGNORE)" }
      ]
    });
    state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance", comments, {
      replaceStrings: [
        { search: /REFLECTIONMAP_SKYBOX/g, replace: reflectionBlock?._defineSkyboxName ?? "REFLECTIONMAP_SKYBOX" },
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" }
      ]
    });
    const subsurfaceBlock = this.subsurface.isConnected ? this.subsurface.connectedPoint?.ownerBlock : null;
    const refractionBlock = this.subsurface.isConnected ? (this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock : null;
    if (refractionBlock) {
      refractionBlock.viewConnectionPoint = this.view;
      refractionBlock.indexOfRefractionConnectionPoint = this.indexOfRefraction;
    }
    state.compilationString += SubSurfaceBlock.GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName);
    state._emitFunctionFromInclude("pbrBlockSubSurface", comments, {
      replaceStrings: [
        { search: /REFLECTIONMAP_3D/g, replace: reflectionBlock?._define3DName ?? "REFLECTIONMAP_3D" },
        { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: reflectionBlock?._defineOppositeZ ?? "REFLECTIONMAP_OPPOSITEZ" },
        { search: /REFLECTIONMAP_PROJECTION/g, replace: reflectionBlock?._defineProjectionName ?? "REFLECTIONMAP_PROJECTION" },
        { search: /SS_REFRACTIONMAP_3D/g, replace: refractionBlock?._define3DName ?? "SS_REFRACTIONMAP_3D" },
        { search: /SS_LODINREFRACTIONALPHA/g, replace: refractionBlock?._defineLODRefractionAlpha ?? "SS_LODINREFRACTIONALPHA" },
        { search: /SS_LINEARSPECULARREFRACTION/g, replace: refractionBlock?._defineLinearSpecularRefraction ?? "SS_LINEARSPECULARREFRACTION" },
        { search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: refractionBlock?._defineOppositeZ ?? "SS_REFRACTIONMAP_OPPOSITEZ" }
      ]
    });
    state.compilationString += state._emitCodeFromInclude("pbrBlockDirectLighting", comments);
    if (this.light) {
      state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
        replaceStrings: [
          { search: /{X}/g, replace: this._lightId.toString() },
          { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vPositionW`, "g"), replace: worldPosVarName + ".xyz" }
        ]
      });
    } else {
      state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
        repeatKey: "maxSimultaneousLights",
        substitutionVars: `${isWebGPU ? "fragmentInputs." : ""}vPositionW,${worldPosVarName}.xyz`
      });
    }
    state.compilationString += state._emitCodeFromInclude("pbrBlockFinalLitComponents", comments);
    state.compilationString += `#endif
`;
    const aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : `vec3${state.fSuffix}(0., 0., 0.)`;
    let aoDirectLightIntensity = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();
    if (aoDirectLightIntensity.indexOf(".") === -1) {
      aoDirectLightIntensity += ".";
    }
    let replaceStrings = [
      { search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g, replace: "" },
      { search: new RegExp(`${isWebGPU ? "uniforms." : ""}vAmbientColor`, "g"), replace: aoColor + ` * ${isWebGPU ? "uniforms." : ""}ambientFromScene` },
      { search: new RegExp(`${isWebGPU ? "uniforms." : ""}vAmbientInfos.w`, "g"), replace: aoDirectLightIntensity }
    ];
    if (isWebGPU) {
      replaceStrings[0] = { search: /var finalEmissive[\s\S]*?finalEmissive\*=uniforms.vLightingIntensity\.y;/g, replace: "" };
    }
    state.compilationString += state._emitCodeFromInclude("pbrBlockFinalUnlitComponents", comments, {
      replaceStrings
    });
    state.compilationString += state._emitCodeFromInclude("pbrBlockFinalColorComposition", comments, {
      replaceStrings: [{ search: /finalEmissive/g, replace: `vec3${state.fSuffix}(0.)` }]
    });
    if (isWebGPU) {
      replaceStrings = [{ search: /mesh.visibility/g, replace: "1." }];
    } else {
      replaceStrings = [{ search: /visibility/g, replace: "1." }];
    }
    state.compilationString += state._emitCodeFromInclude("pbrBlockImageProcessing", comments, {
      replaceStrings
    });
    const colorOutput = isWebGPU ? "fragmentOutputs.color" : "gl_FragColor";
    replaceStrings = [
      { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vNormalW`, "g"), replace: this._vNormalWName },
      { search: new RegExp(`${isWebGPU ? "fragmentInputs." : ""}vPositionW`, "g"), replace: worldPosVarName },
      {
        search: /albedoTexture\.rgb;/g,
        replace: `vec3${state.fSuffix}(1.);
${colorOutput}.rgb = toGammaSpace(${colorOutput}.rgb);
`
      }
    ];
    state.compilationString += state._emitCodeFromInclude("pbrDebug", comments, {
      replaceStrings
    });
    for (const output of this._outputs) {
      if (output.hasEndpoints) {
        const remap = mapOutputToVariable[output.name];
        if (remap) {
          const [varName, conditions] = remap;
          if (conditions) {
            state.compilationString += `#if ${conditions}
`;
          }
          state.compilationString += `${state._declareOutput(output)} = ${varName};
`;
          if (conditions) {
            state.compilationString += `#else
`;
            state.compilationString += `${state._declareOutput(output)} = vec3${state.fSuffix}(0.);
`;
            state.compilationString += `#endif
`;
          }
        } else {
          Logger.Error(`There's no remapping for the ${output.name} end point! No code generated`);
        }
      }
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.lightFalloff = ${this.lightFalloff};
`;
    codeString += `${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};
`;
    codeString += `${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};
`;
    codeString += `${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};
`;
    codeString += `${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};
`;
    codeString += `${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};
`;
    codeString += `${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};
`;
    codeString += `${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};
`;
    codeString += `${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};
`;
    codeString += `${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};
`;
    codeString += `${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};
`;
    codeString += `${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};
`;
    codeString += `${this._codeVariableName}.unlit = ${this.unlit};
`;
    codeString += `${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};
`;
    codeString += `${this._codeVariableName}.debugMode = ${this.debugMode};
`;
    codeString += `${this._codeVariableName}.debugLimit = ${this.debugLimit};
`;
    codeString += `${this._codeVariableName}.debugFactor = ${this.debugFactor};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    if (this.light) {
      serializationObject.lightId = this.light.id;
    }
    serializationObject.lightFalloff = this.lightFalloff;
    serializationObject.useAlphaTest = this.useAlphaTest;
    serializationObject.alphaTestCutoff = this.alphaTestCutoff;
    serializationObject.useAlphaBlending = this.useAlphaBlending;
    serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha;
    serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;
    serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing;
    serializationObject.realTimeFiltering = this.realTimeFiltering;
    serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality;
    serializationObject.useEnergyConservation = this.useEnergyConservation;
    serializationObject.useRadianceOcclusion = this.useRadianceOcclusion;
    serializationObject.useHorizonOcclusion = this.useHorizonOcclusion;
    serializationObject.unlit = this.unlit;
    serializationObject.forceNormalForward = this.forceNormalForward;
    serializationObject.debugMode = this.debugMode;
    serializationObject.debugLimit = this.debugLimit;
    serializationObject.debugFactor = this.debugFactor;
    serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    if (serializationObject.lightId) {
      this.light = scene.getLightById(serializationObject.lightId);
    }
    this.lightFalloff = serializationObject.lightFalloff ?? 0;
    this.useAlphaTest = serializationObject.useAlphaTest;
    this.alphaTestCutoff = serializationObject.alphaTestCutoff;
    this.useAlphaBlending = serializationObject.useAlphaBlending;
    this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha;
    this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha;
    this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing;
    this.realTimeFiltering = !!serializationObject.realTimeFiltering;
    this.realTimeFilteringQuality = serializationObject.realTimeFilteringQuality ?? 8;
    this.useEnergyConservation = serializationObject.useEnergyConservation;
    this.useRadianceOcclusion = serializationObject.useRadianceOcclusion;
    this.useHorizonOcclusion = serializationObject.useHorizonOcclusion;
    this.unlit = serializationObject.unlit;
    this.forceNormalForward = !!serializationObject.forceNormalForward;
    this.debugMode = serializationObject.debugMode;
    this.debugLimit = serializationObject.debugLimit;
    this.debugFactor = serializationObject.debugFactor;
    this.generateOnlyFragmentCode = !!serializationObject.generateOnlyFragmentCode;
    this._setTarget();
  }
}
__decorate([
  editableInPropertyPage("Direct lights", 1, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "directIntensity", undefined);
__decorate([
  editableInPropertyPage("Environment lights", 1, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "environmentIntensity", undefined);
__decorate([
  editableInPropertyPage("Specular highlights", 1, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "specularIntensity", undefined);
__decorate([
  editableInPropertyPage("Light falloff", 4, "LIGHTING & COLORS", {
    notifiers: { update: true },
    options: [
      { label: "Physical", value: PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL },
      { label: "GLTF", value: PBRBaseMaterial.LIGHTFALLOFF_GLTF },
      { label: "Standard", value: PBRBaseMaterial.LIGHTFALLOFF_STANDARD }
    ]
  })
], PBRMetallicRoughnessBlock.prototype, "lightFalloff", undefined);
__decorate([
  editableInPropertyPage("Alpha Testing", 0, "OPACITY")
], PBRMetallicRoughnessBlock.prototype, "useAlphaTest", undefined);
__decorate([
  editableInPropertyPage("Alpha CutOff", 1, "OPACITY", { min: 0, max: 1, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "alphaTestCutoff", undefined);
__decorate([
  editableInPropertyPage("Alpha blending", 0, "OPACITY")
], PBRMetallicRoughnessBlock.prototype, "useAlphaBlending", undefined);
__decorate([
  editableInPropertyPage("Radiance over alpha", 0, "RENDERING", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "useRadianceOverAlpha", undefined);
__decorate([
  editableInPropertyPage("Specular over alpha", 0, "RENDERING", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "useSpecularOverAlpha", undefined);
__decorate([
  editableInPropertyPage("Specular anti-aliasing", 0, "RENDERING", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "enableSpecularAntiAliasing", undefined);
__decorate([
  editableInPropertyPage("Realtime filtering", 0, "RENDERING", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "realTimeFiltering", undefined);
__decorate([
  editableInPropertyPage("Realtime filtering quality", 4, "RENDERING", {
    notifiers: { update: true },
    options: [
      { label: "Low", value: 8 },
      { label: "Medium", value: 16 },
      { label: "High", value: 64 }
    ]
  })
], PBRMetallicRoughnessBlock.prototype, "realTimeFilteringQuality", undefined);
__decorate([
  editableInPropertyPage("Energy Conservation", 0, "ADVANCED", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "useEnergyConservation", undefined);
__decorate([
  editableInPropertyPage("Radiance occlusion", 0, "ADVANCED", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "useRadianceOcclusion", undefined);
__decorate([
  editableInPropertyPage("Horizon occlusion", 0, "ADVANCED", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "useHorizonOcclusion", undefined);
__decorate([
  editableInPropertyPage("Unlit", 0, "ADVANCED", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "unlit", undefined);
__decorate([
  editableInPropertyPage("Force normal forward", 0, "ADVANCED", { notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "forceNormalForward", undefined);
__decorate([
  editableInPropertyPage("Generate only fragment code", 0, "ADVANCED", {
    notifiers: { rebuild: true, update: true, onValidation: PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged }
  })
], PBRMetallicRoughnessBlock.prototype, "generateOnlyFragmentCode", undefined);
__decorate([
  editableInPropertyPage("Debug mode", 4, "DEBUG", {
    notifiers: { update: true },
    options: [
      { label: "None", value: 0 },
      { label: "Normalized position", value: 1 },
      { label: "Normals", value: 2 },
      { label: "Tangents", value: 3 },
      { label: "Bitangents", value: 4 },
      { label: "Bump Normals", value: 5 },
      { label: "ClearCoat Normals", value: 8 },
      { label: "ClearCoat Tangents", value: 9 },
      { label: "ClearCoat Bitangents", value: 10 },
      { label: "Anisotropic Normals", value: 11 },
      { label: "Anisotropic Tangents", value: 12 },
      { label: "Anisotropic Bitangents", value: 13 },
      { label: "Env Refraction", value: 40 },
      { label: "Env Reflection", value: 41 },
      { label: "Env Clear Coat", value: 42 },
      { label: "Direct Diffuse", value: 50 },
      { label: "Direct Specular", value: 51 },
      { label: "Direct Clear Coat", value: 52 },
      { label: "Direct Sheen", value: 53 },
      { label: "Env Irradiance", value: 54 },
      { label: "Surface Albedo", value: 60 },
      { label: "Reflectance 0", value: 61 },
      { label: "Metallic", value: 62 },
      { label: "Metallic F0", value: 71 },
      { label: "Roughness", value: 63 },
      { label: "AlphaG", value: 64 },
      { label: "NdotV", value: 65 },
      { label: "ClearCoat Color", value: 66 },
      { label: "ClearCoat Roughness", value: 67 },
      { label: "ClearCoat NdotV", value: 68 },
      { label: "Transmittance", value: 69 },
      { label: "Refraction Transmittance", value: 70 },
      { label: "SEO", value: 80 },
      { label: "EHO", value: 81 },
      { label: "Energy Factor", value: 82 },
      { label: "Specular Reflectance", value: 83 },
      { label: "Clear Coat Reflectance", value: 84 },
      { label: "Sheen Reflectance", value: 85 },
      { label: "Luminance Over Alpha", value: 86 },
      { label: "Alpha", value: 87 },
      { label: "Albedo color", value: 88 },
      { label: "Ambient occlusion color", value: 89 }
    ]
  })
], PBRMetallicRoughnessBlock.prototype, "debugMode", undefined);
__decorate([
  editableInPropertyPage("Split position", 1, "DEBUG", { min: -1, max: 1, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "debugLimit", undefined);
__decorate([
  editableInPropertyPage("Output factor", 1, "DEBUG", { min: 0, max: 5, notifiers: { update: true } })
], PBRMetallicRoughnessBlock.prototype, "debugFactor", undefined);
RegisterClass("BABYLON.PBRMetallicRoughnessBlock", PBRMetallicRoughnessBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/modBlock.js
init_typeStore();

class ModBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "ModBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    if (state.shaderLanguage === 0) {
      state.compilationString += state._declareOutput(output) + ` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});
`;
    } else {
      state.compilationString += state._declareOutput(output) + ` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.ModBlock", ModBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/matrixBuilderBlock.js
init_typeStore();
init_math_vector();

class MatrixBuilderBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("row0", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("row1", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("row2", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerInput("row3", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "MatrixBuilder";
  }
  get row0() {
    return this._inputs[0];
  }
  get row1() {
    return this._inputs[1];
  }
  get row2() {
    return this._inputs[2];
  }
  get row3() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.row0.isConnected) {
      const row0Input = new InputBlock("row0");
      row0Input.value = new Vector4(1, 0, 0, 0);
      row0Input.output.connectTo(this.row0);
    }
    if (!this.row1.isConnected) {
      const row1Input = new InputBlock("row1");
      row1Input.value = new Vector4(0, 1, 0, 0);
      row1Input.output.connectTo(this.row1);
    }
    if (!this.row2.isConnected) {
      const row2Input = new InputBlock("row2");
      row2Input.value = new Vector4(0, 0, 1, 0);
      row2Input.output.connectTo(this.row2);
    }
    if (!this.row3.isConnected) {
      const row3Input = new InputBlock("row3");
      row3Input.value = new Vector4(0, 0, 0, 1);
      row3Input.output.connectTo(this.row3);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const row0 = this.row0;
    const row1 = this.row1;
    const row2 = this.row2;
    const row3 = this.row3;
    const mat4 = state.shaderLanguage === 1 ? "mat4x4f" : "mat4";
    state.compilationString += state._declareOutput(output) + ` = ${mat4}(${row0.associatedVariableName}, ${row1.associatedVariableName}, ${row2.associatedVariableName}, ${row3.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.MatrixBuilder", MatrixBuilderBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/conditionalBlock.js
init_tslib_es6();
init_typeStore();
var ConditionalBlockConditions;
(function(ConditionalBlockConditions2) {
  ConditionalBlockConditions2[ConditionalBlockConditions2["Equal"] = 0] = "Equal";
  ConditionalBlockConditions2[ConditionalBlockConditions2["NotEqual"] = 1] = "NotEqual";
  ConditionalBlockConditions2[ConditionalBlockConditions2["LessThan"] = 2] = "LessThan";
  ConditionalBlockConditions2[ConditionalBlockConditions2["GreaterThan"] = 3] = "GreaterThan";
  ConditionalBlockConditions2[ConditionalBlockConditions2["LessOrEqual"] = 4] = "LessOrEqual";
  ConditionalBlockConditions2[ConditionalBlockConditions2["GreaterOrEqual"] = 5] = "GreaterOrEqual";
  ConditionalBlockConditions2[ConditionalBlockConditions2["Xor"] = 6] = "Xor";
  ConditionalBlockConditions2[ConditionalBlockConditions2["Or"] = 7] = "Or";
  ConditionalBlockConditions2[ConditionalBlockConditions2["And"] = 8] = "And";
})(ConditionalBlockConditions || (ConditionalBlockConditions = {}));

class ConditionalBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.condition = ConditionalBlockConditions.LessThan;
    this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("true", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("false", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._linkConnectionTypes(2, 3);
    this._outputs[0]._typeConnectionSource = this._inputs[2];
    this._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float;
  }
  getClassName() {
    return "ConditionalBlock";
  }
  get a() {
    return this._inputs[0];
  }
  get b() {
    return this._inputs[1];
  }
  get true() {
    return this._inputs[2];
  }
  get false() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure(nodeMaterial) {
    if (!this.true.isConnected) {
      const minInput = nodeMaterial.getBlockByPredicate((b) => b.isInput && b.value === 1 && b.name === "True") || new InputBlock("True");
      minInput.value = 1;
      minInput.output.connectTo(this.true);
    }
    if (!this.false.isConnected) {
      const maxInput = nodeMaterial.getBlockByPredicate((b) => b.isInput && b.value === 0 && b.name === "False") || new InputBlock("False");
      maxInput.value = 0;
      maxInput.output.connectTo(this.false);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const trueStatement = this.true.isConnected ? this.true.associatedVariableName : "1.0";
    const falseStatement = this.false.isConnected ? this.false.associatedVariableName : "0.0";
    switch (this.condition) {
      case ConditionalBlockConditions.Equal: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.NotEqual: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.LessThan: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.LessOrEqual: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.GreaterThan: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.GreaterOrEqual: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};
`;
        break;
      }
      case ConditionalBlockConditions.Xor: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};
`;
        break;
      }
      case ConditionalBlockConditions.Or: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};
`;
        break;
      }
      case ConditionalBlockConditions.And: {
        state.compilationString += state._declareOutput(output) + ` = ${state._generateTernary(trueStatement, falseStatement, `(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};
`;
        break;
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.condition = this.condition;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.condition = serializationObject.condition;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ConditionalBlockConditions[this.condition]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Condition", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Equal", value: ConditionalBlockConditions.Equal },
      { label: "NotEqual", value: ConditionalBlockConditions.NotEqual },
      { label: "LessThan", value: ConditionalBlockConditions.LessThan },
      { label: "GreaterThan", value: ConditionalBlockConditions.GreaterThan },
      { label: "LessOrEqual", value: ConditionalBlockConditions.LessOrEqual },
      { label: "GreaterOrEqual", value: ConditionalBlockConditions.GreaterOrEqual },
      { label: "Xor", value: ConditionalBlockConditions.Xor },
      { label: "And", value: ConditionalBlockConditions.And },
      { label: "Or", value: ConditionalBlockConditions.Or }
    ]
  })
], ConditionalBlock.prototype, "condition", undefined);
RegisterClass("BABYLON.ConditionalBlock", ConditionalBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/cloudBlock.js
init_tslib_es6();
init_typeStore();
class CloudBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.octaves = 6;
    this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("chaos", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.registerInput("offsetX", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("offsetY", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("offsetZ", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);
    this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "CloudBlock";
  }
  get seed() {
    return this._inputs[0];
  }
  get chaos() {
    return this._inputs[1];
  }
  get offsetX() {
    return this._inputs[2];
  }
  get offsetY() {
    return this._inputs[3];
  }
  get offsetZ() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this.seed.isConnected) {
      return;
    }
    if (!this._outputs[0].hasEndpoints) {
      return;
    }
    let functionString = `

        float cloudRandom(float p) { 
            float temp = fract(p * 0.011); 
            temp *= temp + 7.5; 
            temp *= temp + temp; 
            return fract(temp); 
        }

        // Based on Morgan McGuire @morgan3d
        // https://www.shadertoy.com/view/4dS3Wd
        float cloudNoise2(vec2 x, vec2 chaos) {
            vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);

            vec2 i = floor(x);
            vec2 f = fract(x);

            float n = dot(i, step);

            vec2 u = f * f * (3.0 - 2.0 * f);
            return mix(
                    mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),
                    mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),
                    u.y
                );
        }

        float cloudNoise3(vec3 x, vec3 chaos) {
            vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);

            vec3 i = floor(x);
            vec3 f = fract(x);

            float n = dot(i, step);

            vec3 u = f * f * (3.0 - 2.0 * f);
            return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),
                       mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),
                           mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);
        }`;
    let fractalBrownianString = `
        float fbm2(vec2 st, vec2 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = .5;
            float frequency = 0.;

            // Loop of octaves
            vec2 tempST = st;
            for (int i = 0; i < OCTAVES; i++) {
                value += amplitude * cloudNoise2(tempST, chaos);
                tempST *= 2.0;
                amplitude *= 0.5;
            }
            return value;
        }

        float fbm3(vec3 x, vec3 chaos) {
            // Initial values
            float value = 0.0;
            float amplitude = 0.5;
            vec3 tempX = x;
            for (int i = 0; i < OCTAVES; i++) {
                value += amplitude * cloudNoise3(tempX, chaos);
                tempX = tempX * 2.0;
                amplitude *= 0.5;
            }
            return value;
        }`;
    if (state.shaderLanguage === 1) {
      functionString = state._babylonSLtoWGSL(functionString);
      fractalBrownianString = state._babylonSLtoWGSL(fractalBrownianString);
    }
    const fbmNewName = `fbm${this.octaves}`;
    state._emitFunction("CloudBlockCode", functionString, "// CloudBlockCode");
    state._emitFunction("CloudBlockCodeFBM" + this.octaves, fractalBrownianString.replace(/fbm/gi, fbmNewName).replace(/OCTAVES/gi, (this.octaves | 0).toString()), "// CloudBlockCode FBM");
    const localVariable = state._getFreeVariableName("st");
    const seedType = this.seed.connectedPoint?.type || NodeMaterialBlockConnectionPointTypes.Vector3;
    state.compilationString += `${state._declareLocalVar(localVariable, seedType)} = ${this.seed.associatedVariableName};
`;
    if (this.offsetX.isConnected) {
      state.compilationString += `${localVariable}.x += 0.1 * ${this.offsetX.associatedVariableName};
`;
    }
    if (this.offsetY.isConnected) {
      state.compilationString += `${localVariable}.y += 0.1 * ${this.offsetY.associatedVariableName};
`;
    }
    if (this.offsetZ.isConnected && seedType === NodeMaterialBlockConnectionPointTypes.Vector3) {
      state.compilationString += `${localVariable}.z += 0.1 * ${this.offsetZ.associatedVariableName};
`;
    }
    let chaosValue = "";
    if (this.chaos.isConnected) {
      chaosValue = this.chaos.associatedVariableName;
    } else {
      const addF = state.fSuffix;
      chaosValue = this.seed.connectedPoint?.type === NodeMaterialBlockConnectionPointTypes.Vector2 ? `vec2${addF}(0., 0.)` : `vec3${addF}(0., 0., 0.)`;
    }
    state.compilationString += state._declareOutput(this._outputs[0]) + ` = ${fbmNewName}${this.seed.connectedPoint?.type === NodeMaterialBlockConnectionPointTypes.Vector2 ? "2" : "3"}(${localVariable}, ${chaosValue});
`;
    return this;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.octaves = ${this.octaves};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.octaves = this.octaves;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.octaves = serializationObject.octaves;
  }
}
__decorate([
  editableInPropertyPage("Octaves", 2, undefined, { embedded: true })
], CloudBlock.prototype, "octaves", undefined);
RegisterClass("BABYLON.CloudBlock", CloudBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/voronoiNoiseBlock.js
init_typeStore();

class VoronoiNoiseBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2);
    this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerInput("density", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
    this.registerOutput("cells", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "VoronoiNoiseBlock";
  }
  get seed() {
    return this._inputs[0];
  }
  get offset() {
    return this._inputs[1];
  }
  get density() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  get cells() {
    return this._outputs[1];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this.seed.isConnected) {
      return;
    }
    let functionString = `vec2 voronoiRandom(vec2 p){
            p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));
            return fract(sin(p)*18.5453);
        }
        `;
    if (state.shaderLanguage === 1) {
      functionString = state._babylonSLtoWGSL(functionString);
    }
    state._emitFunction("voronoiRandom", functionString, "// Voronoi random generator");
    functionString = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){
            vec2 n = floor(seed * density);
            vec2 f = fract(seed * density);
            vec3 m = vec3( 8.0 );
            for( int j=-1; j<=1; j++ ){
                for( int i=-1; i<=1; i++ ){
                    vec2  g = vec2( float(i), float(j) );
                    vec2  o = voronoiRandom( n + g);
                    vec2  r = g - f + (0.5+0.5*sin(offset+6.2831*o));
                    float d = dot( r, r );
                    if( d<m.x ){
                        m = vec3( d, o );
                        outValue = m.x;
                        cells = m.y;
                    }
                }
			}
        }
        `;
    if (state.shaderLanguage === 1) {
      functionString = state._babylonSLtoWGSL(functionString);
    } else {
      functionString = state._babylonSLtoGLSL(functionString);
    }
    state._emitFunction("voronoi", functionString, "// Voronoi");
    const tempOutput = state._getFreeVariableName("tempOutput");
    const tempCells = state._getFreeVariableName("tempCells");
    const ref = state.shaderLanguage === 1 ? "&" : "";
    state.compilationString += `${state._declareLocalVar(tempOutput, NodeMaterialBlockConnectionPointTypes.Float)} = 0.0;
`;
    state.compilationString += `${state._declareLocalVar(tempCells, NodeMaterialBlockConnectionPointTypes.Float)} = 0.0;
`;
    state.compilationString += `voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${ref}${tempOutput}, ${ref}${tempCells});
`;
    if (this.output.hasEndpoints) {
      state.compilationString += state._declareOutput(this.output) + ` = ${tempOutput};
`;
    }
    if (this.cells.hasEndpoints) {
      state.compilationString += state._declareOutput(this.cells) + ` = ${tempCells};
`;
    }
    return this;
  }
}
RegisterClass("BABYLON.VoronoiNoiseBlock", VoronoiNoiseBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/elbowBlock.js
init_typeStore();

class ElbowBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "ElbowBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  get target() {
    const input = this._inputs[0];
    if (input.isConnected) {
      const block = input.connectedPoint.ownerBlock;
      if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) {
        return block.target;
      }
      if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) {
        return input.connectedPoint.target;
      }
    }
    return this._target;
  }
  set target(value) {
    if ((this._target & value) !== 0) {
      return;
    }
    this._target = value;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input = this._inputs[0];
    state.compilationString += state._declareOutput(output) + ` = ${input.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.ElbowBlock", ElbowBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/triPlanarBlock.js
init_tslib_es6();
init_typeStore();
init_texture();
init_helperFunctions2();
init_engineStore();
class TriPlanarBlock extends NodeMaterialBlock {
  get texture() {
    if (this.source.isConnected) {
      return (this.source.connectedPoint?.ownerBlock).texture;
    }
    return this._texture;
  }
  set texture(texture2) {
    if (this._texture === texture2) {
      return;
    }
    const scene = texture2?.getScene() ?? EngineStore.LastCreatedScene;
    if (!texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this._texture);
      });
    }
    this._texture = texture2;
    if (texture2 && scene) {
      scene.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(texture2);
      });
    }
  }
  get textureY() {
    if (this.sourceY.isConnected) {
      return (this.sourceY.connectedPoint?.ownerBlock).texture;
    }
    return null;
  }
  get textureZ() {
    if (this.sourceZ?.isConnected) {
      return (this.sourceY.connectedPoint?.ownerBlock).texture;
    }
    return null;
  }
  _getImageSourceBlock(connectionPoint) {
    return connectionPoint?.isConnected ? connectionPoint.connectedPoint.ownerBlock : null;
  }
  get samplerName() {
    const imageSourceBlock2 = this._getImageSourceBlock(this.source);
    if (imageSourceBlock2) {
      return imageSourceBlock2.samplerName;
    }
    return this._samplerName;
  }
  get samplerYName() {
    return this._getImageSourceBlock(this.sourceY)?.samplerName ?? null;
  }
  get samplerZName() {
    return this._getImageSourceBlock(this.sourceZ)?.samplerName ?? null;
  }
  get hasImageSource() {
    return this.source.isConnected;
  }
  set convertToGammaSpace(value) {
    if (value === this._convertToGammaSpace) {
      return;
    }
    this._convertToGammaSpace = value;
    if (this.texture) {
      const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene;
      scene?.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this.texture);
      });
    }
  }
  get convertToGammaSpace() {
    return this._convertToGammaSpace;
  }
  set convertToLinearSpace(value) {
    if (value === this._convertToLinearSpace) {
      return;
    }
    this._convertToLinearSpace = value;
    if (this.texture) {
      const scene = this.texture.getScene() ?? EngineStore.LastCreatedScene;
      scene?.markAllMaterialsAsDirty(1, (mat) => {
        return mat.hasTexture(this.texture);
      });
    }
  }
  get convertToLinearSpace() {
    return this._convertToLinearSpace;
  }
  constructor(name370, hideSourceZ = false) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.projectAsCube = false;
    this._convertToGammaSpace = false;
    this._convertToLinearSpace = false;
    this.disableLevelMultiplication = false;
    this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);
    this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);
    this.registerInput("sharpness", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, 0, ImageSourceBlock, "ImageSourceBlock"));
    this.registerInput("sourceY", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceY", this, 0, ImageSourceBlock, "ImageSourceBlock"));
    if (!hideSourceZ) {
      this.registerInput("sourceZ", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceZ", this, 0, ImageSourceBlock, "ImageSourceBlock"));
    }
    this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);
    this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
    this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "TriPlanarBlock";
  }
  get position() {
    return this._inputs[0];
  }
  get normal() {
    return this._inputs[1];
  }
  get sharpness() {
    return this._inputs[2];
  }
  get source() {
    return this._inputs[3];
  }
  get sourceY() {
    return this._inputs[4];
  }
  get sourceZ() {
    return this._inputs[5];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  get level() {
    return this._outputs[6];
  }
  prepareDefines(mesh, nodeMaterial, defines) {
    if (!defines._areTexturesDirty) {
      return;
    }
    const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;
    const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;
    defines.setValue(this._linearDefineName, toGamma, true);
    defines.setValue(this._gammaDefineName, toLinear, true);
  }
  isReady() {
    if (this.texture && !this.texture.isReadyOrNotBlocking()) {
      return false;
    }
    return true;
  }
  bind(effect) {
    if (!this.texture) {
      return;
    }
    effect.setFloat(this._textureInfoName, this.texture.level);
    if (!this._imageSource) {
      effect.setTexture(this._samplerName, this.texture);
    }
  }
  _samplerFunc(state) {
    if (state.shaderLanguage === 1) {
      return "textureSample";
    }
    return "texture2D";
  }
  _generateTextureSample(textureName, uv, state) {
    if (state.shaderLanguage === 1) {
      return `${this._samplerFunc(state)}(${textureName},${textureName + `Sampler`}, ${uv})`;
    }
    return `${this._samplerFunc(state)}(${textureName}, ${uv})`;
  }
  _generateTextureLookup(state) {
    const samplerName = this.samplerName;
    const samplerYName = this.samplerYName ?? samplerName;
    const samplerZName = this.samplerZName ?? samplerName;
    const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0";
    const x = state._getFreeVariableName("x");
    const y = state._getFreeVariableName("y");
    const z = state._getFreeVariableName("z");
    const w = state._getFreeVariableName("w");
    const n = state._getFreeVariableName("n");
    const uvx = state._getFreeVariableName("uvx");
    const uvy = state._getFreeVariableName("uvy");
    const uvz = state._getFreeVariableName("uvz");
    state.compilationString += `
            ${state._declareLocalVar(n, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${this.normal.associatedVariableName}.xyz;

            ${state._declareLocalVar(uvx, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.yz;
            ${state._declareLocalVar(uvy, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.zx;
            ${state._declareLocalVar(uvz, NodeMaterialBlockConnectionPointTypes.Vector2)} = ${this.position.associatedVariableName}.xy;
        `;
    if (this.projectAsCube) {
      state.compilationString += `
                ${uvx}.xy = ${uvx}.yx;

                if (${n}.x >= 0.0) {
                    ${uvx}.x = -${uvx}.x;
                }
                if (${n}.y < 0.0) {
                    ${uvy}.y = -${uvy}.y;
                }
                if (${n}.z < 0.0) {
                    ${uvz}.x = -${uvz}.x;
                }
            `;
    }
    const suffix3 = state.fSuffix;
    state.compilationString += `
            ${state._declareLocalVar(x, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerName, uvx, state)};
            ${state._declareLocalVar(y, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerYName, uvy, state)};
            ${state._declareLocalVar(z, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._generateTextureSample(samplerZName, uvz, state)};
           
            // blend weights
            ${state._declareLocalVar(w, NodeMaterialBlockConnectionPointTypes.Vector3)} = pow(abs(${n}), vec3${suffix3}(${sharpness}));

            // blend and return
            ${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = (${x}*${w}.x + ${y}*${w}.y + ${z}*${w}.z) / (${w}.x + ${w}.y + ${w}.z);        
        `;
  }
  _generateConversionCode(state, output, swizzle) {
    let vecSpecifier = "";
    if (state.shaderLanguage === 1 && (output.type === NodeMaterialBlockConnectionPointTypes.Vector3 || output.type === NodeMaterialBlockConnectionPointTypes.Color3)) {
      vecSpecifier = "Vec3";
    }
    if (swizzle !== "a") {
      if (!this.texture || !this.texture.gammaSpace) {
        state.compilationString += `#ifdef ${this._linearDefineName}
                    ${output.associatedVariableName} = toGammaSpace${vecSpecifier}(${output.associatedVariableName});
                    #endif
                `;
      }
      state.compilationString += `#ifdef ${this._gammaDefineName}
                ${output.associatedVariableName} = toLinearSpace${vecSpecifier}(${output.associatedVariableName});
                #endif
            `;
    }
  }
  _writeOutput(state, output, swizzle) {
    let complement = "";
    if (!this.disableLevelMultiplication) {
      complement = ` * ${state.shaderLanguage === 1 ? "uniforms." : ""}${this._textureInfoName}`;
    }
    state.compilationString += `${state._declareOutput(output)} = ${this._tempTextureRead}.${swizzle}${complement};
`;
    this._generateConversionCode(state, output, swizzle);
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.source.isConnected) {
      this._imageSource = this.source.connectedPoint.ownerBlock;
    } else {
      this._imageSource = null;
    }
    this._textureInfoName = state._getFreeVariableName("textureInfoName");
    this.level.associatedVariableName = (state.shaderLanguage === 1 ? "uniforms." : "") + this._textureInfoName;
    this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
    this._linearDefineName = state._getFreeDefineName("ISLINEAR");
    this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
    if (!this._imageSource) {
      this._samplerName = state._getFreeVariableName(this.name + "Texture");
      state._emit2DSampler(this._samplerName);
    }
    state.sharedData.blockingBlocks.push(this);
    state.sharedData.textureBlocks.push(this);
    state.sharedData.blocksWithDefines.push(this);
    state.sharedData.bindableBlocks.push(this);
    const comments = `//${this.name}`;
    state._emitFunctionFromInclude("helperFunctions", comments);
    state._emitUniformFromString(this._textureInfoName, NodeMaterialBlockConnectionPointTypes.Float);
    this._generateTextureLookup(state);
    for (const output of this._outputs) {
      if (output.hasEndpoints && output.name !== "level") {
        this._writeOutput(state, output, output.name);
      }
    }
    return this;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};
`;
    codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};
`;
    codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};
`;
    codeString += `${this._codeVariableName}.projectAsCube = ${this.projectAsCube};
`;
    if (!this.texture) {
      return codeString;
    }
    codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});
`;
    codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};
`;
    codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};
`;
    codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};
`;
    codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};
`;
    codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};
`;
    codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};
`;
    codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};
`;
    codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};
`;
    codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};
`;
    codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.convertToGammaSpace = this.convertToGammaSpace;
    serializationObject.convertToLinearSpace = this.convertToLinearSpace;
    serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;
    serializationObject.projectAsCube = this.projectAsCube;
    if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") {
      serializationObject.texture = this.texture.serialize();
    }
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.convertToGammaSpace = serializationObject.convertToGammaSpace;
    this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
    this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;
    this.projectAsCube = !!serializationObject.projectAsCube;
    if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {
      rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
      this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);
    }
  }
}
__decorate([
  editableInPropertyPage("Project as cube", 0, "ADVANCED", { embedded: true, notifiers: { update: true } })
], TriPlanarBlock.prototype, "projectAsCube", undefined);
RegisterClass("BABYLON.TriPlanarBlock", TriPlanarBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/biPlanarBlock.js
init_typeStore();
class BiPlanarBlock extends TriPlanarBlock {
  constructor(name370) {
    super(name370, true);
  }
  getClassName() {
    return "BiPlanarBlock";
  }
  _declareLocalVarAsVec3I(name370, state) {
    if (state.shaderLanguage === 1) {
      return `var ${name370}: vec3<i32>`;
    } else {
      return `ivec3 ${name370}`;
    }
  }
  _getTextureGrad(state, samplerName) {
    if (state.shaderLanguage === 1) {
      return `textureSampleGrad(${samplerName},${samplerName + `Sampler`}`;
    }
    return `textureGrad(${samplerName}`;
  }
  _generateTextureLookup(state) {
    const samplerName = this.samplerName;
    const samplerYName = this.samplerYName ?? this.samplerName;
    const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0";
    const dpdx = state._getFreeVariableName("dxValue");
    const dpdy = state._getFreeVariableName("dyValue");
    const n = state._getFreeVariableName("n");
    const ma = state._getFreeVariableName("ma");
    const mi = state._getFreeVariableName("mi");
    const me = state._getFreeVariableName("me");
    const x = state._getFreeVariableName("x");
    const y = state._getFreeVariableName("y");
    const w = state._getFreeVariableName("w");
    let ivec3 = "ivec3";
    let dpdxFunc = "dFdx";
    let dpdyFunc = "dFdy";
    const suffix3 = state.fSuffix;
    if (state.shaderLanguage === 1) {
      ivec3 = "vec3<i32>";
      dpdxFunc = "dpdx";
      dpdyFunc = "dpdy";
    }
    state.compilationString += `
            // grab coord derivatives for texturing
            ${state._declareLocalVar(dpdx, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${dpdxFunc}(${this.position.associatedVariableName}.xyz);
            ${state._declareLocalVar(dpdy, NodeMaterialBlockConnectionPointTypes.Vector3)} = ${dpdyFunc}(${this.position.associatedVariableName}.xyz);
            ${state._declareLocalVar(n, NodeMaterialBlockConnectionPointTypes.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);
        
            // determine major axis (in x; yz are following axis)
            ${this._declareLocalVarAsVec3I(ma, state)} = ${state._generateTernary(`${ivec3}(0,1,2)`, `${state._generateTernary(`${ivec3}(1,2,0)`, `${ivec3}(2,0,1)`, `(${n}.y>${n}.z)`)}`, `(${n}.x>${n}.y && ${n}.x>${n}.z)`)};                    

            // determine minor axis (in x; yz are following axis)
            ${this._declareLocalVarAsVec3I(mi, state)} =  ${state._generateTernary(`${ivec3}(0,1,2)`, `${state._generateTernary(`${ivec3}(1,2,0)`, `${ivec3}(2,0,1)`, `(${n}.y<${n}.z)`)}`, `(${n}.x<${n}.y && ${n}.x<${n}.z)`)};  
                              
            // determine median axis (in x;  yz are following axis)
            ${this._declareLocalVarAsVec3I(me, state)} = ${ivec3}(3) - ${mi} - ${ma};
            
            // project+fetch
            ${state._declareLocalVar(x, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._getTextureGrad(state, samplerName)}, vec2${suffix3}(${this.position.associatedVariableName}[${ma}.y], ${this.position.associatedVariableName}[${ma}.z]), 
                                    vec2${suffix3}(${dpdx}[${ma}.y],${dpdx}[${ma}.z]), 
                                    vec2${suffix3}(${dpdy}[${ma}.y],${dpdy}[${ma}.z]));
            ${state._declareLocalVar(y, NodeMaterialBlockConnectionPointTypes.Vector4)} = ${this._getTextureGrad(state, samplerYName)}, vec2${suffix3}(${this.position.associatedVariableName}[${me}.y], ${this.position.associatedVariableName}[${me}.z]), 
                                    vec2${suffix3}(${dpdx}[${me}.y],${dpdx}[${me}.z]),
                                    vec2${suffix3}(${dpdy}[${me}.y],${dpdy}[${me}.z]));
            
            // blend factors
            ${state._declareLocalVar(w, NodeMaterialBlockConnectionPointTypes.Vector2)} = vec2${suffix3}(${n}[${ma}.x],${n}[${me}.x]);
            // make local support
            ${w} = clamp( (${w}-0.5773)/(1.0-0.5773), vec2${suffix3}(0.0), vec2${suffix3}(1.0) );
            // shape transition
            ${w} = pow( ${w}, vec2${suffix3}(${sharpness}/8.0) );
            // blend and return
            ${state._declareLocalVar(this._tempTextureRead, NodeMaterialBlockConnectionPointTypes.Vector4)} = (${x}*${w}.x + ${y}*${w}.y) / (${w}.x + ${w}.y);
        `;
  }
}
RegisterClass("BABYLON.BiPlanarBlock", BiPlanarBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/matrixDeterminantBlock.js
init_typeStore();

class MatrixDeterminantBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "MatrixDeterminantBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this.output;
    const input = this.input;
    state.compilationString += state._declareOutput(output) + ` = determinant(${input.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.MatrixDeterminantBlock", MatrixDeterminantBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/matrixTransposeBlock.js
init_typeStore();

class MatrixTransposeBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "MatrixTransposeBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this.output;
    const input = this.input;
    state.compilationString += state._declareOutput(output) + ` = transpose(${input.associatedVariableName});
`;
    return this;
  }
}
RegisterClass("BABYLON.MatrixTransposeBlock", MatrixTransposeBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/meshAttributeExistsBlock.js
init_tslib_es6();
init_typeStore();
var MeshAttributeExistsBlockTypes;
(function(MeshAttributeExistsBlockTypes2) {
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["None"] = 0] = "None";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["Normal"] = 1] = "Normal";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["Tangent"] = 2] = "Tangent";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["VertexColor"] = 3] = "VertexColor";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV1"] = 4] = "UV1";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV2"] = 5] = "UV2";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV3"] = 6] = "UV3";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV4"] = 7] = "UV4";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV5"] = 8] = "UV5";
  MeshAttributeExistsBlockTypes2[MeshAttributeExistsBlockTypes2["UV6"] = 9] = "UV6";
})(MeshAttributeExistsBlockTypes || (MeshAttributeExistsBlockTypes = {}));

class MeshAttributeExistsBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.attributeType = 0;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("fallback", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].onConnectionObservable.add((other) => {
      if (this.attributeType) {
        return;
      }
      const sourceBlock = other.ownerBlock;
      if (sourceBlock instanceof InputBlock && sourceBlock.isAttribute) {
        switch (sourceBlock.name) {
          case "color":
            this.attributeType = 3;
            break;
          case "normal":
            this.attributeType = 1;
            break;
          case "tangent":
            this.attributeType = 2;
            break;
          case "uv":
            this.attributeType = 4;
            break;
          case "uv2":
            this.attributeType = 5;
            break;
          case "uv3":
            this.attributeType = 6;
            break;
          case "uv4":
            this.attributeType = 7;
            break;
          case "uv5":
            this.attributeType = 8;
            break;
          case "uv6":
            this.attributeType = 9;
            break;
        }
      } else if (sourceBlock instanceof MorphTargetsBlock) {
        switch (this.input.connectedPoint?.name) {
          case "normalOutput":
            this.attributeType = 1;
            break;
          case "tangentOutput":
            this.attributeType = 2;
            break;
          case "uvOutput":
            this.attributeType = 4;
            break;
          case "uv2Output":
            this.attributeType = 5;
            break;
        }
      }
    });
  }
  getClassName() {
    return "MeshAttributeExistsBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get fallback() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    let attributeDefine2 = null;
    switch (this.attributeType) {
      case 3:
        attributeDefine2 = "VERTEXCOLOR_NME";
        break;
      case 1:
        attributeDefine2 = "NORMAL";
        break;
      case 2:
        attributeDefine2 = "TANGENT";
        break;
      case 4:
        attributeDefine2 = "UV1";
        break;
      case 5:
        attributeDefine2 = "UV2";
        break;
      case 6:
        attributeDefine2 = "UV3";
        break;
      case 7:
        attributeDefine2 = "UV4";
        break;
      case 8:
        attributeDefine2 = "UV5";
        break;
      case 9:
        attributeDefine2 = "UV6";
        break;
    }
    const output = state._declareOutput(this.output);
    if (attributeDefine2) {
      state.compilationString += `#ifdef ${attributeDefine2}
`;
    }
    state.compilationString += `${output} = ${this.input.associatedVariableName};
`;
    if (attributeDefine2) {
      state.compilationString += `#else
`;
      state.compilationString += `${output} = ${this.fallback.associatedVariableName};
`;
      state.compilationString += `#endif
`;
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.attributeType = this.attributeType;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.attributeType = serializationObject.attributeType ?? 0;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    codeString += `${this._codeVariableName}.attributeType = ${this.attributeType};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Attribute lookup", 4, undefined, {
    notifiers: { update: true },
    embedded: true,
    options: [
      { label: "(None)", value: 0 },
      { label: "Normal", value: 1 },
      { label: "Tangent", value: 2 },
      { label: "Vertex Color", value: 3 },
      { label: "UV1", value: 4 },
      { label: "UV2", value: 5 },
      { label: "UV3", value: 6 },
      { label: "UV4", value: 7 },
      { label: "UV5", value: 8 },
      { label: "UV6", value: 9 }
    ]
  })
], MeshAttributeExistsBlock.prototype, "attributeType", undefined);
RegisterClass("BABYLON.MeshAttributeExistsBlock", MeshAttributeExistsBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/curveBlock.js
init_tslib_es6();
init_typeStore();
var CurveBlockTypes;
(function(CurveBlockTypes2) {
  CurveBlockTypes2[CurveBlockTypes2["EaseInSine"] = 0] = "EaseInSine";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutSine"] = 1] = "EaseOutSine";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutSine"] = 2] = "EaseInOutSine";
  CurveBlockTypes2[CurveBlockTypes2["EaseInQuad"] = 3] = "EaseInQuad";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutQuad"] = 4] = "EaseOutQuad";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutQuad"] = 5] = "EaseInOutQuad";
  CurveBlockTypes2[CurveBlockTypes2["EaseInCubic"] = 6] = "EaseInCubic";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutCubic"] = 7] = "EaseOutCubic";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutCubic"] = 8] = "EaseInOutCubic";
  CurveBlockTypes2[CurveBlockTypes2["EaseInQuart"] = 9] = "EaseInQuart";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutQuart"] = 10] = "EaseOutQuart";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutQuart"] = 11] = "EaseInOutQuart";
  CurveBlockTypes2[CurveBlockTypes2["EaseInQuint"] = 12] = "EaseInQuint";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutQuint"] = 13] = "EaseOutQuint";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutQuint"] = 14] = "EaseInOutQuint";
  CurveBlockTypes2[CurveBlockTypes2["EaseInExpo"] = 15] = "EaseInExpo";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutExpo"] = 16] = "EaseOutExpo";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutExpo"] = 17] = "EaseInOutExpo";
  CurveBlockTypes2[CurveBlockTypes2["EaseInCirc"] = 18] = "EaseInCirc";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutCirc"] = 19] = "EaseOutCirc";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutCirc"] = 20] = "EaseInOutCirc";
  CurveBlockTypes2[CurveBlockTypes2["EaseInBack"] = 21] = "EaseInBack";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutBack"] = 22] = "EaseOutBack";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutBack"] = 23] = "EaseInOutBack";
  CurveBlockTypes2[CurveBlockTypes2["EaseInElastic"] = 24] = "EaseInElastic";
  CurveBlockTypes2[CurveBlockTypes2["EaseOutElastic"] = 25] = "EaseOutElastic";
  CurveBlockTypes2[CurveBlockTypes2["EaseInOutElastic"] = 26] = "EaseInOutElastic";
})(CurveBlockTypes || (CurveBlockTypes = {}));

class CurveBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.type = CurveBlockTypes.EaseInOutSine;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Object);
    this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Int);
  }
  getClassName() {
    return "CurveBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _duplicateEntry(entry, component) {
    return `ret.${component} = ${entry.replace(/VAL/g, "v." + component)}`;
  }
  _duplicateEntryDirect(entry) {
    return `return ${entry.replace(/VAL/g, "v")}`;
  }
  _duplicateVector(entry, inputType, isWGSL) {
    if (inputType === "float" || inputType === "f32") {
      return this._duplicateEntryDirect(entry);
    }
    const size = parseInt(inputType.replace("vec", ""));
    let code = isWGSL ? `
            var ret: vec${size}f = vec${size}f(0.0);
        ` : `
            vec${size} ret = vec${size}(0.0);
        `;
    for (let i = 1;i <= size; i++) {
      code += this._duplicateEntry(entry, i === 1 ? "x" : i === 2 ? "y" : i === 3 ? "z" : "w") + `;
`;
    }
    code += `return ret;
`;
    return code;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    let registeredFunction = "";
    let registeredFunctionName = "";
    const inputType = state._getShaderType(this.input.type);
    const isWGSL = state.shaderLanguage === 1;
    registeredFunctionName = CurveBlockTypes[this.type] + "_" + inputType.replace("<", "").replace(">", "");
    switch (this.type) {
      case CurveBlockTypes.EaseInSine:
        registeredFunction = `return 1.0 - cos((v * 3.1415) / 2.0)`;
        break;
      case CurveBlockTypes.EaseOutSine:
        registeredFunction = `return sin((v * 3.1415) / 2.0)`;
        break;
      case CurveBlockTypes.EaseInOutSine:
        registeredFunction = `return -(cos(v * 3.1415) - 1.0) / 2.0`;
        break;
      case CurveBlockTypes.EaseInQuad:
        registeredFunction = `return v * v`;
        break;
      case CurveBlockTypes.EaseOutQuad:
        registeredFunction = `return (1.0 - v) * (1.0 - v)`;
        break;
      case CurveBlockTypes.EaseInOutQuad: {
        const entry = state._generateTernary("2.0 * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInCubic:
        registeredFunction = `return v * v * v`;
        break;
      case CurveBlockTypes.EaseOutCubic: {
        const entry = "1.0 - pow(1.0 - VAL, 3.0)";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutCubic: {
        const entry = state._generateTernary("4.0 * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInQuart:
        registeredFunction = `return v * v * v * v`;
        break;
      case CurveBlockTypes.EaseOutQuart: {
        const entry = "1.0 - pow(1.0 - VAL, 4.0)";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutQuart: {
        const entry = state._generateTernary("8.0 * VAL * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInQuint:
        registeredFunction = `return v * v * v * v * v`;
        break;
      case CurveBlockTypes.EaseOutQuint: {
        const entry = "1.0 - pow(1.0 - VAL, 5.0)";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutQuint: {
        const entry = state._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL", "1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInExpo: {
        const entry = state._generateTernary("0.0", "pow(2.0, 10.0 * VAL - 10.0)", "VAL == 0.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseOutExpo: {
        const entry = state._generateTernary("1.0", "1.0 - pow(2.0, -10.0 * VAL)", "VAL == 1.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutExpo: {
        const entry = state._generateTernary("0.0", state._generateTernary("1.0", state._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0", "(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0", "VAL < 0.5"), "VAL == 1.0"), "VAL == 0.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInCirc: {
        const entry = "1.0 - sqrt(1.0 - pow(VAL, 2.0))";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseOutCirc: {
        const entry = "sqrt(1.0 - pow(VAL - 1.0, 2.0))";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutCirc: {
        const entry = state._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0", "(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInBack: {
        registeredFunction = "return 2.70158 * v * v * v - 1.70158 * v * v";
        break;
      }
      case CurveBlockTypes.EaseOutBack: {
        const entry = "2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutBack: {
        const entry = state._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0", "(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0", "VAL < 0.5");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInElastic: {
        const entry = state._generateTernary("0.0", state._generateTernary("1.0", "-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))", "VAL == 1.0"), "VAL == 0.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseOutElastic: {
        const entry = state._generateTernary("0.0", state._generateTernary("1.0", "pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0", "VAL == 1.0"), "VAL == 0.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
      case CurveBlockTypes.EaseInOutElastic: {
        const entry = state._generateTernary("0.0", state._generateTernary("1.0", state._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0", "(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0", "VAL < 0.5"), "VAL == 1.0"), "VAL == 0.0");
        registeredFunction = this._duplicateVector(entry, inputType, isWGSL);
        break;
      }
    }
    if (isWGSL) {
      state._emitFunction(registeredFunctionName, `fn ${registeredFunctionName}(v: ${inputType}) -> ${inputType}  {${registeredFunction};}
`, "");
    } else {
      state._emitFunction(registeredFunctionName, `${inputType} ${registeredFunctionName}(${inputType} v) {${registeredFunction};}
`, "");
    }
    state.compilationString += state._declareOutput(output) + ` = ${registeredFunctionName}(${this.input.associatedVariableName});
`;
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.curveType = this.type;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.type = serializationObject.curveType;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${CurveBlockTypes[this.type]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Type", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "EaseInSine", value: CurveBlockTypes.EaseInSine },
      { label: "EaseOutSine", value: CurveBlockTypes.EaseOutSine },
      { label: "EaseInOutSine", value: CurveBlockTypes.EaseInOutSine },
      { label: "EaseInQuad", value: CurveBlockTypes.EaseInQuad },
      { label: "EaseOutQuad", value: CurveBlockTypes.EaseOutQuad },
      { label: "EaseInOutQuad", value: CurveBlockTypes.EaseInOutQuad },
      { label: "EaseInCubic", value: CurveBlockTypes.EaseInCubic },
      { label: "EaseOutCubic", value: CurveBlockTypes.EaseOutCubic },
      { label: "EaseInOutCubic", value: CurveBlockTypes.EaseInOutCubic },
      { label: "EaseInQuart", value: CurveBlockTypes.EaseInQuart },
      { label: "EaseOutQuart", value: CurveBlockTypes.EaseOutQuart },
      { label: "EaseInOutQuart", value: CurveBlockTypes.EaseInOutQuart },
      { label: "EaseInQuint", value: CurveBlockTypes.EaseInQuint },
      { label: "EaseOutQuint", value: CurveBlockTypes.EaseOutQuint },
      { label: "EaseInOutQuint", value: CurveBlockTypes.EaseInOutQuint },
      { label: "EaseInExpo", value: CurveBlockTypes.EaseInExpo },
      { label: "EaseOutExpo", value: CurveBlockTypes.EaseOutExpo },
      { label: "EaseInOutExpo", value: CurveBlockTypes.EaseInOutExpo },
      { label: "EaseInCirc", value: CurveBlockTypes.EaseInCirc },
      { label: "EaseOutCirc", value: CurveBlockTypes.EaseOutCirc },
      { label: "EaseInOutCirc", value: CurveBlockTypes.EaseInOutCirc },
      { label: "EaseInBack", value: CurveBlockTypes.EaseInBack },
      { label: "EaseOutBack", value: CurveBlockTypes.EaseOutBack },
      { label: "EaseInOutBack", value: CurveBlockTypes.EaseInOutBack },
      { label: "EaseInElastic", value: CurveBlockTypes.EaseInElastic },
      { label: "EaseOutElastic", value: CurveBlockTypes.EaseOutElastic },
      { label: "EaseInOutElastic", value: CurveBlockTypes.EaseInOutElastic }
    ]
  })
], CurveBlock.prototype, "type", undefined);
RegisterClass("BABYLON.CurveBlock", CurveBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/colorConverterBlock.js
init_typeStore();

class ColorConverterBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.registerInput("hsl ", NodeMaterialBlockConnectionPointTypes.Color3, true);
    this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3);
    this.registerOutput("hsl", NodeMaterialBlockConnectionPointTypes.Color3);
  }
  getClassName() {
    return "ColorConverterBlock";
  }
  get rgbIn() {
    return this._inputs[0];
  }
  get hslIn() {
    return this._inputs[1];
  }
  get rgbOut() {
    return this._outputs[0];
  }
  get hslOut() {
    return this._outputs[1];
  }
  _inputRename(name370) {
    if (name370 === "rgb ") {
      return "rgbIn";
    }
    if (name370 === "hsl ") {
      return "hslIn";
    }
    return name370;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const rgbInput = this.rgbIn;
    const hslInput = this.hslIn;
    const rbgOutput = this._outputs[0];
    const hslOutput = this._outputs[1];
    const vec3 = state._getShaderType(NodeMaterialBlockConnectionPointTypes.Vector3);
    let rgb2hsl = `
            vec3 rgb2hsl(vec3 color) {
                float r = color.r;
                float g = color.g;
                float b = color.b;

                float maxc = max(r, max(g, b));
                float minc = min(r, min(g, b));
                float h = 0.0;
                float s = 0.0;
                float l = (maxc + minc) / 2.0;

                if (maxc != minc) {
                    float d = maxc - minc;
                    if (l > 0.5) {
                        s = d / (2.0 - maxc - minc);
                    } else {
                        s = d / (maxc + minc);
                    }

                    if (maxc == r) {
                        float add = 0.0;
                        if (g < b) {
                            add = 6.0;
                        }
                        h = (g - b) / d + add;
                    } else if (maxc == g) {
                        h = (b - r) / d + 2.0;
                    } else if (maxc == b) {
                        h = (r - g) / d + 4.0;
                    }
                    h /= 6.0;
                }

                return vec3(h, s, l);
            }`;
    let hue2rgb = `
            float hue2rgb(float p, float q, float tt) {
                float t = tt;
                if (t < 0.0) {
                    t += 1.0;
                }
                if (t > 1.0) {
                    t -= 1.0;
                }
                if (t < 1.0/6.0) {
                    return p + (q - p) * 6.0 * t;
                }
                if (t < 1.0/2.0) {
                    return q;
                }
                if (t < 2.0/3.0) {
                    return p + (q - p) * (2.0/3.0 - t) * 6.0;
                }
                return p;
            }`;
    let hsl2rgb = `
            vec3 hsl2rgb(vec3 hsl) {
                float h = hsl.x;
                float s = hsl.y;
                float l = hsl.z;

                float r;
                float g;
                float b;

                if (s == 0.0) {
                    // Achromatic (grey)
                    r = l;
                    g = l;
                    b = l; 
                } else {
                    float q;
                
                    if (l < 0.5) {
                        q = l * (1.0 + s);
                    } else {
                        q = (l + s - l * s);
                    }

                    float p = 2.0 * l - q;

                    r = hue2rgb(p, q, h + 1.0/3.0);
                    g = hue2rgb(p, q, h);
                    b = hue2rgb(p, q, h - 1.0/3.0);
                }

                return vec3(r, g, b);
            }`;
    if (state.shaderLanguage === 1) {
      rgb2hsl = state._babylonSLtoWGSL(rgb2hsl);
      hue2rgb = state._babylonSLtoWGSL(hue2rgb);
      hsl2rgb = state._babylonSLtoWGSL(hsl2rgb);
    }
    state._emitFunction("rgb2hsl", rgb2hsl, "");
    state._emitFunction("hue2rgb", hue2rgb, "");
    state._emitFunction("hsl2rgb", hsl2rgb, "");
    if (rgbInput.isConnected) {
      if (rbgOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(rbgOutput) + ` = ${rgbInput.associatedVariableName};
`;
      }
      if (hslOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(hslOutput) + ` = rgb2hsl(${rgbInput.associatedVariableName});
`;
      }
    } else if (hslInput.isConnected) {
      if (rbgOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(rbgOutput) + ` = hsl2rgb(${hslInput.associatedVariableName});
`;
      }
      if (hslOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(hslOutput) + ` = ${hslInput.associatedVariableName};
`;
      }
    } else {
      if (rbgOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(rbgOutput) + ` =  ${vec3}(0.);
`;
      }
      if (hslOutput.hasEndpoints) {
        state.compilationString += state._declareOutput(hslOutput) + ` =  ${vec3}(0.);
`;
      }
    }
    return this;
  }
}
RegisterClass("BABYLON.ColorConverterBlock", ColorConverterBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/loopBlock.js
init_tslib_es6();
init_typeStore();
class LoopBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.iterations = 4;
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this.registerInput("iterations", NodeMaterialBlockConnectionPointTypes.Float, true);
    this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput);
    this.registerOutput("index", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);
    this.registerOutput("loopID", NodeMaterialBlockConnectionPointTypes.Object, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 1, LoopBlock, "LoopBlock"));
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._outputs[0]._forPostBuild = true;
    this._outputs[2]._redirectedSource = this._inputs[0];
    this._outputs[1]._preventBubbleUp = true;
    this._outputs[2]._preventBubbleUp = true;
  }
  getClassName() {
    return "LoopBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get iterationsInput() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  get index() {
    return this._outputs[1];
  }
  get loopID() {
    return this._outputs[2];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const index = this._outputs[1];
    const indexName = state._getFreeVariableName("index");
    const decl = state.shaderLanguage === 1 ? "var" : "int";
    const castFloat = state.shaderLanguage === 1 ? "f32" : "float";
    const castInt = state.shaderLanguage === 1 ? "i32" : "int";
    state.compilationString += state._declareOutput(output) + ` = ${this.input.associatedVariableName};
`;
    const iterations = this.iterationsInput.isConnected ? `${castInt}(${this.iterationsInput.associatedVariableName})` : this.iterations;
    state.compilationString += `for (${decl} ${indexName} = 0; ${indexName} < ${iterations}; ${indexName}++){
`;
    state.compilationString += `${state._declareOutput(index)} = ${castFloat}(${indexName});
`;
    return this;
  }
  _postBuildBlock(state) {
    super._postBuildBlock(state);
    state.compilationString += `}
`;
    return this;
  }
  _dumpPropertiesCode() {
    return super._dumpPropertiesCode() + `${this._codeVariableName}.iterations = ${this.iterations};
`;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.iterations = this.iterations;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.iterations = serializationObject.iterations;
  }
}
__decorate([
  editableInPropertyPage("Iterations", 2, undefined, { embedded: true })
], LoopBlock.prototype, "iterations", undefined);
RegisterClass("BABYLON.LoopBlock", LoopBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/storageReadBlock.js
init_typeStore();
class StorageReadBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("loopID", NodeMaterialBlockConnectionPointTypes.Object, false, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 0, LoopBlock, "LoopBlock"));
    this.registerOutput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this._outputs[0]._linkedConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "StorageReadBlock";
  }
  get loopID() {
    return this._inputs[0];
  }
  get value() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const value = this.value;
    if (!this.loopID.isConnected) {
      return this;
    }
    const loopBlock = this.loopID.connectedPoint.ownerBlock;
    state.compilationString += state._declareOutput(value) + ` = ${loopBlock.output.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.StorageReadBlock", StorageReadBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/storageWriteBlock.js
init_typeStore();
class StorageWriteBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("loopID", NodeMaterialBlockConnectionPointTypes.Object, false, undefined, new NodeMaterialConnectionPointCustomObject("loopID", this, 0, LoopBlock, "LoopBlock"));
    this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect);
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "StorageWriteBlock";
  }
  get loopID() {
    return this._inputs[0];
  }
  get value() {
    return this._inputs[1];
  }
  isConnectedInFragmentShader() {
    if (!this.loopID.isConnected) {
      return false;
    }
    const loopBlock = this.loopID.connectedPoint.ownerBlock;
    return loopBlock.output.isConnectedInFragmentShader;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const value = this.value;
    if (!this.loopID.isConnected) {
      return this;
    }
    const loopBlock = this.loopID.connectedPoint.ownerBlock;
    state.compilationString += `${loopBlock.output.associatedVariableName} = ${value.associatedVariableName};
`;
    return this;
  }
}
RegisterClass("BABYLON.StorageWriteBlock", StorageWriteBlock);
// node_modules/@babylonjs/core/Materials/Node/Blocks/matrixSplitterBlock.js
init_typeStore();

class MatrixSplitterBlock extends NodeMaterialBlock {
  constructor(name370) {
    super(name370, NodeMaterialBlockTargets.Neutral);
    this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix);
    this.registerOutput("row0", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("row1", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("row2", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("row3", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("col0", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("col1", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("col2", NodeMaterialBlockConnectionPointTypes.Vector4);
    this.registerOutput("col3", NodeMaterialBlockConnectionPointTypes.Vector4);
  }
  getClassName() {
    return "MatrixSplitterBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get row0() {
    return this._outputs[0];
  }
  get row1() {
    return this._outputs[1];
  }
  get row2() {
    return this._outputs[2];
  }
  get row3() {
    return this._outputs[3];
  }
  get col0() {
    return this._outputs[4];
  }
  get col1() {
    return this._outputs[5];
  }
  get col2() {
    return this._outputs[6];
  }
  get col3() {
    return this._outputs[7];
  }
  _exportColumn(state, col, input, columnIndex) {
    const vec4 = state.shaderLanguage === 1 ? "vec4f" : "vec4";
    state.compilationString += state._declareOutput(col) + ` = ${vec4}(${input}[0][${columnIndex}], ${input}[1][${columnIndex}], ${input}[2][${columnIndex}], ${input}[3][${columnIndex}]);
`;
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const input = this._inputs[0].associatedVariableName;
    const row0 = this.row0;
    const row1 = this.row1;
    const row2 = this.row2;
    const row3 = this.row3;
    const col0 = this.col0;
    const col1 = this.col1;
    const col2 = this.col2;
    const col3 = this.col3;
    if (row0.hasEndpoints) {
      state.compilationString += state._declareOutput(row0) + ` = ${input}[0];
`;
    }
    if (row1.hasEndpoints) {
      state.compilationString += state._declareOutput(row1) + ` = ${input}[1];
`;
    }
    if (row2.hasEndpoints) {
      state.compilationString += state._declareOutput(row2) + ` = ${input}[2];
`;
    }
    if (row3.hasEndpoints) {
      state.compilationString += state._declareOutput(row3) + ` = ${input}[3];
`;
    }
    if (col0.hasEndpoints) {
      this._exportColumn(state, col0, input, 0);
    }
    if (col1.hasEndpoints) {
      this._exportColumn(state, col1, input, 1);
    }
    if (col2.hasEndpoints) {
      this._exportColumn(state, col2, input, 2);
    }
    if (col3.hasEndpoints) {
      this._exportColumn(state, col3, input, 3);
    }
    return this;
  }
}
RegisterClass("BABYLON.MatrixSplitterBlock", MatrixSplitterBlock);
// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/gaussianSplattingVertexDeclaration.js
init_shaderStore();
var name370 = "gaussianSplattingVertexDeclaration";
var shader369 = `attribute position: vec2f;
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name370]) {
  ShaderStore.IncludesShadersStoreWGSL[name370] = shader369;
}

// node_modules/@babylonjs/core/Materials/Node/Blocks/GaussianSplatting/index.js
init_gaussianSplattingVertexDeclaration();
// node_modules/@babylonjs/core/Materials/Node/Blocks/debugBlock.js
init_tslib_es6();
init_typeStore();
class NodeMaterialDebugBlock extends NodeMaterialBlock {
  get isActive() {
    return this._isActive && this.debug.isConnected;
  }
  set isActive(value) {
    if (this._isActive === value) {
      return;
    }
    this._isActive = value;
  }
  constructor(name371) {
    super(name371, NodeMaterialBlockTargets.Fragment, true, true);
    this._isActive = false;
    this.renderAlpha = false;
    this.registerInput("debug", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);
    this.debug.excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);
  }
  get _isFinalOutputAndActive() {
    return this.isActive;
  }
  get _hasPrecedence() {
    return true;
  }
  get debug() {
    return this._inputs[0];
  }
  getClassName() {
    return "NodeMaterialDebugBlock";
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this._isActive) {
      return this;
    }
    let outputString = "gl_FragColor";
    if (state.shaderLanguage === 1) {
      outputString = "fragmentOutputs.color";
    }
    const debug = this.debug;
    if (!debug.connectedPoint) {
      return this;
    }
    if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) {
      state.compilationString += `${outputString}  = vec4${state.fSuffix}(${debug.associatedVariableName}, ${debug.associatedVariableName}, ${debug.associatedVariableName}, 1.0);
`;
    } else if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector2) {
      state.compilationString += `${outputString}  = vec4${state.fSuffix}(${debug.associatedVariableName}, 0., 1.0);
`;
    } else if (debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color3 || debug.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector3) {
      state.compilationString += `${outputString}  = vec4${state.fSuffix}(${debug.associatedVariableName}, 1.0);
`;
    } else if (this.renderAlpha) {
      state.compilationString += `${outputString}  =${debug.associatedVariableName};
`;
    } else {
      state.compilationString += `${outputString}  = vec4${state.fSuffix}(${debug.associatedVariableName}.rgb, 1.0);
`;
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.isActive = this._isActive;
    serializationObject.renderAlpha = this.renderAlpha;
    return serializationObject;
  }
  _deserialize(serializationObject, scene, rootUrl) {
    super._deserialize(serializationObject, scene, rootUrl);
    this.isActive = serializationObject.isActive;
    this.renderAlpha = serializationObject.renderAlpha;
  }
}
__decorate([
  editableInPropertyPage("Render Alpha", 0, undefined)
], NodeMaterialDebugBlock.prototype, "renderAlpha", undefined);
RegisterClass("BABYLON.NodeMaterialDebugBlock", NodeMaterialDebugBlock);
// node_modules/@babylonjs/core/Materials/index.js
init_effectRenderer();

// node_modules/@babylonjs/core/Materials/shadowDepthWrapper.js
init_effect();
init_guid();
init_drawWrapper();
init_engineStore();

// node_modules/@babylonjs/core/Materials/index.js
init_drawWrapper();

// node_modules/@babylonjs/core/Materials/materialPluginEvent.js
var MaterialPluginEvent;
(function(MaterialPluginEvent2) {
  MaterialPluginEvent2[MaterialPluginEvent2["Created"] = 1] = "Created";
  MaterialPluginEvent2[MaterialPluginEvent2["Disposed"] = 2] = "Disposed";
  MaterialPluginEvent2[MaterialPluginEvent2["GetDefineNames"] = 4] = "GetDefineNames";
  MaterialPluginEvent2[MaterialPluginEvent2["PrepareUniformBuffer"] = 8] = "PrepareUniformBuffer";
  MaterialPluginEvent2[MaterialPluginEvent2["IsReadyForSubMesh"] = 16] = "IsReadyForSubMesh";
  MaterialPluginEvent2[MaterialPluginEvent2["PrepareDefines"] = 32] = "PrepareDefines";
  MaterialPluginEvent2[MaterialPluginEvent2["BindForSubMesh"] = 64] = "BindForSubMesh";
  MaterialPluginEvent2[MaterialPluginEvent2["PrepareEffect"] = 128] = "PrepareEffect";
  MaterialPluginEvent2[MaterialPluginEvent2["GetAnimatables"] = 256] = "GetAnimatables";
  MaterialPluginEvent2[MaterialPluginEvent2["GetActiveTextures"] = 512] = "GetActiveTextures";
  MaterialPluginEvent2[MaterialPluginEvent2["HasTexture"] = 1024] = "HasTexture";
  MaterialPluginEvent2[MaterialPluginEvent2["FillRenderTargetTextures"] = 2048] = "FillRenderTargetTextures";
  MaterialPluginEvent2[MaterialPluginEvent2["HasRenderTargetTextures"] = 4096] = "HasRenderTargetTextures";
  MaterialPluginEvent2[MaterialPluginEvent2["HardBindForSubMesh"] = 8192] = "HardBindForSubMesh";
})(MaterialPluginEvent || (MaterialPluginEvent = {}));
// node_modules/@babylonjs/core/Materials/material.decalMapConfiguration.js
init_tslib_es6();
init_decorators();
init_typeStore();
init_materialHelper_functions();

class DecalMapDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.DECAL = false;
    this.DECALDIRECTUV = 0;
    this.DECAL_SMOOTHALPHA = false;
    this.GAMMADECAL = false;
  }
}

class DecalMapConfiguration extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material, addToPluginList = true) {
    super(material, "DecalMap", 150, new DecalMapDefines, addToPluginList);
    this._isEnabled = false;
    this.isEnabled = false;
    this._smoothAlpha = false;
    this.smoothAlpha = false;
    this.registerForExtraEvents = true;
    this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];
  }
  isReadyForSubMesh(defines, scene, engine2, subMesh) {
    const decalMap = subMesh.getMesh().decalMap;
    if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {
      return true;
    }
    return decalMap.isReady();
  }
  prepareDefinesBeforeAttributes(defines, scene, mesh) {
    const decalMap = mesh.decalMap;
    if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {
      const isDirty = defines.DECAL;
      if (isDirty) {
        defines.markAsTexturesDirty();
      }
      defines.DECAL = false;
    } else {
      const isDirty = !defines.DECAL || defines.GAMMADECAL !== decalMap.texture.gammaSpace;
      if (isDirty) {
        defines.markAsTexturesDirty();
      }
      defines.DECAL = true;
      defines.GAMMADECAL = decalMap.texture.gammaSpace;
      defines.DECAL_SMOOTHALPHA = this._smoothAlpha;
      PrepareDefinesForMergedUV(decalMap.texture, defines, "DECAL");
    }
  }
  hardBindForSubMesh(uniformBuffer, scene, _engine, subMesh) {
    const decalMap = subMesh.getMesh().decalMap;
    if (!this._isEnabled || !decalMap?.texture || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {
      return;
    }
    const isFrozen = this._material.isFrozen;
    const texture2 = decalMap.texture;
    if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
      uniformBuffer.updateFloat4("vDecalInfos", texture2.coordinatesIndex, 0, 0, 0);
      BindTextureMatrix(texture2, uniformBuffer, "decal");
    }
    uniformBuffer.setTexture("decalSampler", texture2);
  }
  getClassName() {
    return "DecalMapConfiguration";
  }
  getSamplers(samplers) {
    samplers.push("decalSampler");
  }
  getUniforms() {
    return {
      ubo: [
        { name: "vDecalInfos", size: 4, type: "vec4" },
        { name: "decalMatrix", size: 16, type: "mat4" }
      ]
    };
  }
}
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], DecalMapConfiguration.prototype, "isEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], DecalMapConfiguration.prototype, "smoothAlpha", undefined);
RegisterClass("BABYLON.DecalMapConfiguration", DecalMapConfiguration);
// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLinePluginMaterial.js
init_math_vector();
init_typeStore();

// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLineMaterialDefaults.js
init_math_color();

class GreasedLineMaterialDefaults {
}
GreasedLineMaterialDefaults.DEFAULT_COLOR = Color3.White();
GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED = 1;
GreasedLineMaterialDefaults.DEFAULT_WIDTH = 0.1;

// node_modules/@babylonjs/core/Misc/greasedLineTools.js
init_math_path();
init_buffer();
init_math_vector();
init_engine();
class GreasedLineTools {
  static ConvertPoints(points, options) {
    if (points.length && Array.isArray(points) && typeof points[0] === "number") {
      return [points];
    } else if (points.length && Array.isArray(points[0]) && typeof points[0][0] === "number") {
      return points;
    } else if (points.length && !Array.isArray(points[0]) && points[0] instanceof Vector3) {
      const positions = [];
      for (let j = 0;j < points.length; j++) {
        const p = points[j];
        positions.push(p.x, p.y, p.z);
      }
      return [positions];
    } else if (points.length > 0 && Array.isArray(points[0]) && points[0].length > 0 && points[0][0] instanceof Vector3) {
      const positions = [];
      const vectorPoints = points;
      vectorPoints.forEach((p) => {
        positions.push(p.flatMap((p2) => [p2.x, p2.y, p2.z]));
      });
      return positions;
    } else if (points instanceof Float32Array) {
      if (options?.floatArrayStride) {
        const positions = [];
        const stride = options.floatArrayStride * 3;
        for (let i = 0;i < points.length; i += stride) {
          const linePoints = new Array(stride);
          for (let j = 0;j < stride; j++) {
            linePoints[j] = points[i + j];
          }
          positions.push(linePoints);
        }
        return positions;
      } else {
        return [Array.from(points)];
      }
    } else if (points.length && points[0] instanceof Float32Array) {
      const positions = [];
      points.forEach((p) => {
        positions.push(Array.from(p));
      });
      return positions;
    }
    return [];
  }
  static OmitZeroLengthPredicate(p1, p2, p3) {
    const fileredPoints = [];
    if (p2.subtract(p1).lengthSquared() > 0) {
      fileredPoints.push([p1, p2]);
    }
    if (p3.subtract(p2).lengthSquared() > 0) {
      fileredPoints.push([p2, p3]);
    }
    if (p1.subtract(p3).lengthSquared() > 0) {
      fileredPoints.push([p3, p1]);
    }
    return fileredPoints.length === 0 ? null : fileredPoints;
  }
  static OmitDuplicatesPredicate(p1, p2, p3, points) {
    const fileredPoints = [];
    if (!GreasedLineTools._SearchInPoints(p1, p2, points)) {
      fileredPoints.push([p1, p2]);
    }
    if (!GreasedLineTools._SearchInPoints(p2, p3, points)) {
      fileredPoints.push([p2, p3]);
    }
    if (!GreasedLineTools._SearchInPoints(p3, p1, points)) {
      fileredPoints.push([p3, p1]);
    }
    return fileredPoints.length === 0 ? null : fileredPoints;
  }
  static _SearchInPoints(p1, p2, points) {
    for (const ps of points) {
      for (let i = 0;i < ps.length; i++) {
        if (ps[i]?.equals(p1)) {
          if (ps[i + 1]?.equals(p2) || ps[i - 1]?.equals(p2)) {
            return true;
          }
        }
      }
    }
    return false;
  }
  static MeshesToLines(meshes, predicate) {
    const points = [];
    meshes.forEach((m, meshIndex) => {
      const vertices = m.getVerticesData(VertexBuffer.PositionKind);
      const indices = m.getIndices();
      if (vertices && indices) {
        for (let i = 0, ii = 0;i < indices.length; i++) {
          const vi1 = indices[ii++] * 3;
          const vi2 = indices[ii++] * 3;
          const vi3 = indices[ii++] * 3;
          const p1 = new Vector3(vertices[vi1], vertices[vi1 + 1], vertices[vi1 + 2]);
          const p2 = new Vector3(vertices[vi2], vertices[vi2 + 1], vertices[vi2 + 2]);
          const p3 = new Vector3(vertices[vi3], vertices[vi3 + 1], vertices[vi3 + 2]);
          if (predicate) {
            const pointsFromPredicate = predicate(p1, p2, p3, points, i, vi1, m, meshIndex, vertices, indices);
            if (pointsFromPredicate) {
              for (const p of pointsFromPredicate) {
                points.push(p);
              }
            }
          } else {
            points.push([p1, p2], [p2, p3], [p3, p1]);
          }
        }
      }
    });
    return points;
  }
  static ToVector3Array(points) {
    if (Array.isArray(points[0])) {
      const array2 = [];
      const inputArray2 = points;
      for (const subInputArray of inputArray2) {
        const subArray = [];
        for (let i = 0;i < subInputArray.length; i += 3) {
          subArray.push(new Vector3(subInputArray[i], subInputArray[i + 1], subInputArray[i + 2]));
        }
        array2.push(subArray);
      }
      return array2;
    }
    const inputArray = points;
    const array = [];
    for (let i = 0;i < inputArray.length; i += 3) {
      array.push(new Vector3(inputArray[i], inputArray[i + 1], inputArray[i + 2]));
    }
    return array;
  }
  static ToNumberArray(points) {
    return points.flatMap((v) => [v.x, v.y, v.z]);
  }
  static GetPointsCountInfo(points) {
    const counts = new Array(points.length);
    let total = 0;
    for (let n = points.length;n--; ) {
      counts[n] = points[n].length / 3;
      total += counts[n];
    }
    return { total, counts };
  }
  static GetLineLength(data) {
    if (data.length === 0) {
      return 0;
    }
    let points;
    if (typeof data[0] === "number") {
      points = GreasedLineTools.ToVector3Array(data);
    } else {
      points = data;
    }
    const tmp = TmpVectors.Vector3[0];
    let length = 0;
    for (let index = 0;index < points.length - 1; index++) {
      const point1 = points[index];
      const point2 = points[index + 1];
      length += point2.subtractToRef(point1, tmp).length();
    }
    return length;
  }
  static GetLineLengthArray(data) {
    const out = new Float32Array(data.length / 3);
    let length = 0;
    for (let index = 0, pointsLength = data.length / 3 - 1;index < pointsLength; index++) {
      let x = data[index * 3 + 0];
      let y = data[index * 3 + 1];
      let z = data[index * 3 + 2];
      x -= data[index * 3 + 3];
      y -= data[index * 3 + 4];
      z -= data[index * 3 + 5];
      const currentLength = Math.sqrt(x * x + y * y + z * z);
      length += currentLength;
      out[index + 1] = length;
    }
    return out;
  }
  static SegmentizeSegmentByCount(point1, point2, segmentCount) {
    const dividedLinePoints = [];
    const diff = point2.subtract(point1);
    const divisor = TmpVectors.Vector3[0];
    divisor.setAll(segmentCount);
    const segmentVector = TmpVectors.Vector3[1];
    diff.divideToRef(divisor, segmentVector);
    let nextPoint = point1.clone();
    dividedLinePoints.push(nextPoint);
    for (let index = 0;index < segmentCount; index++) {
      nextPoint = nextPoint.clone();
      dividedLinePoints.push(nextPoint.addInPlace(segmentVector));
    }
    return dividedLinePoints;
  }
  static SegmentizeLineBySegmentLength(what, segmentLength) {
    const subLines = what[0] instanceof Vector3 ? GreasedLineTools.GetLineSegments(what) : typeof what[0] === "number" ? GreasedLineTools.GetLineSegments(GreasedLineTools.ToVector3Array(what)) : what;
    const points = [];
    subLines.forEach((s) => {
      if (s.length > segmentLength) {
        const segments = GreasedLineTools.SegmentizeSegmentByCount(s.point1, s.point2, Math.ceil(s.length / segmentLength));
        segments.forEach((seg) => {
          points.push(seg);
        });
      } else {
        points.push(s.point1);
        points.push(s.point2);
      }
    });
    return points;
  }
  static SegmentizeLineBySegmentCount(what, segmentCount) {
    const points = typeof what[0] === "number" ? GreasedLineTools.ToVector3Array(what) : what;
    const segmentLength = GreasedLineTools.GetLineLength(points) / segmentCount;
    return GreasedLineTools.SegmentizeLineBySegmentLength(points, segmentLength);
  }
  static GetLineSegments(points) {
    const segments = [];
    for (let index = 0;index < points.length - 1; index++) {
      const point1 = points[index];
      const point2 = points[index + 1];
      const length = point2.subtract(point1).length();
      segments.push({ point1, point2, length });
    }
    return segments;
  }
  static GetMinMaxSegmentLength(points) {
    const subLines = GreasedLineTools.GetLineSegments(points);
    const sorted = subLines.sort((s) => s.length);
    return {
      min: sorted[0].length,
      max: sorted[sorted.length - 1].length
    };
  }
  static GetPositionOnLineByVisibility(lineSegments, lineLength, visbility, localSpace = false) {
    const lengthVisibilityRatio = lineLength * visbility;
    let sumSegmentLengths = 0;
    let segmentIndex = 0;
    const lineSegmentsLength = lineSegments.length;
    for (let i = 0;i < lineSegmentsLength; i++) {
      if (lengthVisibilityRatio <= sumSegmentLengths + lineSegments[i].length) {
        segmentIndex = i;
        break;
      }
      sumSegmentLengths += lineSegments[i].length;
    }
    const s = (lengthVisibilityRatio - sumSegmentLengths) / lineSegments[segmentIndex].length;
    lineSegments[segmentIndex].point2.subtractToRef(lineSegments[segmentIndex].point1, TmpVectors.Vector3[0]);
    TmpVectors.Vector3[1] = TmpVectors.Vector3[0].multiplyByFloats(s, s, s);
    if (!localSpace) {
      TmpVectors.Vector3[1].addInPlace(lineSegments[segmentIndex].point1);
    }
    return TmpVectors.Vector3[1].clone();
  }
  static GetCircleLinePoints(radiusX, segments, z = 0, radiusY = radiusX, segmentAngle = Math.PI * 2 / segments) {
    const points = [];
    for (let i = 0;i <= segments; i++) {
      points.push(new Vector3(Math.cos(i * segmentAngle) * radiusX, Math.sin(i * segmentAngle) * radiusY, z));
    }
    return points;
  }
  static GetBezierLinePoints(p0, p1, p2, segments) {
    return Curve3.CreateQuadraticBezier(p0, p1, p2, segments).getPoints().flatMap((v) => [v.x, v.y, v.z]);
  }
  static GetArrowCap(position, direction, length, widthUp, widthDown, widthStartUp = 0, widthStartDown = 0) {
    const points = [position.clone(), position.add(direction.multiplyByFloats(length, length, length))];
    const widths = [widthUp, widthDown, widthStartUp, widthStartDown];
    return {
      points,
      widths
    };
  }
  static GetPointsFromText(text, size, resolution, fontData, z = 0, includeInner = true) {
    const allPoints = [];
    const shapePaths = CreateTextShapePaths(text, size, resolution, fontData);
    for (const sp of shapePaths) {
      for (const p of sp.paths) {
        const points = [];
        const points2d = p.getPoints();
        for (const p2d of points2d) {
          points.push(p2d.x, p2d.y, z);
        }
        allPoints.push(points);
      }
      if (includeInner) {
        for (const h of sp.holes) {
          const holes = [];
          const points2d = h.getPoints();
          for (const p2d of points2d) {
            holes.push(p2d.x, p2d.y, z);
          }
          allPoints.push(holes);
        }
      }
    }
    return allPoints;
  }
  static Color3toRGBAUint8(colors) {
    const colorTable = new Uint8Array(colors.length * 4);
    for (let i = 0, j = 0;i < colors.length; i++) {
      colorTable[j++] = colors[i].r * 255;
      colorTable[j++] = colors[i].g * 255;
      colorTable[j++] = colors[i].b * 255;
      colorTable[j++] = 255;
    }
    return colorTable;
  }
  static CreateColorsTexture(name371, colors, colorsSampling, scene) {
    const maxTextureSize = scene.getEngine().getCaps().maxTextureSize ?? 1;
    const width = colors.length > maxTextureSize ? maxTextureSize : colors.length;
    const height = Math.ceil(colors.length / maxTextureSize);
    if (height > 1) {
      colors = [...colors, ...Array(width * height - colors.length).fill(colors[0])];
    }
    const colorsArray = GreasedLineTools.Color3toRGBAUint8(colors);
    const colorsTexture = new RawTexture(colorsArray, width, height, Engine.TEXTUREFORMAT_RGBA, scene, false, true, colorsSampling);
    colorsTexture.name = name371;
    return colorsTexture;
  }
  static PrepareEmptyColorsTexture(scene) {
    if (!GreasedLineMaterialDefaults.EmptyColorsTexture) {
      const colorsArray = new Uint8Array(4);
      GreasedLineMaterialDefaults.EmptyColorsTexture = new RawTexture(colorsArray, 1, 1, Engine.TEXTUREFORMAT_RGBA, scene, false, false, RawTexture.NEAREST_NEAREST);
      GreasedLineMaterialDefaults.EmptyColorsTexture.name = "grlEmptyColorsTexture";
    }
    return GreasedLineMaterialDefaults.EmptyColorsTexture;
  }
  static DisposeEmptyColorsTexture() {
    GreasedLineMaterialDefaults.EmptyColorsTexture?.dispose();
    GreasedLineMaterialDefaults.EmptyColorsTexture = null;
  }
  static BooleanToNumber(bool) {
    return bool ? 1 : 0;
  }
}

// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLinePluginMaterialShadersGLSL.js
function GetCustomCode(shaderType, cameraFacing) {
  if (shaderType === "vertex") {
    const obj = {
      CUSTOM_VERTEX_DEFINITIONS: `
                attribute float grl_widths;
                attribute vec3 grl_offsets;
                attribute float grl_colorPointers;
                varying float grlCounters;
                varying float grlColorPointer;

                #ifdef GREASED_LINE_CAMERA_FACING
                    attribute vec4 grl_previousAndSide;
                    attribute vec4 grl_nextAndCounters;

                    vec2 grlFix( vec4 i, float aspect ) {
                        vec2 res = i.xy / i.w;
                        res.x *= aspect;
                        return res;
                    }
                #else
                    attribute vec3 grl_slopes;
                    attribute float grl_counters;
                #endif
                `,
      CUSTOM_VERTEX_UPDATE_POSITION: `
                #ifdef GREASED_LINE_CAMERA_FACING
                    vec3 grlPositionOffset = grl_offsets;
                    positionUpdated += grlPositionOffset;
                #else
                    positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);
                #endif
                `,
      CUSTOM_VERTEX_MAIN_END: `
                grlColorPointer = grl_colorPointers;

                #ifdef GREASED_LINE_CAMERA_FACING

                    float grlAspect = grl_aspect_resolution_lineWidth.x;
                    float grlBaseWidth = grl_aspect_resolution_lineWidth.w;

                    vec3 grlPrevious = grl_previousAndSide.xyz;
                    float grlSide = grl_previousAndSide.w;

                    vec3 grlNext = grl_nextAndCounters.xyz;
                    grlCounters = grl_nextAndCounters.w;
                    float grlWidth = grlBaseWidth * grl_widths;
                    
                    vec3 worldDir = normalize(grlNext - grlPrevious);
                    vec3 nearPosition = positionUpdated + (worldDir * 0.001);
                    mat4 grlMatrix = viewProjection * finalWorld;
                    vec4 grlFinalPosition = grlMatrix * vec4(positionUpdated , 1.0);
                    vec4 screenNearPos = grlMatrix * vec4(nearPosition, 1.0);
                    vec2 grlLinePosition = grlFix(grlFinalPosition, grlAspect);
                    vec2 grlLineNearPosition = grlFix(screenNearPos, grlAspect);
                    vec2 grlDir = normalize(grlLineNearPosition - grlLinePosition);

                    vec4 grlNormal = vec4(-grlDir.y, grlDir.x, 0., 1.);

                    #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM
                        grlNormal.xy *= -.5 * grlWidth;
                    #else
                        grlNormal.xy *= .5 * grlWidth;
                    #endif

                    grlNormal *= grl_projection;

                    #ifdef GREASED_LINE_SIZE_ATTENUATION
                        grlNormal.xy *= grlFinalPosition.w;
                        grlNormal.xy /= (vec4(grl_aspect_resolution_lineWidth.yz, 0., 1.) * grl_projection).xy;
                    #endif

                    grlFinalPosition.xy += grlNormal.xy * grlSide;
                    gl_Position = grlFinalPosition;

                    vPositionW = vec3(grlFinalPosition);
                #else
                    grlCounters = grl_counters;
                #endif
                `
    };
    cameraFacing && (obj["!gl_Position\\=viewProjection\\*worldPos;"] = "//");
    return obj;
  }
  if (shaderType === "fragment") {
    return {
      CUSTOM_FRAGMENT_DEFINITIONS: `
                    #ifdef PBR
                         #define grlFinalColor finalColor
                    #else
                         #define grlFinalColor color
                    #endif

                    varying float grlCounters;
                    varying float grlColorPointer;
                    uniform sampler2D grl_colors;
                `,
      CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `
                    float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;
                    float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;
                    float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;
                    float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;

                    float grlUseDash = grl_dashOptions.x;
                    float grlDashArray = grl_dashOptions.y;
                    float grlDashOffset = grl_dashOptions.z;
                    float grlDashRatio = grl_dashOptions.w;

                    grlFinalColor.a *= step(grlCounters, grlVisibility);
                    if(grlFinalColor.a == 0.) discard;

                    if(grlUseDash == 1.){
                        grlFinalColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));
                        if (grlFinalColor.a == 0.) discard;
                    }

                    #ifdef GREASED_LINE_HAS_COLOR
                        if (grlColorMode == ${0}.) {
                            grlFinalColor.rgb = grl_singleColor;
                        } else if (grlColorMode == ${1}.) {
                            grlFinalColor.rgb += grl_singleColor;
                        } else if (grlColorMode == ${2}.) {
                            grlFinalColor.rgb *= grl_singleColor;
                        }
                    #else
                        if (grlUseColors == 1.) {
                            #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE
                                vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);
                            #else
                                vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));
                                vec4 grlColor = texture2D(grl_colors, lookup, 0.0);
                            #endif
                            if (grlColorMode == ${0}.) {
                                grlFinalColor = grlColor;
                            } else if (grlColorMode == ${1}.) {
                                grlFinalColor += grlColor;
                            } else if (grlColorMode == ${2}.) {
                                grlFinalColor *= grlColor;
                            }
                        }
                    #endif
                `
    };
  }
  return null;
}

// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLinePluginMaterialShadersWGSL.js
function GetCustomCode2(shaderType, cameraFacing) {
  if (shaderType === "vertex") {
    const obj = {
      CUSTOM_VERTEX_DEFINITIONS: `
                attribute grl_widths: f32;
                attribute grl_colorPointers: f32;
                varying grlCounters: f32;
                varying grlColorPointer: f32;

                #ifdef GREASED_LINE_USE_OFFSETS
                    attribute grl_offsets: vec3f;   
                #endif

                #ifdef GREASED_LINE_CAMERA_FACING
                    attribute grl_previousAndSide : vec4f;
                    attribute grl_nextAndCounters : vec4f;

                    fn grlFix(i: vec4f, aspect: f32) -> vec2f {
                        var res = i.xy / i.w;
                        res.x *= aspect;
                        return res;
                    }
                #else
                    attribute grl_slopes: f32;
                    attribute grl_counters: f32;
                #endif


                `,
      CUSTOM_VERTEX_UPDATE_POSITION: `
                #ifdef GREASED_LINE_USE_OFFSETS
                    var grlPositionOffset: vec3f = input.grl_offsets;
                #else
                    var grlPositionOffset = vec3f(0.);
                #endif

                #ifdef GREASED_LINE_CAMERA_FACING
                    positionUpdated += grlPositionOffset;
                #else
                    positionUpdated = (positionUpdated + grlPositionOffset) + (input.grl_slopes * input.grl_widths);
                #endif
                `,
      CUSTOM_VERTEX_MAIN_END: `
                vertexOutputs.grlColorPointer = input.grl_colorPointers;

                #ifdef GREASED_LINE_CAMERA_FACING

                    let grlAspect: f32 = uniforms.grl_aspect_resolution_lineWidth.x;
                    let grlBaseWidth: f32 = uniforms.grl_aspect_resolution_lineWidth.w;

                    let grlPrevious: vec3f = input.grl_previousAndSide.xyz;
                    let grlSide: f32 = input.grl_previousAndSide.w;

                    let grlNext: vec3f = input.grl_nextAndCounters.xyz;
                    vertexOutputs.grlCounters = input.grl_nextAndCounters.w;

                    let grlWidth: f32 = grlBaseWidth * input.grl_widths;

                    let worldDir: vec3f = normalize(grlNext - grlPrevious);
                    let nearPosition: vec3f = positionUpdated + (worldDir * 0.001);
                    let grlMatrix: mat4x4f = uniforms.viewProjection * finalWorld;
                    let grlFinalPosition: vec4f = grlMatrix * vec4f(positionUpdated, 1.0); 
                    let screenNearPos: vec4f = grlMatrix * vec4(nearPosition, 1.0);
                    let grlLinePosition: vec2f = grlFix(grlFinalPosition, grlAspect);
                    let grlLineNearPosition: vec2f = grlFix(screenNearPos, grlAspect);
                    let grlDir: vec2f = normalize(grlLineNearPosition - grlLinePosition);

                    var grlNormal: vec4f = vec4f(-grlDir.y, grlDir.x, 0.0, 1.0);

                    let grlHalfWidth: f32 = 0.5 * grlWidth;
                    #if defined(GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM)
                        grlNormal.x *= -grlHalfWidth;
                        grlNormal.y *= -grlHalfWidth;
                    #else
                        grlNormal.x *= grlHalfWidth;
                        grlNormal.y *= grlHalfWidth;
                    #endif

                    grlNormal *= uniforms.grl_projection;

                    #if defined(GREASED_LINE_SIZE_ATTENUATION)
                        grlNormal.x *= grlFinalPosition.w;
                        grlNormal.y *= grlFinalPosition.w;

                        let pr = vec4f(uniforms.grl_aspect_resolution_lineWidth.yz, 0.0, 1.0) * uniforms.grl_projection;
                        grlNormal.x /= pr.x;
                        grlNormal.y /= pr.y;
                    #endif

                    vertexOutputs.position = vec4f(grlFinalPosition.xy + grlNormal.xy * grlSide, grlFinalPosition.z, grlFinalPosition.w);
                    vertexOutputs.vPositionW = vertexOutputs.position.xyz;
                
                #else
                    vertexOutputs.grlCounters = input.grl_counters;
                #endif
                `
    };
    cameraFacing && (obj["!vertexOutputs\\.position\\s=\\sscene\\.viewProjection\\s\\*\\sworldPos;"] = "//");
    return obj;
  }
  if (shaderType === "fragment") {
    return {
      CUSTOM_FRAGMENT_DEFINITIONS: `
                    #ifdef PBR
                         #define grlFinalColor finalColor
                    #else
                         #define grlFinalColor color
                    #endif

                    varying grlCounters: f32;
                    varying grlColorPointer: 32;

                    var grl_colors: texture_2d<f32>;
                    var grl_colorsSampler: sampler;
                `,
      CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `
                    let grlColorMode: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.x;
                    let grlVisibility: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.y;
                    let grlColorsWidth: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.z;
                    let grlUseColors: f32 = uniforms.grl_colorMode_visibility_colorsWidth_useColors.w;

                    let grlUseDash: f32 = uniforms.grl_dashOptions.x;
                    let grlDashArray: f32 = uniforms.grl_dashOptions.y;
                    let grlDashOffset: f32 = uniforms.grl_dashOptions.z;
                    let grlDashRatio: f32 = uniforms.grl_dashOptions.w;

                    grlFinalColor.a *= step(fragmentInputs.grlCounters, grlVisibility);
                    if (grlFinalColor.a == 0.0) {
                        discard;
                    }

                    if (grlUseDash == 1.0) {
                        let dashPosition = (fragmentInputs.grlCounters + grlDashOffset) % grlDashArray;
                        grlFinalColor.a *= ceil(dashPosition - (grlDashArray * grlDashRatio));

                        if (grlFinalColor.a == 0.0) {
                            discard;
                        }
                    }

                    #ifdef GREASED_LINE_HAS_COLOR
                        if (grlColorMode == ${0}.) {
                            grlFinalColor = vec4f(uniforms.grl_singleColor, grlFinalColor.a);
                        } else if (grlColorMode == ${1}.) {
                            grlFinalColor += vec4f(uniforms.grl_singleColor, grlFinalColor.a);
                        } else if (grlColorMode == ${2}.) {
                            grlFinalColor *= vec4f(uniforms.grl_singleColor, grlFinalColor.a);
                        }
                    #else
                        if (grlUseColors == 1.) {
                            #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE
                                let grlColor: vec4f = textureSample(grl_colors, grl_colorsSampler, vec2f(fragmentInputs.grlCounters, 0.));
                            #else
                                let lookup: vec2f = vec2(fract(fragmentInputs.grlColorPointer / uniforms.grl_textureSize.x), 1.0 - floor(fragmentInputs.grlColorPointer / uniforms.grl_textureSize.x) / max(uniforms.grl_textureSize.y - 1.0, 1.0));
                                let grlColor: vec4f = textureSample(grl_colors, grl_colorsSampler, lookup);
                            #endif
                            if (grlColorMode == ${0}.) {
                                grlFinalColor = grlColor;
                            } else if (grlColorMode == ${1}.) {
                                grlFinalColor += grlColor;
                            } else if (grlColorMode == ${2}.) {
                                grlFinalColor *= grlColor;
                            }
                        }
                    #endif


                `
    };
  }
  return null;
}

// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLinePluginMaterial.js
class MaterialGreasedLineDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.GREASED_LINE_HAS_COLOR = false;
    this.GREASED_LINE_SIZE_ATTENUATION = false;
    this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = false;
    this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = false;
    this.GREASED_LINE_CAMERA_FACING = true;
    this.GREASED_LINE_USE_OFFSETS = false;
  }
}

class GreasedLinePluginMaterial extends MaterialPluginBase {
  isCompatible(_shaderLanguage) {
    return true;
  }
  constructor(material, scene, options) {
    options = options || {
      color: GreasedLineMaterialDefaults.DEFAULT_COLOR
    };
    const defines = new MaterialGreasedLineDefines;
    defines.GREASED_LINE_HAS_COLOR = !!options.color && !options.useColors;
    defines.GREASED_LINE_SIZE_ATTENUATION = options.sizeAttenuation ?? false;
    defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === 1;
    defines.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = (scene ?? material.getScene()).useRightHandedSystem;
    defines.GREASED_LINE_CAMERA_FACING = options.cameraFacing ?? true;
    super(material, GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME, 200, defines, true, true);
    this.colorsTexture = null;
    this._forceGLSL = false;
    this._forceGLSL = options?.forceGLSL || GreasedLinePluginMaterial.ForceGLSL;
    this._scene = scene ?? material.getScene();
    this._engine = this._scene.getEngine();
    this._cameraFacing = options.cameraFacing ?? true;
    this.visibility = options.visibility ?? 1;
    this.useDash = options.useDash ?? false;
    this.dashRatio = options.dashRatio ?? 0.5;
    this.dashOffset = options.dashOffset ?? 0;
    this.width = options.width ? options.width : options.sizeAttenuation ? GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED : GreasedLineMaterialDefaults.DEFAULT_WIDTH;
    this._sizeAttenuation = options.sizeAttenuation ?? false;
    this.colorMode = options.colorMode ?? 0;
    this._color = options.color ?? null;
    this.useColors = options.useColors ?? false;
    this._colorsDistributionType = options.colorDistributionType ?? 0;
    this.colorsSampling = options.colorsSampling ?? RawTexture.NEAREST_NEAREST;
    this._colors = options.colors ?? null;
    this.dashCount = options.dashCount ?? 1;
    this.resolution = options.resolution ?? new Vector2(this._engine.getRenderWidth(), this._engine.getRenderHeight());
    if (options.colorsTexture) {
      this.colorsTexture = options.colorsTexture;
    } else {
      if (this._colors) {
        this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${material.name}-colors-texture`, this._colors, this.colorsSampling, this._scene);
      } else {
        this._color = this._color ?? GreasedLineMaterialDefaults.DEFAULT_COLOR;
        GreasedLineTools.PrepareEmptyColorsTexture(this._scene);
      }
    }
    this._engine.onDisposeObservable.add(() => {
      GreasedLineTools.DisposeEmptyColorsTexture();
    });
  }
  getAttributes(attributes) {
    attributes.push("grl_offsets");
    attributes.push("grl_widths");
    attributes.push("grl_colorPointers");
    attributes.push("grl_counters");
    if (this._cameraFacing) {
      attributes.push("grl_previousAndSide");
      attributes.push("grl_nextAndCounters");
    } else {
      attributes.push("grl_slopes");
    }
  }
  getSamplers(samplers) {
    samplers.push("grl_colors");
  }
  getActiveTextures(activeTextures) {
    if (this.colorsTexture) {
      activeTextures.push(this.colorsTexture);
    }
  }
  getUniforms(shaderLanguage = 0) {
    const ubo = [
      { name: "grl_singleColor", size: 3, type: "vec3" },
      { name: "grl_textureSize", size: 2, type: "vec2" },
      { name: "grl_dashOptions", size: 4, type: "vec4" },
      { name: "grl_colorMode_visibility_colorsWidth_useColors", size: 4, type: "vec4" }
    ];
    if (this._cameraFacing) {
      ubo.push({ name: "grl_projection", size: 16, type: "mat4" }, { name: "grl_aspect_resolution_lineWidth", size: 4, type: "vec4" });
    }
    if (shaderLanguage === 1) {
      ubo.push({
        name: "viewProjection",
        size: 16,
        type: "mat4"
      });
    }
    return {
      ubo,
      vertex: this._cameraFacing && this._isGLSL(shaderLanguage) ? `
                    uniform vec4 grl_aspect_resolution_lineWidth;
                    uniform mat4 grl_projection;
    ` : "",
      fragment: this._isGLSL(shaderLanguage) ? `
                    uniform vec4 grl_dashOptions;
                    uniform vec2 grl_textureSize;
                    uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;
                    uniform vec3 grl_singleColor;
    ` : ""
    };
  }
  get isEnabled() {
    return true;
  }
  bindForSubMesh(uniformBuffer) {
    if (this._cameraFacing) {
      uniformBuffer.updateMatrix("grl_projection", this._scene.getProjectionMatrix());
      !this._isGLSL(this._material.shaderLanguage) && uniformBuffer.updateMatrix("viewProjection", this._scene.getTransformMatrix());
      const resolutionLineWidth = TmpVectors.Vector4[0];
      resolutionLineWidth.x = this._aspect;
      resolutionLineWidth.y = this._resolution.x;
      resolutionLineWidth.z = this._resolution.y;
      resolutionLineWidth.w = this.width;
      uniformBuffer.updateVector4("grl_aspect_resolution_lineWidth", resolutionLineWidth);
    }
    const dashOptions = TmpVectors.Vector4[0];
    dashOptions.x = GreasedLineTools.BooleanToNumber(this.useDash);
    dashOptions.y = this._dashArray;
    dashOptions.z = this.dashOffset;
    dashOptions.w = this.dashRatio;
    uniformBuffer.updateVector4("grl_dashOptions", dashOptions);
    const colorModeVisibilityColorsWidthUseColors = TmpVectors.Vector4[1];
    colorModeVisibilityColorsWidthUseColors.x = this.colorMode;
    colorModeVisibilityColorsWidthUseColors.y = this.visibility;
    colorModeVisibilityColorsWidthUseColors.z = this.colorsTexture ? this.colorsTexture.getSize().width : 0;
    colorModeVisibilityColorsWidthUseColors.w = GreasedLineTools.BooleanToNumber(this.useColors);
    uniformBuffer.updateVector4("grl_colorMode_visibility_colorsWidth_useColors", colorModeVisibilityColorsWidthUseColors);
    if (this._color) {
      uniformBuffer.updateColor3("grl_singleColor", this._color);
    }
    const texture2 = this.colorsTexture ?? GreasedLineMaterialDefaults.EmptyColorsTexture;
    uniformBuffer.setTexture("grl_colors", texture2);
    uniformBuffer.updateFloat2("grl_textureSize", texture2?.getSize().width ?? 1, texture2?.getSize().height ?? 1);
  }
  prepareDefines(defines, _scene, mesh) {
    defines.GREASED_LINE_HAS_COLOR = !!this.color && !this.useColors;
    defines.GREASED_LINE_SIZE_ATTENUATION = this._sizeAttenuation;
    defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = this._colorsDistributionType === 1;
    defines.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM = _scene.useRightHandedSystem;
    defines.GREASED_LINE_CAMERA_FACING = this._cameraFacing;
    defines.GREASED_LINE_USE_OFFSETS = !!mesh.offsets;
  }
  getClassName() {
    return GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME;
  }
  getCustomCode(shaderType, shaderLanguage = 0) {
    if (this._isGLSL(shaderLanguage)) {
      return GetCustomCode(shaderType, this._cameraFacing);
    }
    return GetCustomCode2(shaderType, this._cameraFacing);
  }
  dispose() {
    this.colorsTexture?.dispose();
    super.dispose();
  }
  get colors() {
    return this._colors;
  }
  set colors(value) {
    this.setColors(value);
  }
  setColors(colors, lazy = false, forceNewTexture = false) {
    const origColorsCount = this._colors?.length ?? 0;
    this._colors = colors;
    if (colors === null || colors.length === 0) {
      this.colorsTexture?.dispose();
      return;
    }
    if (lazy && !forceNewTexture) {
      return;
    }
    if (this.colorsTexture && origColorsCount === colors.length && !forceNewTexture) {
      const colorArray = GreasedLineTools.Color3toRGBAUint8(colors);
      this.colorsTexture.update(colorArray);
    } else {
      this.colorsTexture?.dispose();
      this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`, colors, this.colorsSampling, this._scene);
    }
  }
  updateLazy() {
    if (this._colors) {
      this.setColors(this._colors, false, true);
    }
  }
  get dashCount() {
    return this._dashCount;
  }
  set dashCount(value) {
    this._dashCount = value;
    this._dashArray = 1 / value;
  }
  get sizeAttenuation() {
    return this._sizeAttenuation;
  }
  set sizeAttenuation(value) {
    this._sizeAttenuation = value;
    this.markAllDefinesAsDirty();
  }
  get color() {
    return this._color;
  }
  set color(value) {
    this.setColor(value);
  }
  setColor(value, doNotMarkDirty = false) {
    if (this._color === null && value !== null || this._color !== null && value === null) {
      this._color = value;
      !doNotMarkDirty && this.markAllDefinesAsDirty();
    } else {
      this._color = value;
    }
  }
  get colorsDistributionType() {
    return this._colorsDistributionType;
  }
  set colorsDistributionType(value) {
    this._colorsDistributionType = value;
    this.markAllDefinesAsDirty();
  }
  get resolution() {
    return this._resolution;
  }
  set resolution(value) {
    this._aspect = value.x / value.y;
    this._resolution = value;
  }
  serialize() {
    const serializationObject = super.serialize();
    const greasedLineMaterialOptions = {
      colorDistributionType: this._colorsDistributionType,
      colorsSampling: this.colorsSampling,
      colorMode: this.colorMode,
      dashCount: this._dashCount,
      dashOffset: this.dashOffset,
      dashRatio: this.dashRatio,
      resolution: this._resolution,
      sizeAttenuation: this._sizeAttenuation,
      useColors: this.useColors,
      useDash: this.useDash,
      visibility: this.visibility,
      width: this.width
    };
    this._colors && (greasedLineMaterialOptions.colors = this._colors);
    this._color && (greasedLineMaterialOptions.color = this._color);
    serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions;
    return serializationObject;
  }
  parse(source, scene, rootUrl) {
    super.parse(source, scene, rootUrl);
    const greasedLineMaterialOptions = source.greasedLineMaterialOptions;
    this.colorsTexture?.dispose();
    greasedLineMaterialOptions.color && this.setColor(greasedLineMaterialOptions.color, true);
    greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType);
    greasedLineMaterialOptions.colors && (this.colors = greasedLineMaterialOptions.colors);
    greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling);
    greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode);
    greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors);
    greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility);
    greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash);
    greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount);
    greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio);
    greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset);
    greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width);
    greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation);
    greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution);
    if (this.colors) {
      this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`, this.colors, this.colorsSampling, scene);
    } else {
      GreasedLineTools.PrepareEmptyColorsTexture(scene);
    }
    this.markAllDefinesAsDirty();
  }
  copyTo(plugin) {
    const dest = plugin;
    dest.colorsTexture?.dispose();
    if (this._colors) {
      dest.colorsTexture = GreasedLineTools.CreateColorsTexture(`${dest._material.name}-colors-texture`, this._colors, dest.colorsSampling, this._scene);
    }
    dest.setColor(this.color, true);
    dest.colorsDistributionType = this.colorsDistributionType;
    dest.colorsSampling = this.colorsSampling;
    dest.colorMode = this.colorMode;
    dest.useColors = this.useColors;
    dest.visibility = this.visibility;
    dest.useDash = this.useDash;
    dest.dashCount = this.dashCount;
    dest.dashRatio = this.dashRatio;
    dest.dashOffset = this.dashOffset;
    dest.width = this.width;
    dest.sizeAttenuation = this.sizeAttenuation;
    dest.resolution = this.resolution;
    dest.markAllDefinesAsDirty();
  }
  _isGLSL(shaderLanguage) {
    return shaderLanguage === 0 || this._forceGLSL;
  }
}
GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME = "GreasedLinePluginMaterial";
GreasedLinePluginMaterial.ForceGLSL = false;
RegisterClass(`BABYLON.${GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`, GreasedLinePluginMaterial);
// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLineSimpleMaterial.js
init_math_color();
init_math_vector();
var GreasedLineUseOffsetsSimpleMaterialDefine = "GREASED_LINE_USE_OFFSETS";

class GreasedLineSimpleMaterial extends ShaderMaterial {
  constructor(name375, scene, options) {
    const engine2 = scene.getEngine();
    const isWGSL = engine2.isWebGPU && !(options.forceGLSL || GreasedLineSimpleMaterial.ForceGLSL);
    const defines = [
      `COLOR_DISTRIBUTION_TYPE_LINE ${1}.`,
      `COLOR_DISTRIBUTION_TYPE_SEGMENT ${0}.`,
      `COLOR_MODE_SET ${0}.`,
      `COLOR_MODE_ADD ${1}.`,
      `COLOR_MODE_MULTIPLY ${2}.`
    ];
    scene.useRightHandedSystem && defines.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM");
    const attributes = ["position", "grl_widths", "grl_offsets", "grl_colorPointers"];
    if (options.cameraFacing) {
      defines.push("GREASED_LINE_CAMERA_FACING");
      attributes.push("grl_previousAndSide", "grl_nextAndCounters");
    } else {
      attributes.push("grl_slopes");
      attributes.push("grl_counters");
    }
    const uniforms = [
      "grlColorsWidth",
      "grlUseColors",
      "grlWidth",
      "grlColor",
      "grl_colorModeAndColorDistributionType",
      "grlResolution",
      "grlAspect",
      "grlAizeAttenuation",
      "grlDashArray",
      "grlDashOffset",
      "grlDashRatio",
      "grlUseDash",
      "grlVisibility",
      "grlColors"
    ];
    if (!isWGSL) {
      uniforms.push("world", "viewProjection", "view", "projection");
    }
    super(name375, scene, {
      vertex: "greasedLine",
      fragment: "greasedLine"
    }, {
      uniformBuffers: isWGSL ? ["Scene", "Mesh"] : undefined,
      attributes,
      uniforms,
      samplers: isWGSL ? [] : ["grlColors"],
      defines,
      extraInitializationsAsync: async () => {
        if (isWGSL) {
          await Promise.all([Promise.resolve().then(() => (init_greasedLine_vertex(), exports_greasedLine_vertex)), Promise.resolve().then(() => (init_greasedLine_fragment(), exports_greasedLine_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_greasedLine_vertex2(), exports_greasedLine_vertex2)), Promise.resolve().then(() => (init_greasedLine_fragment2(), exports_greasedLine_fragment2))]);
        }
      },
      shaderLanguage: isWGSL ? 1 : 0
    });
    this._color = Color3.White();
    this._colorsDistributionType = 0;
    this._colorsTexture = null;
    options = options || {
      color: GreasedLineMaterialDefaults.DEFAULT_COLOR
    };
    this.visibility = options.visibility ?? 1;
    this.useDash = options.useDash ?? false;
    this.dashRatio = options.dashRatio ?? 0.5;
    this.dashOffset = options.dashOffset ?? 0;
    this.dashCount = options.dashCount ?? 1;
    this.width = options.width ? options.width : options.sizeAttenuation && options.cameraFacing ? GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED : GreasedLineMaterialDefaults.DEFAULT_WIDTH;
    this.sizeAttenuation = options.sizeAttenuation ?? false;
    this.color = options.color ?? Color3.White();
    this.useColors = options.useColors ?? false;
    this.colorsDistributionType = options.colorDistributionType ?? 0;
    this.colorsSampling = options.colorsSampling ?? RawTexture.NEAREST_NEAREST;
    this.colorMode = options.colorMode ?? 0;
    this._colors = options.colors ?? null;
    this._cameraFacing = options.cameraFacing ?? true;
    this.resolution = options.resolution ?? new Vector2(engine2.getRenderWidth(), engine2.getRenderHeight());
    if (options.colorsTexture) {
      this.colorsTexture = options.colorsTexture;
    } else {
      if (this._colors) {
        this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, this._colors, this.colorsSampling, scene);
      } else {
        this._color = this._color ?? GreasedLineMaterialDefaults.DEFAULT_COLOR;
        this.colorsTexture = GreasedLineTools.PrepareEmptyColorsTexture(scene);
      }
    }
    if (isWGSL) {
      const sampler = new TextureSampler;
      sampler.setParameters();
      sampler.samplingMode = this.colorsSampling;
      this.setTextureSampler("grlColorsSampler", sampler);
    }
    engine2.onDisposeObservable.add(() => {
      GreasedLineTools.DisposeEmptyColorsTexture();
    });
  }
  dispose() {
    this._colorsTexture?.dispose();
    super.dispose();
  }
  _setColorModeAndColorDistributionType() {
    this.setVector2("grl_colorModeAndColorDistributionType", new Vector2(this._colorMode, this._colorsDistributionType));
  }
  updateLazy() {
    if (this._colors) {
      this.setColors(this._colors, false, true);
    }
  }
  get colors() {
    return this._colors;
  }
  set colors(value) {
    this.setColors(value);
  }
  setColors(colors, lazy = false, forceNewTexture = false) {
    const origColorsCount = this._colors?.length ?? 0;
    this._colors = colors;
    if (colors === null || colors.length === 0) {
      this._colorsTexture?.dispose();
      return;
    }
    if (lazy && !forceNewTexture) {
      return;
    }
    if (this._colorsTexture && origColorsCount === colors.length && !forceNewTexture) {
      const colorArray = GreasedLineTools.Color3toRGBAUint8(colors);
      this._colorsTexture.update(colorArray);
    } else {
      this._colorsTexture?.dispose();
      this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, colors, this.colorsSampling, this.getScene());
    }
  }
  get colorsTexture() {
    return this._colorsTexture ?? null;
  }
  set colorsTexture(value) {
    this._colorsTexture = value;
    this.setFloat("grlColorsWidth", this._colorsTexture.getSize().width);
    this.setTexture("grlColors", this._colorsTexture);
  }
  get width() {
    return this._width;
  }
  set width(value) {
    this._width = value;
    this.setFloat("grlWidth", value);
  }
  get useColors() {
    return this._useColors;
  }
  set useColors(value) {
    this._useColors = value;
    this.setFloat("grlUseColors", GreasedLineTools.BooleanToNumber(value));
  }
  get colorsSampling() {
    return this._colorsSampling;
  }
  set colorsSampling(value) {
    this._colorsSampling = value;
  }
  get visibility() {
    return this._visibility;
  }
  set visibility(value) {
    this._visibility = value;
    this.setFloat("grlVisibility", value);
  }
  get useDash() {
    return this._useDash;
  }
  set useDash(value) {
    this._useDash = value;
    this.setFloat("grlUseDash", GreasedLineTools.BooleanToNumber(value));
  }
  get dashOffset() {
    return this._dashOffset;
  }
  set dashOffset(value) {
    this._dashOffset = value;
    this.setFloat("grlDashOffset", value);
  }
  get dashRatio() {
    return this._dashRatio;
  }
  set dashRatio(value) {
    this._dashRatio = value;
    this.setFloat("grlDashRatio", value);
  }
  get dashCount() {
    return this._dashCount;
  }
  set dashCount(value) {
    this._dashCount = value;
    this._dashArray = 1 / value;
    this.setFloat("grlDashArray", this._dashArray);
  }
  get sizeAttenuation() {
    return this._sizeAttenuation;
  }
  set sizeAttenuation(value) {
    this._sizeAttenuation = value;
    this.setFloat("grlSizeAttenuation", GreasedLineTools.BooleanToNumber(value));
  }
  get color() {
    return this._color;
  }
  set color(value) {
    this.setColor(value);
  }
  setColor(value) {
    value = value ?? GreasedLineMaterialDefaults.DEFAULT_COLOR;
    this._color = value;
    this.setColor3("grlColor", value);
  }
  get colorsDistributionType() {
    return this._colorsDistributionType;
  }
  set colorsDistributionType(value) {
    this._colorsDistributionType = value;
    this._setColorModeAndColorDistributionType();
  }
  get colorMode() {
    return this._colorMode;
  }
  set colorMode(value) {
    this._colorMode = value;
    this._setColorModeAndColorDistributionType();
  }
  get resolution() {
    return this._resolution;
  }
  set resolution(value) {
    this._resolution = value;
    this.setVector2("grlResolution", value);
    this.setFloat("grlAspect", value.x / value.y);
  }
  serialize() {
    const serializationObject = super.serialize();
    const greasedLineMaterialOptions = {
      colorDistributionType: this._colorsDistributionType,
      colorsSampling: this._colorsSampling,
      colorMode: this._colorMode,
      color: this._color,
      dashCount: this._dashCount,
      dashOffset: this._dashOffset,
      dashRatio: this._dashRatio,
      resolution: this._resolution,
      sizeAttenuation: this._sizeAttenuation,
      useColors: this._useColors,
      useDash: this._useDash,
      visibility: this._visibility,
      width: this._width,
      cameraFacing: this._cameraFacing
    };
    this._colors && (greasedLineMaterialOptions.colors = this._colors);
    serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions;
    return serializationObject;
  }
  parse(source, scene, _rootUrl) {
    const greasedLineMaterialOptions = source.greasedLineMaterialOptions;
    this._colorsTexture?.dispose();
    greasedLineMaterialOptions.color && (this.color = greasedLineMaterialOptions.color);
    greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType);
    greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling);
    greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode);
    greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors);
    greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility);
    greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash);
    greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount);
    greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio);
    greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset);
    greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width);
    greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation);
    greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution);
    if (greasedLineMaterialOptions.colors) {
      this.colorsTexture = GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`, greasedLineMaterialOptions.colors, this.colorsSampling, this.getScene());
    } else {
      this.colorsTexture = GreasedLineTools.PrepareEmptyColorsTexture(scene);
    }
    this._cameraFacing = greasedLineMaterialOptions.cameraFacing ?? true;
    this.setDefine("GREASED_LINE_CAMERA_FACING", this._cameraFacing);
  }
}
GreasedLineSimpleMaterial.ForceGLSL = false;
// node_modules/@babylonjs/core/Materials/GreasedLine/greasedLineMaterialInterfaces.js
var GreasedLineMeshMaterialType;
(function(GreasedLineMeshMaterialType2) {
  GreasedLineMeshMaterialType2[GreasedLineMeshMaterialType2["MATERIAL_TYPE_STANDARD"] = 0] = "MATERIAL_TYPE_STANDARD";
  GreasedLineMeshMaterialType2[GreasedLineMeshMaterialType2["MATERIAL_TYPE_PBR"] = 1] = "MATERIAL_TYPE_PBR";
  GreasedLineMeshMaterialType2[GreasedLineMeshMaterialType2["MATERIAL_TYPE_SIMPLE"] = 2] = "MATERIAL_TYPE_SIMPLE";
})(GreasedLineMeshMaterialType || (GreasedLineMeshMaterialType = {}));
var GreasedLineMeshColorMode;
(function(GreasedLineMeshColorMode2) {
  GreasedLineMeshColorMode2[GreasedLineMeshColorMode2["COLOR_MODE_SET"] = 0] = "COLOR_MODE_SET";
  GreasedLineMeshColorMode2[GreasedLineMeshColorMode2["COLOR_MODE_ADD"] = 1] = "COLOR_MODE_ADD";
  GreasedLineMeshColorMode2[GreasedLineMeshColorMode2["COLOR_MODE_MULTIPLY"] = 2] = "COLOR_MODE_MULTIPLY";
})(GreasedLineMeshColorMode || (GreasedLineMeshColorMode = {}));
var GreasedLineMeshColorDistributionType;
(function(GreasedLineMeshColorDistributionType2) {
  GreasedLineMeshColorDistributionType2[GreasedLineMeshColorDistributionType2["COLOR_DISTRIBUTION_TYPE_SEGMENT"] = 0] = "COLOR_DISTRIBUTION_TYPE_SEGMENT";
  GreasedLineMeshColorDistributionType2[GreasedLineMeshColorDistributionType2["COLOR_DISTRIBUTION_TYPE_LINE"] = 1] = "COLOR_DISTRIBUTION_TYPE_LINE";
})(GreasedLineMeshColorDistributionType || (GreasedLineMeshColorDistributionType = {}));
// node_modules/@babylonjs/core/Materials/meshDebugPluginMaterial.js
init_tslib_es6();
init_typeStore();
init_math();
init_logger();
init_decorators();
var vertexDefinitions = `#if defined(DBG_ENABLED)
attribute float dbg_initialPass;
varying vec3 dbg_vBarycentric;
flat varying vec3 dbg_vVertexWorldPos;
flat varying float dbg_vPass;
#endif`;
var vertexDefinitionsWebGPU = `#if defined(DBG_ENABLED)
attribute dbg_initialPass: f32;
varying dbg_vBarycentric: vec3f;
varying dbg_vVertexWorldPos: vec3f;
varying dbg_vPass: f32;
#endif`;
var vertexMainEnd = `#if defined(DBG_ENABLED)
float dbg_vertexIndex = mod(float(gl_VertexID), 3.);
if (dbg_vertexIndex == 0.0) { 
    dbg_vBarycentric = vec3(1.,0.,0.); 
}
else if (dbg_vertexIndex == 1.0) { 
    dbg_vBarycentric = vec3(0.,1.,0.); 
}
else { 
    dbg_vBarycentric = vec3(0.,0.,1.); 
}

dbg_vVertexWorldPos = vPositionW;
dbg_vPass = dbg_initialPass;
#endif`;
var vertexMainEndWebGPU = `#if defined(DBG_ENABLED)
var dbg_vertexIndex = f32(input.vertexIndex) % 3.;
if (dbg_vertexIndex == 0.0) { 
    vertexOutputs.dbg_vBarycentric = vec3f(1.,0.,0.); 
}
else if (dbg_vertexIndex == 1.0) { 
    vertexOutputs.dbg_vBarycentric = vec3f(0.,1.,0.); 
}
else { 
    vertexOutputs.dbg_vBarycentric = vec3f(0.,0.,1.); 
}

vertexOutputs.dbg_vVertexWorldPos = vertexOutputs.vPositionW;
vertexOutputs.dbg_vPass = input.dbg_initialPass;
#endif`;
var fragmentUniforms = `#if defined(DBG_ENABLED)
uniform vec3 dbg_shadedDiffuseColor;
uniform vec4 dbg_shadedSpecularColorPower;
uniform vec3 dbg_thicknessRadiusScale;

#if DBG_MODE == 2 || DBG_MODE == 3
    uniform vec3 dbg_vertexColor;
#endif

#if DBG_MODE == 1
    uniform vec3 dbg_wireframeTrianglesColor;
#elif DBG_MODE == 3
    uniform vec3 dbg_wireframeVerticesColor;
#elif DBG_MODE == 4 || DBG_MODE == 5
    uniform vec3 dbg_uvPrimaryColor;
    uniform vec3 dbg_uvSecondaryColor;
#elif DBG_MODE == 7
    uniform vec3 dbg_materialColor;
#endif
#endif`;
var fragmentUniformsWebGPU = `#if defined(DBG_ENABLED)
uniform dbg_shadedDiffuseColor: vec3f;
uniform dbg_shadedSpecularColorPower: vec4f;
uniform dbg_thicknessRadiusScale: vec3f;

#if DBG_MODE == 2 || DBG_MODE == 3
    uniform dbg_vertexColor: vec3f;
#endif

#if DBG_MODE == 1
    uniform dbg_wireframeTrianglesColor: vec3f;
#elif DBG_MODE == 3
    uniform  dbg_wireframeVerticesColor: vec3f;
#elif DBG_MODE == 4 || DBG_MODE == 5
    uniform dbg_uvPrimaryColor: vec3f;
    uniform dbg_uvSecondaryColor: vec3f;
#elif DBG_MODE == 7
    uniform dbg_materialColor: vec3f;
#endif
#endif`;
var fragmentDefinitions = `#if defined(DBG_ENABLED)
varying vec3 dbg_vBarycentric;
flat varying vec3 dbg_vVertexWorldPos;
flat varying float dbg_vPass;

#if !defined(DBG_MULTIPLY)
    vec3 dbg_applyShading(vec3 color) {
        vec3 N = vNormalW.xyz;
        vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);
        vec3 H = normalize(L + L);
        float LdotN = clamp(dot(L,N), 0., 1.);
        float HdotN = clamp(dot(H,N), 0., 1.);
        float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);
        color *= (LdotN / PI);
        color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);
        return color;
    }
#endif

#if DBG_MODE == 1 || DBG_MODE == 3
    float dbg_edgeFactor() {
        vec3 d = fwidth(dbg_vBarycentric);
        vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);
        return min(min(a3.x, a3.y), a3.z);
    }
#endif

#if DBG_MODE == 2 || DBG_MODE == 3
    float dbg_cornerFactor() {
        vec3 worldPos = vPositionW;
        float dist = length(worldPos - dbg_vVertexWorldPos);
        float camDist = length(worldPos - vEyePosition.xyz);
        float d = sqrt(camDist) * .001;
        return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);
    }
#endif

#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))
    float dbg_checkerboardFactor(vec2 uv) {
        vec2 f = fract(uv * dbg_thicknessRadiusScale.z);
        f -= .5;
        return (f.x * f.y) > 0. ? 1. : 0.;
    }
#endif
#endif`;
var fragmentDefinitionsWebGPU = `#if defined(DBG_ENABLED)
varying dbg_vBarycentric: vec3f;
varying dbg_vVertexWorldPos: vec3f;
varying dbg_vPass: f32;

#if !defined(DBG_MULTIPLY)
    fn dbg_applyShading(color: vec3f) -> vec3f {
        var N = fragmentInputs.vNormalW.xyz;
        var L = normalize(scene.vEyePosition.xyz - fragmentInputs.vPositionW.xyz);
        var H = normalize(L + L);
        var LdotN = clamp(dot(L,N), 0., 1.);
        var HdotN = clamp(dot(H,N), 0., 1.);
        var specTerm = pow(HdotN, uniforms.dbg_shadedSpecularColorPower.w);
        var result = color * (LdotN / PI);
        result += uniforms.dbg_shadedSpecularColorPower.rgb * (specTerm / PI);
        return result;
    }
#endif

#if DBG_MODE == 1 || DBG_MODE == 3
    fn dbg_edgeFactor() -> f32 {
        var d = fwidth(fragmentInputs.dbg_vBarycentric);
        var a3 = smoothstep(vec3f(0.), d * uniforms.dbg_thicknessRadiusScale.x, fragmentInputs.dbg_vBarycentric);
        return min(min(a3.x, a3.y), a3.z);
    }
#endif

#if DBG_MODE == 2 || DBG_MODE == 3
    fn dbg_cornerFactor() -> f32 {
        var worldPos = fragmentInputs.vPositionW;
        float dist = length(worldPos - fragmentInputs.dbg_vVertexWorldPos);
        float camDist = length(worldPos - scene.vEyePosition.xyz);
        float d = sqrt(camDist) * .001;
        return smoothstep((uniforms.dbg_thicknessRadiusScale.y * d), ((uniforms.dbg_thicknessRadiusScale.y * 1.01) * d), dist);
    }
#endif

#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))
    fn dbg_checkerboardFactor(uv: vec2f) -> f32 {
        var f = fract(uv * uniforms.dbg_thicknessRadiusScale.z);
        f -= .5;
        return (f.x * f.y) > 0. ? 1. : 0.;
    }
#endif
#endif`;
var fragmentMainEnd = `#if defined(DBG_ENABLED)
vec3 dbg_color = vec3(1.);
#if DBG_MODE == 1
    dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());
#elif DBG_MODE == 2 || DBG_MODE == 3
    float dbg_cornerFactor = dbg_cornerFactor();
    if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;
    dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);
    #if DBG_MODE == 3
        dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());
    #endif
#elif DBG_MODE == 4 && defined(MAINUV1)
    dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));
#elif DBG_MODE == 5 && defined(MAINUV2)
    dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));
#elif DBG_MODE == 6 && defined(VERTEXCOLOR)
    dbg_color = vColor.rgb;
#elif DBG_MODE == 7
    dbg_color = dbg_materialColor;
#endif

#if defined(DBG_MULTIPLY)
    gl_FragColor *= vec4(dbg_color, 1.);
#else
    #if DBG_MODE != 6
        gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);
    #else
        gl_FragColor = vec4(dbg_color, 1.);
    #endif
#endif
#endif`;
var fragmentMainEndWebGPU = `#if defined(DBG_ENABLED)
var dbg_color = vec3f(1.);
#if DBG_MODE == 1
    dbg_color = mix(uniforms.dbg_wireframeTrianglesColor, vec3f(1.), dbg_edgeFactor());
#elif DBG_MODE == 2 || DBG_MODE == 3
    var dbg_cornerFactor = dbg_cornerFactor();
    if (fragmentInputs.dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;
    dbg_color = mix(uniforms.dbg_vertexColor, vec3(1.), dbg_cornerFactor);
    #if DBG_MODE == 3
        dbg_color *= mix(uniforms.dbg_wireframeVerticesColor, vec3f(1.), dbg_edgeFactor());
    #endif
#elif DBG_MODE == 4 && defined(MAINUV1)
    dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV1));
#elif DBG_MODE == 5 && defined(MAINUV2)
    dbg_color = mix(uniforms.dbg_uvPrimaryColor, uniforms.dbg_uvSecondaryColor, dbg_checkerboardFactor(fragmentInputs.vMainUV2));
#elif DBG_MODE == 6 && defined(VERTEXCOLOR)
    dbg_color = fragmentInputs.vColor.rgb;
#elif DBG_MODE == 7
    dbg_color = uniforms.dbg_materialColor;
#endif

#if defined(DBG_MULTIPLY)
    fragmentOutputs.color *= vec4f(dbg_color, 1.);
#else
    #if DBG_MODE != 6
        fragmentOutputs.color = vec4f(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);
    #else
        fragmentOutputs.color = vec4f(dbg_color, 1.);
    #endif
#endif
#endif`;
var defaultMaterialColors = [
  new Color3(0.98, 0.26, 0.38),
  new Color3(0.47, 0.75, 0.3),
  new Color3(0, 0.26, 0.77),
  new Color3(0.97, 0.6, 0.76),
  new Color3(0.19, 0.63, 0.78),
  new Color3(0.98, 0.8, 0.6),
  new Color3(0.65, 0.43, 0.15),
  new Color3(0.15, 0.47, 0.22),
  new Color3(0.67, 0.71, 0.86),
  new Color3(0.09, 0.46, 0.56),
  new Color3(0.8, 0.98, 0.02),
  new Color3(0.39, 0.29, 0.13),
  new Color3(0.53, 0.63, 0.06),
  new Color3(0.95, 0.96, 0.41),
  new Color3(1, 0.72, 0.94),
  new Color3(0.63, 0.08, 0.31),
  new Color3(0.66, 0.96, 0.95),
  new Color3(0.22, 0.14, 0.19),
  new Color3(0.14, 0.65, 0.59),
  new Color3(0.93, 1, 0.68),
  new Color3(0.93, 0.14, 0.44),
  new Color3(0.47, 0.86, 0.67),
  new Color3(0.85, 0.07, 0.78),
  new Color3(0.53, 0.64, 0.98),
  new Color3(0.43, 0.37, 0.56),
  new Color3(0.71, 0.65, 0.25),
  new Color3(0.66, 0.19, 0.01),
  new Color3(0.94, 0.53, 0.12),
  new Color3(0.41, 0.44, 0.44),
  new Color3(0.24, 0.71, 0.96),
  new Color3(0.57, 0.28, 0.56),
  new Color3(0.44, 0.98, 0.42)
];
var MeshDebugMode;
(function(MeshDebugMode2) {
  MeshDebugMode2[MeshDebugMode2["NONE"] = 0] = "NONE";
  MeshDebugMode2[MeshDebugMode2["TRIANGLES"] = 1] = "TRIANGLES";
  MeshDebugMode2[MeshDebugMode2["VERTICES"] = 2] = "VERTICES";
  MeshDebugMode2[MeshDebugMode2["TRIANGLES_VERTICES"] = 3] = "TRIANGLES_VERTICES";
  MeshDebugMode2[MeshDebugMode2["UV0"] = 4] = "UV0";
  MeshDebugMode2[MeshDebugMode2["UV1"] = 5] = "UV1";
  MeshDebugMode2[MeshDebugMode2["VERTEXCOLORS"] = 6] = "VERTEXCOLORS";
  MeshDebugMode2[MeshDebugMode2["MATERIALIDS"] = 7] = "MATERIALIDS";
})(MeshDebugMode || (MeshDebugMode = {}));

class MeshDebugDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.DBG_MODE = 0;
    this.DBG_MULTIPLY = true;
    this.DBG_ENABLED = true;
  }
}

class MeshDebugPluginMaterial extends MaterialPluginBase {
  _markAllDefinesAsDirty() {
    this._enable(this._isEnabled);
    this.markAllDefinesAsDirty();
  }
  isCompatible(shaderLanguage) {
    switch (shaderLanguage) {
      case 0:
      case 1:
        return true;
      default:
        return false;
    }
  }
  constructor(material, options = {}) {
    const defines = new MeshDebugDefines;
    defines.DBG_MODE = options.mode ?? defines.DBG_MODE;
    defines.DBG_MULTIPLY = options.multiply ?? defines.DBG_MULTIPLY;
    super(material, "MeshDebug", 200, defines, true, true);
    this._mode = defines.DBG_MODE;
    this._multiply = defines.DBG_MULTIPLY;
    this.shadedDiffuseColor = options.shadedDiffuseColor ?? new Color3(1, 1, 1);
    this.shadedSpecularColor = options.shadedSpecularColor ?? new Color3(0.8, 0.8, 0.8);
    this.shadedSpecularPower = options.shadedSpecularPower ?? 10;
    this.wireframeThickness = options.wireframeThickness ?? 0.7;
    this.wireframeTrianglesColor = options.wireframeTrianglesColor ?? new Color3(0, 0, 0);
    this.wireframeVerticesColor = options.wireframeVerticesColor ?? new Color3(0.8, 0.8, 0.8);
    this.vertexColor = options.vertexColor ?? new Color3(0, 0, 0);
    this.vertexRadius = options.vertexRadius ?? 1.2;
    this.uvScale = options.uvScale ?? 20;
    this.uvPrimaryColor = options.uvPrimaryColor ?? new Color3(1, 1, 1);
    this.uvSecondaryColor = options.uvSecondaryColor ?? new Color3(0.5, 0.5, 0.5);
    this._materialColor = MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++ % MeshDebugPluginMaterial.MaterialColors.length];
    this.isEnabled = true;
  }
  getClassName() {
    return "MeshDebugPluginMaterial";
  }
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    if (this._isEnabled === value) {
      return;
    }
    if (!this._material.getScene().getEngine().isWebGPU && this._material.getScene().getEngine().version == 1) {
      Logger.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0.");
      this._isEnabled = false;
      return;
    }
    this._isEnabled = value;
    this._markAllDefinesAsDirty();
  }
  prepareDefines(defines, scene, mesh) {
    if ((this._mode == 2 || this._mode == 1 || this._mode == 3) && !mesh.isVerticesDataPresent("dbg_initialPass")) {
      Logger.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.", 1);
    }
    defines.DBG_MODE = this._mode;
    defines.DBG_MULTIPLY = this._multiply;
    defines.DBG_ENABLED = this._isEnabled;
  }
  getAttributes(attributes) {
    attributes.push("dbg_initialPass");
  }
  getUniforms(shaderLanguage = 0) {
    return {
      ubo: [
        { name: "dbg_shadedDiffuseColor", size: 3, type: "vec3" },
        { name: "dbg_shadedSpecularColorPower", size: 4, type: "vec4" },
        { name: "dbg_thicknessRadiusScale", size: 3, type: "vec3" },
        { name: "dbg_wireframeTrianglesColor", size: 3, type: "vec3" },
        { name: "dbg_wireframeVerticesColor", size: 3, type: "vec3" },
        { name: "dbg_vertexColor", size: 3, type: "vec3" },
        { name: "dbg_uvPrimaryColor", size: 3, type: "vec3" },
        { name: "dbg_uvSecondaryColor", size: 3, type: "vec3" },
        { name: "dbg_materialColor", size: 3, type: "vec3" }
      ],
      fragment: shaderLanguage === 0 ? fragmentUniforms : fragmentUniformsWebGPU
    };
  }
  bindForSubMesh(uniformBuffer) {
    if (!this._isEnabled) {
      return;
    }
    uniformBuffer.updateFloat3("dbg_shadedDiffuseColor", this.shadedDiffuseColor.r, this.shadedDiffuseColor.g, this.shadedDiffuseColor.b);
    uniformBuffer.updateFloat4("dbg_shadedSpecularColorPower", this.shadedSpecularColor.r, this.shadedSpecularColor.g, this.shadedSpecularColor.b, this.shadedSpecularPower);
    uniformBuffer.updateFloat3("dbg_thicknessRadiusScale", this.wireframeThickness, this.vertexRadius, this.uvScale);
    uniformBuffer.updateColor3("dbg_wireframeTrianglesColor", this.wireframeTrianglesColor);
    uniformBuffer.updateColor3("dbg_wireframeVerticesColor", this.wireframeVerticesColor);
    uniformBuffer.updateColor3("dbg_vertexColor", this.vertexColor);
    uniformBuffer.updateColor3("dbg_uvPrimaryColor", this.uvPrimaryColor);
    uniformBuffer.updateColor3("dbg_uvSecondaryColor", this.uvSecondaryColor);
    uniformBuffer.updateColor3("dbg_materialColor", this._materialColor);
  }
  getCustomCode(shaderType, shaderLanguage = 0) {
    if (shaderLanguage === 1) {
      return shaderType === "vertex" ? {
        CUSTOM_VERTEX_DEFINITIONS: vertexDefinitionsWebGPU,
        CUSTOM_VERTEX_MAIN_END: vertexMainEndWebGPU
      } : {
        CUSTOM_FRAGMENT_DEFINITIONS: fragmentDefinitionsWebGPU,
        CUSTOM_FRAGMENT_MAIN_END: fragmentMainEndWebGPU
      };
    }
    return shaderType === "vertex" ? {
      CUSTOM_VERTEX_DEFINITIONS: vertexDefinitions,
      CUSTOM_VERTEX_MAIN_END: vertexMainEnd
    } : {
      CUSTOM_FRAGMENT_DEFINITIONS: fragmentDefinitions,
      CUSTOM_FRAGMENT_MAIN_END: fragmentMainEnd
    };
  }
  static Reset() {
    this._PluginCount = 0;
    this.MaterialColors = defaultMaterialColors;
  }
  static PrepareMeshForTrianglesAndVerticesMode(mesh, returnRollback = false) {
    let rollback = () => {};
    if (mesh.getTotalIndices() == 0)
      return rollback;
    if (returnRollback) {
      const kinds = mesh.getVerticesDataKinds();
      const indices2 = mesh.getIndices();
      const data = {};
      for (const kind of kinds) {
        data[kind] = mesh.getVerticesData(kind);
      }
      rollback = function() {
        mesh.setIndices(indices2);
        for (const kind of kinds) {
          const stride = mesh.getVertexBuffer(kind).getStrideSize();
          mesh.setVerticesData(kind, data[kind], undefined, stride);
        }
        mesh.removeVerticesData("dbg_initialPass");
      };
    }
    let indices = Array.from(mesh.getIndices());
    const newIndices1 = [];
    for (let i = 0;i < indices.length; i += 3) {
      newIndices1.push(indices[i + 1], indices[i + 2], indices[i + 0]);
    }
    mesh.setIndices(indices.concat(newIndices1));
    mesh.convertToUnIndexedMesh();
    mesh.isUnIndexed = false;
    indices = Array.from(mesh.getIndices());
    const newIndices2 = [];
    for (let i = indices.length / 2;i < indices.length; i += 3) {
      newIndices2.push(indices[i + 1], indices[i + 2], indices[i + 0]);
    }
    mesh.setIndices(indices.concat(newIndices2));
    const num = mesh.getTotalVertices();
    const mid = num / 2;
    const pass2 = new Array(num).fill(1, 0, mid).fill(0, mid, num);
    mesh.setVerticesData("dbg_initialPass", pass2, false, 1);
    return rollback;
  }
}
MeshDebugPluginMaterial._PluginCount = 0;
MeshDebugPluginMaterial.MaterialColors = defaultMaterialColors;
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "_materialColor", undefined);
__decorate([
  serialize()
], MeshDebugPluginMaterial.prototype, "_isEnabled", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllDefinesAsDirty")
], MeshDebugPluginMaterial.prototype, "mode", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllDefinesAsDirty")
], MeshDebugPluginMaterial.prototype, "multiply", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "shadedDiffuseColor", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "shadedSpecularColor", undefined);
__decorate([
  serialize()
], MeshDebugPluginMaterial.prototype, "shadedSpecularPower", undefined);
__decorate([
  serialize()
], MeshDebugPluginMaterial.prototype, "wireframeThickness", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "wireframeTrianglesColor", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "wireframeVerticesColor", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "vertexColor", undefined);
__decorate([
  serialize()
], MeshDebugPluginMaterial.prototype, "vertexRadius", undefined);
__decorate([
  serialize()
], MeshDebugPluginMaterial.prototype, "uvScale", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "uvPrimaryColor", undefined);
__decorate([
  serializeAsColor3()
], MeshDebugPluginMaterial.prototype, "uvSecondaryColor", undefined);
RegisterClass("BABYLON.MeshDebugPluginMaterial", MeshDebugPluginMaterial);

// node_modules/@babylonjs/core/Materials/index.js
init_materialHelper_functions();

// node_modules/@babylonjs/core/Materials/standardMaterial.decalMap.js
Object.defineProperty(StandardMaterial.prototype, "decalMap", {
  get: function() {
    if (!this._decalMap) {
      if (this._uniformBufferLayoutBuilt) {
        return null;
      }
      this._decalMap = new DecalMapConfiguration(this);
    }
    return this._decalMap;
  },
  enumerable: true,
  configurable: true
});

// node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.decalMap.js
Object.defineProperty(PBRBaseMaterial.prototype, "decalMap", {
  get: function() {
    if (!this._decalMap) {
      if (this._uniformBufferLayoutBuilt) {
        return null;
      }
      this._decalMap = new DecalMapConfiguration(this);
    }
    return this._decalMap;
  },
  enumerable: true,
  configurable: true
});

// node_modules/@babylonjs/core/Meshes/abstractMesh.decalMap.js
Object.defineProperty(AbstractMesh.prototype, "decalMap", {
  get: function() {
    return this._decalMap;
  },
  set: function(decalMap) {
    this._decalMap = decalMap;
  },
  enumerable: true,
  configurable: true
});

// node_modules/@babylonjs/core/Materials/index.js
init_default_fragment2();
init_default_vertex2();
init_default_fragment();
init_default_vertex();
init_greasedLine_fragment2();
init_greasedLine_vertex2();
init_greasedLine_fragment();
init_greasedLine_vertex();
// node_modules/@babylonjs/core/Maths/math.scalar.js
var HCF = HighestCommonFactor;
var Scalar = {
  ...exports_math_scalar_functions,
  TwoPi: Math.PI * 2,
  Sign: Math.sign,
  Log2: Math.log2,
  HCF
};

// node_modules/@babylonjs/core/Maths/index.js
init_math_functions();

// node_modules/@babylonjs/core/Maths/math.polar.js
init_math_vector();

// node_modules/@babylonjs/core/Maths/index.js
init_math();
init_sphericalPolynomial();

// node_modules/@babylonjs/core/Maths/math.vector.functions.js
function Vector2ToFixed(vector, decimalCount) {
  return `{X: ${vector.x.toFixed(decimalCount)} Y: ${vector.y.toFixed(decimalCount)}}`;
}
function Vector3ToFixed(vector, decimalCount) {
  return `{X: ${vector._x.toFixed(decimalCount)} Y: ${vector._y.toFixed(decimalCount)} Z: ${vector._z.toFixed(decimalCount)}}`;
}
function Vector4ToFixed(vector, decimalCount) {
  return `{X: ${vector.x.toFixed(decimalCount)} Y: ${vector.y.toFixed(decimalCount)} Z: ${vector.z.toFixed(decimalCount)} W: ${vector.w.toFixed(decimalCount)}}`;
}
// node_modules/@babylonjs/core/Meshes/abstractMesh.hotSpot.js
init_math_vector();
init_buffer();
// node_modules/@babylonjs/core/Meshes/Compression/dracoCodec.js
init_tools();
init_workerPool();

// node_modules/@babylonjs/core/Meshes/Compression/dracoCompressionWorker.js
function EncodeMesh(module, attributes, indices, options) {
  const encoderModule = module;
  let encoder = null;
  let meshBuilder = null;
  let mesh = null;
  let encodedNativeBuffer = null;
  const attributeIDs = {};
  const positionAttribute = attributes.find((a) => a.dracoName === "POSITION");
  if (!positionAttribute) {
    throw new Error("Position attribute is required for Draco encoding");
  }
  if (!indices) {
    const positionVerticesCount = positionAttribute.data.length / positionAttribute.size;
    indices = new (positionVerticesCount > 65535 ? Uint32Array : Uint16Array)(positionVerticesCount);
    for (let i = 0;i < positionVerticesCount; i++) {
      indices[i] = i;
    }
  }
  try {
    encoder = new encoderModule.Encoder;
    meshBuilder = new encoderModule.MeshBuilder;
    mesh = new encoderModule.Mesh;
    meshBuilder.AddFacesToMesh(mesh, indices.length / 3, indices);
    const addAttributeMap = new Map([
      [Float32Array, (mb, m, a, c, s, d) => mb.AddFloatAttribute(m, a, c, s, d)],
      [Uint32Array, (mb, m, a, c, s, d) => mb.AddUInt32Attribute(m, a, c, s, d)],
      [Uint16Array, (mb, m, a, c, s, d) => mb.AddUInt16Attribute(m, a, c, s, d)],
      [Uint8Array, (mb, m, a, c, s, d) => mb.AddUInt8Attribute(m, a, c, s, d)],
      [Int32Array, (mb, m, a, c, s, d) => mb.AddInt32Attribute(m, a, c, s, d)],
      [Int16Array, (mb, m, a, c, s, d) => mb.AddInt16Attribute(m, a, c, s, d)],
      [Int8Array, (mb, m, a, c, s, d) => mb.AddInt8Attribute(m, a, c, s, d)]
    ]);
    for (const attribute of attributes) {
      if (attribute.data instanceof Uint8ClampedArray) {
        attribute.data = new Uint8Array(attribute.data);
      }
      const addAttribute = addAttributeMap.get(attribute.data.constructor);
      const verticesCount = attribute.data.length / attribute.size;
      attributeIDs[attribute.kind] = addAttribute(meshBuilder, mesh, encoderModule[attribute.dracoName], verticesCount, attribute.size, attribute.data);
      if (options.quantizationBits && options.quantizationBits[attribute.dracoName]) {
        encoder.SetAttributeQuantization(encoderModule[attribute.dracoName], options.quantizationBits[attribute.dracoName]);
      }
    }
    if (options.method) {
      encoder.SetEncodingMethod(encoderModule[options.method]);
    }
    if (options.encodeSpeed !== undefined && options.decodeSpeed !== undefined) {
      encoder.SetSpeedOptions(options.encodeSpeed, options.decodeSpeed);
    }
    encodedNativeBuffer = new encoderModule.DracoInt8Array;
    const encodedLength = encoder.EncodeMeshToDracoBuffer(mesh, encodedNativeBuffer);
    if (encodedLength <= 0) {
      throw new Error("Draco encoding failed.");
    }
    const encodedData = new Int8Array(encodedLength);
    for (let i = 0;i < encodedLength; i++) {
      encodedData[i] = encodedNativeBuffer.GetValue(i);
    }
    return { data: encodedData, attributeIDs };
  } finally {
    if (mesh) {
      encoderModule.destroy(mesh);
    }
    if (meshBuilder) {
      encoderModule.destroy(meshBuilder);
    }
    if (encoder) {
      encoderModule.destroy(encoder);
    }
    if (encodedNativeBuffer) {
      encoderModule.destroy(encodedNativeBuffer);
    }
  }
}
function EncoderWorkerFunction() {
  let encoderPromise;
  onmessage = (event) => {
    const message = event.data;
    switch (message.id) {
      case "init": {
        if (message.url) {
          importScripts(message.url);
        }
        const initEncoderObject = message.wasmBinary ? { wasmBinary: message.wasmBinary } : {};
        encoderPromise = DracoEncoderModule(initEncoderObject);
        postMessage({ id: "initDone" });
        break;
      }
      case "encodeMesh": {
        if (!encoderPromise) {
          throw new Error("Draco encoder module is not available");
        }
        encoderPromise.then((encoder) => {
          const result = EncodeMesh(encoder, message.attributes, message.indices, message.options);
          postMessage({ id: "encodeMeshDone", encodedMeshData: result }, result ? [result.data.buffer] : undefined);
        });
        break;
      }
    }
  };
}
function DecodeMesh(module, data, attributeIDs, onIndicesData, onAttributeData) {
  const decoderModule = module;
  let decoder = null;
  let buffer2 = null;
  let geometry = null;
  try {
    decoder = new decoderModule.Decoder;
    buffer2 = new decoderModule.DecoderBuffer;
    buffer2.Init(data, data.byteLength);
    let status;
    const type = decoder.GetEncodedGeometryType(buffer2);
    switch (type) {
      case decoderModule.TRIANGULAR_MESH: {
        const mesh = new decoderModule.Mesh;
        status = decoder.DecodeBufferToMesh(buffer2, mesh);
        if (!status.ok() || mesh.ptr === 0) {
          throw new Error(status.error_msg());
        }
        const numFaces = mesh.num_faces();
        const numIndices = numFaces * 3;
        const byteLength = numIndices * 4;
        const ptr3 = decoderModule._malloc(byteLength);
        try {
          decoder.GetTrianglesUInt32Array(mesh, byteLength, ptr3);
          const indices = new Uint32Array(numIndices);
          indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr3, numIndices));
          onIndicesData(indices);
        } finally {
          decoderModule._free(ptr3);
        }
        geometry = mesh;
        break;
      }
      case decoderModule.POINT_CLOUD: {
        const pointCloud = new decoderModule.PointCloud;
        status = decoder.DecodeBufferToPointCloud(buffer2, pointCloud);
        if (!status.ok() || !pointCloud.ptr) {
          throw new Error(status.error_msg());
        }
        geometry = pointCloud;
        break;
      }
      default: {
        throw new Error(`Invalid geometry type ${type}`);
      }
    }
    const numPoints = geometry.num_points();
    const processAttribute = (decoder2, geometry2, kind, attribute) => {
      const dataType = attribute.data_type();
      const numComponents = attribute.num_components();
      const normalized = attribute.normalized();
      const byteStride = attribute.byte_stride();
      const byteOffset = attribute.byte_offset();
      const dataTypeInfo = {
        [decoderModule.DT_FLOAT32]: { typedArrayConstructor: Float32Array, heap: decoderModule.HEAPF32 },
        [decoderModule.DT_INT8]: { typedArrayConstructor: Int8Array, heap: decoderModule.HEAP8 },
        [decoderModule.DT_INT16]: { typedArrayConstructor: Int16Array, heap: decoderModule.HEAP16 },
        [decoderModule.DT_INT32]: { typedArrayConstructor: Int32Array, heap: decoderModule.HEAP32 },
        [decoderModule.DT_UINT8]: { typedArrayConstructor: Uint8Array, heap: decoderModule.HEAPU8 },
        [decoderModule.DT_UINT16]: { typedArrayConstructor: Uint16Array, heap: decoderModule.HEAPU16 },
        [decoderModule.DT_UINT32]: { typedArrayConstructor: Uint32Array, heap: decoderModule.HEAPU32 }
      };
      const info = dataTypeInfo[dataType];
      if (!info) {
        throw new Error(`Invalid data type ${dataType}`);
      }
      const numValues = numPoints * numComponents;
      const byteLength = numValues * info.typedArrayConstructor.BYTES_PER_ELEMENT;
      const ptr3 = decoderModule._malloc(byteLength);
      try {
        decoder2.GetAttributeDataArrayForAllPoints(geometry2, attribute, dataType, byteLength, ptr3);
        const data2 = new info.typedArrayConstructor(info.heap.buffer, ptr3, numValues);
        onAttributeData(kind, data2.slice(), numComponents, byteOffset, byteStride, normalized);
      } finally {
        decoderModule._free(ptr3);
      }
    };
    if (attributeIDs) {
      for (const kind in attributeIDs) {
        const id = attributeIDs[kind];
        const attribute = decoder.GetAttributeByUniqueId(geometry, id);
        processAttribute(decoder, geometry, kind, attribute);
      }
    } else {
      const dracoAttributeTypes = {
        position: decoderModule.POSITION,
        normal: decoderModule.NORMAL,
        color: decoderModule.COLOR,
        uv: decoderModule.TEX_COORD
      };
      for (const kind in dracoAttributeTypes) {
        const id = decoder.GetAttributeId(geometry, dracoAttributeTypes[kind]);
        if (id !== -1) {
          const attribute = decoder.GetAttribute(geometry, id);
          processAttribute(decoder, geometry, kind, attribute);
        }
      }
    }
    return numPoints;
  } finally {
    if (geometry) {
      decoderModule.destroy(geometry);
    }
    if (buffer2) {
      decoderModule.destroy(buffer2);
    }
    if (decoder) {
      decoderModule.destroy(decoder);
    }
  }
}
function DecoderWorkerFunction() {
  let decoderPromise;
  onmessage = (event) => {
    const message = event.data;
    switch (message.id) {
      case "init": {
        if (message.url) {
          importScripts(message.url);
        }
        const initDecoderObject = message.wasmBinary ? { wasmBinary: message.wasmBinary } : {};
        decoderPromise = DracoDecoderModule(initDecoderObject);
        postMessage({ id: "initDone" });
        break;
      }
      case "decodeMesh": {
        if (!decoderPromise) {
          throw new Error("Draco decoder module is not available");
        }
        decoderPromise.then((decoder) => {
          const numPoints = DecodeMesh(decoder, message.dataView, message.attributes, (indices) => {
            postMessage({ id: "indices", data: indices }, [indices.buffer]);
          }, (kind, data, size, offset, stride, normalized) => {
            postMessage({ id: "attribute", kind, data, size, byteOffset: offset, byteStride: stride, normalized }, [data.buffer]);
          });
          postMessage({ id: "decodeMeshDone", totalVertices: numPoints });
        });
        break;
      }
    }
  };
}
function initializeWebWorker3(worker, wasmBinary, moduleUrl) {
  return new Promise((resolve3, reject) => {
    const onError = (error) => {
      worker.removeEventListener("error", onError);
      worker.removeEventListener("message", onMessage);
      reject(error);
    };
    const onMessage = (event) => {
      if (event.data.id === "initDone") {
        worker.removeEventListener("error", onError);
        worker.removeEventListener("message", onMessage);
        resolve3(worker);
      }
    };
    worker.addEventListener("error", onError);
    worker.addEventListener("message", onMessage);
    if (!wasmBinary) {
      worker.postMessage({
        id: "init",
        url: moduleUrl
      });
    } else {
      const clone = wasmBinary.slice(0);
      worker.postMessage({
        id: "init",
        url: moduleUrl,
        wasmBinary: clone
      }, [clone]);
    }
  });
}

// node_modules/@babylonjs/core/Meshes/Compression/dracoCodec.js
function _GetDefaultNumWorkers() {
  if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
    return 1;
  }
  return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
}
function _IsConfigurationAvailable(config) {
  return !!(config.wasmUrl && (config.wasmBinary || config.wasmBinaryUrl) && typeof WebAssembly === "object" || config.fallbackUrl);
}

class DracoCodec {
  constructor(configuration) {
    if (configuration.workerPool) {
      this._workerPoolPromise = Promise.resolve(configuration.workerPool);
      return;
    }
    const wasmBinaryProvided = configuration.wasmBinary;
    const numberOfWorkers = configuration.numWorkers ?? _GetDefaultNumWorkers();
    const useWorkers = numberOfWorkers && typeof Worker === "function" && typeof URL === "function";
    const urlNeeded = useWorkers || !configuration.jsModule;
    const codecInfo = configuration.wasmUrl && configuration.wasmBinaryUrl && typeof WebAssembly === "object" ? {
      url: urlNeeded ? Tools.GetBabylonScriptURL(configuration.wasmUrl, true) : "",
      wasmBinaryPromise: wasmBinaryProvided ? Promise.resolve(wasmBinaryProvided) : Tools.LoadFileAsync(Tools.GetBabylonScriptURL(configuration.wasmBinaryUrl, true))
    } : {
      url: urlNeeded ? Tools.GetBabylonScriptURL(configuration.fallbackUrl) : "",
      wasmBinaryPromise: Promise.resolve(undefined)
    };
    if (useWorkers) {
      this._workerPoolPromise = codecInfo.wasmBinaryPromise.then((wasmBinary) => {
        const workerContent = this._getWorkerContent();
        const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
        return new AutoReleaseWorkerPool(numberOfWorkers, () => {
          const worker = new Worker(workerBlobUrl);
          return initializeWebWorker3(worker, wasmBinary, codecInfo.url);
        });
      });
    } else {
      this._modulePromise = codecInfo.wasmBinaryPromise.then(async (wasmBinary) => {
        if (!this._isModuleAvailable()) {
          if (!configuration.jsModule) {
            if (!codecInfo.url) {
              throw new Error("Draco codec module is not available");
            }
            await Tools.LoadBabylonScriptAsync(codecInfo.url);
          }
        }
        return this._createModuleAsync(wasmBinary, configuration.jsModule);
      });
    }
  }
  async whenReadyAsync() {
    if (this._workerPoolPromise) {
      await this._workerPoolPromise;
      return;
    }
    if (this._modulePromise) {
      await this._modulePromise;
      return;
    }
  }
  dispose() {
    if (this._workerPoolPromise) {
      this._workerPoolPromise.then((workerPool) => {
        workerPool.dispose();
      });
    }
    delete this._workerPoolPromise;
    delete this._modulePromise;
  }
}

// node_modules/@babylonjs/core/Meshes/Compression/dracoDecoder.js
init_tools();
init_logger();
class DracoDecoder extends DracoCodec {
  static get DefaultAvailable() {
    return _IsConfigurationAvailable(DracoDecoder.DefaultConfiguration);
  }
  static get Default() {
    DracoDecoder._Default ?? (DracoDecoder._Default = new DracoDecoder);
    return DracoDecoder._Default;
  }
  static ResetDefault(skipDispose) {
    if (DracoDecoder._Default) {
      if (!skipDispose) {
        DracoDecoder._Default.dispose();
      }
      DracoDecoder._Default = null;
    }
  }
  _isModuleAvailable() {
    return typeof DracoDecoderModule !== "undefined";
  }
  async _createModuleAsync(wasmBinary, jsModule) {
    const module = await (jsModule || DracoDecoderModule)({ wasmBinary });
    return { module };
  }
  _getWorkerContent() {
    return `${DecodeMesh}(${DecoderWorkerFunction})()`;
  }
  constructor(configuration = DracoDecoder.DefaultConfiguration) {
    super(configuration);
  }
  decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride) {
    const dataView = data instanceof ArrayBuffer ? new Int8Array(data) : new Int8Array(data.buffer, data.byteOffset, data.byteLength);
    const applyGltfNormalizedOverride = (kind, normalized) => {
      if (gltfNormalizedOverride && gltfNormalizedOverride[kind] !== undefined) {
        if (normalized !== gltfNormalizedOverride[kind]) {
          Logger.Warn(`Normalized flag from Draco data (${normalized}) does not match normalized flag from glTF accessor (${gltfNormalizedOverride[kind]}). Using flag from glTF accessor.`);
        }
        return gltfNormalizedOverride[kind];
      } else {
        return normalized;
      }
    };
    if (this._workerPoolPromise) {
      return this._workerPoolPromise.then((workerPool) => {
        return new Promise((resolve3, reject) => {
          workerPool.push((worker, onComplete) => {
            let resultIndices = null;
            const resultAttributes = [];
            const onError = (error) => {
              worker.removeEventListener("error", onError);
              worker.removeEventListener("message", onMessage);
              reject(error);
              onComplete();
            };
            const onMessage = (event) => {
              const message = event.data;
              switch (message.id) {
                case "indices": {
                  resultIndices = message.data;
                  break;
                }
                case "attribute": {
                  resultAttributes.push({
                    kind: message.kind,
                    data: message.data,
                    size: message.size,
                    byteOffset: message.byteOffset,
                    byteStride: message.byteStride,
                    normalized: applyGltfNormalizedOverride(message.kind, message.normalized)
                  });
                  break;
                }
                case "decodeMeshDone": {
                  worker.removeEventListener("error", onError);
                  worker.removeEventListener("message", onMessage);
                  resolve3({ indices: resultIndices, attributes: resultAttributes, totalVertices: message.totalVertices });
                  onComplete();
                  break;
                }
              }
            };
            worker.addEventListener("error", onError);
            worker.addEventListener("message", onMessage);
            const dataViewCopy = dataView.slice();
            worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes }, [dataViewCopy.buffer]);
          });
        });
      });
    }
    if (this._modulePromise) {
      return this._modulePromise.then((decoder) => {
        let resultIndices = null;
        const resultAttributes = [];
        const numPoints = DecodeMesh(decoder.module, dataView, attributes, (indices) => {
          resultIndices = indices;
        }, (kind, data2, size, byteOffset, byteStride, normalized) => {
          resultAttributes.push({
            kind,
            data: data2,
            size,
            byteOffset,
            byteStride,
            normalized
          });
        });
        return { indices: resultIndices, attributes: resultAttributes, totalVertices: numPoints };
      });
    }
    throw new Error("Draco decoder module is not available");
  }
  async decodeMeshToGeometryAsync(name375, scene, data, attributes) {
    const meshData = await this.decodeMeshToMeshDataAsync(data, attributes);
    const geometry = new Geometry(name375, scene);
    if (meshData.indices) {
      geometry.setIndices(meshData.indices);
    }
    for (const attribute of meshData.attributes) {
      geometry.setVerticesBuffer(new VertexBuffer(scene.getEngine(), attribute.data, attribute.kind, false, undefined, attribute.byteStride, undefined, attribute.byteOffset, attribute.size, undefined, attribute.normalized, true), meshData.totalVertices);
    }
    return geometry;
  }
  async _decodeMeshToGeometryForGltfAsync(name375, scene, data, attributes, gltfNormalizedOverride, boundingInfo2) {
    const meshData = await this.decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride);
    const geometry = new Geometry(name375, scene);
    if (boundingInfo2) {
      geometry._boundingInfo = boundingInfo2;
      geometry.useBoundingInfoFromGeometry = true;
    }
    if (meshData.indices) {
      geometry.setIndices(meshData.indices);
    }
    for (const attribute of meshData.attributes) {
      geometry.setVerticesBuffer(new VertexBuffer(scene.getEngine(), attribute.data, attribute.kind, false, undefined, attribute.byteStride, undefined, attribute.byteOffset, attribute.size, undefined, attribute.normalized, true), meshData.totalVertices);
    }
    return geometry;
  }
}
DracoDecoder.DefaultConfiguration = {
  wasmUrl: `${Tools._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,
  wasmBinaryUrl: `${Tools._DefaultCdnUrl}/draco_decoder_gltf.wasm`,
  fallbackUrl: `${Tools._DefaultCdnUrl}/draco_decoder_gltf.js`
};
DracoDecoder._Default = null;

// node_modules/@babylonjs/core/Meshes/Compression/dracoCompression.js
class DracoCompression {
  static get Configuration() {
    return {
      get decoder() {
        return DracoDecoder.DefaultConfiguration;
      },
      set decoder(value) {
        DracoDecoder.DefaultConfiguration = value;
      }
    };
  }
  static set Configuration(value) {
    DracoDecoder.DefaultConfiguration = value.decoder;
  }
  static get DecoderAvailable() {
    return _IsConfigurationAvailable(DracoDecoder.DefaultConfiguration);
  }
  static get Default() {
    DracoCompression._Default ?? (DracoCompression._Default = new DracoCompression);
    return DracoCompression._Default;
  }
  static ResetDefault(skipDispose) {
    if (DracoCompression._Default) {
      if (!skipDispose) {
        DracoCompression._Default.dispose();
      }
      DracoCompression._Default = null;
    }
  }
  constructor(numWorkersOrOptions = DracoCompression.DefaultNumWorkers) {
    const configuration = typeof numWorkersOrOptions === "number" ? { ...DracoDecoder.DefaultConfiguration, numWorkers: numWorkersOrOptions } : { ...DracoDecoder.DefaultConfiguration, ...numWorkersOrOptions };
    this._decoder = new DracoDecoder(configuration);
  }
  dispose() {
    this._decoder.dispose();
  }
  async whenReadyAsync() {
    return this._decoder.whenReadyAsync();
  }
  decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride) {
    return this._decoder.decodeMeshToMeshDataAsync(data, attributes, gltfNormalizedOverride);
  }
  async decodeMeshToGeometryAsync(name375, scene, data, attributes) {
    return this._decoder.decodeMeshToGeometryAsync(name375, scene, data, attributes);
  }
  async _decodeMeshToGeometryForGltfAsync(name375, scene, data, attributes, gltfNormalizedOverride, boundingInfo2) {
    return this._decoder._decodeMeshToGeometryForGltfAsync(name375, scene, data, attributes, gltfNormalizedOverride, boundingInfo2);
  }
  async decodeMeshAsync(data, attributes) {
    const meshData = await this._decoder.decodeMeshToMeshDataAsync(data, attributes);
    const vertexData = new VertexData;
    if (meshData.indices) {
      vertexData.indices = meshData.indices;
    }
    for (const attribute of meshData.attributes) {
      const floatData = VertexBuffer.GetFloatData(attribute.data, attribute.size, VertexBuffer.GetDataType(attribute.data), attribute.byteOffset, attribute.byteStride, attribute.normalized, meshData.totalVertices);
      vertexData.set(floatData, attribute.kind);
    }
    return vertexData;
  }
}
DracoCompression.DefaultNumWorkers = _GetDefaultNumWorkers();
DracoCompression._Default = null;
// node_modules/@babylonjs/core/Meshes/Compression/meshoptCompression.js
init_tools();
var NumberOfWorkers = 0;
var WorkerTimeout = null;

class MeshoptCompression {
  static get Default() {
    if (!MeshoptCompression._Default) {
      MeshoptCompression._Default = new MeshoptCompression;
    }
    return MeshoptCompression._Default;
  }
  constructor() {
    const decoder = MeshoptCompression.Configuration.decoder;
    this._decoderModulePromise = Tools.LoadBabylonScriptAsync(decoder.url).then(() => {
      return MeshoptDecoder.ready;
    });
  }
  dispose() {
    delete this._decoderModulePromise;
  }
  decodeGltfBufferAsync(source, count, stride, mode, filter) {
    return this._decoderModulePromise.then(async () => {
      if (NumberOfWorkers === 0) {
        MeshoptDecoder.useWorkers(1);
        NumberOfWorkers = 1;
      }
      const result = await MeshoptDecoder.decodeGltfBufferAsync(count, stride, source, mode, filter);
      if (WorkerTimeout !== null) {
        clearTimeout(WorkerTimeout);
      }
      WorkerTimeout = setTimeout(() => {
        MeshoptDecoder.useWorkers(0);
        NumberOfWorkers = 0;
        WorkerTimeout = null;
      }, 1000);
      return result;
    });
  }
}
MeshoptCompression.Configuration = {
  decoder: {
    url: `${Tools._DefaultCdnUrl}/meshopt_decoder.js`
  }
};
MeshoptCompression._Default = null;
// node_modules/@babylonjs/core/Meshes/Compression/dracoEncoder.js
init_tools();
init_logger();

// node_modules/@babylonjs/core/Misc/deepMerger.js
function deepMerge(...objects) {
  const isRecord = (obj) => !!obj && typeof obj === "object";
  return objects.reduce((prev, obj) => {
    Object.keys(obj).forEach((key) => {
      const pVal = prev[key];
      const oVal = obj[key];
      if (Array.isArray(pVal) && Array.isArray(oVal)) {
        prev[key] = pVal.concat(...oVal);
      } else if (isRecord(pVal) && isRecord(oVal)) {
        prev[key] = deepMerge(pVal, oVal);
      } else {
        prev[key] = oVal;
      }
    });
    return prev;
  }, {});
}

// node_modules/@babylonjs/core/Meshes/Compression/dracoEncoder.js
init_bufferUtils();
function GetDracoAttributeName(kind) {
  if (kind === VertexBuffer.PositionKind) {
    return "POSITION";
  } else if (kind === VertexBuffer.NormalKind) {
    return "NORMAL";
  } else if (kind === VertexBuffer.ColorKind) {
    return "COLOR";
  } else if (kind.startsWith(VertexBuffer.UVKind)) {
    return "TEX_COORD";
  }
  return "GENERIC";
}
function PrepareIndicesForDraco(input) {
  let indices = input.getIndices(undefined, true);
  if (indices && !(indices instanceof Uint32Array) && !(indices instanceof Uint16Array)) {
    indices = (AreIndices32Bits(indices, indices.length) ? Uint32Array : Uint16Array).from(indices);
  }
  return indices;
}
function PrepareAttributesForDraco(input, excludedAttributes) {
  const attributes = [];
  for (const kind of input.getVerticesDataKinds()) {
    if (excludedAttributes?.includes(kind)) {
      if (kind === VertexBuffer.PositionKind) {
        throw new Error("Cannot exclude position attribute from Draco encoding.");
      }
      continue;
    }
    const vertexBuffer = input.getVertexBuffer(kind);
    const size = vertexBuffer.getSize();
    const data = GetTypedArrayData(vertexBuffer.getData(), size, vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, input.getTotalVertices(), true);
    attributes.push({ kind, dracoName: GetDracoAttributeName(kind), size, data });
  }
  return attributes;
}
var DefaultEncoderOptions = {
  decodeSpeed: 5,
  encodeSpeed: 5,
  method: "MESH_EDGEBREAKER_ENCODING",
  quantizationBits: {
    POSITION: 14,
    NORMAL: 10,
    COLOR: 8,
    TEX_COORD: 12,
    GENERIC: 12
  }
};

class DracoEncoder extends DracoCodec {
  static get DefaultAvailable() {
    return _IsConfigurationAvailable(DracoEncoder.DefaultConfiguration);
  }
  static get Default() {
    DracoEncoder._Default ?? (DracoEncoder._Default = new DracoEncoder);
    return DracoEncoder._Default;
  }
  static ResetDefault(skipDispose) {
    if (DracoEncoder._Default) {
      if (!skipDispose) {
        DracoEncoder._Default.dispose();
      }
      DracoEncoder._Default = null;
    }
  }
  _isModuleAvailable() {
    return typeof DracoEncoderModule !== "undefined";
  }
  async _createModuleAsync(wasmBinary, jsModule) {
    const module = await (jsModule || DracoEncoderModule)({ wasmBinary });
    return { module };
  }
  _getWorkerContent() {
    return `${EncodeMesh}(${EncoderWorkerFunction})()`;
  }
  constructor(configuration = DracoEncoder.DefaultConfiguration) {
    super(configuration);
  }
  async _encodeAsync(attributes, indices, options) {
    const mergedOptions = options ? deepMerge(DefaultEncoderOptions, options) : DefaultEncoderOptions;
    if (this._workerPoolPromise) {
      const workerPool = await this._workerPoolPromise;
      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.id === "encodeMeshDone") {
              worker.removeEventListener("error", onError);
              worker.removeEventListener("message", onMessage);
              resolve3(message.data.encodedMeshData);
              onComplete();
            }
          };
          worker.addEventListener("error", onError);
          worker.addEventListener("message", onMessage);
          const transferList = [];
          attributes.forEach((attribute) => {
            transferList.push(attribute.data.buffer);
          });
          if (indices) {
            transferList.push(indices.buffer);
          }
          worker.postMessage({ id: "encodeMesh", attributes, indices, options: mergedOptions }, transferList);
        });
      });
    }
    if (this._modulePromise) {
      const encoder = await this._modulePromise;
      return EncodeMesh(encoder.module, attributes, indices, mergedOptions);
    }
    throw new Error("Draco encoder module is not available");
  }
  async encodeMeshAsync(input, options) {
    const verticesCount = input.getTotalVertices();
    if (verticesCount == 0) {
      throw new Error("Cannot compress geometry with Draco. There are no vertices.");
    }
    if (input instanceof Mesh && input.morphTargetManager && options?.method === "MESH_EDGEBREAKER_ENCODING") {
      Logger.Warn("Cannot use Draco EDGEBREAKER method with morph targets. Falling back to SEQUENTIAL method.");
      options.method = "MESH_SEQUENTIAL_ENCODING";
    }
    const indices = PrepareIndicesForDraco(input);
    const attributes = PrepareAttributesForDraco(input, options?.excludedAttributes);
    return this._encodeAsync(attributes, indices, options);
  }
}
DracoEncoder.DefaultConfiguration = {
  wasmUrl: `${Tools._DefaultCdnUrl}/draco_encoder_wasm_wrapper.js`,
  wasmBinaryUrl: `${Tools._DefaultCdnUrl}/draco_encoder.wasm`,
  fallbackUrl: `${Tools._DefaultCdnUrl}/draco_encoder.js`
};
DracoEncoder._Default = null;
// node_modules/@babylonjs/core/Meshes/csg.js
init_math_vector();
init_buffer();
init_math_color();
var currentCSGMeshId = 0;

class Vertex2 {
  constructor(pos, normal, uv, vertColor) {
    this.pos = pos;
    this.normal = normal;
    this.uv = uv;
    this.vertColor = vertColor;
  }
  clone() {
    return new Vertex2(this.pos.clone(), this.normal.clone(), this.uv?.clone(), this.vertColor?.clone());
  }
  flip() {
    this.normal = this.normal.scale(-1);
  }
  interpolate(other, t) {
    return new Vertex2(Vector3.Lerp(this.pos, other.pos, t), Vector3.Lerp(this.normal, other.normal, t), this.uv && other.uv ? Vector2.Lerp(this.uv, other.uv, t) : undefined, this.vertColor && other.vertColor ? Color4.Lerp(this.vertColor, other.vertColor, t) : undefined);
  }
}

class CSGPlane {
  constructor(normal, w) {
    this.normal = normal;
    this.w = w;
  }
  static FromPoints(a, b, c) {
    const v0 = c.subtract(a);
    const v1 = b.subtract(a);
    if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
      return null;
    }
    const n = Vector3.Normalize(Vector3.Cross(v0, v1));
    return new CSGPlane(n, Vector3.Dot(n, a));
  }
  clone() {
    return new CSGPlane(this.normal.clone(), this.w);
  }
  flip() {
    this.normal.scaleInPlace(-1);
    this.w = -this.w;
  }
  splitPolygon(polygon, coplanarFront, coplanarBack, front, back) {
    const COPLANAR = 0;
    const FRONT = 1;
    const BACK = 2;
    const SPANNING = 3;
    let polygonType = 0;
    const types = [];
    let i;
    let t;
    for (i = 0;i < polygon.vertices.length; i++) {
      t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
      const type = t < -CSGPlane.EPSILON ? BACK : t > CSGPlane.EPSILON ? FRONT : COPLANAR;
      polygonType |= type;
      types.push(type);
    }
    switch (polygonType) {
      case COPLANAR:
        (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
        break;
      case FRONT:
        front.push(polygon);
        break;
      case BACK:
        back.push(polygon);
        break;
      case SPANNING: {
        const f = [], b = [];
        for (i = 0;i < polygon.vertices.length; i++) {
          const j = (i + 1) % polygon.vertices.length;
          const ti = types[i], tj = types[j];
          const vi = polygon.vertices[i], vj = polygon.vertices[j];
          if (ti !== BACK) {
            f.push(vi);
          }
          if (ti !== FRONT) {
            b.push(ti !== BACK ? vi.clone() : vi);
          }
          if ((ti | tj) === SPANNING) {
            t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
            const v = vi.interpolate(vj, t);
            f.push(v);
            b.push(v.clone());
          }
        }
        let poly;
        if (f.length >= 3) {
          poly = new CSGPolygon(f, polygon.shared);
          if (poly.plane) {
            front.push(poly);
          }
        }
        if (b.length >= 3) {
          poly = new CSGPolygon(b, polygon.shared);
          if (poly.plane) {
            back.push(poly);
          }
        }
        break;
      }
    }
  }
}
CSGPlane.EPSILON = 0.00001;

class CSGPolygon {
  constructor(vertices, shared) {
    this.vertices = vertices;
    this.shared = shared;
    this.plane = CSGPlane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  }
  clone() {
    const vertices = this.vertices.map((v) => v.clone());
    return new CSGPolygon(vertices, this.shared);
  }
  flip() {
    this.vertices.reverse().map((v) => {
      v.flip();
    });
    this.plane.flip();
  }
}

class Node4 {
  constructor(polygons) {
    this._plane = null;
    this._front = null;
    this._back = null;
    this._polygons = new Array;
    if (polygons) {
      this.build(polygons);
    }
  }
  clone() {
    const node = new Node4;
    node._plane = this._plane && this._plane.clone();
    node._front = this._front && this._front.clone();
    node._back = this._back && this._back.clone();
    node._polygons = this._polygons.map((p) => p.clone());
    return node;
  }
  invert() {
    for (let i = 0;i < this._polygons.length; i++) {
      this._polygons[i].flip();
    }
    if (this._plane) {
      this._plane.flip();
    }
    if (this._front) {
      this._front.invert();
    }
    if (this._back) {
      this._back.invert();
    }
    const temp = this._front;
    this._front = this._back;
    this._back = temp;
  }
  clipPolygons(polygons) {
    if (!this._plane) {
      return polygons.slice();
    }
    let front = [], back = [];
    for (let i = 0;i < polygons.length; i++) {
      this._plane.splitPolygon(polygons[i], front, back, front, back);
    }
    if (this._front) {
      front = this._front.clipPolygons(front);
    }
    if (this._back) {
      back = this._back.clipPolygons(back);
    } else {
      back = [];
    }
    return front.concat(back);
  }
  clipTo(bsp) {
    this._polygons = bsp.clipPolygons(this._polygons);
    if (this._front) {
      this._front.clipTo(bsp);
    }
    if (this._back) {
      this._back.clipTo(bsp);
    }
  }
  allPolygons() {
    let polygons = this._polygons.slice();
    if (this._front) {
      polygons = polygons.concat(this._front.allPolygons());
    }
    if (this._back) {
      polygons = polygons.concat(this._back.allPolygons());
    }
    return polygons;
  }
  build(polygons) {
    if (!polygons.length) {
      return;
    }
    if (!this._plane) {
      this._plane = polygons[0].plane.clone();
    }
    const front = [], back = [];
    for (let i = 0;i < polygons.length; i++) {
      this._plane.splitPolygon(polygons[i], this._polygons, this._polygons, front, back);
    }
    if (front.length) {
      if (!this._front) {
        this._front = new Node4;
      }
      this._front.build(front);
    }
    if (back.length) {
      if (!this._back) {
        this._back = new Node4;
      }
      this._back.build(back);
    }
  }
}

class CSG {
  constructor() {
    this._polygons = new Array;
  }
  static FromVertexData(data) {
    let vertex, polygon, vertices;
    const polygons = [];
    const indices = data.indices;
    const positions = data.positions;
    const normals = data.normals;
    const uvs = data.uvs;
    const vertColors = data.colors;
    if (!indices || !positions) {
      throw "BABYLON.CSG: VertexData must at least contain positions and indices";
    }
    for (let i = 0;i < indices.length; i += 3) {
      vertices = [];
      for (let j = 0;j < 3; j++) {
        const indexIndices = i + j;
        const offset = indices[indexIndices];
        const normal = normals ? Vector3.FromArray(normals, offset * 3) : Vector3.Zero();
        const uv = uvs ? Vector2.FromArray(uvs, offset * 2) : undefined;
        const vertColor = vertColors ? Color4.FromArray(vertColors, offset * 4) : undefined;
        const position = Vector3.FromArray(positions, offset * 3);
        vertex = new Vertex2(position, normal, uv, vertColor);
        vertices.push(vertex);
      }
      polygon = new CSGPolygon(vertices, { subMeshId: 0, meshId: currentCSGMeshId, materialIndex: 0 });
      if (polygon.plane) {
        polygons.push(polygon);
      }
    }
    const csg = CSG._FromPolygons(polygons);
    csg.matrix = Matrix.Identity();
    csg.position = Vector3.Zero();
    csg.rotation = Vector3.Zero();
    csg.scaling = Vector3.One();
    csg.rotationQuaternion = Quaternion.Identity();
    currentCSGMeshId++;
    return csg;
  }
  static FromMesh(mesh, absolute = false) {
    let vertex, normal, uv = undefined, position, vertColor = undefined, polygon, vertices;
    const polygons = [];
    let matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
    let invertWinding = false;
    if (mesh instanceof Mesh) {
      mesh.computeWorldMatrix(true);
      matrix = mesh.getWorldMatrix();
      meshPosition = mesh.position.clone();
      meshRotation = mesh.rotation.clone();
      if (mesh.rotationQuaternion) {
        meshRotationQuaternion = mesh.rotationQuaternion.clone();
      }
      meshScaling = mesh.scaling.clone();
      if (mesh.material && absolute) {
        invertWinding = mesh.material.sideOrientation === 0;
      }
    } else {
      throw "BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";
    }
    const indices = mesh.getIndices(), positions = mesh.getVerticesData(VertexBuffer.PositionKind), normals = mesh.getVerticesData(VertexBuffer.NormalKind), uvs = mesh.getVerticesData(VertexBuffer.UVKind), vertColors = mesh.getVerticesData(VertexBuffer.ColorKind);
    if (indices === null) {
      throw "BABYLON.CSG: Mesh has no indices";
    }
    if (positions === null) {
      throw "BABYLON.CSG: Mesh has no positions";
    }
    if (normals === null) {
      throw "BABYLON.CSG: Mesh has no normals";
    }
    const subMeshes = mesh.subMeshes;
    if (!subMeshes) {
      throw "BABYLON.CSG: Mesh has no submeshes";
    }
    for (let sm = 0, sml = subMeshes.length;sm < sml; sm++) {
      for (let i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart;i < il; i += 3) {
        vertices = [];
        for (let j = 0;j < 3; j++) {
          const indexIndices = j === 0 ? i + j : invertWinding ? i + 3 - j : i + j;
          const sourceNormal = new Vector3(normals[indices[indexIndices] * 3], normals[indices[indexIndices] * 3 + 1], normals[indices[indexIndices] * 3 + 2]);
          if (uvs) {
            uv = new Vector2(uvs[indices[indexIndices] * 2], uvs[indices[indexIndices] * 2 + 1]);
          }
          if (vertColors) {
            vertColor = new Color4(vertColors[indices[indexIndices] * 4], vertColors[indices[indexIndices] * 4 + 1], vertColors[indices[indexIndices] * 4 + 2], vertColors[indices[indexIndices] * 4 + 3]);
          }
          const sourcePosition = new Vector3(positions[indices[indexIndices] * 3], positions[indices[indexIndices] * 3 + 1], positions[indices[indexIndices] * 3 + 2]);
          position = Vector3.TransformCoordinates(sourcePosition, matrix);
          normal = Vector3.TransformNormal(sourceNormal, matrix);
          vertex = new Vertex2(position, normal, uv, vertColor);
          vertices.push(vertex);
        }
        polygon = new CSGPolygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
        if (polygon.plane) {
          polygons.push(polygon);
        }
      }
    }
    const csg = CSG._FromPolygons(polygons);
    csg.matrix = absolute ? Matrix.Identity() : matrix;
    csg.position = absolute ? Vector3.Zero() : meshPosition;
    csg.rotation = absolute ? Vector3.Zero() : meshRotation;
    csg.scaling = absolute ? Vector3.One() : meshScaling;
    csg.rotationQuaternion = absolute && meshRotationQuaternion ? Quaternion.Identity() : meshRotationQuaternion;
    currentCSGMeshId++;
    return csg;
  }
  static _FromPolygons(polygons) {
    const csg = new CSG;
    csg._polygons = polygons;
    return csg;
  }
  clone() {
    const csg = new CSG;
    csg._polygons = this._polygons.map((p) => p.clone());
    csg.copyTransformAttributes(this);
    return csg;
  }
  union(csg) {
    const a = new Node4(this.clone()._polygons);
    const b = new Node4(csg.clone()._polygons);
    a.clipTo(b);
    b.clipTo(a);
    b.invert();
    b.clipTo(a);
    b.invert();
    a.build(b.allPolygons());
    return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  }
  unionInPlace(csg) {
    const a = new Node4(this._polygons);
    const b = new Node4(csg._polygons);
    a.clipTo(b);
    b.clipTo(a);
    b.invert();
    b.clipTo(a);
    b.invert();
    a.build(b.allPolygons());
    this._polygons = a.allPolygons();
  }
  subtract(csg) {
    const a = new Node4(this.clone()._polygons);
    const b = new Node4(csg.clone()._polygons);
    a.invert();
    a.clipTo(b);
    b.clipTo(a);
    b.invert();
    b.clipTo(a);
    b.invert();
    a.build(b.allPolygons());
    a.invert();
    return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  }
  subtractInPlace(csg) {
    const a = new Node4(this._polygons);
    const b = new Node4(csg._polygons);
    a.invert();
    a.clipTo(b);
    b.clipTo(a);
    b.invert();
    b.clipTo(a);
    b.invert();
    a.build(b.allPolygons());
    a.invert();
    this._polygons = a.allPolygons();
  }
  intersect(csg) {
    const a = new Node4(this.clone()._polygons);
    const b = new Node4(csg.clone()._polygons);
    a.invert();
    b.clipTo(a);
    b.invert();
    a.clipTo(b);
    b.clipTo(a);
    a.build(b.allPolygons());
    a.invert();
    return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  }
  intersectInPlace(csg) {
    const a = new Node4(this._polygons);
    const b = new Node4(csg._polygons);
    a.invert();
    b.clipTo(a);
    b.invert();
    a.clipTo(b);
    b.clipTo(a);
    a.build(b.allPolygons());
    a.invert();
    this._polygons = a.allPolygons();
  }
  inverse() {
    const csg = this.clone();
    csg.inverseInPlace();
    return csg;
  }
  inverseInPlace() {
    this._polygons.map((p) => {
      p.flip();
    });
  }
  copyTransformAttributes(csg) {
    this.matrix = csg.matrix;
    this.position = csg.position;
    this.rotation = csg.rotation;
    this.scaling = csg.scaling;
    this.rotationQuaternion = csg.rotationQuaternion;
    return this;
  }
  toVertexData(onBeforePolygonProcessing = null, onAfterPolygonProcessing = null) {
    const matrix = this.matrix.clone();
    matrix.invert();
    const polygons = this._polygons;
    const vertices = [];
    const indices = [];
    const normals = [];
    let uvs = null;
    let vertColors = null;
    const vertex = Vector3.Zero();
    const normal = Vector3.Zero();
    const uv = Vector2.Zero();
    const vertColor = new Color4(0, 0, 0, 0);
    const polygonIndices = [0, 0, 0];
    const vertice_dict = {};
    let vertex_idx;
    for (let i = 0, il = polygons.length;i < il; i++) {
      const polygon = polygons[i];
      if (onBeforePolygonProcessing) {
        onBeforePolygonProcessing(polygon);
      }
      for (let j = 2, jl = polygon.vertices.length;j < jl; j++) {
        polygonIndices[0] = 0;
        polygonIndices[1] = j - 1;
        polygonIndices[2] = j;
        for (let k = 0;k < 3; k++) {
          vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
          normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
          if (polygon.vertices[polygonIndices[k]].uv) {
            if (!uvs) {
              uvs = [];
            }
            uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
          }
          if (polygon.vertices[polygonIndices[k]].vertColor) {
            if (!vertColors) {
              vertColors = [];
            }
            vertColor.copyFrom(polygon.vertices[polygonIndices[k]].vertColor);
          }
          const localVertex = Vector3.TransformCoordinates(vertex, matrix);
          const localNormal = Vector3.TransformNormal(normal, matrix);
          vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z];
          let areUvsDifferent = false;
          if (uvs && !(uvs[vertex_idx * 2] === uv.x || uvs[vertex_idx * 2 + 1] === uv.y)) {
            areUvsDifferent = true;
          }
          let areColorsDifferent = false;
          if (vertColors && !(vertColors[vertex_idx * 4] === vertColor.r || vertColors[vertex_idx * 4 + 1] === vertColor.g || vertColors[vertex_idx * 4 + 2] === vertColor.b || vertColors[vertex_idx * 4 + 3] === vertColor.a)) {
            areColorsDifferent = true;
          }
          if (!(typeof vertex_idx !== "undefined" && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z) || areUvsDifferent || areColorsDifferent) {
            vertices.push(localVertex.x, localVertex.y, localVertex.z);
            if (uvs) {
              uvs.push(uv.x, uv.y);
            }
            normals.push(normal.x, normal.y, normal.z);
            if (vertColors) {
              vertColors.push(vertColor.r, vertColor.g, vertColor.b, vertColor.a);
            }
            vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z] = vertices.length / 3 - 1;
          }
          indices.push(vertex_idx);
          if (onAfterPolygonProcessing) {
            onAfterPolygonProcessing();
          }
        }
      }
    }
    const result = new VertexData;
    result.positions = vertices;
    result.normals = normals;
    if (uvs) {
      result.uvs = uvs;
    }
    if (vertColors) {
      result.colors = vertColors;
    }
    result.indices = indices;
    return result;
  }
  buildMeshGeometry(name375, scene, keepSubMeshes) {
    const mesh = new Mesh(name375, scene);
    const polygons = this._polygons;
    let currentIndex = 0;
    const subMeshDict = {};
    let subMeshObj;
    if (keepSubMeshes) {
      polygons.sort((a, b) => {
        if (a.shared.meshId === b.shared.meshId) {
          return a.shared.subMeshId - b.shared.subMeshId;
        } else {
          return a.shared.meshId - b.shared.meshId;
        }
      });
    }
    const vertexData = this.toVertexData((polygon) => {
      if (!subMeshDict[polygon.shared.meshId]) {
        subMeshDict[polygon.shared.meshId] = {};
      }
      if (!subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]) {
        subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId] = {
          indexStart: Infinity,
          indexEnd: -Infinity,
          materialIndex: polygon.shared.materialIndex
        };
      }
      subMeshObj = subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId];
    }, () => {
      subMeshObj.indexStart = Math.min(currentIndex, subMeshObj.indexStart);
      subMeshObj.indexEnd = Math.max(currentIndex, subMeshObj.indexEnd);
      currentIndex++;
    });
    vertexData.applyToMesh(mesh);
    if (keepSubMeshes) {
      let materialIndexOffset = 0, materialMaxIndex;
      mesh.subMeshes = [];
      for (const m in subMeshDict) {
        materialMaxIndex = -1;
        for (const sm in subMeshDict[m]) {
          subMeshObj = subMeshDict[m][sm];
          SubMesh.CreateFromIndices(subMeshObj.materialIndex + materialIndexOffset, subMeshObj.indexStart, subMeshObj.indexEnd - subMeshObj.indexStart + 1, mesh);
          materialMaxIndex = Math.max(subMeshObj.materialIndex, materialMaxIndex);
        }
        materialIndexOffset += ++materialMaxIndex;
      }
    }
    return mesh;
  }
  toMesh(name375, material2 = null, scene, keepSubMeshes) {
    const mesh = this.buildMeshGeometry(name375, scene, keepSubMeshes);
    mesh.material = material2;
    mesh.position.copyFrom(this.position);
    mesh.rotation.copyFrom(this.rotation);
    if (this.rotationQuaternion) {
      mesh.rotationQuaternion = this.rotationQuaternion.clone();
    }
    mesh.scaling.copyFrom(this.scaling);
    mesh.computeWorldMatrix(true);
    return mesh;
  }
}
// node_modules/@babylonjs/core/Meshes/meshUVSpaceRenderer.js
init_math_vector();
init_renderTargetTexture();
init_math_color();
init_postProcess();
// node_modules/@babylonjs/core/Meshes/trailMesh.js
init_math_vector();
init_buffer();
Mesh._TrailMeshParser = (parsedMesh, scene) => {
  return TrailMesh.Parse(parsedMesh, scene);
};

class TrailMesh extends Mesh {
  constructor(name375, generator, scene, diameterOrOptions, length = 60, autoStart = true) {
    super(name375, scene);
    this._sectionPolygonPointsCount = 4;
    this._running = false;
    this._generator = generator;
    if (typeof diameterOrOptions === "object" && diameterOrOptions !== null) {
      this.diameter = diameterOrOptions.diameter || 1;
      this._length = diameterOrOptions.length || 60;
      this._segments = diameterOrOptions.segments ? diameterOrOptions.segments > this._length ? this._length : diameterOrOptions.segments : this._length;
      this._sectionPolygonPointsCount = diameterOrOptions.sections || 4;
      this._doNotTaper = diameterOrOptions.doNotTaper || false;
      this._autoStart = diameterOrOptions.autoStart || true;
    } else {
      this.diameter = diameterOrOptions || 1;
      this._length = length;
      this._segments = this._length;
      this._doNotTaper = false;
      this._autoStart = autoStart;
    }
    this._sectionVectors = [];
    this._sectionNormalVectors = [];
    for (let i = 0;i <= this._sectionPolygonPointsCount; i++) {
      this._sectionVectors[i] = Vector3.Zero();
      this._sectionNormalVectors[i] = Vector3.Zero();
    }
    this._createMesh();
  }
  getClassName() {
    return "TrailMesh";
  }
  _createMesh() {
    const data = new VertexData;
    const positions = [];
    const normals = [];
    const indices = [];
    const uvs = [];
    let meshCenter = Vector3.Zero();
    if (this._generator instanceof AbstractMesh && this._generator.hasBoundingInfo) {
      meshCenter = this._generator.getBoundingInfo().boundingBox.centerWorld;
    } else {
      meshCenter = this._generator.absolutePosition;
    }
    const alpha = 2 * Math.PI / this._sectionPolygonPointsCount;
    for (let i = 0;i <= this._sectionPolygonPointsCount; i++) {
      const angle = i !== this._sectionPolygonPointsCount ? i * alpha : 0;
      positions.push(meshCenter.x + Math.cos(angle) * this.diameter, meshCenter.y + Math.sin(angle) * this.diameter, meshCenter.z);
      uvs.push(i / this._sectionPolygonPointsCount, 0);
    }
    for (let i = 1;i <= this._segments; i++) {
      for (let j = 0;j <= this._sectionPolygonPointsCount; j++) {
        const angle = j !== this._sectionPolygonPointsCount ? j * alpha : 0;
        positions.push(meshCenter.x + Math.cos(angle) * this.diameter, meshCenter.y + Math.sin(angle) * this.diameter, meshCenter.z);
        uvs.push(j / this._sectionPolygonPointsCount, i / this._segments);
      }
      const l = positions.length / 3 - 2 * (this._sectionPolygonPointsCount + 1);
      for (let j = 0;j <= this._sectionPolygonPointsCount; j++) {
        indices.push(l + j, l + j + this._sectionPolygonPointsCount, l + j + this._sectionPolygonPointsCount + 1);
        indices.push(l + j, l + j + this._sectionPolygonPointsCount + 1, l + j + 1);
      }
    }
    VertexData.ComputeNormals(positions, indices, normals);
    data.positions = positions;
    data.normals = normals;
    data.indices = indices;
    data.uvs = uvs;
    data.applyToMesh(this, true);
    if (this._autoStart) {
      this.start();
    }
  }
  _updateSectionVectors() {
    const wm = this._generator.getWorldMatrix();
    const alpha = 2 * Math.PI / this._sectionPolygonPointsCount;
    for (let i = 0;i <= this._sectionPolygonPointsCount; i++) {
      const angle = i !== this._sectionPolygonPointsCount ? i * alpha : 0;
      this._sectionVectors[i].copyFromFloats(Math.cos(angle) * this.diameter, Math.sin(angle) * this.diameter, 0);
      this._sectionNormalVectors[i].copyFromFloats(Math.cos(angle), Math.sin(angle), 0);
      Vector3.TransformCoordinatesToRef(this._sectionVectors[i], wm, this._sectionVectors[i]);
      Vector3.TransformNormalToRef(this._sectionNormalVectors[i], wm, this._sectionNormalVectors[i]);
    }
  }
  start() {
    if (!this._running) {
      this._running = true;
      this._beforeRenderObserver = this.getScene().onBeforeRenderObservable.add(() => {
        this.update();
      });
    }
  }
  stop() {
    if (this._beforeRenderObserver && this._running) {
      this._running = false;
      this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver);
    }
  }
  update() {
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    const normals = this.getVerticesData(VertexBuffer.NormalKind);
    const index = 3 * (this._sectionPolygonPointsCount + 1);
    if (positions && normals) {
      if (this._doNotTaper) {
        for (let i = index;i < positions.length; i++) {
          positions[i - index] = Lerp(positions[i - index], positions[i], this._segments / this._length);
        }
      } else {
        for (let i = index;i < positions.length; i++) {
          positions[i - index] = Lerp(positions[i - index], positions[i], this._segments / this._length) - normals[i] / this._length * this.diameter;
        }
      }
      for (let i = index;i < normals.length; i++) {
        normals[i - index] = Lerp(normals[i - index], normals[i], this._segments / this._length);
      }
      this._updateSectionVectors();
      const l = positions.length - 3 * (this._sectionPolygonPointsCount + 1);
      for (let i = 0;i <= this._sectionPolygonPointsCount; i++) {
        positions[l + 3 * i] = this._sectionVectors[i].x;
        positions[l + 3 * i + 1] = this._sectionVectors[i].y;
        positions[l + 3 * i + 2] = this._sectionVectors[i].z;
        normals[l + 3 * i] = this._sectionNormalVectors[i].x;
        normals[l + 3 * i + 1] = this._sectionNormalVectors[i].y;
        normals[l + 3 * i + 2] = this._sectionNormalVectors[i].z;
      }
      this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false);
      this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false);
    }
  }
  reset() {
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    const normals = this.getVerticesData(VertexBuffer.NormalKind);
    if (positions && normals) {
      this._updateSectionVectors();
      for (let i = 0;i <= this._segments; i++) {
        const l = 3 * i * (this._sectionPolygonPointsCount + 1);
        for (let j = 0;j <= this._sectionPolygonPointsCount; j++) {
          positions[l + 3 * j] = this._sectionVectors[j].x;
          positions[l + 3 * j + 1] = this._sectionVectors[j].y;
          positions[l + 3 * j + 2] = this._sectionVectors[j].z;
          normals[l + 3 * j] = this._sectionNormalVectors[j].x;
          normals[l + 3 * j + 1] = this._sectionNormalVectors[j].y;
          normals[l + 3 * j + 2] = this._sectionNormalVectors[j].z;
        }
      }
      this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false);
      this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false);
    }
  }
  clone(name375 = "", newGenerator) {
    const options = {
      diameter: this.diameter,
      length: this._length,
      segments: this._segments,
      sections: this._sectionPolygonPointsCount,
      doNotTaper: this._doNotTaper,
      autoStart: this._autoStart
    };
    return new TrailMesh(name375, newGenerator ?? this._generator, this.getScene(), options);
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.generatorId = this._generator.id;
  }
  static Parse(parsedMesh, scene) {
    const generator = scene.getLastMeshById(parsedMesh.generatorId) ?? scene.getLastTransformNodeById(parsedMesh.generatorId);
    if (!generator) {
      throw new Error("TrailMesh: generator not found with ID " + parsedMesh.generatorId);
    }
    const options = {
      diameter: parsedMesh.diameter ?? parsedMesh._diameter,
      length: parsedMesh._length,
      segments: parsedMesh._segments,
      sections: parsedMesh._sectionPolygonPointsCount,
      doNotTaper: parsedMesh._doNotTaper,
      autoStart: parsedMesh._autoStart
    };
    return new TrailMesh(parsedMesh.name, generator, scene, options);
  }
}
// node_modules/@babylonjs/core/Meshes/meshSimplification.js
init_math_vector();
init_buffer();
init_tools();
init_math_constants();
class SimplificationQueue {
  constructor() {
    this.running = false;
    this._simplificationArray = [];
  }
  addTask(task) {
    this._simplificationArray.push(task);
  }
  executeNext() {
    const task = this._simplificationArray.pop();
    if (task) {
      this.running = true;
      this.runSimplification(task);
    } else {
      this.running = false;
    }
  }
  runSimplification(task) {
    if (task.parallelProcessing) {
      task.settings.forEach((setting) => {
        const simplifier = this._getSimplifier(task);
        simplifier.simplify(setting, (newMesh) => {
          if (setting.distance !== undefined) {
            task.mesh.addLODLevel(setting.distance, newMesh);
          }
          newMesh.isVisible = true;
          if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
            task.successCallback();
          }
          this.executeNext();
        });
      });
    } else {
      const simplifier = this._getSimplifier(task);
      const runDecimation = (setting, callback) => {
        simplifier.simplify(setting, (newMesh) => {
          if (setting.distance !== undefined) {
            task.mesh.addLODLevel(setting.distance, newMesh);
          }
          newMesh.isVisible = true;
          callback();
        });
      };
      AsyncLoop.Run(task.settings.length, (loop) => {
        runDecimation(task.settings[loop.index], () => {
          loop.executeNext();
        });
      }, () => {
        if (task.successCallback) {
          task.successCallback();
        }
        this.executeNext();
      });
    }
  }
  _getSimplifier(task) {
    switch (task.simplificationType) {
      case 0:
      default:
        return new QuadraticErrorSimplification(task.mesh);
    }
  }
}
var SimplificationType;
(function(SimplificationType2) {
  SimplificationType2[SimplificationType2["QUADRATIC"] = 0] = "QUADRATIC";
})(SimplificationType || (SimplificationType = {}));

class DecimationTriangle {
  constructor(_vertices) {
    this._vertices = _vertices;
    this.error = new Array(4);
    this.deleted = false;
    this.isDirty = false;
    this.deletePending = false;
    this.borderFactor = 0;
  }
}

class DecimationVertex {
  constructor(position, id) {
    this.position = position;
    this.id = id;
    this.isBorder = true;
    this.q = new QuadraticMatrix;
    this.triangleCount = 0;
    this.triangleStart = 0;
    this.originalOffsets = [];
  }
  updatePosition(newPosition) {
    this.position.copyFrom(newPosition);
  }
}

class QuadraticMatrix {
  constructor(data) {
    this.data = new Array(10);
    for (let i = 0;i < 10; ++i) {
      if (data && data[i]) {
        this.data[i] = data[i];
      } else {
        this.data[i] = 0;
      }
    }
  }
  det(a11, a12, a13, a21, a22, a23, a31, a32, a33) {
    const det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
    return det;
  }
  addInPlace(matrix) {
    for (let i = 0;i < 10; ++i) {
      this.data[i] += matrix.data[i];
    }
  }
  addArrayInPlace(data) {
    for (let i = 0;i < 10; ++i) {
      this.data[i] += data[i];
    }
  }
  add(matrix) {
    const m = new QuadraticMatrix;
    for (let i = 0;i < 10; ++i) {
      m.data[i] = this.data[i] + matrix.data[i];
    }
    return m;
  }
  static FromData(a, b, c, d) {
    return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  }
  static DataFromNumbers(a, b, c, d) {
    return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  }
}

class Reference {
  constructor(vertexId, triangleId) {
    this.vertexId = vertexId;
    this.triangleId = triangleId;
  }
}

class QuadraticErrorSimplification {
  constructor(_mesh) {
    this._mesh = _mesh;
    this.syncIterations = 5000;
    this.aggressiveness = 7;
    this.decimationIterations = 100;
    this.boundingBoxEpsilon = Epsilon;
  }
  simplify(settings, successCallback) {
    this._initDecimatedMesh();
    AsyncLoop.Run(this._mesh.subMeshes.length, (loop) => {
      this._initWithMesh(loop.index, () => {
        this._runDecimation(settings, loop.index, () => {
          loop.executeNext();
        });
      }, settings.optimizeMesh);
    }, () => {
      setTimeout(() => {
        successCallback(this._reconstructedMesh);
      }, 0);
    });
  }
  _runDecimation(settings, submeshIndex, successCallback) {
    const targetCount = ~~(this._triangles.length * settings.quality);
    let deletedTriangles = 0;
    const triangleCount = this._triangles.length;
    const iterationFunction = (iteration, callback) => {
      setTimeout(() => {
        if (iteration % 5 === 0) {
          this._updateMesh(iteration === 0);
        }
        for (let i = 0;i < this._triangles.length; ++i) {
          this._triangles[i].isDirty = false;
        }
        const threshold = 0.000000001 * Math.pow(iteration + 3, this.aggressiveness);
        const trianglesIterator = (i) => {
          const tIdx = ~~((this._triangles.length / 2 + i) % this._triangles.length);
          const t = this._triangles[tIdx];
          if (!t) {
            return;
          }
          if (t.error[3] > threshold || t.deleted || t.isDirty) {
            return;
          }
          for (let j = 0;j < 3; ++j) {
            if (t.error[j] < threshold) {
              const deleted0 = [];
              const deleted1 = [];
              const v0 = t._vertices[j];
              const v1 = t._vertices[(j + 1) % 3];
              if (v0.isBorder || v1.isBorder) {
                continue;
              }
              const p = Vector3.Zero();
              this._calculateError(v0, v1, p);
              const delTr = [];
              if (this._isFlipped(v0, v1, p, deleted0, delTr)) {
                continue;
              }
              if (this._isFlipped(v1, v0, p, deleted1, delTr)) {
                continue;
              }
              if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
                continue;
              }
              const uniqueArray = [];
              delTr.forEach((deletedT) => {
                if (uniqueArray.indexOf(deletedT) === -1) {
                  deletedT.deletePending = true;
                  uniqueArray.push(deletedT);
                }
              });
              if (uniqueArray.length % 2 !== 0) {
                continue;
              }
              v0.q = v1.q.add(v0.q);
              v0.updatePosition(p);
              const tStart = this._references.length;
              deletedTriangles = this._updateTriangles(v0, v0, deleted0, deletedTriangles);
              deletedTriangles = this._updateTriangles(v0, v1, deleted1, deletedTriangles);
              const tCount = this._references.length - tStart;
              if (tCount <= v0.triangleCount) {
                if (tCount) {
                  for (let c = 0;c < tCount; c++) {
                    this._references[v0.triangleStart + c] = this._references[tStart + c];
                  }
                }
              } else {
                v0.triangleStart = tStart;
              }
              v0.triangleCount = tCount;
              break;
            }
          }
        };
        AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, trianglesIterator, callback, () => {
          return triangleCount - deletedTriangles <= targetCount;
        });
      }, 0);
    };
    AsyncLoop.Run(this.decimationIterations, (loop) => {
      if (triangleCount - deletedTriangles <= targetCount) {
        loop.breakLoop();
      } else {
        iterationFunction(loop.index, () => {
          loop.executeNext();
        });
      }
    }, () => {
      setTimeout(() => {
        this._reconstructMesh(submeshIndex);
        successCallback();
      }, 0);
    });
  }
  _initWithMesh(submeshIndex, callback, optimizeMesh) {
    this._vertices = [];
    this._triangles = [];
    const positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);
    const indices = this._mesh.getIndices();
    const submesh = this._mesh.subMeshes[submeshIndex];
    const findInVertices = (positionToSearch) => {
      if (optimizeMesh) {
        for (let ii = 0;ii < this._vertices.length; ++ii) {
          if (this._vertices[ii].position.equalsWithEpsilon(positionToSearch, 0.0001)) {
            return this._vertices[ii];
          }
        }
      }
      return null;
    };
    const vertexReferences = [];
    const vertexInit = (i) => {
      if (!positionData) {
        return;
      }
      const offset = i + submesh.verticesStart;
      const position = Vector3.FromArray(positionData, offset * 3);
      const vertex = findInVertices(position) || new DecimationVertex(position, this._vertices.length);
      vertex.originalOffsets.push(offset);
      if (vertex.id === this._vertices.length) {
        this._vertices.push(vertex);
      }
      vertexReferences.push(vertex.id);
    };
    const totalVertices = submesh.verticesCount;
    AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations / 4 >> 0, vertexInit, () => {
      const indicesInit = (i) => {
        if (!indices) {
          return;
        }
        const offset = submesh.indexStart / 3 + i;
        const pos = offset * 3;
        const i0 = indices[pos + 0];
        const i1 = indices[pos + 1];
        const i2 = indices[pos + 2];
        const v0 = this._vertices[vertexReferences[i0 - submesh.verticesStart]];
        const v1 = this._vertices[vertexReferences[i1 - submesh.verticesStart]];
        const v2 = this._vertices[vertexReferences[i2 - submesh.verticesStart]];
        const triangle = new DecimationTriangle([v0, v1, v2]);
        triangle.originalOffset = pos;
        this._triangles.push(triangle);
      };
      AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => {
        this._init(callback);
      });
    });
  }
  _init(callback) {
    const triangleInit1 = (i) => {
      const t = this._triangles[i];
      t.normal = Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position), t._vertices[2].position.subtract(t._vertices[0].position)).normalize();
      for (let j = 0;j < 3; j++) {
        t._vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -Vector3.Dot(t.normal, t._vertices[0].position)));
      }
    };
    AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit1, () => {
      const triangleInit2 = (i) => {
        const t = this._triangles[i];
        for (let j = 0;j < 3; ++j) {
          t.error[j] = this._calculateError(t._vertices[j], t._vertices[(j + 1) % 3]);
        }
        t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
      };
      AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit2, () => {
        callback();
      });
    });
  }
  _reconstructMesh(submeshIndex) {
    const newTriangles = [];
    let i;
    for (i = 0;i < this._vertices.length; ++i) {
      this._vertices[i].triangleCount = 0;
    }
    let t;
    let j;
    for (i = 0;i < this._triangles.length; ++i) {
      if (!this._triangles[i].deleted) {
        t = this._triangles[i];
        for (j = 0;j < 3; ++j) {
          t._vertices[j].triangleCount = 1;
        }
        newTriangles.push(t);
      }
    }
    const newPositionData = this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || [];
    const newNormalData = this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || [];
    const newUVsData = this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || [];
    const newColorsData = this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || [];
    const normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);
    const uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);
    const colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind);
    let vertexCount = 0;
    for (i = 0;i < this._vertices.length; ++i) {
      const vertex = this._vertices[i];
      vertex.id = vertexCount;
      if (vertex.triangleCount) {
        vertex.originalOffsets.forEach((originalOffset) => {
          newPositionData.push(vertex.position.x);
          newPositionData.push(vertex.position.y);
          newPositionData.push(vertex.position.z);
          if (normalData && normalData.length) {
            newNormalData.push(normalData[originalOffset * 3]);
            newNormalData.push(normalData[originalOffset * 3 + 1]);
            newNormalData.push(normalData[originalOffset * 3 + 2]);
          }
          if (uvs && uvs.length) {
            newUVsData.push(uvs[originalOffset * 2]);
            newUVsData.push(uvs[originalOffset * 2 + 1]);
          }
          if (colorsData && colorsData.length) {
            newColorsData.push(colorsData[originalOffset * 4]);
            newColorsData.push(colorsData[originalOffset * 4 + 1]);
            newColorsData.push(colorsData[originalOffset * 4 + 2]);
            newColorsData.push(colorsData[originalOffset * 4 + 3]);
          }
          ++vertexCount;
        });
      }
    }
    const startingIndex = this._reconstructedMesh.getTotalIndices();
    const startingVertex = this._reconstructedMesh.getTotalVertices();
    const submeshesArray = this._reconstructedMesh.subMeshes;
    this._reconstructedMesh.subMeshes = [];
    const newIndicesArray = this._reconstructedMesh.getIndices();
    const originalIndices = this._mesh.getIndices();
    for (i = 0;i < newTriangles.length; ++i) {
      t = newTriangles[i];
      [0, 1, 2].forEach((idx) => {
        const id = originalIndices[t.originalOffset + idx];
        let offset = t._vertices[idx].originalOffsets.indexOf(id);
        if (offset < 0) {
          offset = 0;
        }
        newIndicesArray.push(t._vertices[idx].id + offset + startingVertex);
      });
    }
    this._reconstructedMesh.setIndices(newIndicesArray);
    this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);
    if (newNormalData.length > 0) {
      this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);
    }
    if (newUVsData.length > 0) {
      this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);
    }
    if (newColorsData.length > 0) {
      this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);
    }
    const originalSubmesh = this._mesh.subMeshes[submeshIndex];
    if (submeshIndex > 0) {
      this._reconstructedMesh.subMeshes = [];
      submeshesArray.forEach((submesh) => {
        SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
      });
      SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
    }
  }
  _initDecimatedMesh() {
    this._reconstructedMesh = new Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
    this._reconstructedMesh.material = this._mesh.material;
    this._reconstructedMesh.parent = this._mesh.parent;
    this._reconstructedMesh.isVisible = false;
    this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  }
  _isFlipped(vertex1, vertex2, point, deletedArray, delTr) {
    for (let i = 0;i < vertex1.triangleCount; ++i) {
      const t = this._triangles[this._references[vertex1.triangleStart + i].triangleId];
      if (t.deleted) {
        continue;
      }
      const s = this._references[vertex1.triangleStart + i].vertexId;
      const v1 = t._vertices[(s + 1) % 3];
      const v2 = t._vertices[(s + 2) % 3];
      if (v1 === vertex2 || v2 === vertex2) {
        deletedArray[i] = true;
        delTr.push(t);
        continue;
      }
      let d1 = v1.position.subtract(point);
      d1 = d1.normalize();
      let d2 = v2.position.subtract(point);
      d2 = d2.normalize();
      if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) {
        return true;
      }
      const normal = Vector3.Cross(d1, d2).normalize();
      deletedArray[i] = false;
      if (Vector3.Dot(normal, t.normal) < 0.2) {
        return true;
      }
    }
    return false;
  }
  _updateTriangles(origVertex, vertex, deletedArray, deletedTriangles) {
    let newDeleted = deletedTriangles;
    for (let i = 0;i < vertex.triangleCount; ++i) {
      const ref = this._references[vertex.triangleStart + i];
      const t = this._triangles[ref.triangleId];
      if (t.deleted) {
        continue;
      }
      if (deletedArray[i] && t.deletePending) {
        t.deleted = true;
        newDeleted++;
        continue;
      }
      t._vertices[ref.vertexId] = origVertex;
      t.isDirty = true;
      t.error[0] = this._calculateError(t._vertices[0], t._vertices[1]) + t.borderFactor / 2;
      t.error[1] = this._calculateError(t._vertices[1], t._vertices[2]) + t.borderFactor / 2;
      t.error[2] = this._calculateError(t._vertices[2], t._vertices[0]) + t.borderFactor / 2;
      t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
      this._references.push(ref);
    }
    return newDeleted;
  }
  _identifyBorder() {
    for (let i = 0;i < this._vertices.length; ++i) {
      const vCount = [];
      const vId = [];
      const v = this._vertices[i];
      let j;
      for (j = 0;j < v.triangleCount; ++j) {
        const triangle = this._triangles[this._references[v.triangleStart + j].triangleId];
        for (let ii = 0;ii < 3; ii++) {
          let ofs = 0;
          const vv = triangle._vertices[ii];
          while (ofs < vCount.length) {
            if (vId[ofs] === vv.id) {
              break;
            }
            ++ofs;
          }
          if (ofs === vCount.length) {
            vCount.push(1);
            vId.push(vv.id);
          } else {
            vCount[ofs]++;
          }
        }
      }
      for (j = 0;j < vCount.length; ++j) {
        if (vCount[j] === 1) {
          this._vertices[vId[j]].isBorder = true;
        } else {
          this._vertices[vId[j]].isBorder = false;
        }
      }
    }
  }
  _updateMesh(identifyBorders = false) {
    let i;
    if (!identifyBorders) {
      const newTrianglesVector = [];
      for (i = 0;i < this._triangles.length; ++i) {
        if (!this._triangles[i].deleted) {
          newTrianglesVector.push(this._triangles[i]);
        }
      }
      this._triangles = newTrianglesVector;
    }
    for (i = 0;i < this._vertices.length; ++i) {
      this._vertices[i].triangleCount = 0;
      this._vertices[i].triangleStart = 0;
    }
    let t;
    let j;
    let v;
    for (i = 0;i < this._triangles.length; ++i) {
      t = this._triangles[i];
      for (j = 0;j < 3; ++j) {
        v = t._vertices[j];
        v.triangleCount++;
      }
    }
    let tStart = 0;
    for (i = 0;i < this._vertices.length; ++i) {
      this._vertices[i].triangleStart = tStart;
      tStart += this._vertices[i].triangleCount;
      this._vertices[i].triangleCount = 0;
    }
    const newReferences = new Array(this._triangles.length * 3);
    for (i = 0;i < this._triangles.length; ++i) {
      t = this._triangles[i];
      for (j = 0;j < 3; ++j) {
        v = t._vertices[j];
        newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
        v.triangleCount++;
      }
    }
    this._references = newReferences;
    if (identifyBorders) {
      this._identifyBorder();
    }
  }
  _vertexError(q, point) {
    const x = point.x;
    const y = point.y;
    const z = point.z;
    return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  }
  _calculateError(vertex1, vertex2, pointResult) {
    const q = vertex1.q.add(vertex2.q);
    const border = vertex1.isBorder && vertex2.isBorder;
    let error = 0;
    const qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
    if (qDet !== 0 && !border) {
      if (!pointResult) {
        pointResult = Vector3.Zero();
      }
      pointResult.x = -1 / qDet * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8);
      pointResult.y = 1 / qDet * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8);
      pointResult.z = -1 / qDet * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8);
      error = this._vertexError(q, pointResult);
    } else {
      const p3 = vertex1.position.add(vertex2.position).divide(new Vector3(2, 2, 2));
      const error1 = this._vertexError(q, vertex1.position);
      const error2 = this._vertexError(q, vertex2.position);
      const error3 = this._vertexError(q, p3);
      error = Math.min(error1, error2, error3);
      if (error === error1) {
        if (pointResult) {
          pointResult.copyFrom(vertex1.position);
        }
      } else if (error === error2) {
        if (pointResult) {
          pointResult.copyFrom(vertex2.position);
        }
      } else {
        if (pointResult) {
          pointResult.copyFrom(p3);
        }
      }
    }
    return error;
  }
}
// node_modules/@babylonjs/core/Meshes/meshSimplificationSceneComponent.js
init_scene();
init_sceneComponent();
Object.defineProperty(Scene.prototype, "simplificationQueue", {
  get: function() {
    if (!this._simplificationQueue) {
      this._simplificationQueue = new SimplificationQueue;
      let component = this._getComponent(SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
      if (!component) {
        component = new SimplicationQueueSceneComponent(this);
        this._addComponent(component);
      }
    }
    return this._simplificationQueue;
  },
  set: function(value) {
    this._simplificationQueue = value;
  },
  enumerable: true,
  configurable: true
});
Mesh.prototype.simplify = function(settings, parallelProcessing = true, simplificationType = 0, successCallback) {
  this.getScene().simplificationQueue.addTask({
    settings,
    parallelProcessing,
    mesh: this,
    simplificationType,
    successCallback
  });
  return this;
};

class SimplicationQueueSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
    this.scene = scene;
  }
  register() {
    this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  }
  rebuild() {}
  dispose() {}
  _beforeCameraUpdate() {
    if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
      this.scene._simplificationQueue.executeNext();
    }
  }
}
// node_modules/@babylonjs/core/Meshes/meshUtils.js
init_buffer();
init_math_vector();
// node_modules/@babylonjs/core/Meshes/lattice.js
init_math_vector();
init_math_constants();

class Lattice {
  getClassName() {
    return "Lattice";
  }
  get resolutionX() {
    return this._resolutionX;
  }
  get resolutionY() {
    return this._resolutionY;
  }
  get resolutionZ() {
    return this._resolutionZ;
  }
  get size() {
    return this._size;
  }
  get position() {
    return this._position;
  }
  get data() {
    return this._data;
  }
  get cellSize() {
    return this._cellSize;
  }
  get min() {
    return this._min;
  }
  get max() {
    return this._max;
  }
  constructor(options) {
    this._cellSize = new Vector3;
    this._min = new Vector3(-0.5, -0.5, -0.5);
    this._max = new Vector3(0.5, 0.5, 0.5);
    this._localPos = new Vector3;
    this._tmpVector = new Vector3;
    this._lerpVector0 = new Vector3;
    this._lerpVector1 = new Vector3;
    this._lerpVector2 = new Vector3;
    this._lerpVector3 = new Vector3;
    this._lerpVector4 = new Vector3;
    this._lerpVector5 = new Vector3;
    const localOptions = {
      resolutionX: 3,
      resolutionY: 3,
      resolutionZ: 3,
      position: Vector3.Zero(),
      size: Vector3.One(),
      ...options
    };
    this._resolutionX = localOptions.resolutionX;
    this._resolutionY = localOptions.resolutionY;
    this._resolutionZ = localOptions.resolutionZ;
    this._position = localOptions.position;
    this._size = localOptions.autoAdaptToMesh ? localOptions.autoAdaptToMesh.getBoundingInfo().boundingBox.extendSize.scale(2) : localOptions.size;
    this._allocateData();
    this.update();
  }
  _allocateData() {
    this._data = new Array(this.resolutionX);
    for (let i = 0;i < this.resolutionX; i++) {
      this._data[i] = new Array(this.resolutionY);
      for (let j = 0;j < this.resolutionY; j++) {
        this._data[i][j] = new Array(this.resolutionZ);
        for (let k = 0;k < this.resolutionZ; k++) {
          this._data[i][j][k] = Vector3.Zero();
        }
      }
    }
  }
  update() {
    for (let i = 0;i < this.resolutionX; i++) {
      for (let j = 0;j < this.resolutionY; j++) {
        for (let k = 0;k < this.resolutionZ; k++) {
          const x = -this.size.x / 2 + this.size.x * (i / (this.resolutionX - 1));
          const y = -this.size.y / 2 + this.size.y * (j / (this.resolutionY - 1));
          const z = -this.size.z / 2 + this.size.z * (k / (this.resolutionZ - 1));
          this._data[i][j][k].set(x, y, z);
        }
      }
    }
  }
  deformMesh(mesh) {
    const positions = mesh.getVerticesData(VertexBuffer.PositionKind);
    if (!positions) {
      return;
    }
    this.deform(positions);
    mesh.setVerticesData(VertexBuffer.PositionKind, positions, true);
  }
  updateInternals() {
    const nx = this._resolutionX;
    const ny = this._resolutionY;
    const nz = this._resolutionZ;
    this._cellSize.set(this.size.x / (nx - 1), this.size.y / (ny - 1), this.size.z / (nz - 1));
    this._min.set(this.position.x - this.size.x / 2, this.position.y - this.size.y / 2, this.position.z - this.size.z / 2);
    this._min.addToRef(this._size, this._max);
  }
  deform(positions, target) {
    const nx = this._resolutionX;
    const ny = this._resolutionY;
    const nz = this._resolutionZ;
    this.updateInternals();
    const min = this._min;
    const max = this._max;
    for (let i = 0;i < positions.length; i += 3) {
      const vertex = this._tmpVector.fromArray(positions, i);
      if (OutsideRange(vertex.x, min.x, max.x, Epsilon) || OutsideRange(vertex.y, min.y, max.y, Epsilon) || OutsideRange(vertex.z, min.z, max.z, Epsilon)) {
        if (target) {
          vertex.toArray(target, i);
        }
        continue;
      }
      const localPos = this._localPos.set((vertex.x - min.x) / this._cellSize.x, (vertex.y - min.y) / this._cellSize.y, (vertex.z - min.z) / this._cellSize.z);
      const i0 = Math.floor(localPos.x);
      const j0 = Math.floor(localPos.y);
      const k0 = Math.floor(localPos.z);
      const i1 = Math.min(i0 + 1, nx - 1);
      const j1 = Math.min(j0 + 1, ny - 1);
      const k1 = Math.min(k0 + 1, nz - 1);
      const tx = localPos.x - i0;
      const ty = localPos.y - j0;
      const tz = localPos.z - k0;
      const ii0 = Clamp(i0, 0, nx - 1);
      const jj0 = Clamp(j0, 0, ny - 1);
      const kk0 = Clamp(k0, 0, nz - 1);
      const ii1 = Clamp(i1, 0, nx - 1);
      const jj1 = Clamp(j1, 0, ny - 1);
      const kk1 = Clamp(k1, 0, nz - 1);
      const p000 = this._data[ii0][jj0][kk0];
      const p100 = this._data[ii1][jj0][kk0];
      const p010 = this._data[ii0][jj1][kk0];
      const p110 = this._data[ii1][jj1][kk0];
      const p001 = this._data[ii0][jj0][kk1];
      const p101 = this._data[ii1][jj0][kk1];
      const p011 = this._data[ii0][jj1][kk1];
      const p111 = this._data[ii1][jj1][kk1];
      const p00 = Vector3.LerpToRef(p000, p100, tx, this._lerpVector0);
      const p01 = Vector3.LerpToRef(p001, p101, tx, this._lerpVector1);
      const p10 = Vector3.LerpToRef(p010, p110, tx, this._lerpVector2);
      const p11 = Vector3.LerpToRef(p011, p111, tx, this._lerpVector3);
      const p0 = Vector3.LerpToRef(p00, p10, ty, this._lerpVector4);
      const p1 = Vector3.LerpToRef(p01, p11, ty, this._lerpVector5);
      const deformedPos = Vector3.LerpToRef(p0, p1, tz, this._lerpVector0);
      deformedPos.addInPlace(this.position);
      deformedPos.toArray(target || positions, i);
    }
  }
}
// node_modules/@babylonjs/core/Meshes/GreasedLine/greasedLineMesh.js
init_math_vector();
init_buffer();
init_pickingInfo();
init_deepCopier();

// node_modules/@babylonjs/core/Meshes/GreasedLine/greasedLineBaseMesh.js
init_buffer();
init_deepCopier();
var GreasedLineRibbonPointsMode;
(function(GreasedLineRibbonPointsMode2) {
  GreasedLineRibbonPointsMode2[GreasedLineRibbonPointsMode2["POINTS_MODE_POINTS"] = 0] = "POINTS_MODE_POINTS";
  GreasedLineRibbonPointsMode2[GreasedLineRibbonPointsMode2["POINTS_MODE_PATHS"] = 1] = "POINTS_MODE_PATHS";
})(GreasedLineRibbonPointsMode || (GreasedLineRibbonPointsMode = {}));
var GreasedLineRibbonFacesMode;
(function(GreasedLineRibbonFacesMode2) {
  GreasedLineRibbonFacesMode2[GreasedLineRibbonFacesMode2["FACES_MODE_SINGLE_SIDED"] = 0] = "FACES_MODE_SINGLE_SIDED";
  GreasedLineRibbonFacesMode2[GreasedLineRibbonFacesMode2["FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING"] = 1] = "FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING";
  GreasedLineRibbonFacesMode2[GreasedLineRibbonFacesMode2["FACES_MODE_DOUBLE_SIDED"] = 2] = "FACES_MODE_DOUBLE_SIDED";
})(GreasedLineRibbonFacesMode || (GreasedLineRibbonFacesMode = {}));
var GreasedLineRibbonAutoDirectionMode;
(function(GreasedLineRibbonAutoDirectionMode2) {
  GreasedLineRibbonAutoDirectionMode2[GreasedLineRibbonAutoDirectionMode2["AUTO_DIRECTIONS_FROM_FIRST_SEGMENT"] = 0] = "AUTO_DIRECTIONS_FROM_FIRST_SEGMENT";
  GreasedLineRibbonAutoDirectionMode2[GreasedLineRibbonAutoDirectionMode2["AUTO_DIRECTIONS_FROM_ALL_SEGMENTS"] = 1] = "AUTO_DIRECTIONS_FROM_ALL_SEGMENTS";
  GreasedLineRibbonAutoDirectionMode2[GreasedLineRibbonAutoDirectionMode2["AUTO_DIRECTIONS_ENHANCED"] = 2] = "AUTO_DIRECTIONS_ENHANCED";
  GreasedLineRibbonAutoDirectionMode2[GreasedLineRibbonAutoDirectionMode2["AUTO_DIRECTIONS_FACE_TO"] = 3] = "AUTO_DIRECTIONS_FACE_TO";
  GreasedLineRibbonAutoDirectionMode2[GreasedLineRibbonAutoDirectionMode2["AUTO_DIRECTIONS_NONE"] = 99] = "AUTO_DIRECTIONS_NONE";
})(GreasedLineRibbonAutoDirectionMode || (GreasedLineRibbonAutoDirectionMode = {}));

class GreasedLineBaseMesh extends Mesh {
  constructor(name375, scene, _options) {
    super(name375, scene, null, null, false, false);
    this.name = name375;
    this._options = _options;
    this._lazy = false;
    this._updatable = false;
    this._engine = scene.getEngine();
    this._lazy = _options.lazy ?? false;
    this._updatable = _options.updatable ?? false;
    this._vertexPositions = [];
    this._indices = [];
    this._uvs = [];
    this._points = [];
    this._colorPointers = _options.colorPointers ?? [];
    this._widths = _options.widths ?? new Array(_options.points.length).fill(1);
  }
  getClassName() {
    return "GreasedLineMesh";
  }
  _updateWidthsWithValue(defaulValue) {
    let pointCount = 0;
    for (const points of this._points) {
      pointCount += points.length;
    }
    const countDiff = pointCount / 3 * 2 - this._widths.length;
    for (let i = 0;i < countDiff; i++) {
      this._widths.push(defaulValue);
    }
  }
  updateLazy() {
    this._setPoints(this._points);
    if (!this._options.colorPointers) {
      this._updateColorPointers();
    }
    this._createVertexBuffers(this._options.ribbonOptions?.smoothShading);
    !this.doNotSyncBoundingInfo && this.refreshBoundingInfo();
    this.greasedLineMaterial?.updateLazy();
  }
  addPoints(points, options) {
    for (const p of points) {
      this._points.push(p);
    }
    if (!this._lazy) {
      this.setPoints(this._points, options);
    }
  }
  dispose(doNotRecurse, disposeMaterialAndTextures = false) {
    super.dispose(doNotRecurse, disposeMaterialAndTextures);
  }
  isLazy() {
    return this._lazy;
  }
  get uvs() {
    return this._uvs;
  }
  set uvs(uvs) {
    this._uvs = uvs instanceof Float32Array ? uvs : new Float32Array(uvs);
    this._createVertexBuffers();
  }
  get offsets() {
    return this._offsets;
  }
  set offsets(offsets) {
    if (this.material instanceof GreasedLineSimpleMaterial) {
      this.material.setDefine(GreasedLineUseOffsetsSimpleMaterialDefine, offsets?.length > 0);
    }
    this._offsets = offsets;
    if (!this._offsetsBuffer) {
      this._createOffsetsBuffer(offsets);
    } else {
      this._offsetsBuffer.update(offsets);
    }
  }
  get widths() {
    return this._widths;
  }
  set widths(widths) {
    this._widths = widths;
    if (!this._lazy) {
      this._widthsBuffer && this._widthsBuffer.update(widths);
    }
  }
  get colorPointers() {
    return this._colorPointers;
  }
  set colorPointers(colorPointers) {
    this._colorPointers = colorPointers;
    if (!this._lazy) {
      this._colorPointersBuffer && this._colorPointersBuffer.update(colorPointers);
    }
  }
  get greasedLineMaterial() {
    if (this.material && this.material instanceof GreasedLineSimpleMaterial) {
      return this.material;
    }
    const materialPlugin = this.material?.pluginManager?.getPlugin(GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME);
    if (materialPlugin) {
      return materialPlugin;
    }
    return;
  }
  get points() {
    const pointsCopy = [];
    DeepCopier.DeepCopy(this._points, pointsCopy);
    return pointsCopy;
  }
  setPoints(points, options) {
    this._points = GreasedLineTools.ConvertPoints(points, options?.pointsOptions ?? this._options.pointsOptions);
    this._updateWidths();
    if (!options?.colorPointers) {
      this._updateColorPointers();
    }
    this._setPoints(this._points, options);
  }
  _initGreasedLine() {
    this._vertexPositions = [];
    this._indices = [];
    this._uvs = [];
  }
  _createLineOptions() {
    const lineOptions = {
      points: this._points,
      colorPointers: this._colorPointers,
      lazy: this._lazy,
      updatable: this._updatable,
      uvs: this._uvs,
      widths: this._widths,
      ribbonOptions: this._options.ribbonOptions
    };
    return lineOptions;
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.type = this.getClassName();
    serializationObject.lineOptions = this._createLineOptions();
  }
  _createVertexBuffers(computeNormals = false) {
    const vertexData = new VertexData;
    vertexData.positions = this._vertexPositions;
    vertexData.indices = this._indices;
    vertexData.uvs = this._uvs;
    if (computeNormals) {
      vertexData.normals = [];
      VertexData.ComputeNormals(this._vertexPositions, this._indices, vertexData.normals);
    }
    vertexData.applyToMesh(this, this._options.updatable);
    return vertexData;
  }
  _createOffsetsBuffer(offsets) {
    const engine2 = this._scene.getEngine();
    const offsetBuffer = new Buffer2(engine2, offsets, this._updatable, 3);
    this.setVerticesBuffer(offsetBuffer.createVertexBuffer("grl_offsets", 0, 3));
    this._offsetsBuffer = offsetBuffer;
  }
}

// node_modules/@babylonjs/core/Meshes/GreasedLine/greasedLineMesh.js
Mesh._GreasedLineMeshParser = (parsedMesh, scene) => {
  return GreasedLineMesh.Parse(parsedMesh, scene);
};

class GreasedLineMesh extends GreasedLineBaseMesh {
  constructor(name375, scene, _options) {
    super(name375, scene, _options);
    this.name = name375;
    this.intersectionThreshold = 0.1;
    this._previousAndSide = [];
    this._nextAndCounters = [];
    if (_options.points) {
      this.addPoints(GreasedLineTools.ConvertPoints(_options.points));
    }
  }
  getClassName() {
    return "GreasedLineMesh";
  }
  _updateColorPointers() {
    if (this._options.colorPointers) {
      return;
    }
    let colorPointer = 0;
    this._colorPointers = [];
    this._points.forEach((p) => {
      for (let jj = 0;jj < p.length; jj += 3) {
        this._colorPointers.push(colorPointer);
        this._colorPointers.push(colorPointer++);
      }
    });
  }
  _updateWidths() {}
  _setPoints(points) {
    this._points = points;
    this._options.points = points;
    this._initGreasedLine();
    let indiceOffset = 0;
    let vertexPositionsLen = 0, indicesLength = 0, uvLength = 0, previousAndSideLength = 0;
    points.forEach((p) => {
      vertexPositionsLen += p.length * 2;
      indicesLength += (p.length - 3) * 2;
      uvLength += p.length * 4 / 3;
      previousAndSideLength += p.length * 8 / 3;
    });
    const vertexPositionsArr = new Float32Array(vertexPositionsLen);
    const indicesArr = vertexPositionsLen > 65535 ? new Uint32Array(indicesLength) : new Uint16Array(indicesLength);
    const uvArr = new Float32Array(uvLength);
    const previousAndSide = new Float32Array(previousAndSideLength);
    const nextAndCounters = new Float32Array(previousAndSideLength);
    let vertexPositionsOffset = 0, indicesOffset = 0, uvOffset = 0, previousAndSideOffset = 0, nextAndCountersOffset = 0;
    points.forEach((p) => {
      const lengthArray = GreasedLineTools.GetLineLengthArray(p);
      const totalLength = lengthArray[lengthArray.length - 1];
      for (let j = 0, jj = 0;jj < p.length; j++, jj += 3) {
        const baseOffset = vertexPositionsOffset + jj * 2;
        vertexPositionsArr[baseOffset + 0] = p[jj + 0];
        vertexPositionsArr[baseOffset + 1] = p[jj + 1];
        vertexPositionsArr[baseOffset + 2] = p[jj + 2];
        vertexPositionsArr[baseOffset + 3] = p[jj + 0];
        vertexPositionsArr[baseOffset + 4] = p[jj + 1];
        vertexPositionsArr[baseOffset + 5] = p[jj + 2];
        if (jj < p.length - 3) {
          const n = j * 2 + indiceOffset;
          const baseIndicesOffset = indicesOffset + jj * 2;
          indicesArr[baseIndicesOffset + 0] = n;
          indicesArr[baseIndicesOffset + 1] = n + 1;
          indicesArr[baseIndicesOffset + 2] = n + 2;
          indicesArr[baseIndicesOffset + 3] = n + 2;
          indicesArr[baseIndicesOffset + 4] = n + 1;
          indicesArr[baseIndicesOffset + 5] = n + 3;
        }
      }
      indiceOffset += p.length / 3 * 2;
      const currVertexPositionsOffsetLength = p.length * 2;
      const positions = vertexPositionsArr.subarray(vertexPositionsOffset, vertexPositionsOffset + currVertexPositionsOffsetLength);
      vertexPositionsOffset += currVertexPositionsOffsetLength;
      indicesOffset += (p.length - 3) * 2;
      const previous = new Float32Array(positions.length);
      const next = new Float32Array(positions.length);
      const l = positions.length / 6;
      let v;
      if (GreasedLineMesh._CompareV3(0, l - 1, positions)) {
        v = positions.subarray((l - 2) * 6, (l - 1) * 6);
      } else {
        v = positions.subarray(0, 6);
      }
      previous.set(v);
      previous.set(positions.subarray(0, positions.length - 6), 6);
      next.set(positions.subarray(6));
      if (GreasedLineMesh._CompareV3(l - 1, 0, positions)) {
        v = positions.subarray(6, 12);
      } else {
        v = positions.subarray((l - 1) * 6, l * 6);
      }
      next.set(v, next.length - 6);
      for (let i = 0, sidesLength = positions.length / 3;i < sidesLength; i++) {
        previousAndSide[previousAndSideOffset++] = previous[i * 3];
        previousAndSide[previousAndSideOffset++] = previous[i * 3 + 1];
        previousAndSide[previousAndSideOffset++] = previous[i * 3 + 2];
        previousAndSide[previousAndSideOffset++] = 1 - ((i & 1) << 1);
        nextAndCounters[nextAndCountersOffset++] = next[i * 3];
        nextAndCounters[nextAndCountersOffset++] = next[i * 3 + 1];
        nextAndCounters[nextAndCountersOffset++] = next[i * 3 + 2];
        nextAndCounters[nextAndCountersOffset++] = lengthArray[i >> 1] / totalLength;
      }
      if (this._options.uvs) {
        for (let i = 0;i < this._options.uvs.length; i++) {
          uvArr[uvOffset++] = this._options.uvs[i];
        }
      } else {
        for (let j = 0;j < l; j++) {
          const lengthRatio = lengthArray[j] / totalLength;
          const uvOffsetBase = uvOffset + j * 4;
          uvArr[uvOffsetBase + 0] = lengthRatio;
          uvArr[uvOffsetBase + 1] = 0;
          uvArr[uvOffsetBase + 2] = lengthRatio;
          uvArr[uvOffsetBase + 3] = 1;
        }
      }
    });
    this._vertexPositions = vertexPositionsArr;
    this._indices = indicesArr;
    this._uvs = uvArr;
    this._previousAndSide = previousAndSide;
    this._nextAndCounters = nextAndCounters;
    if (!this._lazy) {
      if (!this._options.colorPointers) {
        this._updateColorPointers();
      }
      this._createVertexBuffers();
      !this.doNotSyncBoundingInfo && this.refreshBoundingInfo();
    }
  }
  clone(name375 = `${this.name}-cloned`, newParent) {
    const lineOptions = this._createLineOptions();
    const deepCopiedLineOptions = {};
    DeepCopier.DeepCopy(lineOptions, deepCopiedLineOptions, ["instance"], undefined, true);
    const cloned = new GreasedLineMesh(name375, this._scene, deepCopiedLineOptions);
    if (newParent) {
      cloned.parent = newParent;
    }
    cloned.material = this.material;
    return cloned;
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.type = this.getClassName();
    serializationObject.lineOptions = this._createLineOptions();
  }
  static Parse(parsedMesh, scene) {
    const lineOptions = parsedMesh.lineOptions;
    const name375 = parsedMesh.name;
    const result = new GreasedLineMesh(name375, scene, lineOptions);
    return result;
  }
  _initGreasedLine() {
    super._initGreasedLine();
    this._previousAndSide = [];
    this._nextAndCounters = [];
  }
  intersects(ray2, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {
    const pickingInfo2 = new PickingInfo;
    const intersections = this.findAllIntersections(ray2, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo, true);
    if (intersections?.length === 1) {
      const intersection = intersections[0];
      pickingInfo2.hit = true;
      pickingInfo2.distance = intersection.distance;
      pickingInfo2.ray = ray2;
      pickingInfo2.pickedMesh = this;
      pickingInfo2.pickedPoint = intersection.point;
    }
    return pickingInfo2;
  }
  findAllIntersections(ray2, _fastCheck, _trianglePredicate, onlyBoundingInfo = false, _worldToUse, skipBoundingInfo = false, firstOnly = false) {
    if (onlyBoundingInfo && !skipBoundingInfo && ray2.intersectsSphere(this._boundingSphere, this.intersectionThreshold) === false) {
      return;
    }
    const indices = this.getIndices();
    const positions = this.getVerticesData(VertexBuffer.PositionKind);
    const widths = this._widths;
    const lineWidth = this.greasedLineMaterial?.width ?? 1;
    const intersects = [];
    if (indices && positions && widths) {
      let i = 0, l = 0;
      for (i = 0, l = indices.length - 1;i < l; i += 3) {
        const a = indices[i];
        const b = indices[i + 1];
        GreasedLineMesh._V_START.fromArray(positions, a * 3);
        GreasedLineMesh._V_END.fromArray(positions, b * 3);
        if (this._offsets) {
          GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets, a * 3);
          GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets, b * 3);
          GreasedLineMesh._V_START.addInPlace(GreasedLineMesh._V_OFFSET_START);
          GreasedLineMesh._V_END.addInPlace(GreasedLineMesh._V_OFFSET_END);
        }
        const iFloored = Math.floor(i / 3);
        const width = widths[iFloored] !== undefined ? widths[iFloored] : 1;
        const precision = this.intersectionThreshold * (lineWidth * width) / 2;
        const distance = ray2.intersectionSegment(GreasedLineMesh._V_START, GreasedLineMesh._V_END, precision);
        if (distance !== -1) {
          intersects.push({
            distance,
            point: ray2.direction.normalize().multiplyByFloats(distance, distance, distance).add(ray2.origin)
          });
          if (firstOnly) {
            return intersects;
          }
        }
      }
      i = l;
    }
    return intersects;
  }
  get _boundingSphere() {
    return this.getBoundingInfo().boundingSphere;
  }
  static _CompareV3(positionIdx1, positionIdx2, positions) {
    const arrayIdx1 = positionIdx1 * 6;
    const arrayIdx2 = positionIdx2 * 6;
    return positions[arrayIdx1] === positions[arrayIdx2] && positions[arrayIdx1 + 1] === positions[arrayIdx2 + 1] && positions[arrayIdx1 + 2] === positions[arrayIdx2 + 2];
  }
  _createVertexBuffers() {
    const vertexData = super._createVertexBuffers();
    const engine2 = this._scene.getEngine();
    const previousAndSideBuffer = new Buffer2(engine2, this._previousAndSide, false, 4);
    this.setVerticesBuffer(previousAndSideBuffer.createVertexBuffer("grl_previousAndSide", 0, 4));
    const nextAndCountersBuffer = new Buffer2(engine2, this._nextAndCounters, false, 4);
    this.setVerticesBuffer(nextAndCountersBuffer.createVertexBuffer("grl_nextAndCounters", 0, 4));
    const widthBuffer = new Buffer2(engine2, this._widths, this._updatable, 1);
    this.setVerticesBuffer(widthBuffer.createVertexBuffer("grl_widths", 0, 1));
    this._widthsBuffer = widthBuffer;
    const colorPointersBuffer = new Buffer2(engine2, this._colorPointers, this._updatable, 1);
    this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer("grl_colorPointers", 0, 1));
    this._colorPointersBuffer = colorPointersBuffer;
    return vertexData;
  }
}
GreasedLineMesh._V_START = new Vector3;
GreasedLineMesh._V_END = new Vector3;
GreasedLineMesh._V_OFFSET_START = new Vector3;
GreasedLineMesh._V_OFFSET_END = new Vector3;

// node_modules/@babylonjs/core/Meshes/Builders/greasedLineBuilder.js
init_engineStore();

// node_modules/@babylonjs/core/Meshes/GreasedLine/greasedLineRibbonMesh.js
init_math_vector();
init_buffer();
init_deepCopier();
Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => {
  return GreasedLineRibbonMesh.Parse(parsedMesh, scene);
};

class GreasedLineRibbonMesh extends GreasedLineBaseMesh {
  constructor(name375, scene, _options, _pathOptions) {
    super(name375, scene, _options);
    this.name = name375;
    if (!_options.ribbonOptions) {
      throw "'GreasedLineMeshOptions.ribbonOptions' is not set.";
    }
    this._paths = [];
    this._counters = [];
    this._slopes = [];
    this._widths = _options.widths ?? [];
    this._ribbonWidths = [];
    this._pathsOptions = _pathOptions ?? [];
    if (_options.points) {
      this.addPoints(GreasedLineTools.ConvertPoints(_options.points), _options, !!_pathOptions);
    }
  }
  addPoints(points, options, hasPathOptions = false) {
    if (!options.ribbonOptions) {
      throw "addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";
    }
    if (!hasPathOptions) {
      this._pathsOptions.push({ options, pathCount: points.length });
    }
    super.addPoints(points, options);
  }
  getClassName() {
    return "GreasedLineRibbonMesh";
  }
  get isFlatLine() {
    return this._paths.length < 3;
  }
  get slopes() {
    return this._slopes;
  }
  set slopes(slopes) {
    this._slopes = slopes;
  }
  _updateColorPointers() {
    if (this._options.colorPointers) {
      return;
    }
    let colorPointer = 0;
    this._colorPointers = [];
    for (let i = 0;i < this._pathsOptions.length; i++) {
      const { options: pathOptions, pathCount } = this._pathsOptions[i];
      const points = this._points[i];
      if (pathOptions.ribbonOptions.pointsMode === 0) {
        for (let k = 0;k < pathCount; k++) {
          for (let j = 0;j < points.length; j += 3) {
            this._colorPointers.push(colorPointer);
            this._colorPointers.push(colorPointer++);
          }
        }
      } else {
        for (let j = 0;j < points.length; j += 3) {
          for (let k = 0;k < pathCount; k++) {
            this._colorPointers.push(colorPointer);
          }
          colorPointer++;
        }
      }
    }
  }
  _updateWidths() {
    super._updateWidthsWithValue(1);
  }
  _setPoints(points, _options) {
    if (!this._options.ribbonOptions) {
      throw "No 'GreasedLineMeshOptions.ribbonOptions' provided.";
    }
    this._points = points;
    this._options.points = points;
    this._initGreasedLine();
    let indiceOffset = 0;
    let directionPlanes;
    for (let i = 0, c = 0;i < this._pathsOptions.length; i++) {
      const { options: pathOptions, pathCount } = this._pathsOptions[i];
      const subPoints = points.slice(c, c + pathCount);
      c += pathCount;
      if (pathOptions.ribbonOptions?.pointsMode === 1) {
        indiceOffset = this._preprocess(GreasedLineTools.ToVector3Array(subPoints), indiceOffset, pathOptions);
      } else {
        if (pathOptions.ribbonOptions?.directionsAutoMode === 99) {
          if (!pathOptions.ribbonOptions.directions) {
            throw "In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined.";
          }
          directionPlanes = GreasedLineRibbonMesh._GetDirectionPlanesFromDirectionsOption(subPoints.length, pathOptions.ribbonOptions.directions);
        }
        subPoints.forEach((p, idx) => {
          const pathArray = GreasedLineRibbonMesh._ConvertToRibbonPath(p, pathOptions.ribbonOptions, this._scene.useRightHandedSystem, directionPlanes ? directionPlanes[idx] : directionPlanes);
          indiceOffset = this._preprocess(pathArray, indiceOffset, pathOptions);
        });
      }
    }
    if (!this._lazy) {
      this._createVertexBuffers();
      !this.doNotSyncBoundingInfo && this.refreshBoundingInfo();
    }
  }
  static _GetDirectionPlanesFromDirectionsOption(count, directions) {
    if (Array.isArray(directions)) {
      return directions;
    }
    return new Array(count).fill(directions);
  }
  static _CreateRibbonVertexData(pathArray, options) {
    const numOfPaths = pathArray.length;
    if (numOfPaths < 2) {
      throw "Minimum of two paths are required to create a GreasedLineRibbonMesh.";
    }
    const positions = [];
    const indices = [];
    const path = pathArray[0];
    for (let i = 0;i < path.length; i++) {
      for (let pi = 0;pi < pathArray.length; pi++) {
        const v2 = pathArray[pi][i];
        positions.push(v2.x, v2.y, v2.z);
      }
    }
    const v = [1, 0, numOfPaths];
    const doubleSided = options.ribbonOptions?.facesMode === 2;
    const closePath = options.ribbonOptions?.pointsMode === 1 && options.ribbonOptions.closePath;
    if (numOfPaths > 2) {
      for (let i = 0;i < path.length - 1; i++) {
        v[0] = 1 + numOfPaths * i;
        v[1] = numOfPaths * i;
        v[2] = (i + 1) * numOfPaths;
        for (let pi = 0;pi < (numOfPaths - 1) * 2; pi++) {
          if (pi % 2 !== 0) {
            v[2] += 1;
          }
          if (pi % 2 === 0 && pi > 0) {
            v[0] += 1;
            v[1] += 1;
          }
          indices.push(v[1] + (pi % 2 !== 0 ? numOfPaths : 0), v[0], v[2]);
          if (doubleSided) {
            indices.push(v[0], v[1] + (pi % 2 !== 0 ? numOfPaths : 0), v[2]);
          }
        }
      }
    } else {
      for (let i = 0;i < positions.length / 3 - 3; i += 2) {
        indices.push(i, i + 1, i + 2);
        indices.push(i + 2, i + 1, i + 3);
        if (doubleSided) {
          indices.push(i + 1, i, i + 2);
          indices.push(i + 1, i + 2, i + 3);
        }
      }
    }
    if (closePath) {
      let lastIndice = numOfPaths * (path.length - 1);
      for (let pi = 0;pi < numOfPaths - 1; pi++) {
        indices.push(lastIndice, pi + 1, pi);
        indices.push(lastIndice + 1, pi + 1, lastIndice);
        if (doubleSided) {
          indices.push(pi, pi + 1, lastIndice);
          indices.push(lastIndice, pi + 1, lastIndice + 1);
        }
        lastIndice++;
      }
    }
    return {
      positions,
      indices
    };
  }
  _preprocess(pathArray, indiceOffset, options) {
    this._paths = pathArray;
    const ribbonVertexData = GreasedLineRibbonMesh._CreateRibbonVertexData(pathArray, options);
    const positions = ribbonVertexData.positions;
    if (!this._options.widths) {
      throw "No 'GreasedLineMeshOptions.widths' table is specified.";
    }
    const vertexPositions = Array.isArray(this._vertexPositions) ? this._vertexPositions : Array.from(this._vertexPositions);
    this._vertexPositions = vertexPositions;
    const uvs = Array.isArray(this._uvs) ? this._uvs : Array.from(this._uvs);
    this._uvs = uvs;
    const indices = Array.isArray(this._indices) ? this._indices : Array.from(this._indices);
    this._indices = indices;
    for (const p of positions) {
      vertexPositions.push(p);
    }
    let pathArrayCopy = pathArray;
    if (options.ribbonOptions?.pointsMode === 1 && options.ribbonOptions.closePath) {
      pathArrayCopy = [];
      for (let i = 0;i < pathArray.length; i++) {
        const pathCopy = pathArray[i].slice();
        pathCopy.push(pathArray[i][0].clone());
        pathArrayCopy.push(pathCopy);
      }
    }
    this._calculateSegmentLengths(pathArrayCopy);
    const pathArrayLength = pathArrayCopy.length;
    const previousCounters = new Array(pathArrayLength).fill(0);
    for (let i = 0;i < pathArrayCopy[0].length; i++) {
      let v = 0;
      for (let pi = 0;pi < pathArrayLength; pi++) {
        const counter = previousCounters[pi] + this._vSegmentLengths[pi][i] / this._vTotalLengths[pi];
        this._counters.push(counter);
        uvs.push(counter, v);
        previousCounters[pi] = counter;
        v += this._uSegmentLengths[i][pi] / this._uTotalLengths[i];
      }
    }
    for (let i = 0, c = 0;i < pathArrayCopy[0].length; i++) {
      const widthLower = this._uSegmentLengths[i][0] / 2;
      const widthUpper = this._uSegmentLengths[i][pathArrayLength - 1] / 2;
      this._ribbonWidths.push(((this._widths[c++] ?? 1) - 1) * widthLower);
      for (let pi = 0;pi < pathArrayLength - 2; pi++) {
        this._ribbonWidths.push(0);
      }
      this._ribbonWidths.push(((this._widths[c++] ?? 1) - 1) * widthUpper);
    }
    const slopes = options.ribbonOptions?.pointsMode === 1 ? new Array(pathArrayCopy[0].length * pathArrayCopy.length * 6).fill(0) : GreasedLineRibbonMesh._CalculateSlopes(pathArrayCopy);
    for (const s of slopes) {
      this._slopes.push(s);
    }
    if (ribbonVertexData.indices) {
      for (let i = 0;i < ribbonVertexData.indices.length; i++) {
        indices.push(ribbonVertexData.indices[i] + indiceOffset);
      }
    }
    indiceOffset += positions.length / 3;
    return indiceOffset;
  }
  static _ConvertToRibbonPath(points, ribbonInfo, rightHandedSystem, directionPlane) {
    if (ribbonInfo.pointsMode === 0 && !ribbonInfo.width) {
      throw "'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS.";
    }
    const path1 = [];
    const path2 = [];
    if (ribbonInfo.pointsMode === 0) {
      const width = ribbonInfo.width / 2;
      const pointVectors = GreasedLineTools.ToVector3Array(points);
      let direction = null;
      let fatDirection = null;
      if (ribbonInfo.directionsAutoMode === 0) {
        directionPlane = GreasedLineRibbonMesh._GetDirectionFromPoints(pointVectors[0], pointVectors[1], null);
      }
      if (ribbonInfo.directionsAutoMode === 3 && !(ribbonInfo.directions instanceof Vector3)) {
        throw "In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FACE_TO 'GreasedLineMeshOptions.ribbonOptions.directions' must be a Vector3.";
      }
      TmpVectors.Vector3[1] = ribbonInfo.directions instanceof Vector3 ? ribbonInfo.directions : GreasedLineRibbonMesh.DIRECTION_XZ;
      for (let i = 0;i < pointVectors.length - (directionPlane ? 0 : 1); i++) {
        const p1 = pointVectors[i];
        const p2 = pointVectors[i + 1];
        if (directionPlane) {
          direction = directionPlane;
        } else if (ribbonInfo.directionsAutoMode === 3) {
          p2.subtractToRef(p1, TmpVectors.Vector3[0]);
          direction = Vector3.CrossToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[1], TmpVectors.Vector3[2]).normalize();
        } else if (ribbonInfo.directionsAutoMode === 1) {
          direction = GreasedLineRibbonMesh._GetDirectionFromPoints(p1, p2, direction);
        } else {
          const directionTemp = p2.subtract(p1);
          directionTemp.applyRotationQuaternionInPlace(directionTemp.x > directionTemp.y && directionTemp.x > directionTemp.z ? rightHandedSystem ? GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion : GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion : GreasedLineRibbonMesh._LeftReadOnlyQuaternion);
          direction = directionTemp.normalize();
        }
        fatDirection = direction.multiplyByFloats(width, width, width);
        path1.push(p1.add(fatDirection));
        path2.push(p1.subtract(fatDirection));
      }
      if (!directionPlane) {
        path1.push(pointVectors[pointVectors.length - 1].add(fatDirection));
        path2.push(pointVectors[pointVectors.length - 1].subtract(fatDirection));
      }
    }
    return [path1, path2];
  }
  static _GetDirectionFromPoints(p1, p2, previousDirection) {
    if (p1.x === p2.x && (!previousDirection || previousDirection?.x === 1)) {
      return GreasedLineRibbonMesh.DIRECTION_YZ;
    }
    if (p1.y === p2.y) {
      return GreasedLineRibbonMesh.DIRECTION_XZ;
    }
    if (p1.z === p2.z) {
      return GreasedLineRibbonMesh.DIRECTION_XY;
    }
    return GreasedLineRibbonMesh.DIRECTION_XZ;
  }
  clone(name375 = `${this.name}-cloned`, newParent) {
    const lineOptions = this._createLineOptions();
    const deepCopiedLineOptions = {};
    const pathOptionsCloned = [];
    DeepCopier.DeepCopy(this._pathsOptions, pathOptionsCloned, undefined, undefined, true);
    DeepCopier.DeepCopy(lineOptions, deepCopiedLineOptions, ["instance"], undefined, true);
    const cloned = new GreasedLineRibbonMesh(name375, this._scene, deepCopiedLineOptions, pathOptionsCloned);
    if (newParent) {
      cloned.parent = newParent;
    }
    cloned.material = this.material;
    return cloned;
  }
  serialize(serializationObject) {
    super.serialize(serializationObject);
    serializationObject.type = this.getClassName();
    serializationObject.lineOptions = this._createLineOptions();
    serializationObject.pathsOptions = this._pathsOptions;
  }
  static Parse(parsedMesh, scene) {
    const lineOptions = parsedMesh.lineOptions;
    const name375 = parsedMesh.name;
    const pathOptions = parsedMesh.pathOptions;
    const result = new GreasedLineRibbonMesh(name375, scene, lineOptions, pathOptions);
    return result;
  }
  _initGreasedLine() {
    super._initGreasedLine();
    this._paths = [];
    this._counters = [];
    this._slopes = [];
    this._ribbonWidths = [];
  }
  _calculateSegmentLengths(pathArray) {
    const pathArrayLength = pathArray.length;
    this._vSegmentLengths = new Array(pathArrayLength);
    this._vTotalLengths = new Array(pathArrayLength);
    let length = 0;
    for (let pi = 0;pi < pathArrayLength; pi++) {
      const points = pathArray[pi];
      this._vSegmentLengths[pi] = [0];
      length = 0;
      for (let i = 0;i < points.length - 1; i++) {
        const l = Math.abs(points[i].subtract(points[i + 1]).lengthSquared());
        length += l;
        this._vSegmentLengths[pi].push(l);
      }
      this._vTotalLengths[pi] = length;
    }
    const positionsLength = pathArray[0].length;
    this._uSegmentLengths = new Array(positionsLength).fill([]);
    this._uTotalLengths = new Array(positionsLength).fill([]);
    const uLength = new Vector3;
    for (let i = 0;i < positionsLength; i++) {
      length = 0;
      for (let pi = 1;pi < pathArrayLength; pi++) {
        pathArray[pi][i].subtractToRef(pathArray[pi - 1][i], uLength);
        const l = uLength.length();
        length += l;
        this._uSegmentLengths[i].push(l);
      }
      this._uTotalLengths[i] = length;
    }
  }
  static _CalculateSlopes(paths2) {
    const points1 = paths2[0];
    const points2 = paths2.length === 2 ? paths2[1] : paths2[paths2.length - 1];
    const slopes = [];
    const slope = new Vector3;
    for (let i = 0;i < points1.length; i++) {
      for (let pi = 0;pi < paths2.length; pi++) {
        if (pi === 0 || pi === paths2.length - 1) {
          points1[i].subtract(points2[i]).normalizeToRef(slope);
          slopes.push(slope.x, slope.y, slope.z);
          slopes.push(-slope.x, -slope.y, -slope.z);
        } else {
          slopes.push(0, 0, 0, 0, 0, 0);
        }
      }
    }
    return slopes;
  }
  _createVertexBuffers() {
    this._uvs = this._options.uvs ?? this._uvs;
    const vertexData = super._createVertexBuffers(this._options.ribbonOptions?.smoothShading);
    const countersBuffer = new Buffer2(this._engine, this._counters, this._updatable, 1);
    this.setVerticesBuffer(countersBuffer.createVertexBuffer("grl_counters", 0, 1));
    const colorPointersBuffer = new Buffer2(this._engine, this._colorPointers, this._updatable, 1);
    this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer("grl_colorPointers", 0, 1));
    const slopesBuffer = new Buffer2(this._engine, this._slopes, this._updatable, 3);
    this.setVerticesBuffer(slopesBuffer.createVertexBuffer("grl_slopes", 0, 3));
    const widthsBuffer = new Buffer2(this._engine, this._ribbonWidths, this._updatable, 1);
    this.setVerticesBuffer(widthsBuffer.createVertexBuffer("grl_widths", 0, 1));
    this._widthsBuffer = widthsBuffer;
    return vertexData;
  }
}
GreasedLineRibbonMesh.DEFAULT_WIDTH = 0.1;
GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.RightHandedForwardReadOnly, Math.PI / 2);
GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.LeftHandedForwardReadOnly, Math.PI / 2);
GreasedLineRibbonMesh._LeftReadOnlyQuaternion = Quaternion.RotationAxis(Vector3.LeftReadOnly, Math.PI / 2);
GreasedLineRibbonMesh.DIRECTION_XY = Vector3.LeftHandedForwardReadOnly;
GreasedLineRibbonMesh.DIRECTION_XZ = Vector3.UpReadOnly;
GreasedLineRibbonMesh.DIRECTION_YZ = Vector3.LeftReadOnly;

// node_modules/@babylonjs/core/Meshes/Builders/greasedLineBuilder.js
var GreasedLineMeshColorDistribution;
(function(GreasedLineMeshColorDistribution2) {
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_NONE"] = 0] = "COLOR_DISTRIBUTION_NONE";
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_REPEAT"] = 1] = "COLOR_DISTRIBUTION_REPEAT";
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_EVEN"] = 2] = "COLOR_DISTRIBUTION_EVEN";
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_START"] = 3] = "COLOR_DISTRIBUTION_START";
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_END"] = 4] = "COLOR_DISTRIBUTION_END";
  GreasedLineMeshColorDistribution2[GreasedLineMeshColorDistribution2["COLOR_DISTRIBUTION_START_END"] = 5] = "COLOR_DISTRIBUTION_START_END";
})(GreasedLineMeshColorDistribution || (GreasedLineMeshColorDistribution = {}));
var GreasedLineMeshWidthDistribution;
(function(GreasedLineMeshWidthDistribution2) {
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_NONE"] = 0] = "WIDTH_DISTRIBUTION_NONE";
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_REPEAT"] = 1] = "WIDTH_DISTRIBUTION_REPEAT";
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_EVEN"] = 2] = "WIDTH_DISTRIBUTION_EVEN";
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_START"] = 3] = "WIDTH_DISTRIBUTION_START";
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_END"] = 4] = "WIDTH_DISTRIBUTION_END";
  GreasedLineMeshWidthDistribution2[GreasedLineMeshWidthDistribution2["WIDTH_DISTRIBUTION_START_END"] = 5] = "WIDTH_DISTRIBUTION_START_END";
})(GreasedLineMeshWidthDistribution || (GreasedLineMeshWidthDistribution = {}));
// node_modules/@babylonjs/core/Meshes/index.js
init_webGLDataBuffer();

// node_modules/@babylonjs/core/Meshes/csg2.js
init_buffer();
init_logger();

// node_modules/@babylonjs/core/Misc/tools.internals.js
init_domManagement();
init_tools();
var _UniqueResolveID = 0;
function _LoadScriptModuleAsync(scriptUrl, scriptId) {
  return new Promise((resolve3, reject) => {
    let windowAsAny;
    let windowString;
    if (IsWindowObjectExist()) {
      windowAsAny = window;
      windowString = "window";
    } else if (typeof self !== "undefined") {
      windowAsAny = self;
      windowString = "self";
    } else {
      reject(new Error("Cannot load script module outside of a window or a worker"));
      return;
    }
    if (!windowAsAny._LoadScriptModuleResolve) {
      windowAsAny._LoadScriptModuleResolve = {};
    }
    windowAsAny._LoadScriptModuleResolve[_UniqueResolveID] = resolve3;
    scriptUrl += `
            ${windowString}._LoadScriptModuleResolve[${_UniqueResolveID}](returnedValue);
            ${windowString}._LoadScriptModuleResolve[${_UniqueResolveID}] = undefined;
        `;
    _UniqueResolveID++;
    Tools.LoadScript(scriptUrl, undefined, (message, exception) => {
      reject(exception || new Error(message));
    }, scriptId, true);
  });
}

// node_modules/@babylonjs/core/Meshes/csg2.js
init_math_vector();
var Manifold;
var ManifoldPromise;
var ManifoldMesh;
var FirstID;

class CSG2 {
  get numProp() {
    return this._numProp;
  }
  constructor(manifold, numProp, vertexStructure) {
    this._manifold = manifold;
    this._numProp = numProp;
    this._vertexStructure = vertexStructure;
  }
  _process(operation, csg) {
    if (this.numProp !== csg.numProp) {
      throw new Error("CSG must be used with geometries having the same number of properties");
    }
    return new CSG2(Manifold[operation](this._manifold, csg._manifold), this.numProp, this._vertexStructure);
  }
  subtract(csg) {
    return this._process("difference", csg);
  }
  intersect(csg) {
    return this._process("intersection", csg);
  }
  add(csg) {
    return this._process("union", csg);
  }
  printDebug() {
    Logger.Log("Genus:" + this._manifold.genus());
    const properties = this._manifold.getProperties();
    Logger.Log("Volume:" + properties.volume);
    Logger.Log("surface area:" + properties.surfaceArea);
  }
  toVertexData(options) {
    const localOptions = {
      rebuildNormals: false,
      ...options
    };
    const vertexData = new VertexData;
    const normalComponent = this._vertexStructure.find((c) => c.kind === VertexBuffer.NormalKind);
    const manifoldMesh = this._manifold.getMesh(localOptions.rebuildNormals && normalComponent ? [3, 4, 5] : undefined);
    vertexData.indices = manifoldMesh.triVerts.length > 65535 ? new Uint32Array(manifoldMesh.triVerts) : new Uint16Array(manifoldMesh.triVerts);
    for (let i = 0;i < manifoldMesh.triVerts.length; i += 3) {
      vertexData.indices[i] = manifoldMesh.triVerts[i + 2];
      vertexData.indices[i + 1] = manifoldMesh.triVerts[i + 1];
      vertexData.indices[i + 2] = manifoldMesh.triVerts[i];
    }
    const vertexCount = manifoldMesh.vertProperties.length / manifoldMesh.numProp;
    let offset = 0;
    for (let componentIndex = 0;componentIndex < this._vertexStructure.length; componentIndex++) {
      const component = this._vertexStructure[componentIndex];
      const data = new Float32Array(vertexCount * component.stride);
      for (let i = 0;i < vertexCount; i++) {
        for (let strideIndex = 0;strideIndex < component.stride; strideIndex++) {
          data[i * component.stride + strideIndex] = manifoldMesh.vertProperties[i * manifoldMesh.numProp + offset + strideIndex];
        }
      }
      vertexData.set(data, component.kind);
      offset += component.stride;
    }
    return vertexData;
  }
  toMesh(name375, scene, options) {
    const localOptions = {
      rebuildNormals: false,
      centerMesh: true,
      ...options
    };
    const vertexData = this.toVertexData({ rebuildNormals: localOptions.rebuildNormals });
    const normalComponent = this._vertexStructure.find((c) => c.kind === VertexBuffer.NormalKind);
    const manifoldMesh = this._manifold.getMesh(localOptions.rebuildNormals && normalComponent ? [3, 4, 5] : undefined);
    const vertexCount = manifoldMesh.vertProperties.length / manifoldMesh.numProp;
    const output = new Mesh(name375, scene);
    vertexData.applyToMesh(output);
    if (localOptions.centerMesh) {
      const extents = output.getBoundingInfo().boundingSphere.center;
      output.position.set(-extents.x, -extents.y, -extents.z);
      output.bakeCurrentTransformIntoVertices();
    }
    let id = manifoldMesh.runOriginalID[0];
    let start = manifoldMesh.runIndex[0];
    let materialIndex = 0;
    const materials = [];
    scene = output.getScene();
    for (let run = 0;run < manifoldMesh.numRun; ++run) {
      const nextID = manifoldMesh.runOriginalID[run + 1];
      if (nextID !== id) {
        const end = manifoldMesh.runIndex[run + 1];
        new SubMesh(materialIndex, 0, vertexCount, start, end - start, output);
        materials.push(scene.getMaterialByUniqueID(id - FirstID) || scene.defaultMaterial);
        id = nextID;
        start = end;
        materialIndex++;
      }
    }
    if (localOptions.materialToUse) {
      output.material = localOptions.materialToUse;
    } else {
      if (materials.length > 1) {
        const multiMaterial2 = new MultiMaterial(name375, scene);
        multiMaterial2.subMaterials = materials;
        output.material = multiMaterial2;
      } else {
        if (output.subMeshes.length > 1) {
          output._createGlobalSubMesh(true);
        }
        output.material = materials[0];
      }
    }
    return output;
  }
  dispose() {
    if (this._manifold) {
      this._manifold.delete();
      this._manifold = null;
    }
  }
  static _ProcessData(vertexCount, triVerts, structure, numProp, runIndex, runOriginalID) {
    const vertProperties = new Float32Array(vertexCount * structure.reduce((acc, cur) => acc + cur.stride, 0));
    for (let i = 0;i < vertexCount; i++) {
      let offset = 0;
      for (let idx = 0;idx < structure.length; idx++) {
        const component = structure[idx];
        for (let strideIndex = 0;strideIndex < component.stride; strideIndex++) {
          vertProperties[i * numProp + offset + strideIndex] = component.data[i * component.stride + strideIndex];
        }
        offset += component.stride;
      }
    }
    const manifoldMesh = new ManifoldMesh({ numProp, vertProperties, triVerts, runIndex, runOriginalID });
    manifoldMesh.merge();
    let returnValue;
    try {
      returnValue = new CSG2(new Manifold(manifoldMesh), numProp, structure);
    } catch (e) {
      throw new Error("Error while creating the CSG: " + e.message);
    }
    return returnValue;
  }
  static _Construct(data, worldMatrix, runIndex, runOriginalID) {
    const triVerts = new Uint32Array(data.indices.length);
    for (let i = 0;i < data.indices.length; i += 3) {
      triVerts[i] = data.indices[i + 2];
      triVerts[i + 1] = data.indices[i + 1];
      triVerts[i + 2] = data.indices[i];
    }
    const tempVector3 = new Vector3;
    let numProp = 3;
    const structure = [{ stride: 3, kind: VertexBuffer.PositionKind }];
    if (!worldMatrix) {
      structure[0].data = data.positions;
    } else {
      const positions = new Float32Array(data.positions.length);
      for (let i = 0;i < data.positions.length; i += 3) {
        Vector3.TransformCoordinatesFromFloatsToRef(data.positions[i], data.positions[i + 1], data.positions[i + 2], worldMatrix, tempVector3);
        tempVector3.toArray(positions, i);
      }
      structure[0].data = positions;
    }
    const sourceNormals = data.normals;
    if (sourceNormals) {
      numProp += 3;
      structure.push({ stride: 3, kind: VertexBuffer.NormalKind });
      if (!worldMatrix) {
        structure[1].data = sourceNormals;
      } else {
        const normals = new Float32Array(sourceNormals.length);
        for (let i = 0;i < sourceNormals.length; i += 3) {
          Vector3.TransformNormalFromFloatsToRef(sourceNormals[i], sourceNormals[i + 1], sourceNormals[i + 2], worldMatrix, tempVector3);
          tempVector3.toArray(normals, i);
        }
        structure[1].data = normals;
      }
    }
    for (const kind of [VertexBuffer.UVKind, VertexBuffer.UV2Kind, VertexBuffer.UV3Kind, VertexBuffer.UV4Kind, VertexBuffer.UV5Kind, VertexBuffer.UV6Kind]) {
      const sourceUV = data[kind === VertexBuffer.UVKind ? "uvs" : kind];
      if (sourceUV) {
        numProp += 2;
        structure.push({ stride: 2, kind, data: sourceUV });
      }
    }
    const sourceColors = data.colors;
    if (sourceColors) {
      numProp += 4;
      structure.push({ stride: 4, kind: VertexBuffer.ColorKind, data: sourceColors });
    }
    return this._ProcessData(data.positions.length / 3, triVerts, structure, numProp, runIndex, runOriginalID);
  }
  static FromVertexData(vertexData) {
    const sourceVertices = vertexData.positions;
    const sourceIndices = vertexData.indices;
    if (!sourceVertices || !sourceIndices) {
      throw new Error("The vertexData must at least have positions and indices");
    }
    return this._Construct(vertexData, null);
  }
  static FromMesh(mesh, ignoreWorldMatrix = false) {
    const sourceVertices = mesh.getVerticesData(VertexBuffer.PositionKind);
    const sourceIndices = mesh.getIndices();
    const worldMatrix = mesh.computeWorldMatrix(true);
    if (!sourceVertices || !sourceIndices) {
      throw new Error("The mesh must at least have positions and indices");
    }
    const starts = [...Array(mesh.subMeshes.length)].map((_, idx) => mesh.subMeshes[idx].indexStart);
    const sourceMaterial = mesh.material || mesh.getScene().defaultMaterial;
    const isMultiMaterial = sourceMaterial.getClassName() === "MultiMaterial";
    const originalIDs = [...Array(mesh.subMeshes.length)].map((_, idx) => {
      if (isMultiMaterial) {
        return FirstID + sourceMaterial.subMaterials[mesh.subMeshes[idx].materialIndex].uniqueId;
      }
      return FirstID + sourceMaterial.uniqueId;
    });
    const indices = Array.from(starts.keys());
    indices.sort((a, b) => starts[a] - starts[b]);
    const runIndex = new Uint32Array(indices.map((i) => starts[i]));
    const runOriginalID = new Uint32Array(indices.map((i) => originalIDs[i]));
    const data = {
      positions: sourceVertices,
      indices: sourceIndices,
      normals: mesh.getVerticesData(VertexBuffer.NormalKind),
      colors: mesh.getVerticesData(VertexBuffer.ColorKind),
      uvs: mesh.getVerticesData(VertexBuffer.UVKind),
      uvs2: mesh.getVerticesData(VertexBuffer.UV2Kind),
      uvs3: mesh.getVerticesData(VertexBuffer.UV3Kind),
      uvs4: mesh.getVerticesData(VertexBuffer.UV4Kind),
      uvs5: mesh.getVerticesData(VertexBuffer.UV5Kind),
      uvs6: mesh.getVerticesData(VertexBuffer.UV6Kind)
    };
    return this._Construct(data, ignoreWorldMatrix ? null : worldMatrix, runIndex, runOriginalID);
  }
}
function IsCSG2Ready() {
  return Manifold !== undefined;
}
async function InitializeCSG2Async(options) {
  const localOptions = {
    manifoldUrl: "https://unpkg.com/manifold-3d@3.0.1",
    ...options
  };
  if (Manifold) {
    return;
  }
  if (ManifoldPromise) {
    await ManifoldPromise;
    return;
  }
  if (localOptions.manifoldInstance) {
    Manifold = localOptions.manifoldInstance;
    ManifoldMesh = localOptions.manifoldMeshInstance;
  } else {
    ManifoldPromise = _LoadScriptModuleAsync(`
            import Module from '${localOptions.manifoldUrl}/manifold.js';
            const wasm = await Module();
            wasm.setup();
            const {Manifold, Mesh} = wasm;
            const returnedValue =  {Manifold, Mesh};
        `);
    const result = await ManifoldPromise;
    Manifold = result.Manifold;
    ManifoldMesh = result.Mesh;
  }
  FirstID = Manifold.reserveIDs(65536);
}

// node_modules/@babylonjs/core/Meshes/index.js
init_mesh_vertexData_functions();

// node_modules/@babylonjs/core/Meshes/mesh.vertexData.subdivide.js
init_math_vector();
var _positionShift = Math.pow(10, 4);
function round(x) {
  return x + (x > 0 ? 0.5 : -0.5) << 0;
}
function hashFromNumber(num, shift = _positionShift) {
  let roundedNumber = round(num * shift);
  if (roundedNumber === 0) {
    roundedNumber = 0;
  }
  return `${roundedNumber}`;
}
function hashFromVector(v, shift = _positionShift) {
  return `${hashFromNumber(v.x, shift)},${hashFromNumber(v.y, shift)},${hashFromNumber(v.z, shift)}`;
}
function gatherAttributes(vertexData) {
  const desired = ["positions", "normals", "uvs"];
  const available = Object.keys(vertexData).filter((k) => Array.isArray(vertexData[k]));
  return Array.from(new Set([...desired, ...available]));
}
function setTriangle(arr, index, itemSize, vec0, vec1, vec2) {
  for (let i = 0;i < itemSize; i++) {
    arr[index + i] = vec0[i];
    arr[index + itemSize + i] = vec1[i];
    arr[index + 2 * itemSize + i] = vec2[i];
  }
}
function toNonIndexed(vertexData) {
  if (!vertexData.indices || vertexData.indices.length === 0) {
    return vertexData;
  }
  const newPositions = [];
  const newNormals = [];
  const newUVs = [];
  const indices = vertexData.indices;
  const pos = vertexData.positions;
  const norm = vertexData.normals;
  const uv = vertexData.uvs;
  for (let i = 0;i < indices.length; i++) {
    const idx = indices[i];
    newPositions.push(pos[3 * idx], pos[3 * idx + 1], pos[3 * idx + 2]);
    if (norm) {
      newNormals.push(norm[3 * idx], norm[3 * idx + 1], norm[3 * idx + 2]);
    }
    if (uv) {
      newUVs.push(uv[2 * idx], uv[2 * idx + 1]);
    }
  }
  const newVertexData = new VertexData;
  newVertexData.positions = newPositions;
  if (newNormals.length) {
    newVertexData.normals = newNormals;
  }
  if (newUVs.length) {
    newVertexData.uvs = newUVs;
  }
  return newVertexData;
}
function readVector(destination, attribute, index, itemSize) {
  if (itemSize === 3) {
    destination.fromArray(attribute, index * 3);
    return;
  }
  destination.set(attribute[index * 2], attribute[index * 2 + 1], 0);
}
function processFlatAttribute(source, vertexCount, output) {
  const v0 = new Vector3;
  const v1 = new Vector3;
  const v2 = new Vector3;
  const m01 = new Vector3;
  const m12 = new Vector3;
  const m20 = new Vector3;
  for (let i = 0;i < vertexCount; i += 3) {
    const j = i * 3;
    v0.set(source[j], source[j + 1], source[j + 2]);
    v1.set(source[j + 3], source[j + 4], source[j + 5]);
    v2.set(source[j + 6], source[j + 7], source[j + 8]);
    v0.addToRef(v1, m01);
    m01.scaleInPlace(0.5);
    v1.addToRef(v2, m12);
    m12.scaleInPlace(0.5);
    v2.addToRef(v0, m20);
    m20.scaleInPlace(0.5);
    output.push(v0.x, v0.y, v0.z, m01.x, m01.y, m01.z, m20.x, m20.y, m20.z);
    output.push(v1.x, v1.y, v1.z, m12.x, m12.y, m12.z, m01.x, m01.y, m01.z);
    output.push(v2.x, v2.y, v2.z, m20.x, m20.y, m20.z, m12.x, m12.y, m12.z);
    output.push(m01.x, m01.y, m01.z, m12.x, m12.y, m12.z, m20.x, m20.y, m20.z);
  }
}
function flat(vertexData) {
  const data = toNonIndexed(vertexData);
  const positions = data.positions;
  const normals = data.normals;
  const uvs = data.uvs;
  const vertexCount = positions.length / 3;
  const newPositions = [];
  const newNormals = [];
  const newUVs = [];
  processFlatAttribute(positions, vertexCount, newPositions);
  if (normals && normals.length) {
    processFlatAttribute(normals, vertexCount, newNormals);
  }
  if (uvs && uvs.length) {
    for (let i = 0;i < vertexCount; i += 3) {
      const j = i * 2;
      const uv0 = [uvs[j], uvs[j + 1]];
      const uv1 = [uvs[j + 2], uvs[j + 3]];
      const uv2 = [uvs[j + 4], uvs[j + 5]];
      const uv01 = [(uv0[0] + uv1[0]) / 2, (uv0[1] + uv1[1]) / 2];
      const uv12 = [(uv1[0] + uv2[0]) / 2, (uv1[1] + uv2[1]) / 2];
      const uv20 = [(uv2[0] + uv0[0]) / 2, (uv2[1] + uv0[1]) / 2];
      newUVs.push(...uv0, ...uv01, ...uv20);
      newUVs.push(...uv1, ...uv12, ...uv01);
      newUVs.push(...uv2, ...uv20, ...uv12);
      newUVs.push(...uv01, ...uv12, ...uv20);
    }
  }
  const newVertexCount = newPositions.length / 3;
  const newIndices = [];
  for (let i = 0;i < newVertexCount; i++) {
    newIndices.push(i);
  }
  const newVertexData = new VertexData;
  newVertexData.positions = newPositions;
  if (newNormals.length) {
    newVertexData.normals = newNormals;
  }
  if (newUVs.length) {
    newVertexData.uvs = newUVs;
  }
  newVertexData.indices = newIndices;
  return newVertexData;
}
function smooth(vertexData, options) {
  const sourceData = toNonIndexed(vertexData);
  const flatData = flat(sourceData);
  const attributeList = gatherAttributes(sourceData);
  const origPositions = sourceData.positions;
  const flatPositions = flatData.positions;
  const vertexCount = origPositions.length / 3;
  const hashToIndex = {};
  const existingNeighbors = {};
  const flatOpposites = {};
  const existingEdges = {};
  function addNeighbor(posHash, neighborHash, index) {
    if (!existingNeighbors[posHash]) {
      existingNeighbors[posHash] = {};
    }
    if (!existingNeighbors[posHash][neighborHash]) {
      existingNeighbors[posHash][neighborHash] = [];
    }
    existingNeighbors[posHash][neighborHash].push(index);
  }
  function addOpposite(posHash, index) {
    if (!flatOpposites[posHash]) {
      flatOpposites[posHash] = [];
    }
    flatOpposites[posHash].push(index);
  }
  function addEdgePoint(posHash, edgeHash) {
    if (!existingEdges[posHash]) {
      existingEdges[posHash] = new Set;
    }
    existingEdges[posHash].add(edgeHash);
  }
  const temp = new Vector3;
  const v0 = new Vector3;
  const v1 = new Vector3;
  const v2 = new Vector3;
  const m01 = new Vector3;
  const m12 = new Vector3;
  const m20 = new Vector3;
  for (let i = 0;i < vertexCount; i += 3) {
    readVector(v0, origPositions, i, 3);
    readVector(v1, origPositions, i + 1, 3);
    readVector(v2, origPositions, i + 2, 3);
    const h0 = hashFromVector(v0);
    const h1 = hashFromVector(v1);
    const h2 = hashFromVector(v2);
    addNeighbor(h0, h1, i + 1);
    addNeighbor(h0, h2, i + 2);
    addNeighbor(h1, h0, i);
    addNeighbor(h1, h2, i + 2);
    addNeighbor(h2, h0, i);
    addNeighbor(h2, h1, i + 1);
    v0.addToRef(v1, m01);
    m01.scaleInPlace(0.5);
    v1.addToRef(v2, m12);
    m12.scaleInPlace(0.5);
    v2.addToRef(v0, m20);
    m20.scaleInPlace(0.5);
    addOpposite(hashFromVector(m01), i + 2);
    addOpposite(hashFromVector(m12), i);
    addOpposite(hashFromVector(m20), i + 1);
    addEdgePoint(h0, hashFromVector(m01));
    addEdgePoint(h0, hashFromVector(m20));
    addEdgePoint(h1, hashFromVector(m01));
    addEdgePoint(h1, hashFromVector(m12));
    addEdgePoint(h2, hashFromVector(m12));
    addEdgePoint(h2, hashFromVector(m20));
  }
  for (let i = 0;i < flatPositions.length / 3; i++) {
    readVector(temp, flatPositions, i, 3);
    const h = hashFromVector(temp);
    if (!hashToIndex[h]) {
      hashToIndex[h] = [];
    }
    hashToIndex[h].push(i);
  }
  const _vertex = [new Vector3, new Vector3, new Vector3];
  const _position = [new Vector3, new Vector3, new Vector3];
  const _average = new Vector3;
  const _temp = new Vector3;
  function subdivideAttribute(attributeName, existingAttribute, flattenedAttribute) {
    const itemSize = attributeName === "uvs" ? 2 : 3;
    const flatVertexCount = flatPositions.length / 3;
    const floatArray = new Array(flatVertexCount * itemSize);
    let index = 0;
    for (let i = 0;i < flatVertexCount; i += 3) {
      for (let v = 0;v < 3; v++) {
        if (attributeName === "uvs" && !options.uvSmooth) {
          readVector(_vertex[v], flattenedAttribute, i + v, 2);
        } else if (attributeName === "normals") {
          readVector(_position[v], flatPositions, i + v, 3);
          const positionHash = hashFromVector(_position[v]);
          const positionsArr = hashToIndex[positionHash] || [];
          const k = positionsArr.length;
          const beta = 0.75 / k;
          const startWeight = 1 - beta * k;
          readVector(_vertex[v], flattenedAttribute, i + v, 3);
          _vertex[v].scaleInPlace(startWeight);
          positionsArr.forEach((positionIndex) => {
            readVector(_average, flattenedAttribute, positionIndex, 3);
            _average.scaleInPlace(beta);
            _vertex[v].addInPlace(_average);
          });
        } else {
          readVector(_vertex[v], flattenedAttribute, i + v, itemSize);
          readVector(_position[v], flatPositions, i + v, 3);
          const positionHash = hashFromVector(_position[v]);
          const neighbors = existingNeighbors[positionHash];
          const opposites = flatOpposites[positionHash];
          if (neighbors) {
            if (options.preserveEdges) {
              const edgeSet = existingEdges[positionHash];
              let hasPair = true;
              edgeSet.forEach((edgeHash) => {
                if (flatOpposites[edgeHash] && flatOpposites[edgeHash].length % 2 !== 0) {
                  hasPair = false;
                }
              });
              if (!hasPair) {
                continue;
              }
            }
            const neighborKeys = Object.keys(neighbors);
            const k = neighborKeys.length;
            const beta = 1 / k * (5 / 8 - Math.pow(3 / 8 + 1 / 4 * Math.cos(2 * Math.PI / k), 2));
            const heavy = 1 / k / k;
            const weight = Scalar.Lerp(heavy, beta, options.weight);
            const startWeight = 1 - weight * k;
            _vertex[v].scaleInPlace(startWeight);
            for (const neighborHash in neighbors) {
              const neighborIndices = neighbors[neighborHash];
              _average.set(0, 0, 0);
              neighborIndices.forEach((neighborIndex) => {
                readVector(_temp, existingAttribute, neighborIndex, itemSize);
                _average.addInPlace(_temp);
              });
              _average.scaleInPlace(1 / neighborIndices.length);
              _average.scaleInPlace(weight);
              _vertex[v].addInPlace(_average);
            }
          } else if (opposites && opposites.length === 2) {
            const k = opposites.length;
            const beta = 0.125;
            const startWeight = 1 - beta * k;
            _vertex[v].scaleInPlace(startWeight);
            opposites.forEach((oppositeIndex) => {
              readVector(_average, existingAttribute, oppositeIndex, itemSize);
              _average.scaleInPlace(beta);
              _vertex[v].addInPlace(_average);
            });
          }
        }
      }
      setTriangle(floatArray, index, itemSize, _vertex[0].asArray(), _vertex[1].asArray(), _vertex[2].asArray());
      index += itemSize * 3;
    }
    return floatArray;
  }
  const smoothData = new VertexData;
  attributeList.forEach((attributeName) => {
    if (attributeName === "indices") {
      return;
    }
    const existingAttribute = sourceData[attributeName];
    const flattenedAttribute = flatData[attributeName];
    if (!existingAttribute || !flattenedAttribute) {
      return;
    }
    const newArray = subdivideAttribute(attributeName, existingAttribute, flattenedAttribute);
    smoothData[attributeName] = newArray;
  });
  const newPositions = smoothData.positions;
  const newIndices = [];
  for (let i = 0;i < newPositions.length / 3; i++) {
    newIndices.push(i);
  }
  smoothData.indices = newIndices;
  return smoothData;
}
function Subdivide(vertexData, level, options) {
  options = {
    flatOnly: false,
    uvSmooth: false,
    preserveEdges: false,
    weight: 1,
    ...options
  };
  if (!vertexData.positions || vertexData.positions.length === 0 || level <= 0) {
    return vertexData;
  }
  let modified = vertexData.clone();
  for (let i = 0;i < level; i++) {
    if (options.flatOnly) {
      modified = flat(modified);
    } else {
      modified = smooth(modified, options);
    }
  }
  return modified;
}
// node_modules/@babylonjs/core/Meshes/thinInstanceMesh.js
init_buffer();
init_math_vector();
init_logger();
Mesh.prototype.thinInstanceAdd = function(matrix, refresh = true) {
  if (!this.getScene().getEngine().getCaps().instancedArrays) {
    Logger.Error("Thin Instances are not supported on this device as Instanced Array extension not supported");
    return -1;
  }
  this._thinInstanceUpdateBufferSize("matrix", Array.isArray(matrix) ? matrix.length : 1);
  const index = this._thinInstanceDataStorage.instancesCount;
  if (Array.isArray(matrix)) {
    for (let i = 0;i < matrix.length; ++i) {
      this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix[i], i === matrix.length - 1 && refresh);
    }
  } else {
    this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix, refresh);
  }
  return index;
};
Mesh.prototype.thinInstanceAddSelf = function(refresh = true) {
  return this.thinInstanceAdd(Matrix.IdentityReadOnly, refresh);
};
Mesh.prototype.thinInstanceRegisterAttribute = function(kind, stride) {
  if (kind === VertexBuffer.ColorKind) {
    kind = VertexBuffer.ColorInstanceKind;
  }
  this.removeVerticesData(kind);
  this._thinInstanceInitializeUserStorage();
  this._userThinInstanceBuffersStorage.strides[kind] = stride;
  this._userThinInstanceBuffersStorage.sizes[kind] = stride * Math.max(32, this._thinInstanceDataStorage.instancesCount);
  this._userThinInstanceBuffersStorage.data[kind] = new Float32Array(this._userThinInstanceBuffersStorage.sizes[kind]);
  this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, true, false, stride, true);
  this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);
};
Mesh.prototype.thinInstanceSetMatrixAt = function(index, matrix, refresh = true) {
  if (!this._thinInstanceDataStorage.matrixData || index >= this._thinInstanceDataStorage.instancesCount) {
    return false;
  }
  const matrixData = this._thinInstanceDataStorage.matrixData;
  matrix.copyToArray(matrixData, index * 16);
  if (this._thinInstanceDataStorage.worldMatrices) {
    this._thinInstanceDataStorage.worldMatrices[index] = matrix;
  }
  if (refresh) {
    this.thinInstanceBufferUpdated("matrix");
    if (!this.doNotSyncBoundingInfo) {
      this.thinInstanceRefreshBoundingInfo(false);
    }
  }
  return true;
};
Mesh.prototype.thinInstanceSetAttributeAt = function(kind, index, value, refresh = true) {
  if (kind === VertexBuffer.ColorKind) {
    kind = VertexBuffer.ColorInstanceKind;
  }
  if (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.data[kind] || index >= this._thinInstanceDataStorage.instancesCount) {
    return false;
  }
  this._thinInstanceUpdateBufferSize(kind, 0);
  this._userThinInstanceBuffersStorage.data[kind].set(value, index * this._userThinInstanceBuffersStorage.strides[kind]);
  if (refresh) {
    this.thinInstanceBufferUpdated(kind);
  }
  return true;
};
Object.defineProperty(Mesh.prototype, "thinInstanceCount", {
  get: function() {
    return this._thinInstanceDataStorage.instancesCount;
  },
  set: function(value) {
    const matrixData = this._thinInstanceDataStorage.matrixData ?? this.source?._thinInstanceDataStorage.matrixData;
    const numMaxInstances = matrixData ? matrixData.length / 16 : 0;
    if (value <= numMaxInstances) {
      this._thinInstanceDataStorage.instancesCount = value;
    }
  },
  enumerable: true,
  configurable: true
});
Mesh.prototype._thinInstanceCreateMatrixBuffer = function(kind, buffer2, staticBuffer = true) {
  const matrixBuffer = new Buffer2(this.getEngine(), buffer2, !staticBuffer, 16, false, true);
  for (let i = 0;i < 4; i++) {
    this.setVerticesBuffer(matrixBuffer.createVertexBuffer(kind + i, i * 4, 4));
  }
  return matrixBuffer;
};
Mesh.prototype.thinInstanceSetBuffer = function(kind, buffer2, stride = 0, staticBuffer = true) {
  stride = stride || 16;
  if (kind === "matrix") {
    this._thinInstanceDataStorage.matrixBuffer?.dispose();
    this._thinInstanceDataStorage.matrixBuffer = null;
    this._thinInstanceDataStorage.matrixBufferSize = buffer2 ? buffer2.length : 32 * stride;
    this._thinInstanceDataStorage.matrixData = buffer2;
    this._thinInstanceDataStorage.worldMatrices = null;
    if (buffer2 !== null) {
      this._thinInstanceDataStorage.instancesCount = buffer2.length / stride;
      this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", buffer2, staticBuffer);
      if (!this.doNotSyncBoundingInfo) {
        this.thinInstanceRefreshBoundingInfo(false);
      }
    } else {
      this._thinInstanceDataStorage.instancesCount = 0;
      if (!this.doNotSyncBoundingInfo) {
        this.refreshBoundingInfo();
      }
    }
  } else if (kind === "previousMatrix") {
    this._thinInstanceDataStorage.previousMatrixBuffer?.dispose();
    this._thinInstanceDataStorage.previousMatrixBuffer = null;
    this._thinInstanceDataStorage.previousMatrixData = buffer2;
    if (buffer2 !== null) {
      this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", buffer2, staticBuffer);
    }
  } else {
    if (kind === VertexBuffer.ColorKind) {
      kind = VertexBuffer.ColorInstanceKind;
    }
    if (buffer2 === null) {
      if (this._userThinInstanceBuffersStorage?.data[kind]) {
        this.removeVerticesData(kind);
        delete this._userThinInstanceBuffersStorage.data[kind];
        delete this._userThinInstanceBuffersStorage.strides[kind];
        delete this._userThinInstanceBuffersStorage.sizes[kind];
        delete this._userThinInstanceBuffersStorage.vertexBuffers[kind];
      }
    } else {
      this._thinInstanceInitializeUserStorage();
      this._userThinInstanceBuffersStorage.data[kind] = buffer2;
      this._userThinInstanceBuffersStorage.strides[kind] = stride;
      this._userThinInstanceBuffersStorage.sizes[kind] = buffer2.length;
      this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), buffer2, kind, !staticBuffer, false, stride, true);
      this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);
    }
  }
};
Mesh.prototype.thinInstanceBufferUpdated = function(kind) {
  if (kind === "matrix") {
    if (this.thinInstanceAllowAutomaticStaticBufferRecreation && this._thinInstanceDataStorage.matrixBuffer && !this._thinInstanceDataStorage.matrixBuffer.isUpdatable()) {
      this._thinInstanceRecreateBuffer(kind);
    }
    this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, this._thinInstanceDataStorage.instancesCount);
  } else if (kind === "previousMatrix") {
    if (this.thinInstanceAllowAutomaticStaticBufferRecreation && this._thinInstanceDataStorage.previousMatrixBuffer && !this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()) {
      this._thinInstanceRecreateBuffer(kind);
    }
    this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData, 0, this._thinInstanceDataStorage.instancesCount);
  } else {
    if (kind === VertexBuffer.ColorKind) {
      kind = VertexBuffer.ColorInstanceKind;
    }
    if (this._userThinInstanceBuffersStorage?.vertexBuffers[kind]) {
      if (this.thinInstanceAllowAutomaticStaticBufferRecreation && !this._userThinInstanceBuffersStorage.vertexBuffers[kind].isUpdatable()) {
        this._thinInstanceRecreateBuffer(kind);
      }
      this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(this._userThinInstanceBuffersStorage.data[kind], 0);
    }
  }
};
Mesh.prototype.thinInstancePartialBufferUpdate = function(kind, data, offset) {
  if (kind === "matrix") {
    if (this._thinInstanceDataStorage.matrixBuffer) {
      this._thinInstanceDataStorage.matrixBuffer.updateDirectly(data, offset);
    }
  } else {
    if (kind === VertexBuffer.ColorKind) {
      kind = VertexBuffer.ColorInstanceKind;
    }
    if (this._userThinInstanceBuffersStorage?.vertexBuffers[kind]) {
      this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(data, offset);
    }
  }
};
Mesh.prototype.thinInstanceGetWorldMatrices = function() {
  if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {
    return [];
  }
  const matrixData = this._thinInstanceDataStorage.matrixData;
  if (!this._thinInstanceDataStorage.worldMatrices) {
    this._thinInstanceDataStorage.worldMatrices = [];
    for (let i = 0;i < this._thinInstanceDataStorage.instancesCount; ++i) {
      this._thinInstanceDataStorage.worldMatrices[i] = Matrix.FromArray(matrixData, i * 16);
    }
  }
  return this._thinInstanceDataStorage.worldMatrices;
};
Mesh.prototype.thinInstanceRefreshBoundingInfo = function(forceRefreshParentInfo = false, applySkeleton2 = false, applyMorph2 = false) {
  if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {
    return;
  }
  const vectors = this._thinInstanceDataStorage.boundingVectors;
  if (forceRefreshParentInfo || !this.rawBoundingInfo) {
    vectors.length = 0;
    this.refreshBoundingInfo(applySkeleton2, applyMorph2);
    const boundingInfo3 = this.getBoundingInfo();
    this.rawBoundingInfo = new BoundingInfo(boundingInfo3.minimum, boundingInfo3.maximum);
  }
  const boundingInfo2 = this.getBoundingInfo();
  const matrixData = this._thinInstanceDataStorage.matrixData;
  if (vectors.length === 0) {
    for (let v = 0;v < boundingInfo2.boundingBox.vectors.length; ++v) {
      vectors.push(boundingInfo2.boundingBox.vectors[v].clone());
    }
  }
  TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY);
  TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY);
  for (let i = 0;i < this._thinInstanceDataStorage.instancesCount; ++i) {
    Matrix.FromArrayToRef(matrixData, i * 16, TmpVectors.Matrix[0]);
    for (let v = 0;v < vectors.length; ++v) {
      Vector3.TransformCoordinatesToRef(vectors[v], TmpVectors.Matrix[0], TmpVectors.Vector3[2]);
      TmpVectors.Vector3[0].minimizeInPlace(TmpVectors.Vector3[2]);
      TmpVectors.Vector3[1].maximizeInPlace(TmpVectors.Vector3[2]);
    }
  }
  boundingInfo2.reConstruct(TmpVectors.Vector3[0], TmpVectors.Vector3[1]);
  this._updateBoundingInfo();
};
Mesh.prototype._thinInstanceRecreateBuffer = function(kind, staticBuffer = true) {
  if (kind === "matrix") {
    this._thinInstanceDataStorage.matrixBuffer?.dispose();
    this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", this._thinInstanceDataStorage.matrixData, staticBuffer);
  } else if (kind === "previousMatrix") {
    if (this._scene.needsPreviousWorldMatrices) {
      this._thinInstanceDataStorage.previousMatrixBuffer?.dispose();
      this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.previousMatrixData ?? this._thinInstanceDataStorage.matrixData, staticBuffer);
    }
  } else {
    if (kind === VertexBuffer.ColorKind) {
      kind = VertexBuffer.ColorInstanceKind;
    }
    this._userThinInstanceBuffersStorage.vertexBuffers[kind]?.dispose();
    this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, !staticBuffer, false, this._userThinInstanceBuffersStorage.strides[kind], true);
    this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);
  }
};
Mesh.prototype._thinInstanceUpdateBufferSize = function(kind, numInstances = 1) {
  if (kind === VertexBuffer.ColorKind) {
    kind = VertexBuffer.ColorInstanceKind;
  }
  const kindIsMatrix = kind === "matrix";
  if (!kindIsMatrix && (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.strides[kind])) {
    return;
  }
  const stride = kindIsMatrix ? 16 : this._userThinInstanceBuffersStorage.strides[kind];
  const currentSize = kindIsMatrix ? this._thinInstanceDataStorage.matrixBufferSize : this._userThinInstanceBuffersStorage.sizes[kind];
  let data = kindIsMatrix ? this._thinInstanceDataStorage.matrixData : this._userThinInstanceBuffersStorage.data[kind];
  const bufferSize = (this._thinInstanceDataStorage.instancesCount + numInstances) * stride;
  let newSize = currentSize;
  while (newSize < bufferSize) {
    newSize *= 2;
  }
  if (!data || currentSize != newSize) {
    if (!data) {
      data = new Float32Array(newSize);
    } else {
      const newData = new Float32Array(newSize);
      newData.set(data, 0);
      data = newData;
    }
    if (kindIsMatrix) {
      this._thinInstanceDataStorage.matrixBuffer?.dispose();
      this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", data, false);
      this._thinInstanceDataStorage.matrixData = data;
      this._thinInstanceDataStorage.matrixBufferSize = newSize;
      if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData) {
        this._thinInstanceDataStorage.previousMatrixBuffer?.dispose();
        this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", data, false);
      }
    } else {
      this._userThinInstanceBuffersStorage.vertexBuffers[kind]?.dispose();
      this._userThinInstanceBuffersStorage.data[kind] = data;
      this._userThinInstanceBuffersStorage.sizes[kind] = newSize;
      this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), data, kind, true, false, stride, true);
      this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);
    }
  }
};
Mesh.prototype._thinInstanceInitializeUserStorage = function() {
  if (!this._userThinInstanceBuffersStorage) {
    this._userThinInstanceBuffersStorage = {
      data: {},
      sizes: {},
      vertexBuffers: {},
      strides: {}
    };
  }
};
Mesh.prototype._disposeThinInstanceSpecificData = function() {
  if (this._thinInstanceDataStorage?.matrixBuffer) {
    this._thinInstanceDataStorage.matrixBuffer.dispose();
    this._thinInstanceDataStorage.matrixBuffer = null;
  }
};
// node_modules/@babylonjs/core/Meshes/Node/nodeGeometry.js
init_tslib_es6();
init_observable();

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlock.js
init_tslib_es6();
init_typeStore();
init_decorators();
init_uniqueIdGenerator();

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlockConnectionPoint.js
init_observable();

// node_modules/@babylonjs/core/Meshes/Node/Enums/nodeGeometryConnectionPointTypes.js
var NodeGeometryBlockConnectionPointTypes;
(function(NodeGeometryBlockConnectionPointTypes2) {
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Int"] = 1] = "Int";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Float"] = 2] = "Float";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Vector2"] = 4] = "Vector2";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Vector3"] = 8] = "Vector3";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Vector4"] = 16] = "Vector4";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Matrix"] = 32] = "Matrix";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Geometry"] = 64] = "Geometry";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Texture"] = 128] = "Texture";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["AutoDetect"] = 1024] = "AutoDetect";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["BasedOnInput"] = 2048] = "BasedOnInput";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["Undefined"] = 4096] = "Undefined";
  NodeGeometryBlockConnectionPointTypes2[NodeGeometryBlockConnectionPointTypes2["All"] = 4095] = "All";
})(NodeGeometryBlockConnectionPointTypes || (NodeGeometryBlockConnectionPointTypes = {}));

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlockConnectionPoint.js
var NodeGeometryConnectionPointCompatibilityStates;
(function(NodeGeometryConnectionPointCompatibilityStates2) {
  NodeGeometryConnectionPointCompatibilityStates2[NodeGeometryConnectionPointCompatibilityStates2["Compatible"] = 0] = "Compatible";
  NodeGeometryConnectionPointCompatibilityStates2[NodeGeometryConnectionPointCompatibilityStates2["TypeIncompatible"] = 1] = "TypeIncompatible";
  NodeGeometryConnectionPointCompatibilityStates2[NodeGeometryConnectionPointCompatibilityStates2["HierarchyIssue"] = 2] = "HierarchyIssue";
})(NodeGeometryConnectionPointCompatibilityStates || (NodeGeometryConnectionPointCompatibilityStates = {}));
var NodeGeometryConnectionPointDirection;
(function(NodeGeometryConnectionPointDirection2) {
  NodeGeometryConnectionPointDirection2[NodeGeometryConnectionPointDirection2["Input"] = 0] = "Input";
  NodeGeometryConnectionPointDirection2[NodeGeometryConnectionPointDirection2["Output"] = 1] = "Output";
})(NodeGeometryConnectionPointDirection || (NodeGeometryConnectionPointDirection = {}));

class NodeGeometryConnectionPoint {
  get direction() {
    return this._direction;
  }
  get type() {
    if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) {
      if (this._ownerBlock.isInput) {
        return this._ownerBlock.type;
      }
      if (this._connectedPoint) {
        return this._connectedPoint.type;
      }
      if (this._linkedConnectionSource) {
        if (this._linkedConnectionSource.isConnected) {
          return this._linkedConnectionSource.type;
        }
        if (this._linkedConnectionSource._defaultConnectionPointType) {
          return this._linkedConnectionSource._defaultConnectionPointType;
        }
      }
      if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    if (this._type === NodeGeometryBlockConnectionPointTypes.BasedOnInput) {
      if (this._typeConnectionSource) {
        if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) {
          return this._defaultConnectionPointType;
        }
        return this._typeConnectionSource.type;
      } else if (this._defaultConnectionPointType) {
        return this._defaultConnectionPointType;
      }
    }
    return this._type;
  }
  set type(value) {
    this._type = value;
  }
  get isConnected() {
    return this.connectedPoint !== null || this.hasEndpoints;
  }
  get connectedPoint() {
    return this._connectedPoint;
  }
  get ownerBlock() {
    return this._ownerBlock;
  }
  get sourceBlock() {
    if (!this._connectedPoint) {
      return null;
    }
    return this._connectedPoint.ownerBlock;
  }
  get connectedBlocks() {
    if (this._endpoints.length === 0) {
      return [];
    }
    return this._endpoints.map((e) => e.ownerBlock);
  }
  get endpoints() {
    return this._endpoints;
  }
  get hasEndpoints() {
    return this._endpoints && this._endpoints.length > 0;
  }
  get innerType() {
    if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) {
      return this.type;
    }
    return this._type;
  }
  _resetCounters() {
    this._callCount = 0;
    this._executionCount = 0;
  }
  get callCount() {
    return this._callCount;
  }
  get executionCount() {
    return this._executionCount;
  }
  getConnectedValue(state) {
    if (this.isConnected) {
      if (this._connectedPoint?._storedFunction) {
        this._connectedPoint._callCount++;
        this._connectedPoint._executionCount++;
        return this._connectedPoint._storedFunction(state);
      }
      this._connectedPoint._callCount++;
      this._connectedPoint._executionCount = 1;
      return this._connectedPoint._storedValue;
    }
    this._callCount++;
    this._executionCount = 1;
    return this.value;
  }
  constructor(name375, ownerBlock, direction) {
    this._connectedPoint = null;
    this._storedValue = null;
    this._storedFunction = null;
    this._acceptedConnectionPointType = null;
    this._endpoints = new Array;
    this._type = NodeGeometryBlockConnectionPointTypes.Geometry;
    this._linkedConnectionSource = null;
    this._typeConnectionSource = null;
    this._defaultConnectionPointType = null;
    this._isMainLinkSource = false;
    this.acceptedConnectionPointTypes = [];
    this.excludedConnectionPointTypes = [];
    this.onConnectionObservable = new Observable;
    this.onDisconnectionObservable = new Observable;
    this.isExposedOnFrame = false;
    this.exposedPortPosition = -1;
    this.defaultValue = null;
    this.value = null;
    this.valueMin = null;
    this.valueMax = null;
    this._callCount = 0;
    this._executionCount = 0;
    this._ownerBlock = ownerBlock;
    this.name = name375;
    this._direction = direction;
  }
  getClassName() {
    return "NodeGeometryConnectionPoint";
  }
  canConnectTo(connectionPoint) {
    return this.checkCompatibilityState(connectionPoint) === 0;
  }
  checkCompatibilityState(connectionPoint) {
    const ownerBlock = this._ownerBlock;
    const otherBlock = connectionPoint.ownerBlock;
    if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeGeometryBlockConnectionPointTypes.AutoDetect) {
      if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) {
        return 0;
      } else {
        return 1;
      }
    }
    if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) {
      return 1;
    }
    let targetBlock = otherBlock;
    let sourceBlock = ownerBlock;
    if (this.direction === 0) {
      targetBlock = ownerBlock;
      sourceBlock = otherBlock;
    }
    if (targetBlock.isAnAncestorOf(sourceBlock)) {
      return 2;
    }
    return 0;
  }
  connectTo(connectionPoint, ignoreConstraints = false) {
    if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {
      throw "Cannot connect these two connectors.";
    }
    this._endpoints.push(connectionPoint);
    connectionPoint._connectedPoint = this;
    this.onConnectionObservable.notifyObservers(connectionPoint);
    connectionPoint.onConnectionObservable.notifyObservers(this);
    return this;
  }
  disconnectFrom(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index === -1) {
      return this;
    }
    this._endpoints.splice(index, 1);
    endpoint._connectedPoint = null;
    this.onDisconnectionObservable.notifyObservers(endpoint);
    endpoint.onDisconnectionObservable.notifyObservers(this);
    return this;
  }
  addExcludedConnectionPointFromAllowedTypes(mask) {
    let bitmask = 1;
    while (bitmask < NodeGeometryBlockConnectionPointTypes.All) {
      if (!(mask & bitmask)) {
        this.excludedConnectionPointTypes.push(bitmask);
      }
      bitmask = bitmask << 1;
    }
  }
  serialize(isInput = true) {
    const serializationObject = {};
    serializationObject.name = this.name;
    serializationObject.displayName = this.displayName;
    if (this.value !== undefined && this.value !== null) {
      if (this.value.asArray) {
        serializationObject.valueType = "BABYLON." + this.value.getClassName();
        serializationObject.value = this.value.asArray();
      } else {
        serializationObject.valueType = "number";
        serializationObject.value = this.value;
      }
    }
    if (isInput && this.connectedPoint) {
      serializationObject.inputName = this.name;
      serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;
      serializationObject.targetConnectionName = this.connectedPoint.name;
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    if (this.isExposedOnFrame || this.exposedPortPosition >= 0) {
      serializationObject.isExposedOnFrame = true;
      serializationObject.exposedPortPosition = this.exposedPortPosition;
    }
    return serializationObject;
  }
  dispose() {
    this.onConnectionObservable.clear();
    this.onDisconnectionObservable.clear();
  }
}

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlock.js
init_observable();
init_precisionDate();
init_logger();

class NodeGeometryBlock {
  get buildExecutionTime() {
    return this._buildExecutionTime;
  }
  get inputs() {
    return this._inputs;
  }
  get outputs() {
    return this._outputs;
  }
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
  get isInput() {
    return this._isInput;
  }
  get isTeleportOut() {
    return this._isTeleportOut;
  }
  get isTeleportIn() {
    return this._isTeleportIn;
  }
  get isDebug() {
    return this._isDebug;
  }
  get isUnique() {
    return this._isUnique;
  }
  getClassName() {
    return "NodeGeometryBlock";
  }
  _inputRename(name375) {
    return name375;
  }
  _outputRename(name375) {
    return name375;
  }
  isAnAncestorOf(block) {
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        if (endpoint.ownerBlock === block) {
          return true;
        }
        if (endpoint.ownerBlock.isAnAncestorOf(block)) {
          return true;
        }
      }
    }
    return false;
  }
  isAnAncestorOfType(type) {
    if (this.getClassName() === type) {
      return true;
    }
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        if (endpoint.ownerBlock.isAnAncestorOfType(type)) {
          return true;
        }
      }
    }
    return false;
  }
  getDescendantOfPredicate(predicate) {
    if (predicate(this)) {
      return this;
    }
    for (const output of this._outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const descendant = endpoint.ownerBlock.getDescendantOfPredicate(predicate);
        if (descendant) {
          return descendant;
        }
      }
    }
    return null;
  }
  get _isReadyState() {
    return null;
  }
  constructor(name375) {
    this._name = "";
    this._isInput = false;
    this._isTeleportOut = false;
    this._isTeleportIn = false;
    this._isDebug = false;
    this._isUnique = false;
    this._buildExecutionTime = 0;
    this.onBuildObservable = new Observable;
    this._inputs = new Array;
    this._outputs = new Array;
    this._codeVariableName = "";
    this.visibleOnFrame = false;
    this._name = name375;
    this.uniqueId = UniqueIdGenerator.UniqueId;
  }
  registerInput(name375, type, isOptional = false, value, valueMin, valueMax) {
    const point = new NodeGeometryConnectionPoint(name375, this, 0);
    point.type = type;
    point.isOptional = isOptional;
    point.defaultValue = value;
    point.value = value;
    point.valueMin = valueMin;
    point.valueMax = valueMax;
    this._inputs.push(point);
    return this;
  }
  registerOutput(name375, type, point) {
    point = point ?? new NodeGeometryConnectionPoint(name375, this, 1);
    point.type = type;
    this._outputs.push(point);
    return this;
  }
  _buildBlock(state) {}
  _customBuildStep(state) {}
  build(state) {
    if (this._buildId === state.buildId) {
      return true;
    }
    if (this._outputs.length > 0) {
      if (!this._outputs.some((o) => o.hasEndpoints) && !this.isDebug) {
        return false;
      }
      this.outputs.forEach((o) => o._resetCounters());
    }
    this._buildId = state.buildId;
    for (const input of this._inputs) {
      if (!input.connectedPoint) {
        if (!input.isOptional) {
          state.notConnectedNonOptionalInputs.push(input);
        }
        continue;
      }
      const block = input.connectedPoint.ownerBlock;
      if (block && block !== this) {
        block.build(state);
      }
    }
    this._customBuildStep(state);
    if (state.verbose) {
      Logger.Log(`Building ${this.name} [${this.getClassName()}]`);
    }
    const now = PrecisionDate.Now;
    this._buildBlock(state);
    this._buildExecutionTime = PrecisionDate.Now - now;
    this.onBuildObservable.notifyObservers(this);
    return false;
  }
  _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) {
    if (looseCoupling) {
      this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0];
    } else {
      this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
      this._inputs[inputIndex0]._isMainLinkSource = true;
    }
    this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
  }
  initialize() {}
  autoConfigure(_nodeGeometry) {}
  getInputByName(name375) {
    const filter = this._inputs.filter((e) => e.name === name375);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  getOutputByName(name375) {
    const filter = this._outputs.filter((e) => e.name === name375);
    if (filter.length) {
      return filter[0];
    }
    return null;
  }
  serialize() {
    const serializationObject = {};
    serializationObject.customType = "BABYLON." + this.getClassName();
    serializationObject.id = this.uniqueId;
    serializationObject.name = this.name;
    serializationObject.visibleOnFrame = this.visibleOnFrame;
    serializationObject.inputs = [];
    serializationObject.outputs = [];
    for (const input of this.inputs) {
      serializationObject.inputs.push(input.serialize());
    }
    for (const output of this.outputs) {
      serializationObject.outputs.push(output.serialize(false));
    }
    return serializationObject;
  }
  _deserialize(serializationObject) {
    this._name = serializationObject.name;
    this.comments = serializationObject.comments;
    this.visibleOnFrame = !!serializationObject.visibleOnFrame;
    this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);
  }
  _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) {
    const serializedInputs = serializationObject.inputs;
    const serializedOutputs = serializationObject.outputs;
    if (serializedInputs) {
      serializedInputs.forEach((port) => {
        const input = this.inputs.find((i) => i.name === port.name);
        if (!input) {
          return;
        }
        if (port.displayName) {
          input.displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          input.isExposedOnFrame = port.isExposedOnFrame;
          input.exposedPortPosition = port.exposedPortPosition;
        }
        if (port.value !== undefined && port.value !== null) {
          if (port.valueType === "number") {
            input.value = port.value;
          } else {
            const valueType = GetClass(port.valueType);
            if (valueType) {
              input.value = valueType.FromArray(port.value);
            }
          }
        }
      });
    }
    if (serializedOutputs) {
      serializedOutputs.forEach((port, i) => {
        if (port.displayName) {
          this.outputs[i].displayName = port.displayName;
        }
        if (port.isExposedOnFrame) {
          this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;
          this.outputs[i].exposedPortPosition = port.exposedPortPosition;
        }
      });
    }
  }
  _dumpPropertiesCode() {
    const variableName = this._codeVariableName;
    return `${variableName}.visibleOnFrame = ${this.visibleOnFrame};
`;
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = "";
    if (alreadyDumped.indexOf(this) !== -1) {
      return codeString;
    }
    alreadyDumped.push(this);
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
      codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});
`;
    }
    return codeString;
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    alreadyDumped.push(this);
    const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
    this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;
    if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
      let index = 0;
      do {
        index++;
        this._codeVariableName = nameAsVariableName + index;
      } while (uniqueNames.indexOf(this._codeVariableName) !== -1);
    }
    uniqueNames.push(this._codeVariableName);
    let codeString = `
// ${this.getClassName()}
`;
    if (this.comments) {
      codeString += `// ${this.comments}
`;
    }
    const className = this.getClassName();
    if (className === "GeometryInputBlock") {
      const block = this;
      const blockType = block.type;
      codeString += `var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${blockType});
`;
    } else {
      codeString += `var ${this._codeVariableName} = new BABYLON.${className}("${this.name}");
`;
    }
    codeString += this._dumpPropertiesCode();
    for (const input of this.inputs) {
      if (!input.isConnected) {
        continue;
      }
      const connectedOutput = input.connectedPoint;
      const connectedBlock = connectedOutput.ownerBlock;
      if (alreadyDumped.indexOf(connectedBlock) === -1) {
        codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    for (const output of this.outputs) {
      if (!output.hasEndpoints) {
        continue;
      }
      for (const endpoint of output.endpoints) {
        const connectedBlock = endpoint.ownerBlock;
        if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
          codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
        }
      }
    }
    return codeString;
  }
  clone() {
    const serializationObject = this.serialize();
    const blockType = GetClass(serializationObject.customType);
    if (blockType) {
      const block = new blockType;
      block._deserialize(serializationObject);
      return block;
    }
    return null;
  }
  dispose() {
    for (const input of this.inputs) {
      input.dispose();
    }
    for (const output of this.outputs) {
      output.dispose();
    }
    this.onBuildObservable.clear();
  }
}
__decorate([
  serialize("comment")
], NodeGeometryBlock.prototype, "comments", undefined);

// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryOutputBlock.js
init_typeStore();
class GeometryOutputBlock extends NodeGeometryBlock {
  get currentVertexData() {
    return this._vertexData;
  }
  constructor(name375) {
    super(name375);
    this._vertexData = null;
    this._isUnique = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "GeometryOutputBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  _buildBlock(state) {
    state.vertexData = this.geometry.getConnectedValue(state);
    this._vertexData = state.vertexData;
  }
}
RegisterClass("BABYLON.GeometryOutputBlock", GeometryOutputBlock);

// node_modules/@babylonjs/core/Meshes/Node/Enums/nodeGeometryContextualSources.js
var NodeGeometryContextualSources;
(function(NodeGeometryContextualSources2) {
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["None"] = 0] = "None";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["Positions"] = 1] = "Positions";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["Normals"] = 2] = "Normals";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["Tangents"] = 3] = "Tangents";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV"] = 4] = "UV";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV2"] = 5] = "UV2";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV3"] = 6] = "UV3";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV4"] = 7] = "UV4";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV5"] = 8] = "UV5";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["UV6"] = 9] = "UV6";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["Colors"] = 10] = "Colors";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["VertexID"] = 11] = "VertexID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["FaceID"] = 12] = "FaceID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["GeometryID"] = 13] = "GeometryID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["CollectionID"] = 14] = "CollectionID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["LoopID"] = 15] = "LoopID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["InstanceID"] = 16] = "InstanceID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["LatticeID"] = 17] = "LatticeID";
  NodeGeometryContextualSources2[NodeGeometryContextualSources2["LatticeControl"] = 18] = "LatticeControl";
})(NodeGeometryContextualSources || (NodeGeometryContextualSources = {}));

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBuildState.js
init_math_vector();
class NodeGeometryBuildState {
  constructor() {
    this._rotationMatrix = new Matrix;
    this._scalingMatrix = new Matrix;
    this._positionMatrix = new Matrix;
    this._scalingRotationMatrix = new Matrix;
    this._transformMatrix = new Matrix;
    this._tempVector3 = new Vector3;
    this.notConnectedNonOptionalInputs = [];
    this.noContextualData = [];
    this.vertexData = null;
    this._geometryContext = null;
    this._executionContext = null;
    this._instancingContext = null;
    this._geometryContextStack = [];
    this._executionContextStack = [];
    this._instancingContextStack = [];
  }
  get geometryContext() {
    return this._geometryContext;
  }
  get executionContext() {
    return this._executionContext;
  }
  get instancingContext() {
    return this._instancingContext;
  }
  pushGeometryContext(geometryContext) {
    this._geometryContext = geometryContext;
    this._geometryContextStack.push(this._geometryContext);
  }
  pushExecutionContext(executionContext) {
    this._executionContext = executionContext;
    this._executionContextStack.push(this._executionContext);
  }
  pushInstancingContext(instancingContext) {
    this._instancingContext = instancingContext;
    this._instancingContextStack.push(this._instancingContext);
  }
  restoreGeometryContext() {
    this._geometryContextStack.pop();
    this._geometryContext = this._geometryContextStack.length > 0 ? this._geometryContextStack[this._geometryContextStack.length - 1] : null;
  }
  restoreExecutionContext() {
    this._executionContextStack.pop();
    this._executionContext = this._executionContextStack.length > 0 ? this._executionContextStack[this._executionContextStack.length - 1] : null;
  }
  restoreInstancingContext() {
    this._instancingContextStack.pop();
    this._instancingContext = this._instancingContextStack.length > 0 ? this._instancingContextStack[this._instancingContextStack.length - 1] : null;
  }
  getContextualValue(source, skipWarning = false) {
    if (!this.executionContext) {
      if (!skipWarning) {
        this.noContextualData.push(source);
      }
      return null;
    }
    const index = this.executionContext.getExecutionIndex();
    switch (source) {
      case NodeGeometryContextualSources.Positions:
        if (this.executionContext.getOverridePositionsContextualValue) {
          return this.executionContext.getOverridePositionsContextualValue();
        }
        if (!this.geometryContext || !this.geometryContext.positions) {
          return Vector3.Zero();
        }
        return Vector3.FromArray(this.geometryContext.positions, index * 3);
      case NodeGeometryContextualSources.Normals:
        if (this.executionContext.getOverrideNormalsContextualValue) {
          return this.executionContext.getOverrideNormalsContextualValue();
        }
        if (!this.geometryContext || !this.geometryContext.normals) {
          return Vector3.Zero();
        }
        return Vector3.FromArray(this.geometryContext.normals, index * 3);
      case NodeGeometryContextualSources.Colors:
        if (!this.geometryContext || !this.geometryContext.colors) {
          return Vector4.Zero();
        }
        return Vector4.FromArray(this.geometryContext.colors, index * 4);
      case NodeGeometryContextualSources.Tangents:
        if (!this.geometryContext || !this.geometryContext.tangents) {
          return Vector4.Zero();
        }
        return Vector4.FromArray(this.geometryContext.tangents, index * 4);
      case NodeGeometryContextualSources.UV:
        if (this.executionContext.getOverrideUVs1ContextualValue) {
          return this.executionContext.getOverrideUVs1ContextualValue();
        }
        if (!this.geometryContext || !this.geometryContext.uvs) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs, index * 2);
      case NodeGeometryContextualSources.UV2:
        if (!this.geometryContext || !this.geometryContext.uvs2) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs2, index * 2);
      case NodeGeometryContextualSources.UV3:
        if (!this.geometryContext || !this.geometryContext.uvs3) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs3, index * 2);
      case NodeGeometryContextualSources.UV4:
        if (!this.geometryContext || !this.geometryContext.uvs4) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs4, index * 2);
      case NodeGeometryContextualSources.UV5:
        if (!this.geometryContext || !this.geometryContext.uvs5) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs5, index * 2);
      case NodeGeometryContextualSources.UV6:
        if (!this.geometryContext || !this.geometryContext.uvs6) {
          return Vector2.Zero();
        }
        return Vector2.FromArray(this.geometryContext.uvs6, index * 2);
      case NodeGeometryContextualSources.VertexID:
        return index;
      case NodeGeometryContextualSources.FaceID:
        return this.executionContext.getExecutionFaceIndex();
      case NodeGeometryContextualSources.LoopID:
        return this.executionContext.getExecutionLoopIndex();
      case NodeGeometryContextualSources.InstanceID:
        return this.instancingContext ? this.instancingContext.getInstanceIndex() : 0;
      case NodeGeometryContextualSources.GeometryID:
        return !this.geometryContext ? 0 : this.geometryContext.uniqueId;
      case NodeGeometryContextualSources.CollectionID: {
        if (!this.geometryContext || !this.geometryContext.metadata) {
          return 0;
        }
        return this.geometryContext.metadata.collectionId || 0;
      }
      case NodeGeometryContextualSources.LatticeID: {
        if (this.executionContext.getOverridePositionsContextualValue) {
          return this.executionContext.getOverridePositionsContextualValue();
        }
        return Vector3.Zero();
      }
      case NodeGeometryContextualSources.LatticeControl: {
        if (this.executionContext.getOverrideNormalsContextualValue) {
          return this.executionContext.getOverrideNormalsContextualValue();
        }
        return Vector3.Zero();
      }
    }
    return null;
  }
  adapt(source, targetType) {
    const value = source.getConnectedValue(this) || 0;
    if (source.type === targetType) {
      return value;
    }
    switch (targetType) {
      case NodeGeometryBlockConnectionPointTypes.Vector2:
        return new Vector2(value, value);
      case NodeGeometryBlockConnectionPointTypes.Vector3:
        return new Vector3(value, value, value);
      case NodeGeometryBlockConnectionPointTypes.Vector4:
        return new Vector4(value, value, value, value);
    }
    return null;
  }
  adaptInput(source, targetType, defaultValue) {
    if (!source.isConnected) {
      return source.value || defaultValue;
    }
    const value = source.getConnectedValue(this);
    if (source._connectedPoint?.type === targetType) {
      return value;
    }
    switch (targetType) {
      case NodeGeometryBlockConnectionPointTypes.Vector2:
        return new Vector2(value, value);
      case NodeGeometryBlockConnectionPointTypes.Vector3:
        return new Vector3(value, value, value);
      case NodeGeometryBlockConnectionPointTypes.Vector4:
        return new Vector4(value, value, value, value);
    }
    return null;
  }
  emitErrors() {
    let errorMessage = "";
    for (const notConnectedInput of this.notConnectedNonOptionalInputs) {
      errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.
`;
    }
    for (const source of this.noContextualData) {
      errorMessage += `Contextual input ${NodeGeometryContextualSources[source]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).
`;
    }
    if (errorMessage) {
      throw `Build of NodeGeometry failed:
` + errorMessage;
    }
  }
  _instantiate(clone, currentPosition, rotation, scaling, additionalVertexData) {
    Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix);
    Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix);
    Matrix.TranslationToRef(currentPosition.x, currentPosition.y, currentPosition.z, this._positionMatrix);
    this._scalingMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix);
    this._scalingRotationMatrix.multiplyToRef(this._positionMatrix, this._transformMatrix);
    for (let clonePositionIndex = 0;clonePositionIndex < clone.positions.length; clonePositionIndex += 3) {
      this._tempVector3.fromArray(clone.positions, clonePositionIndex);
      Vector3.TransformCoordinatesToRef(this._tempVector3, this._transformMatrix, this._tempVector3);
      this._tempVector3.toArray(clone.positions, clonePositionIndex);
      if (clone.normals) {
        this._tempVector3.fromArray(clone.normals, clonePositionIndex);
        Vector3.TransformNormalToRef(this._tempVector3, this._scalingRotationMatrix, this._tempVector3);
        this._tempVector3.toArray(clone.normals, clonePositionIndex);
      }
    }
    additionalVertexData.push(clone);
  }
  _instantiateWithMatrix(clone, transform, additionalVertexData) {
    for (let clonePositionIndex = 0;clonePositionIndex < clone.positions.length; clonePositionIndex += 3) {
      this._tempVector3.fromArray(clone.positions, clonePositionIndex);
      Vector3.TransformCoordinatesToRef(this._tempVector3, transform, this._tempVector3);
      this._tempVector3.toArray(clone.positions, clonePositionIndex);
      if (clone.normals) {
        this._tempVector3.fromArray(clone.normals, clonePositionIndex);
        Vector3.TransformNormalToRef(this._tempVector3, transform, this._tempVector3);
        this._tempVector3.toArray(clone.normals, clonePositionIndex);
      }
    }
    additionalVertexData.push(clone);
  }
  _instantiateWithPositionAndMatrix(clone, currentPosition, transform, additionalVertexData) {
    Matrix.TranslationToRef(currentPosition.x, currentPosition.y, currentPosition.z, this._positionMatrix);
    transform.multiplyToRef(this._positionMatrix, this._transformMatrix);
    for (let clonePositionIndex = 0;clonePositionIndex < clone.positions.length; clonePositionIndex += 3) {
      this._tempVector3.fromArray(clone.positions, clonePositionIndex);
      Vector3.TransformCoordinatesToRef(this._tempVector3, this._transformMatrix, this._tempVector3);
      this._tempVector3.toArray(clone.positions, clonePositionIndex);
      if (clone.normals) {
        this._tempVector3.fromArray(clone.normals, clonePositionIndex);
        Vector3.TransformNormalToRef(this._tempVector3, this._transformMatrix, this._tempVector3);
        this._tempVector3.toArray(clone.normals, clonePositionIndex);
      }
    }
    additionalVertexData.push(clone);
  }
}

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometry.js
init_typeStore();
init_decorators();
init_decorators_serialization();
init_webRequest();

// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/boxBlock.js
init_tslib_es6();

// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryInputBlock.js
init_observable();
init_typeStore();
init_math_vector();
class GeometryInputBlock extends NodeGeometryBlock {
  get type() {
    if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) {
      if (this.value != null) {
        if (!isNaN(this.value)) {
          this._type = NodeGeometryBlockConnectionPointTypes.Float;
          return this._type;
        }
        switch (this.value.getClassName()) {
          case "Vector2":
            this._type = NodeGeometryBlockConnectionPointTypes.Vector2;
            return this._type;
          case "Vector3":
            this._type = NodeGeometryBlockConnectionPointTypes.Vector3;
            return this._type;
          case "Vector4":
            this._type = NodeGeometryBlockConnectionPointTypes.Vector4;
            return this._type;
          case "Matrix":
            this._type = NodeGeometryBlockConnectionPointTypes.Matrix;
            return this._type;
        }
      }
    }
    return this._type;
  }
  get isContextual() {
    return this._contextualSource !== NodeGeometryContextualSources.None;
  }
  get contextualValue() {
    return this._contextualSource;
  }
  set contextualValue(value) {
    this._contextualSource = value;
    switch (value) {
      case NodeGeometryContextualSources.Positions:
      case NodeGeometryContextualSources.Normals:
      case NodeGeometryContextualSources.LatticeID:
      case NodeGeometryContextualSources.LatticeControl:
        this._type = NodeGeometryBlockConnectionPointTypes.Vector3;
        break;
      case NodeGeometryContextualSources.Colors:
      case NodeGeometryContextualSources.Tangents:
        this._type = NodeGeometryBlockConnectionPointTypes.Vector4;
        break;
      case NodeGeometryContextualSources.UV:
      case NodeGeometryContextualSources.UV2:
      case NodeGeometryContextualSources.UV3:
      case NodeGeometryContextualSources.UV4:
      case NodeGeometryContextualSources.UV5:
      case NodeGeometryContextualSources.UV6:
        this._type = NodeGeometryBlockConnectionPointTypes.Vector2;
        break;
      case NodeGeometryContextualSources.VertexID:
      case NodeGeometryContextualSources.GeometryID:
      case NodeGeometryContextualSources.CollectionID:
      case NodeGeometryContextualSources.FaceID:
      case NodeGeometryContextualSources.LoopID:
      case NodeGeometryContextualSources.InstanceID:
        this._type = NodeGeometryBlockConnectionPointTypes.Int;
        break;
    }
    if (this.output) {
      this.output.type = this._type;
    }
  }
  constructor(name375, type = NodeGeometryBlockConnectionPointTypes.AutoDetect) {
    super(name375);
    this._type = NodeGeometryBlockConnectionPointTypes.Undefined;
    this._contextualSource = NodeGeometryContextualSources.None;
    this.min = 0;
    this.max = 0;
    this.groupInInspector = "";
    this.displayInInspector = true;
    this.onValueChangedObservable = new Observable;
    this._type = type;
    this._isInput = true;
    this.setDefaultValue();
    this.registerOutput("output", type);
  }
  get value() {
    return this._storedValue;
  }
  set value(value) {
    if (this.type === NodeGeometryBlockConnectionPointTypes.Float) {
      if (this.min !== this.max) {
        value = Math.max(this.min, value);
        value = Math.min(this.max, value);
      }
    }
    this._storedValue = value;
    this.onValueChangedObservable.notifyObservers(this);
  }
  get valueCallback() {
    return this._valueCallback;
  }
  set valueCallback(value) {
    this._valueCallback = value;
  }
  getClassName() {
    return "GeometryInputBlock";
  }
  get output() {
    return this._outputs[0];
  }
  setDefaultValue() {
    this.contextualValue = NodeGeometryContextualSources.None;
    switch (this.type) {
      case NodeGeometryBlockConnectionPointTypes.Int:
      case NodeGeometryBlockConnectionPointTypes.Float:
        this.value = 0;
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector2:
        this.value = Vector2.Zero();
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector3:
        this.value = Vector3.Zero();
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector4:
        this.value = Vector4.Zero();
        break;
      case NodeGeometryBlockConnectionPointTypes.Matrix:
        this.value = Matrix.Identity();
        break;
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (this.isContextual) {
      this.output._storedValue = null;
      this.output._storedFunction = (state2) => {
        return state2.getContextualValue(this._contextualSource);
      };
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = this.value;
    }
  }
  dispose() {
    this.onValueChangedObservable.clear();
    super.dispose();
  }
  _dumpPropertiesCode() {
    const variableName = this._codeVariableName;
    if (this.isContextual) {
      return super._dumpPropertiesCode() + `${variableName}.contextualValue = BABYLON.NodeGeometryContextualSources.${NodeGeometryContextualSources[this._contextualSource]};
`;
    }
    const codes = [];
    let valueString = "";
    switch (this.type) {
      case NodeGeometryBlockConnectionPointTypes.Float:
      case NodeGeometryBlockConnectionPointTypes.Int:
        valueString = `${this.value}`;
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector2:
        valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector3:
        valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;
        break;
      case NodeGeometryBlockConnectionPointTypes.Vector4:
        valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;
        break;
    }
    codes.push(`${variableName}.value = ${valueString}`);
    if (this.type === NodeGeometryBlockConnectionPointTypes.Float || this.type === NodeGeometryBlockConnectionPointTypes.Int) {
      codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`);
    }
    codes.push("");
    return super._dumpPropertiesCode() + codes.join(`;
`);
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.type = this.type;
    serializationObject.contextualValue = this.contextualValue;
    serializationObject.min = this.min;
    serializationObject.max = this.max;
    serializationObject.groupInInspector = this.groupInInspector;
    serializationObject.displayInInspector = this.displayInInspector;
    if (this._storedValue !== null && !this.isContextual) {
      if (this._storedValue.asArray) {
        serializationObject.valueType = "BABYLON." + this._storedValue.getClassName();
        serializationObject.value = this._storedValue.asArray();
      } else {
        serializationObject.valueType = "number";
        serializationObject.value = this._storedValue;
      }
    }
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this._type = serializationObject.type;
    this.contextualValue = serializationObject.contextualValue;
    this.min = serializationObject.min || 0;
    this.max = serializationObject.max || 0;
    this.groupInInspector = serializationObject.groupInInspector || "";
    if (serializationObject.displayInInspector !== undefined) {
      this.displayInInspector = serializationObject.displayInInspector;
    }
    if (!serializationObject.valueType) {
      return;
    }
    if (serializationObject.valueType === "number") {
      this._storedValue = serializationObject.value;
    } else {
      const valueType = GetClass(serializationObject.valueType);
      if (valueType) {
        this._storedValue = valueType.FromArray(serializationObject.value);
      }
    }
  }
}
RegisterClass("BABYLON.GeometryInputBlock", GeometryInputBlock);

// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/boxBlock.js
init_typeStore();
class BoxBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("depth", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0);
    this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerInput("subdivisionsZ", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "BoxBlock";
  }
  get size() {
    return this._inputs[0];
  }
  get width() {
    return this._inputs[1];
  }
  get height() {
    return this._inputs[2];
  }
  get depth() {
    return this._inputs[3];
  }
  get subdivisions() {
    return this._inputs[4];
  }
  get subdivisionsX() {
    return this._inputs[5];
  }
  get subdivisionsY() {
    return this._inputs[6];
  }
  get subdivisionsZ() {
    return this._inputs[7];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (this.size.isConnected) {
      return;
    }
    if (!this.width.isConnected && !this.height.isConnected && !this.depth.isConnected) {
      const sizeInput = new GeometryInputBlock("Size");
      sizeInput.value = 1;
      sizeInput.output.connectTo(this.size);
      return;
    }
    if (!this.width.isConnected) {
      const widthInput = new GeometryInputBlock("Width");
      widthInput.value = 1;
      widthInput.output.connectTo(this.width);
    }
    if (!this.height.isConnected) {
      const heightInput = new GeometryInputBlock("Height");
      heightInput.value = 1;
      heightInput.output.connectTo(this.height);
    }
    if (!this.depth.isConnected) {
      const depthInput = new GeometryInputBlock("Depth");
      depthInput.value = 1;
      depthInput.output.connectTo(this.depth);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.size = this.size.getConnectedValue(state2);
      options.width = this.width.getConnectedValue(state2);
      options.height = this.height.getConnectedValue(state2);
      options.depth = this.depth.getConnectedValue(state2);
      const subdivisions = this.subdivisions.getConnectedValue(state2);
      const subdivisionsX = this.subdivisionsX.getConnectedValue(state2);
      const subdivisionsY = this.subdivisionsY.getConnectedValue(state2);
      const subdivisionsZ = this.subdivisionsZ.getConnectedValue(state2);
      if (subdivisions) {
        options.segments = subdivisions;
      }
      if (subdivisionsX) {
        options.widthSegments = subdivisionsX;
      }
      if (subdivisionsY) {
        options.heightSegments = subdivisionsY;
      }
      if (subdivisionsZ) {
        options.depthSegments = subdivisionsZ;
      }
      return CreateSegmentedBoxVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], BoxBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.BoxBlock", BoxBlock);

// node_modules/@babylonjs/core/Meshes/Node/nodeGeometry.js
init_precisionDate();
init_tools();
init_abstractEngine();

class NodeGeometry {
  _getGlobalNodeGeometryEditor() {
    if (typeof NODEGEOMETRYEDITOR !== "undefined") {
      return NODEGEOMETRYEDITOR;
    }
    if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeGeometryEditor !== "undefined") {
      return BABYLON;
    }
    return;
  }
  get buildExecutionTime() {
    return this._buildExecutionTime;
  }
  constructor(name375) {
    this._buildId = NodeGeometry._BuildIdGenerator++;
    this._buildWasSuccessful = false;
    this._vertexData = null;
    this._buildExecutionTime = 0;
    this.BJSNODEGEOMETRYEDITOR = this._getGlobalNodeGeometryEditor();
    this.editorData = null;
    this.attachedBlocks = [];
    this.onBuildObservable = new Observable;
    this.outputBlock = null;
    this.name = name375;
  }
  getClassName() {
    return "NodeGeometry";
  }
  get vertexData() {
    return this._vertexData;
  }
  getBlockByName(name375) {
    let result = null;
    for (const block of this.attachedBlocks) {
      if (block.name === name375) {
        if (!result) {
          result = block;
        } else {
          Tools.Warn("More than one block was found with the name `" + name375 + "`");
          return result;
        }
      }
    }
    return result;
  }
  getBlockByPredicate(predicate) {
    for (const block of this.attachedBlocks) {
      if (predicate(block)) {
        return block;
      }
    }
    return null;
  }
  getInputBlocks() {
    const blocks = [];
    for (const block of this.attachedBlocks) {
      if (block.isInput) {
        blocks.push(block);
      }
    }
    return blocks;
  }
  edit(config) {
    return new Promise((resolve3) => {
      this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor();
      if (typeof this.BJSNODEGEOMETRYEDITOR == "undefined") {
        const editorUrl = config && config.editorURL ? config.editorURL : NodeGeometry.EditorURL;
        Tools.LoadBabylonScript(editorUrl, () => {
          this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor();
          this._createNodeEditor(config?.nodeGeometryEditorConfig);
          resolve3();
        });
      } else {
        this._createNodeEditor(config?.nodeGeometryEditorConfig);
        resolve3();
      }
    });
  }
  _createNodeEditor(additionalConfig) {
    const nodeEditorConfig = {
      nodeGeometry: this,
      ...additionalConfig
    };
    this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(nodeEditorConfig);
  }
  build(verbose = false, updateBuildId = true, autoConfigure = false) {
    this._buildWasSuccessful = false;
    if (!this.outputBlock) {
      throw "You must define the outputBlock property before building the geometry";
    }
    const now = PrecisionDate.Now;
    this._initializeBlock(this.outputBlock, autoConfigure);
    const promises = [];
    for (const block of this.attachedBlocks) {
      if (block._isReadyState) {
        promises.push(block._isReadyState);
      }
    }
    if (promises.length) {
      Promise.all(promises).then(() => {
        this.build(verbose, updateBuildId, autoConfigure);
      });
      return;
    }
    const state = new NodeGeometryBuildState;
    state.buildId = this._buildId;
    state.verbose = verbose;
    try {
      this.outputBlock.build(state);
    } finally {
      if (updateBuildId) {
        this._buildId = NodeGeometry._BuildIdGenerator++;
      }
    }
    this._buildExecutionTime = PrecisionDate.Now - now;
    state.emitErrors();
    this._buildWasSuccessful = true;
    this._vertexData = state.vertexData;
    this.onBuildObservable.notifyObservers(this);
  }
  createMesh(name375, scene = null) {
    if (!this._buildWasSuccessful) {
      this.build();
    }
    if (!this._vertexData) {
      return null;
    }
    const mesh = new Mesh(name375, scene);
    this._vertexData.applyToMesh(mesh);
    mesh._internalMetadata = mesh._internalMetadata || {};
    mesh._internalMetadata.nodeGeometry = this;
    return mesh;
  }
  updateMesh(mesh) {
    if (!this._buildWasSuccessful) {
      this.build();
    }
    if (!this._vertexData) {
      return false;
    }
    this._vertexData.applyToMesh(mesh);
    mesh._internalMetadata = mesh._internalMetadata || {};
    mesh._internalMetadata.nodeGeometry = this;
    return mesh;
  }
  _initializeBlock(node, autoConfigure = true) {
    node.initialize();
    if (autoConfigure) {
      node.autoConfigure(this);
    }
    node._preparationId = this._buildId;
    if (this.attachedBlocks.indexOf(node) === -1) {
      this.attachedBlocks.push(node);
    }
    for (const input of node.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint) {
        const block = connectedPoint.ownerBlock;
        if (block !== node) {
          this._initializeBlock(block, autoConfigure);
        }
      }
    }
  }
  clear() {
    this.outputBlock = null;
    this.attachedBlocks.length = 0;
  }
  removeBlock(block) {
    const attachedBlockIndex = this.attachedBlocks.indexOf(block);
    if (attachedBlockIndex > -1) {
      this.attachedBlocks.splice(attachedBlockIndex, 1);
    }
    if (block === this.outputBlock) {
      this.outputBlock = null;
    }
  }
  parseSerializedObject(source, merge = false) {
    if (!merge) {
      this.clear();
    }
    const map = {};
    for (const parsedBlock of source.blocks) {
      const blockType = GetClass(parsedBlock.customType);
      if (blockType) {
        const block = new blockType;
        block._deserialize(parsedBlock);
        map[parsedBlock.id] = block;
        this.attachedBlocks.push(block);
      }
    }
    for (const block of this.attachedBlocks) {
      if (block.isTeleportOut) {
        const teleportOut = block;
        const id = teleportOut._tempEntryPointUniqueId;
        if (id) {
          const source2 = map[id];
          if (source2) {
            source2.attachToEndpoint(teleportOut);
          }
        }
      }
    }
    for (let blockIndex = 0;blockIndex < source.blocks.length; blockIndex++) {
      const parsedBlock = source.blocks[blockIndex];
      const block = map[parsedBlock.id];
      if (!block) {
        continue;
      }
      if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) {
        continue;
      }
      this._restoreConnections(block, source, map);
    }
    if (source.outputNodeId) {
      this.outputBlock = map[source.outputNodeId];
    }
    if (source.locations || source.editorData && source.editorData.locations) {
      const locations = source.locations || source.editorData.locations;
      for (const location2 of locations) {
        if (map[location2.blockId]) {
          location2.blockId = map[location2.blockId].uniqueId;
        }
      }
      if (merge && this.editorData && this.editorData.locations) {
        locations.concat(this.editorData.locations);
      }
      if (source.locations) {
        this.editorData = {
          locations
        };
      } else {
        this.editorData = source.editorData;
        this.editorData.locations = locations;
      }
      const blockMap = [];
      for (const key in map) {
        blockMap[key] = map[key].uniqueId;
      }
      this.editorData.map = blockMap;
    }
    this.comment = source.comment;
  }
  _restoreConnections(block, source, map) {
    for (const outputPoint of block.outputs) {
      for (const candidate of source.blocks) {
        const target = map[candidate.id];
        if (!target) {
          continue;
        }
        for (const input of candidate.inputs) {
          if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
            const inputPoint = target.getInputByName(input.inputName);
            if (!inputPoint || inputPoint.isConnected) {
              continue;
            }
            outputPoint.connectTo(inputPoint, true);
            this._restoreConnections(target, source, map);
            continue;
          }
        }
      }
    }
  }
  generateCode() {
    let alreadyDumped = [];
    const blocks = [];
    const uniqueNames = ["const", "var", "let"];
    if (this.outputBlock) {
      this._gatherBlocks(this.outputBlock, blocks);
    }
    let codeString = `let nodeGeometry = new BABYLON.NodeGeometry("${this.name || "node geometry"}");
`;
    for (const node of blocks) {
      if (node.isInput && alreadyDumped.indexOf(node) === -1) {
        codeString += node._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    if (this.outputBlock) {
      alreadyDumped = [];
      codeString += `// Connections
`;
      codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped);
      codeString += `// Output nodes
`;
      codeString += `nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};
`;
      codeString += `nodeGeometry.build();
`;
    }
    return codeString;
  }
  _gatherBlocks(rootNode, list) {
    if (list.indexOf(rootNode) !== -1) {
      return;
    }
    list.push(rootNode);
    for (const input of rootNode.inputs) {
      const connectedPoint = input.connectedPoint;
      if (connectedPoint) {
        const block = connectedPoint.ownerBlock;
        if (block !== rootNode) {
          this._gatherBlocks(block, list);
        }
      }
    }
    if (rootNode.isTeleportOut) {
      const block = rootNode;
      if (block.entryPoint) {
        this._gatherBlocks(block.entryPoint, list);
      }
    }
  }
  setToDefault() {
    this.clear();
    this.editorData = null;
    const dataBlock = new BoxBlock("Box");
    dataBlock.autoConfigure();
    const output = new GeometryOutputBlock("Geometry Output");
    dataBlock.geometry.connectTo(output.geometry);
    this.outputBlock = output;
  }
  clone(name375) {
    const serializationObject = this.serialize();
    const clone = SerializationHelper.Clone(() => new NodeGeometry(name375), this);
    clone.name = name375;
    clone.parseSerializedObject(serializationObject);
    clone._buildId = this._buildId;
    clone.build(false);
    return clone;
  }
  serialize(selectedBlocks) {
    const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);
    serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData));
    let blocks = [];
    if (selectedBlocks) {
      blocks = selectedBlocks;
    } else {
      serializationObject.customType = "BABYLON.NodeGeometry";
      if (this.outputBlock) {
        serializationObject.outputNodeId = this.outputBlock.uniqueId;
      }
    }
    serializationObject.blocks = [];
    for (const block of blocks) {
      serializationObject.blocks.push(block.serialize());
    }
    if (!selectedBlocks) {
      for (const block of this.attachedBlocks) {
        if (blocks.indexOf(block) !== -1) {
          continue;
        }
        serializationObject.blocks.push(block.serialize());
      }
    }
    return serializationObject;
  }
  dispose() {
    for (const block of this.attachedBlocks) {
      block.dispose();
    }
    this.attachedBlocks.length = 0;
    this.onBuildObservable.clear();
  }
  static CreateDefault(name375) {
    const nodeGeometry = new NodeGeometry(name375);
    nodeGeometry.setToDefault();
    nodeGeometry.build();
    return nodeGeometry;
  }
  static Parse(source) {
    const nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(source.name), source, null);
    nodeGeometry.parseSerializedObject(source);
    nodeGeometry.build();
    return nodeGeometry;
  }
  static ParseFromSnippetAsync(snippetId, nodeGeometry, skipBuild = false) {
    if (snippetId === "_BLANK") {
      return Promise.resolve(NodeGeometry.CreateDefault("blank"));
    }
    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);
            const serializationObject = JSON.parse(snippet.nodeGeometry);
            if (!nodeGeometry) {
              nodeGeometry = SerializationHelper.Parse(() => new NodeGeometry(snippetId), serializationObject, null);
            }
            nodeGeometry.parseSerializedObject(serializationObject);
            nodeGeometry.snippetId = snippetId;
            try {
              if (!skipBuild) {
                nodeGeometry.build();
              }
              resolve3(nodeGeometry);
            } catch (err) {
              reject(err);
            }
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
}
NodeGeometry._BuildIdGenerator = 0;
NodeGeometry.EditorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`;
NodeGeometry.SnippetUrl = `https://snippet.babylonjs.com`;
__decorate([
  serialize()
], NodeGeometry.prototype, "name", undefined);
__decorate([
  serialize("comment")
], NodeGeometry.prototype, "comment", undefined);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryOptimizeBlock.js
init_tslib_es6();
init_typeStore();
init_math_constants();

class GeometryOptimizeBlock extends NodeGeometryBlock {
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.epsilon = Epsilon;
    this.optimizeFaces = false;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("selector", NodeGeometryBlockConnectionPointTypes.Int, true);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "GeometryOptimizeBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get selector() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      if (!this.geometry.isConnected) {
        return null;
      }
      const vertexData = this.geometry.getConnectedValue(state2);
      const newPositions = [];
      const newIndicesMap = {};
      state2.pushExecutionContext(this);
      state2.pushGeometryContext(vertexData);
      for (let index = 0;index < vertexData.positions.length; index += 3) {
        this._currentIndex = index / 3;
        if (this.selector.isConnected) {
          const selector = this.selector.getConnectedValue(state2);
          if (!selector) {
            continue;
          }
        }
        const x = vertexData.positions[index];
        const y = vertexData.positions[index + 1];
        const z = vertexData.positions[index + 2];
        let found = false;
        for (let checkIndex = 0;checkIndex < newPositions.length; checkIndex += 3) {
          if (WithinEpsilon(x, newPositions[checkIndex], this.epsilon) && WithinEpsilon(y, newPositions[checkIndex + 1], this.epsilon) && WithinEpsilon(z, newPositions[checkIndex + 2], this.epsilon)) {
            newIndicesMap[index / 3] = checkIndex / 3;
            found = true;
            continue;
          }
        }
        if (!found) {
          newIndicesMap[index / 3] = newPositions.length / 3;
          newPositions.push(x, y, z);
        }
      }
      const newVertexData = new VertexData;
      newVertexData.positions = newPositions;
      const indices = vertexData.indices.map((index) => newIndicesMap[index]);
      const newIndices = [];
      if (this.optimizeFaces) {
        for (let index = 0;index < indices.length; index += 3) {
          const a = indices[index];
          const b = indices[index + 1];
          const c = indices[index + 2];
          if (a === b || b == c || c === a) {
            continue;
          }
          let found = false;
          for (let checkIndex = 0;checkIndex < newIndices.length; checkIndex += 3) {
            if (a === newIndices[checkIndex] && b === newIndices[checkIndex + 1] && c === newIndices[checkIndex + 2]) {
              found = true;
              continue;
            }
            if (a === newIndices[checkIndex + 1] && b === newIndices[checkIndex + 2] && c === newIndices[checkIndex]) {
              found = true;
              continue;
            }
            if (a === newIndices[checkIndex + 2] && b === newIndices[checkIndex] && c === newIndices[checkIndex + 1]) {
              found = true;
              continue;
            }
          }
          if (!found) {
            newIndices.push(a, b, c);
          }
        }
        newVertexData.indices = newIndices;
      } else {
        newVertexData.indices = indices;
      }
      return newVertexData;
    };
    state.restoreGeometryContext();
    state.restoreExecutionContext();
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.epsilon = ${this.epsilon};
`;
    codeString += `${this._codeVariableName}.optimizeFaces = ${this.optimizeFaces ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.epsilon = this.epsilon;
    serializationObject.optimizeFaces = this.optimizeFaces;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
    this.epsilon = serializationObject.epsilon;
    this.optimizeFaces = serializationObject.optimizeFaces;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryOptimizeBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("Epsilon", 1, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryOptimizeBlock.prototype, "epsilon", undefined);
__decorate([
  editableInPropertyPage("Optimize faces", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryOptimizeBlock.prototype, "optimizeFaces", undefined);
RegisterClass("BABYLON.GeometryOptimizeBlock", GeometryOptimizeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/planeBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
class PlaneBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._rotationMatrix = new Matrix;
    this.evaluateContext = false;
    this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0);
    this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "PlaneBlock";
  }
  get size() {
    return this._inputs[0];
  }
  get width() {
    return this._inputs[1];
  }
  get height() {
    return this._inputs[2];
  }
  get subdivisions() {
    return this._inputs[3];
  }
  get subdivisionsX() {
    return this._inputs[4];
  }
  get subdivisionsY() {
    return this._inputs[5];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (this.size.isConnected) {
      return;
    }
    if (!this.width.isConnected && !this.height.isConnected) {
      const sizeInput = new GeometryInputBlock("Size");
      sizeInput.value = 1;
      sizeInput.output.connectTo(this.size);
      return;
    }
    if (!this.width.isConnected) {
      const widthInput = new GeometryInputBlock("Width");
      widthInput.value = 1;
      widthInput.output.connectTo(this.width);
    }
    if (!this.height.isConnected) {
      const heightInput = new GeometryInputBlock("Height");
      heightInput.value = 1;
      heightInput.output.connectTo(this.height);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.size = this.size.getConnectedValue(state2);
      options.width = this.width.getConnectedValue(state2);
      options.height = this.height.getConnectedValue(state2);
      const subdivisions = this.subdivisions.getConnectedValue(state2);
      const subdivisionsX = this.subdivisionsX.getConnectedValue(state2);
      const subdivisionsY = this.subdivisionsY.getConnectedValue(state2);
      if (subdivisions) {
        options.subdivisions = subdivisions;
      }
      if (subdivisionsX) {
        options.subdivisionsX = subdivisionsX;
      }
      if (subdivisionsY) {
        options.subdivisionsY = subdivisionsY;
      }
      const vertexData = CreateGroundVertexData(options);
      Matrix.RotationYawPitchRollToRef(-Math.PI / 2, 0, Math.PI / 2, this._rotationMatrix);
      vertexData.transform(this._rotationMatrix);
      return vertexData;
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], PlaneBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.PlaneBlock", PlaneBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/meshBlock.js
init_tslib_es6();
init_typeStore();
class MeshBlock extends NodeGeometryBlock {
  get mesh() {
    return this._mesh;
  }
  set mesh(value) {
    this._mesh = value;
  }
  constructor(name375) {
    super(name375);
    this._cachedVertexData = null;
    this.reverseWindingOrder = false;
    this.serializedCachedData = false;
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "MeshBlock";
  }
  get isUsingCachedData() {
    return !this.mesh && !!this._cachedVertexData;
  }
  get geometry() {
    return this._outputs[0];
  }
  cleanData() {
    this._mesh = null;
    this._cachedVertexData = null;
  }
  _buildBlock() {
    if (!this._mesh) {
      if (this._cachedVertexData) {
        this.geometry._storedValue = this._cachedVertexData.clone();
      } else {
        this.geometry._storedValue = null;
      }
      return;
    }
    const vertexData = VertexData.ExtractFromMesh(this._mesh, false, true);
    this._cachedVertexData = null;
    if (this.reverseWindingOrder && vertexData.indices) {
      for (let index = 0;index < vertexData.indices.length; index += 3) {
        const tmp = vertexData.indices[index];
        vertexData.indices[index] = vertexData.indices[index + 2];
        vertexData.indices[index + 2] = tmp;
      }
    }
    this.geometry._storedFunction = () => {
      return vertexData.clone();
    };
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.serializedCachedData = this.serializedCachedData;
    if (this.serializedCachedData) {
      if (this._mesh) {
        serializationObject.cachedVertexData = VertexData.ExtractFromMesh(this._mesh, false, true).serialize();
      } else if (this._cachedVertexData) {
        serializationObject.cachedVertexData = this._cachedVertexData.serialize();
      }
    }
    serializationObject.reverseWindingOrder = this.reverseWindingOrder;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.cachedVertexData) {
      this._cachedVertexData = VertexData.Parse(serializationObject.cachedVertexData);
    }
    this.serializedCachedData = !!serializationObject.serializedCachedData;
    this.reverseWindingOrder = serializationObject.reverseWindingOrder;
  }
}
__decorate([
  editableInPropertyPage("Serialize cached data", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], MeshBlock.prototype, "serializedCachedData", undefined);
RegisterClass("BABYLON.MeshBlock", MeshBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/icoSphereBlock.js
init_tslib_es6();
init_typeStore();
class IcoSphereBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("radiusX", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("radiusY", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("radiusZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 4);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "IcoSphereBlock";
  }
  get radius() {
    return this._inputs[0];
  }
  get radiusX() {
    return this._inputs[1];
  }
  get radiusY() {
    return this._inputs[2];
  }
  get radiusZ() {
    return this._inputs[3];
  }
  get subdivisions() {
    return this._inputs[4];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.radius.isConnected) {
      const radiusInput = new GeometryInputBlock("Radius");
      radiusInput.value = 0.2;
      radiusInput.output.connectTo(this.radius);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.radius = this.radius.getConnectedValue(state2);
      options.subdivisions = this.subdivisions.getConnectedValue(state2);
      options.radiusX = this.radiusX.getConnectedValue(state2);
      options.radiusY = this.radiusY.getConnectedValue(state2);
      options.radiusZ = this.radiusZ.getConnectedValue(state2);
      return CreateIcoSphereVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], IcoSphereBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.IcoSphereBlock", IcoSphereBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/sphereBlock.js
init_tslib_es6();
init_typeStore();
class SphereBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("segments", NodeGeometryBlockConnectionPointTypes.Int, true, 32);
    this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("diameterX", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("diameterY", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("diameterZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("slice", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "SphereBlock";
  }
  get segments() {
    return this._inputs[0];
  }
  get diameter() {
    return this._inputs[1];
  }
  get diameterX() {
    return this._inputs[2];
  }
  get diameterY() {
    return this._inputs[3];
  }
  get diameterZ() {
    return this._inputs[4];
  }
  get arc() {
    return this._inputs[5];
  }
  get slice() {
    return this._inputs[6];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.diameter.isConnected) {
      const diameterInput = new GeometryInputBlock("Diameter");
      diameterInput.value = 1;
      diameterInput.output.connectTo(this.diameter);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.segments = this.segments.getConnectedValue(state2);
      options.diameter = this.diameter.getConnectedValue(state2);
      options.diameterX = this.diameterX.getConnectedValue(state2);
      options.diameterY = this.diameterY.getConnectedValue(state2);
      options.diameterZ = this.diameterZ.getConnectedValue(state2);
      options.arc = this.arc.getConnectedValue(state2);
      options.slice = this.slice.getConnectedValue(state2);
      return CreateSphereVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SphereBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SphereBlock", SphereBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/gridBlock.js
init_tslib_es6();
init_typeStore();
class GridBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0);
    this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "GridBlock";
  }
  get width() {
    return this._inputs[0];
  }
  get height() {
    return this._inputs[1];
  }
  get subdivisions() {
    return this._inputs[2];
  }
  get subdivisionsX() {
    return this._inputs[3];
  }
  get subdivisionsY() {
    return this._inputs[4];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.width.isConnected) {
      const widthInput = new GeometryInputBlock("Width");
      widthInput.value = 1;
      widthInput.output.connectTo(this.width);
    }
    if (!this.height.isConnected) {
      const heightInput = new GeometryInputBlock("Height");
      heightInput.value = 1;
      heightInput.output.connectTo(this.height);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.width = this.width.getConnectedValue(state2);
      options.height = this.height.getConnectedValue(state2);
      options.subdivisions = this.subdivisions.getConnectedValue(state2);
      options.subdivisionsX = this.subdivisionsX.getConnectedValue(state2);
      options.subdivisionsY = this.subdivisionsY.getConnectedValue(state2);
      return CreateGroundVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GridBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.GridBlock", GridBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/torusBlock.js
init_tslib_es6();
init_typeStore();
class TorusBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("thickness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5);
    this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "TorusBlock";
  }
  get diameter() {
    return this._inputs[0];
  }
  get thickness() {
    return this._inputs[1];
  }
  get tessellation() {
    return this._inputs[2];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.diameter.isConnected) {
      const diameterInput = new GeometryInputBlock("Diameter");
      diameterInput.value = 1;
      diameterInput.output.connectTo(this.diameter);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.thickness = this.thickness.getConnectedValue(state2);
      options.diameter = this.diameter.getConnectedValue(state2);
      options.tessellation = this.tessellation.getConnectedValue(state2);
      return CreateTorusVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], TorusBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.TorusBlock", TorusBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/cylinderBlock.js
init_tslib_es6();
init_typeStore();
class CylinderBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 25);
    this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("diameterTop", NodeGeometryBlockConnectionPointTypes.Float, true, -1);
    this.registerInput("diameterBottom", NodeGeometryBlockConnectionPointTypes.Float, true, -1);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1);
    this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 24);
    this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "CylinderBlock";
  }
  get height() {
    return this._inputs[0];
  }
  get diameter() {
    return this._inputs[1];
  }
  get diameterTop() {
    return this._inputs[2];
  }
  get diameterBottom() {
    return this._inputs[3];
  }
  get subdivisions() {
    return this._inputs[4];
  }
  get tessellation() {
    return this._inputs[5];
  }
  get arc() {
    return this._inputs[6];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.diameter.isConnected) {
      const diameterInput = new GeometryInputBlock("Diameter");
      diameterInput.value = 1;
      diameterInput.output.connectTo(this.diameter);
    }
    if (!this.height.isConnected) {
      const heightInput = new GeometryInputBlock("Height");
      heightInput.value = 1;
      heightInput.output.connectTo(this.height);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.height = this.height.getConnectedValue(state2);
      options.diameter = this.diameter.getConnectedValue(state2);
      options.diameterTop = this.diameterTop.getConnectedValue(state2);
      options.diameterBottom = this.diameterBottom.getConnectedValue(state2);
      if (options.diameterTop === -1) {
        options.diameterTop = options.diameter;
      }
      if (options.diameterBottom === -1) {
        options.diameterBottom = options.diameter;
      }
      options.tessellation = this.tessellation.getConnectedValue(state2);
      options.subdivisions = this.subdivisions.getConnectedValue(state2);
      options.arc = this.arc.getConnectedValue(state2);
      return CreateCylinderVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], CylinderBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.CylinderBlock", CylinderBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/capsuleBlock.js
init_tslib_es6();
init_typeStore();
class CapsuleBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.25);
    this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16);
    this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 2);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "CapsuleBlock";
  }
  get height() {
    return this._inputs[0];
  }
  get radius() {
    return this._inputs[1];
  }
  get tessellation() {
    return this._inputs[2];
  }
  get subdivisions() {
    return this._inputs[3];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.height.isConnected) {
      const heightInput = new GeometryInputBlock("Height");
      heightInput.value = 1;
      heightInput.output.connectTo(this.height);
    }
    if (!this.radius.isConnected) {
      const radiusInput = new GeometryInputBlock("Radius");
      radiusInput.value = 0.2;
      radiusInput.output.connectTo(this.radius);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.height = this.height.getConnectedValue(state2);
      options.radius = this.radius.getConnectedValue(state2);
      options.tessellation = this.tessellation.getConnectedValue(state2);
      options.subdivisions = this.subdivisions.getConnectedValue(state2);
      return CreateCapsuleVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], CapsuleBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.CapsuleBlock", CapsuleBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/discBlock.js
init_tslib_es6();
init_typeStore();
class DiscBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5);
    this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 64);
    this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "DiscBlock";
  }
  get radius() {
    return this._inputs[0];
  }
  get tessellation() {
    return this._inputs[1];
  }
  get arc() {
    return this._inputs[2];
  }
  get geometry() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.radius.isConnected) {
      const radiusInput = new GeometryInputBlock("Radius");
      radiusInput.value = 0.2;
      radiusInput.output.connectTo(this.radius);
    }
  }
  _buildBlock(state) {
    const options = {};
    const func = (state2) => {
      options.radius = this.radius.getConnectedValue(state2);
      options.tessellation = this.tessellation.getConnectedValue(state2);
      options.arc = this.arc.getConnectedValue(state2);
      return CreateDiscVertexData(options);
    };
    if (this.evaluateContext) {
      this.geometry._storedFunction = func;
    } else {
      const value = func(state);
      this.geometry._storedFunction = () => {
        this.geometry._executionCount = 1;
        return value.clone();
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], DiscBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.DiscBlock", DiscBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/nullBlock.js
init_typeStore();

class NullBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("vector", NodeGeometryBlockConnectionPointTypes.Vector3);
  }
  getClassName() {
    return "NullBlock";
  }
  get geometry() {
    return this._outputs[0];
  }
  get vector() {
    return this._outputs[1];
  }
  _buildBlock() {
    this.geometry._storedValue = null;
    this.vector._storedValue = null;
  }
}
RegisterClass("BABYLON.NullBlock", NullBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/pointListBlock.js
init_typeStore();
init_math_vector();
class PointListBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.points = [];
    this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "PointListBlock";
  }
  get geometry() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    this.geometry._storedFunction = () => {
      this.geometry._executionCount = 1;
      if (this.points.length === 0) {
        return null;
      }
      const vertexData = new VertexData;
      vertexData.positions = this.points.reduce((acc, point) => {
        acc.push(point.x, point.y, point.z);
        return acc;
      }, []);
      return vertexData;
    };
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.points = [];
`;
    for (let i = 0;i < this.points.length; i++) {
      const point = this.points[i];
      codeString += `${this._codeVariableName}.points.push(new BABYLON.Vector3(${point.x}, ${point.y}, ${point.z}));
`;
    }
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.points = this.points.map((point) => {
      return point.asArray();
    });
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.points = serializationObject.points.map((point) => {
      return Vector3.FromArray(point);
    });
  }
}
RegisterClass("BABYLON.PointListBlock", PointListBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setPositionsBlock.js
init_tslib_es6();
init_typeStore();
class SetPositionsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("positions", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "SetPositionsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get positions() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _remapVector3Data(source, remap) {
    const newData = [];
    for (let index = 0;index < source.length; index += 3) {
      const remappedIndex = remap[index / 3];
      if (remappedIndex !== undefined) {
        newData.push(source[index], source[index + 1], source[index + 2]);
      }
    }
    return newData;
  }
  _remapVector4Data(source, remap) {
    const newData = [];
    for (let index = 0;index < source.length; index += 4) {
      const remappedIndex = remap[index / 4];
      if (remappedIndex !== undefined) {
        newData.push(source[index], source[index + 1], source[index + 2], source[index + 3]);
      }
    }
    return newData;
  }
  _remapVector2Data(source, remap) {
    const newData = [];
    for (let index = 0;index < source.length; index += 2) {
      const remappedIndex = remap[index / 2];
      if (remappedIndex !== undefined) {
        newData.push(source[index], source[index + 1]);
      }
    }
    return newData;
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions || !this.positions.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      const remap = {};
      const vertexCount = this._vertexData.positions.length / 3;
      const newPositions = [];
      let activeIndex = 0;
      let resize = false;
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        const tempVector3 = this.positions.getConnectedValue(state2);
        if (tempVector3) {
          tempVector3.toArray(newPositions, activeIndex * 3);
          remap[this._currentIndex] = activeIndex;
          activeIndex++;
        } else {
          resize = true;
        }
      }
      if (resize) {
        if (this._vertexData.indices) {
          const newIndices = [];
          for (let index = 0;index < this._vertexData.indices.length; index += 3) {
            const a = this._vertexData.indices[index];
            const b = this._vertexData.indices[index + 1];
            const c = this._vertexData.indices[index + 2];
            const remappedA = remap[a];
            const remappedB = remap[b];
            const remappedC = remap[c];
            if (remappedA !== undefined && remappedB !== undefined && remappedC !== undefined) {
              newIndices.push(remappedA);
              newIndices.push(remappedB);
              newIndices.push(remappedC);
            }
          }
          this._vertexData.indices = newIndices;
        }
        if (this._vertexData.normals) {
          this._vertexData.normals = this._remapVector3Data(this._vertexData.normals, remap);
        }
        if (this._vertexData.tangents) {
          this._vertexData.tangents = this._remapVector4Data(this._vertexData.tangents, remap);
        }
        if (this._vertexData.colors) {
          this._vertexData.colors = this._remapVector4Data(this._vertexData.colors, remap);
        }
        if (this._vertexData.uvs) {
          this._vertexData.uvs = this._remapVector2Data(this._vertexData.uvs, remap);
        }
        if (this._vertexData.uvs2) {
          this._vertexData.uvs2 = this._remapVector2Data(this._vertexData.uvs2, remap);
        }
        if (this._vertexData.uvs3) {
          this._vertexData.uvs3 = this._remapVector2Data(this._vertexData.uvs3, remap);
        }
        if (this._vertexData.uvs4) {
          this._vertexData.uvs4 = this._remapVector2Data(this._vertexData.uvs4, remap);
        }
        if (this._vertexData.uvs5) {
          this._vertexData.uvs5 = this._remapVector2Data(this._vertexData.uvs5, remap);
        }
        if (this._vertexData.uvs6) {
          this._vertexData.uvs6 = this._remapVector2Data(this._vertexData.uvs6, remap);
        }
      }
      this._vertexData.positions = newPositions;
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetPositionsBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SetPositionsBlock", SetPositionsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setNormalsBlock.js
init_tslib_es6();
init_typeStore();
class SetNormalsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("normals", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "SetNormalsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get normals() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      if (!this.normals.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = this._vertexData;
        return;
      }
      if (!this._vertexData.normals) {
        this._vertexData.normals = [];
      }
      const vertexCount = this._vertexData.positions.length / 3;
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        const tempVector3 = this.normals.getConnectedValue(state2);
        if (tempVector3) {
          tempVector3.toArray(this._vertexData.normals, this._currentIndex * 3);
        }
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetNormalsBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SetNormalsBlock", SetNormalsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setUVsBlock.js
init_tslib_es6();
init_typeStore();
class SetUVsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.textureCoordinateIndex = 0;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("uvs", NodeGeometryBlockConnectionPointTypes.Vector2);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "SetUVsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get uvs() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      if (!this.uvs.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = this._vertexData;
        return;
      }
      const uvs = [];
      const vertexCount = this._vertexData.positions.length / 3;
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        const tempVector2 = this.uvs.getConnectedValue(state2);
        if (tempVector2) {
          tempVector2.toArray(uvs, this._currentIndex * 2);
        }
      }
      switch (this.textureCoordinateIndex) {
        case 0:
          this._vertexData.uvs = uvs;
          break;
        case 1:
          this._vertexData.uvs2 = uvs;
          break;
        case 2:
          this._vertexData.uvs3 = uvs;
          break;
        case 3:
          this._vertexData.uvs4 = uvs;
          break;
        case 4:
          this._vertexData.uvs5 = uvs;
          break;
        case 5:
          this._vertexData.uvs6 = uvs;
          break;
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.textureCoordinateIndex};
`;
    codeString += `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.textureCoordinateIndex = this.textureCoordinateIndex;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.textureCoordinateIndex = serializationObject.textureCoordinateIndex;
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetUVsBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("Texture coordinates index", 4, "ADVANCED", {
    notifiers: { update: true },
    embedded: true,
    options: [
      { label: "UV1", value: 0 },
      { label: "UV2", value: 1 },
      { label: "UV3", value: 2 },
      { label: "UV4", value: 3 },
      { label: "UV5", value: 4 },
      { label: "UV6", value: 5 }
    ]
  })
], SetUVsBlock.prototype, "textureCoordinateIndex", undefined);
RegisterClass("BABYLON.SetUVsBlock", SetUVsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setColorsBlock.js
init_tslib_es6();
init_typeStore();
class SetColorsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("colors", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "SetColorsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get colors() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      if (!this.colors.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = this._vertexData;
        return;
      }
      if (!this._vertexData.colors) {
        this._vertexData.colors = [];
      }
      const vertexCount = this._vertexData.positions.length / 3;
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        if (this.colors.connectedPoint?.type === NodeGeometryBlockConnectionPointTypes.Vector3) {
          const tempVector3 = this.colors.getConnectedValue(state2);
          if (tempVector3) {
            tempVector3.toArray(this._vertexData.colors, this._currentIndex * 4);
            this._vertexData.colors[this._currentIndex * 4 + 3] = 1;
            this._vertexData.hasVertexAlpha = false;
          }
        } else {
          const tempVector4 = this.colors.getConnectedValue(state2);
          if (tempVector4) {
            tempVector4.toArray(this._vertexData.colors, this._currentIndex * 4);
            this._vertexData.hasVertexAlpha = true;
          }
        }
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetColorsBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SetColorsBlock", SetColorsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setTangentsBlock.js
init_tslib_es6();
init_typeStore();
class SetTangentsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("tangents", NodeGeometryBlockConnectionPointTypes.Vector4);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "SetTangentsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get tangents() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      if (!this.tangents.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = this._vertexData;
        return;
      }
      if (!this._vertexData.tangents) {
        this._vertexData.tangents = [];
      }
      const vertexCount = this._vertexData.positions.length / 3;
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        const tempVector4 = this.tangents.getConnectedValue(state2);
        if (tempVector4) {
          tempVector4.toArray(this._vertexData.tangents, this._currentIndex * 4);
        }
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetTangentsBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SetTangentsBlock", SetTangentsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/mathBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var MathBlockOperations;
(function(MathBlockOperations2) {
  MathBlockOperations2[MathBlockOperations2["Add"] = 0] = "Add";
  MathBlockOperations2[MathBlockOperations2["Subtract"] = 1] = "Subtract";
  MathBlockOperations2[MathBlockOperations2["Multiply"] = 2] = "Multiply";
  MathBlockOperations2[MathBlockOperations2["Divide"] = 3] = "Divide";
  MathBlockOperations2[MathBlockOperations2["Max"] = 4] = "Max";
  MathBlockOperations2[MathBlockOperations2["Min"] = 5] = "Min";
})(MathBlockOperations || (MathBlockOperations = {}));

class MathBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.operation = MathBlockOperations.Add;
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this.output._typeConnectionSource = this.left;
    const excludedConnectionPointTypes = [
      NodeGeometryBlockConnectionPointTypes.Matrix,
      NodeGeometryBlockConnectionPointTypes.Geometry,
      NodeGeometryBlockConnectionPointTypes.Texture
    ];
    this.left.excludedConnectionPointTypes.push(...excludedConnectionPointTypes);
    this.right.excludedConnectionPointTypes.push(...excludedConnectionPointTypes);
    this._linkConnectionTypes(0, 1);
    this._connectionObservers = [
      this.left.onConnectionObservable.add(() => this._updateInputOutputTypes()),
      this.left.onDisconnectionObservable.add(() => this._updateInputOutputTypes()),
      this.right.onConnectionObservable.add(() => this._updateInputOutputTypes()),
      this.right.onDisconnectionObservable.add(() => this._updateInputOutputTypes())
    ];
  }
  getClassName() {
    return "MathBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    let func;
    const left = this.left;
    const right = this.right;
    if (!left.isConnected || !right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const leftIsScalar = left.type === NodeGeometryBlockConnectionPointTypes.Float || left.type === NodeGeometryBlockConnectionPointTypes.Int;
    const rightIsScalar = right.type === NodeGeometryBlockConnectionPointTypes.Float || right.type === NodeGeometryBlockConnectionPointTypes.Int;
    const isScalar = leftIsScalar && rightIsScalar;
    switch (this.operation) {
      case MathBlockOperations.Add: {
        if (isScalar) {
          func = (state) => {
            return left.getConnectedValue(state) + right.getConnectedValue(state);
          };
        } else if (leftIsScalar) {
          func = (state) => {
            return state.adapt(left, right.type).add(right.getConnectedValue(state));
          };
        } else {
          func = (state) => {
            return left.getConnectedValue(state).add(state.adapt(right, left.type));
          };
        }
        break;
      }
      case MathBlockOperations.Subtract: {
        if (isScalar) {
          func = (state) => {
            return left.getConnectedValue(state) - right.getConnectedValue(state);
          };
        } else if (leftIsScalar) {
          func = (state) => {
            return state.adapt(left, right.type).subtract(right.getConnectedValue(state));
          };
        } else {
          func = (state) => {
            return left.getConnectedValue(state).subtract(state.adapt(right, left.type));
          };
        }
        break;
      }
      case MathBlockOperations.Multiply: {
        if (isScalar) {
          func = (state) => {
            return left.getConnectedValue(state) * right.getConnectedValue(state);
          };
        } else if (leftIsScalar) {
          func = (state) => {
            return state.adapt(left, right.type).multiply(right.getConnectedValue(state));
          };
        } else {
          func = (state) => {
            return left.getConnectedValue(state).multiply(state.adapt(right, left.type));
          };
        }
        break;
      }
      case MathBlockOperations.Divide: {
        if (isScalar) {
          func = (state) => {
            return left.getConnectedValue(state) / right.getConnectedValue(state);
          };
        } else if (leftIsScalar) {
          func = (state) => {
            return state.adapt(left, right.type).divide(right.getConnectedValue(state));
          };
        } else {
          func = (state) => {
            return left.getConnectedValue(state).divide(state.adapt(right, left.type));
          };
        }
        break;
      }
      case MathBlockOperations.Min: {
        if (isScalar) {
          func = (state) => {
            return Math.min(left.getConnectedValue(state), right.getConnectedValue(state));
          };
        } else {
          const [vector, scalar] = leftIsScalar ? [right, left] : [left, right];
          switch (vector.type) {
            case NodeGeometryBlockConnectionPointTypes.Vector2: {
              func = (state) => {
                return Vector2.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
            case NodeGeometryBlockConnectionPointTypes.Vector3: {
              func = (state) => {
                return Vector3.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
            case NodeGeometryBlockConnectionPointTypes.Vector4: {
              func = (state) => {
                return Vector4.Minimize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
          }
        }
        break;
      }
      case MathBlockOperations.Max: {
        if (isScalar) {
          func = (state) => {
            return Math.max(left.getConnectedValue(state), right.getConnectedValue(state));
          };
        } else {
          const [vector, scalar] = leftIsScalar ? [right, left] : [left, right];
          switch (vector.type) {
            case NodeGeometryBlockConnectionPointTypes.Vector2: {
              func = (state) => {
                return Vector2.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
            case NodeGeometryBlockConnectionPointTypes.Vector3: {
              func = (state) => {
                return Vector3.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
            case NodeGeometryBlockConnectionPointTypes.Vector4: {
              func = (state) => {
                return Vector4.Maximize(vector.getConnectedValue(state), state.adapt(scalar, vector.type));
              };
              break;
            }
          }
          break;
        }
      }
    }
    this.output._storedFunction = (state) => {
      if (left.type === NodeGeometryBlockConnectionPointTypes.Int) {
        return func(state) | 0;
      }
      return func(state);
    };
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${MathBlockOperations[this.operation]};
`;
    return codeString;
  }
  _updateInputOutputTypes() {
    this.output._typeConnectionSource = this.left;
    if (this.left.isConnected && this.right.isConnected) {
      if (this.left.type === NodeGeometryBlockConnectionPointTypes.Int || this.left.type === NodeGeometryBlockConnectionPointTypes.Float && this.right.type !== NodeGeometryBlockConnectionPointTypes.Int) {
        this.output._typeConnectionSource = this.right;
      }
    } else if (this.left.isConnected !== this.right.isConnected) {
      this.output._typeConnectionSource = this.left.isConnected ? this.left : this.right;
    }
    if (this.left.isConnected || this.right.isConnected) {
      for (const [first, second] of [
        [this.left, this.right],
        [this.right, this.left]
      ]) {
        first.acceptedConnectionPointTypes = [NodeGeometryBlockConnectionPointTypes.Int, NodeGeometryBlockConnectionPointTypes.Float];
        if (second.isConnected) {
          first.acceptedConnectionPointTypes.push(second.type);
          if (second.type === NodeGeometryBlockConnectionPointTypes.Int || second.type === NodeGeometryBlockConnectionPointTypes.Float) {
            first.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2, NodeGeometryBlockConnectionPointTypes.Vector3, NodeGeometryBlockConnectionPointTypes.Vector4);
          }
        }
      }
    }
  }
  dispose() {
    super.dispose();
    this._connectionObservers.forEach((observer2) => observer2.remove());
    this._connectionObservers.length = 0;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.operation = this.operation;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.operation = serializationObject.operation;
  }
}
__decorate([
  editableInPropertyPage("Operation", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Add", value: MathBlockOperations.Add },
      { label: "Subtract", value: MathBlockOperations.Subtract },
      { label: "Multiply", value: MathBlockOperations.Multiply },
      { label: "Divide", value: MathBlockOperations.Divide },
      { label: "Max", value: MathBlockOperations.Max },
      { label: "Min", value: MathBlockOperations.Min }
    ]
  })
], MathBlock.prototype, "operation", undefined);
RegisterClass("BABYLON.MathBlock", MathBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/mapRangeBlock.js
init_typeStore();
class MapRangeBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("fromMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("fromMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("toMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("toMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector3);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector4);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "MapRangeBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get fromMin() {
    return this._inputs[1];
  }
  get fromMax() {
    return this._inputs[2];
  }
  get toMin() {
    return this._inputs[3];
  }
  get toMax() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const value = this.value.getConnectedValue(state);
      const fromMin = this.fromMin.getConnectedValue(state);
      const fromMax = this.fromMax.getConnectedValue(state);
      const toMin = this.toMin.getConnectedValue(state);
      const toMax = this.toMax.getConnectedValue(state);
      const result = (value - fromMin) / (fromMax - fromMin) * (toMax - toMin) + toMin;
      if (this.output.type === NodeGeometryBlockConnectionPointTypes.Int) {
        return Math.floor(result);
      }
      return result;
    };
  }
}
RegisterClass("BABYLON.MapRangeBlock", MapRangeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/conditionBlock.js
init_tslib_es6();
init_typeStore();
var ConditionBlockTests;
(function(ConditionBlockTests2) {
  ConditionBlockTests2[ConditionBlockTests2["Equal"] = 0] = "Equal";
  ConditionBlockTests2[ConditionBlockTests2["NotEqual"] = 1] = "NotEqual";
  ConditionBlockTests2[ConditionBlockTests2["LessThan"] = 2] = "LessThan";
  ConditionBlockTests2[ConditionBlockTests2["GreaterThan"] = 3] = "GreaterThan";
  ConditionBlockTests2[ConditionBlockTests2["LessOrEqual"] = 4] = "LessOrEqual";
  ConditionBlockTests2[ConditionBlockTests2["GreaterOrEqual"] = 5] = "GreaterOrEqual";
  ConditionBlockTests2[ConditionBlockTests2["Xor"] = 6] = "Xor";
  ConditionBlockTests2[ConditionBlockTests2["Or"] = 7] = "Or";
  ConditionBlockTests2[ConditionBlockTests2["And"] = 8] = "And";
})(ConditionBlockTests || (ConditionBlockTests = {}));

class ConditionBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.test = ConditionBlockTests.Equal;
    this.epsilon = 0;
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("ifTrue", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 1);
    this.registerInput("ifFalse", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 0);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[2];
    this._outputs[0]._defaultConnectionPointType = NodeGeometryBlockConnectionPointTypes.Float;
    this._inputs[0].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[1].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._linkConnectionTypes(2, 3);
  }
  getClassName() {
    return "ConditionBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get ifTrue() {
    return this._inputs[2];
  }
  get ifFalse() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure(nodeGeometry) {
    if (!this.ifTrue.isConnected) {
      const minInput = nodeGeometry.getBlockByPredicate((b) => b.isInput && b.value === 1 && b.name === "True") || new GeometryInputBlock("True");
      minInput.value = 1;
      minInput.output.connectTo(this.ifTrue);
    }
    if (!this.ifFalse.isConnected) {
      const maxInput = nodeGeometry.getBlockByPredicate((b) => b.isInput && b.value === 0 && b.name === "False") || new GeometryInputBlock("False");
      maxInput.value = 0;
      maxInput.output.connectTo(this.ifFalse);
    }
  }
  _buildBlock() {
    if (!this.left.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      let condition2 = false;
      switch (this.test) {
        case ConditionBlockTests.Equal:
          condition2 = WithinEpsilon(left, right, this.epsilon);
          break;
        case ConditionBlockTests.NotEqual:
          condition2 = !WithinEpsilon(left, right, this.epsilon);
          break;
        case ConditionBlockTests.LessThan:
          condition2 = left < right + this.epsilon;
          break;
        case ConditionBlockTests.GreaterThan:
          condition2 = left > right - this.epsilon;
          break;
        case ConditionBlockTests.LessOrEqual:
          condition2 = left <= right + this.epsilon;
          break;
        case ConditionBlockTests.GreaterOrEqual:
          condition2 = left >= right - this.epsilon;
          break;
        case ConditionBlockTests.Xor:
          condition2 = !!left && !right || !left && !!right;
          break;
        case ConditionBlockTests.Or:
          condition2 = !!left || !!right;
          break;
        case ConditionBlockTests.And:
          condition2 = !!left && !!right;
          break;
      }
      return condition2;
    };
    this.output._storedFunction = (state) => {
      if (func(state)) {
        return this.ifTrue.getConnectedValue(state);
      }
      return this.ifFalse.getConnectedValue(state);
    };
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${ConditionBlockTests[this.test]};
`;
    codeString += `${this._codeVariableName}.epsilon = ${this.epsilon};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.test = this.test;
    serializationObject.epsilon = this.epsilon;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.test = serializationObject.test;
    if (serializationObject.epsilon !== undefined) {
      this.epsilon = serializationObject.epsilon;
    }
  }
}
__decorate([
  editableInPropertyPage("Test", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Equal", value: ConditionBlockTests.Equal },
      { label: "NotEqual", value: ConditionBlockTests.NotEqual },
      { label: "LessThan", value: ConditionBlockTests.LessThan },
      { label: "GreaterThan", value: ConditionBlockTests.GreaterThan },
      { label: "LessOrEqual", value: ConditionBlockTests.LessOrEqual },
      { label: "GreaterOrEqual", value: ConditionBlockTests.GreaterOrEqual },
      { label: "Xor", value: ConditionBlockTests.Xor },
      { label: "Or", value: ConditionBlockTests.Or },
      { label: "And", value: ConditionBlockTests.And }
    ]
  })
], ConditionBlock.prototype, "test", undefined);
__decorate([
  editableInPropertyPage("Epsilon", 1, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], ConditionBlock.prototype, "epsilon", undefined);
RegisterClass("BABYLON.ConditionBlock", ConditionBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/randomBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var RandomBlockLocks;
(function(RandomBlockLocks2) {
  RandomBlockLocks2[RandomBlockLocks2["None"] = 0] = "None";
  RandomBlockLocks2[RandomBlockLocks2["LoopID"] = 1] = "LoopID";
  RandomBlockLocks2[RandomBlockLocks2["InstanceID"] = 2] = "InstanceID";
  RandomBlockLocks2[RandomBlockLocks2["Once"] = 3] = "Once";
})(RandomBlockLocks || (RandomBlockLocks = {}));

class RandomBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._currentLockId = -1;
    this.lockMode = RandomBlockLocks.None;
    this.registerInput("min", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("max", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "RandomBlock";
  }
  get min() {
    return this._inputs[0];
  }
  get max() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.min.isConnected) {
      const minInput = new GeometryInputBlock("Min");
      minInput.value = 0;
      minInput.output.connectTo(this.min);
    }
    if (!this.max.isConnected) {
      const maxInput = new GeometryInputBlock("Max");
      maxInput.value = 1;
      maxInput.output.connectTo(this.max);
    }
  }
  _buildBlock() {
    let func = null;
    this._currentLockId = -1;
    switch (this.min.type) {
      case NodeGeometryBlockConnectionPointTypes.Int:
      case NodeGeometryBlockConnectionPointTypes.Float: {
        func = (state) => {
          const min = this.min.getConnectedValue(state) || 0;
          const max = this.max.getConnectedValue(state) || 0;
          return min + Math.random() * (max - min);
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector2: {
        func = (state) => {
          const min = this.min.getConnectedValue(state) || Vector2.Zero();
          const max = this.max.getConnectedValue(state) || Vector2.Zero();
          return new Vector2(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector3: {
        func = (state) => {
          const min = this.min.getConnectedValue(state) || Vector3.Zero();
          const max = this.max.getConnectedValue(state) || Vector3.Zero();
          return new Vector3(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector4: {
        func = (state) => {
          const min = this.min.getConnectedValue(state) || Vector4.Zero();
          const max = this.max.getConnectedValue(state) || Vector4.Zero();
          return new Vector4(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z), min.w + Math.random() * (max.w - min.w));
        };
        break;
      }
    }
    if (this.lockMode === RandomBlockLocks.None || !func) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = (state) => {
        let lockId = 0;
        switch (this.lockMode) {
          case RandomBlockLocks.InstanceID:
            lockId = state.getContextualValue(NodeGeometryContextualSources.InstanceID, true) || 0;
            break;
          case RandomBlockLocks.LoopID:
            lockId = state.getContextualValue(NodeGeometryContextualSources.LoopID, true) || 0;
            break;
          case RandomBlockLocks.Once:
            lockId = state.buildId || 0;
            break;
        }
        if (this._currentLockId !== lockId || this.lockMode === RandomBlockLocks.None) {
          this._currentLockId = lockId;
          this.output._storedValue = func(state);
        }
        return this.output._storedValue;
      };
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${RandomBlockLocks[this.lockMode]};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.lockMode = this.lockMode;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.lockMode = serializationObject.lockMode;
  }
}
__decorate([
  editableInPropertyPage("LockMode", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "None", value: RandomBlockLocks.None },
      { label: "LoopID", value: RandomBlockLocks.LoopID },
      { label: "InstanceID", value: RandomBlockLocks.InstanceID },
      { label: "Once", value: RandomBlockLocks.Once }
    ]
  })
], RandomBlock.prototype, "lockMode", undefined);
RegisterClass("BABYLON.RandomBlock", RandomBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/noiseBlock.js
init_typeStore();
init_math_vector();
class NoiseBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerInput("octaves", NodeGeometryBlockConnectionPointTypes.Float, true, 2, 0, 16);
    this.registerInput("roughness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5, 0, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "NoiseBlock";
  }
  get offset() {
    return this._inputs[0];
  }
  get scale() {
    return this._inputs[1];
  }
  get octaves() {
    return this._inputs[2];
  }
  get roughness() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  _negateIf(value, condition2) {
    return condition2 !== 0 ? -value : value;
  }
  _noiseGrad(hash2, x, y, z) {
    const h = hash2 & 15;
    const u = h < 8 ? x : y;
    const vt = h === 12 || h == 14 ? x : z;
    const v = h < 4 ? y : vt;
    return this._negateIf(u, h & u) + this._negateIf(v, h & 2);
  }
  _fade(t) {
    return t * t * t * (t * (t * 6 - 15) + 10);
  }
  _hashBitRotate(x, k) {
    return x << k | x >> 32 - k;
  }
  _hash(kx, ky, kz) {
    let a, b, c;
    a = b = c = 3735928559 + (3 << 2) + 13;
    c += kz;
    b += ky;
    a += kx;
    c ^= b;
    c -= this._hashBitRotate(b, 14);
    a ^= c;
    a -= this._hashBitRotate(c, 11);
    b ^= a;
    b -= this._hashBitRotate(a, 25);
    c ^= b;
    c -= this._hashBitRotate(b, 16);
    a ^= c;
    a -= this._hashBitRotate(c, 4);
    b ^= a;
    b -= this._hashBitRotate(a, 14);
    c ^= b;
    c -= this._hashBitRotate(b, 24);
    return c;
  }
  _mix(v0, v1, v2, v3, v4, v5, v6, v7, x, y, z) {
    const x1 = 1 - x;
    const y1 = 1 - y;
    const z1 = 1 - z;
    return z1 * (y1 * (v0 * x1 + v1 * x) + y * (v2 * x1 + v3 * x)) + z * (y1 * (v4 * x1 + v5 * x) + y * (v6 * x1 + v7 * x));
  }
  _perlinNoise(position) {
    const X = (position.x | 0) - (position.x < 0 ? 1 : 0);
    const Y = (position.y | 0) - (position.y < 0 ? 1 : 0);
    const Z = (position.z | 0) - (position.z < 0 ? 1 : 0);
    const fx = position.x - X;
    const fy = position.y - Y;
    const fz = position.z - Z;
    const u = this._fade(fx);
    const v = this._fade(fy);
    const w = this._fade(fz);
    return this._mix(this._noiseGrad(this._hash(X, Y, Z), fx, fy, fz), this._noiseGrad(this._hash(X + 1, Y, Z), fx - 1, fy, fz), this._noiseGrad(this._hash(X, Y + 1, Z), fx, fy - 1, fz), this._noiseGrad(this._hash(X + 1, Y + 1, Z), fx - 1, fy - 1, fz), this._noiseGrad(this._hash(X, Y, Z + 1), fx, fy, fz - 1), this._noiseGrad(this._hash(X + 1, Y, Z + 1), fx - 1, fy, fz - 1), this._noiseGrad(this._hash(X, Y + 1, Z + 1), fx, fy - 1, fz - 1), this._noiseGrad(this._hash(X + 1, Y + 1, Z + 1), fx - 1, fy - 1, fz - 1), u, v, w);
  }
  _perlinSigned(position) {
    return this._perlinNoise(position) * 0.982;
  }
  _perlin(position) {
    return this._perlinSigned(position) / 2 + 0.5;
  }
  noise(octaves, roughness, _position, offset, scale) {
    const position = new Vector3(_position.x * scale + offset.x, _position.y * scale + offset.y, _position.z * scale + offset.z);
    let fscale = 1;
    let amp = 1;
    let maxamp = 0;
    let sum = 0;
    octaves = Clamp(octaves, 0, 15);
    const step = octaves | 0;
    for (let i = 0;i <= step; i++) {
      const t2 = this._perlin(position.scale(fscale));
      sum += t2 * amp;
      maxamp += amp;
      amp *= Clamp(roughness, 0, 1);
      fscale *= 2;
    }
    const rmd = octaves - Math.floor(octaves);
    if (rmd == 0) {
      return sum / maxamp;
    }
    const t = this._perlin(position.scale(fscale));
    let sum2 = sum + t * amp;
    sum /= maxamp;
    sum2 /= maxamp + amp;
    return (1 - rmd) * sum + rmd * sum2;
  }
  _buildBlock() {
    this.output._storedFunction = (state) => {
      const position = state.getContextualValue(NodeGeometryContextualSources.Positions);
      const octaves = this.octaves.getConnectedValue(state);
      const roughness = this.roughness.getConnectedValue(state);
      const offset = this.offset.getConnectedValue(state);
      const scale = this.scale.getConnectedValue(state);
      return this.noise(octaves, roughness, position, offset, scale);
    };
  }
}
RegisterClass("BABYLON.NoiseBlock", NoiseBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/mergeGeometryBlock.js
init_tslib_es6();
init_typeStore();
class MergeGeometryBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "MergeGeometryBlock";
  }
  get geometry0() {
    return this._inputs[0];
  }
  get geometry1() {
    return this._inputs[1];
  }
  get geometry2() {
    return this._inputs[2];
  }
  get geometry3() {
    return this._inputs[3];
  }
  get geometry4() {
    return this._inputs[4];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      const vertexDataSource = [];
      if (this.geometry0.isConnected) {
        const data = this.geometry0.getConnectedValue(state2);
        if (data) {
          vertexDataSource.push(data);
        }
      }
      if (this.geometry1.isConnected) {
        const data = this.geometry1.getConnectedValue(state2);
        if (data) {
          vertexDataSource.push(data);
        }
      }
      if (this.geometry2.isConnected) {
        const data = this.geometry2.getConnectedValue(state2);
        if (data) {
          vertexDataSource.push(data);
        }
      }
      if (this.geometry3.isConnected) {
        const data = this.geometry3.getConnectedValue(state2);
        if (data) {
          vertexDataSource.push(data);
        }
      }
      if (this.geometry4.isConnected) {
        const data = this.geometry4.getConnectedValue(state2);
        if (data) {
          vertexDataSource.push(data);
        }
      }
      if (vertexDataSource.length === 0) {
        return null;
      }
      let vertexData = vertexDataSource[0].clone();
      const additionalVertexData = vertexDataSource.slice(1);
      if (additionalVertexData.length && vertexData) {
        vertexData = vertexData.merge(additionalVertexData, true, false, true, true);
      }
      return vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], MergeGeometryBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.MergeGeometryBlock", MergeGeometryBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryCollectionBlock.js
init_tslib_es6();
init_typeStore();
class GeometryCollectionBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry5", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry6", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry7", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry8", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("geometry9", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
  }
  getClassName() {
    return "GeometryCollectionBlock";
  }
  get geometry0() {
    return this._inputs[0];
  }
  get geometry1() {
    return this._inputs[1];
  }
  get geometry2() {
    return this._inputs[2];
  }
  get geometry3() {
    return this._inputs[3];
  }
  get geometry4() {
    return this._inputs[4];
  }
  get geometry5() {
    return this._inputs[5];
  }
  get geometry6() {
    return this._inputs[6];
  }
  get geometry7() {
    return this._inputs[7];
  }
  get geometry8() {
    return this._inputs[8];
  }
  get geometry9() {
    return this._inputs[9];
  }
  get output() {
    return this._outputs[0];
  }
  _storeGeometry(input, state, index, availables) {
    if (input.isConnected) {
      const vertexData = input.getConnectedValue(state);
      if (!vertexData) {
        return;
      }
      vertexData.metadata = vertexData.metadata || {};
      vertexData.metadata.collectionId = index;
      availables.push(vertexData);
    }
  }
  _buildBlock(state) {
    const func = (state2) => {
      const availables = [];
      this._storeGeometry(this.geometry0, state2, 0, availables);
      this._storeGeometry(this.geometry1, state2, 1, availables);
      this._storeGeometry(this.geometry2, state2, 2, availables);
      this._storeGeometry(this.geometry3, state2, 3, availables);
      this._storeGeometry(this.geometry4, state2, 4, availables);
      this._storeGeometry(this.geometry5, state2, 5, availables);
      this._storeGeometry(this.geometry6, state2, 6, availables);
      this._storeGeometry(this.geometry7, state2, 7, availables);
      this._storeGeometry(this.geometry8, state2, 8, availables);
      this._storeGeometry(this.geometry9, state2, 9, availables);
      if (!availables.length) {
        return null;
      }
      return availables[Math.round(Math.random() * (availables.length - 1))];
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryCollectionBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.GeometryCollectionBlock", GeometryCollectionBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/cleanGeometryBlock.js
init_tslib_es6();
init_typeStore();
init_math_functions();

class CleanGeometryBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "CleanGeometryBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      if (!this.geometry.isConnected) {
        return null;
      }
      const vertexData = this.geometry.getConnectedValue(state2).clone();
      if (!vertexData.positions || !vertexData.indices || !vertexData.normals) {
        return vertexData;
      }
      const indices = vertexData.indices;
      const positions = vertexData.positions;
      FixFlippedFaces(positions, indices);
      return vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    return super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], CleanGeometryBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.CleanGeometryBlock", CleanGeometryBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryElbowBlock.js
init_typeStore();
class GeometryElbowBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  get buildExecutionTime() {
    return -1;
  }
  getClassName() {
    return "GeometryElbowBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input = this._inputs[0];
    output._storedFunction = (state2) => {
      return input.getConnectedValue(state2);
    };
  }
}
RegisterClass("BABYLON.GeometryElbowBlock", GeometryElbowBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/computeNormalsBlock.js
init_typeStore();
class ComputeNormalsBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "ComputeNormalsBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    this.output._storedFunction = (state) => {
      if (!this.geometry.isConnected) {
        return null;
      }
      const vertexData = this.geometry.getConnectedValue(state);
      if (!vertexData) {
        return null;
      }
      if (!vertexData.normals) {
        vertexData.normals = [];
      }
      VertexData.ComputeNormals(vertexData.positions, vertexData.indices, vertexData.normals);
      return vertexData;
    };
  }
}
RegisterClass("BABYLON.ComputeNormalsBlock", ComputeNormalsBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/vectorConverterBlock.js
init_math_vector();
init_typeStore();
class VectorConverterBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("xyzw ", NodeGeometryBlockConnectionPointTypes.Vector4, true);
    this.registerInput("xyz ", NodeGeometryBlockConnectionPointTypes.Vector3, true);
    this.registerInput("xy ", NodeGeometryBlockConnectionPointTypes.Vector2, true);
    this.registerInput("zw ", NodeGeometryBlockConnectionPointTypes.Vector2, true);
    this.registerInput("x ", NodeGeometryBlockConnectionPointTypes.Float, true);
    this.registerInput("y ", NodeGeometryBlockConnectionPointTypes.Float, true);
    this.registerInput("z ", NodeGeometryBlockConnectionPointTypes.Float, true);
    this.registerInput("w ", NodeGeometryBlockConnectionPointTypes.Float, true);
    this.registerOutput("xyzw", NodeGeometryBlockConnectionPointTypes.Vector4);
    this.registerOutput("xyz", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("xy", NodeGeometryBlockConnectionPointTypes.Vector2);
    this.registerOutput("zw", NodeGeometryBlockConnectionPointTypes.Vector2);
    this.registerOutput("x", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("y", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("z", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("w", NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "VectorConverterBlock";
  }
  get xyzwIn() {
    return this._inputs[0];
  }
  get xyzIn() {
    return this._inputs[1];
  }
  get xyIn() {
    return this._inputs[2];
  }
  get zwIn() {
    return this._inputs[3];
  }
  get xIn() {
    return this._inputs[4];
  }
  get yIn() {
    return this._inputs[5];
  }
  get zIn() {
    return this._inputs[6];
  }
  get wIn() {
    return this._inputs[7];
  }
  get xyzwOut() {
    return this._outputs[0];
  }
  get xyzOut() {
    return this._outputs[1];
  }
  get xyOut() {
    return this._outputs[2];
  }
  get zwOut() {
    return this._outputs[3];
  }
  get xOut() {
    return this._outputs[4];
  }
  get yOut() {
    return this._outputs[5];
  }
  get zOut() {
    return this._outputs[6];
  }
  get wOut() {
    return this._outputs[7];
  }
  _inputRename(name375) {
    if (name375 === "xyzw ") {
      return "xyzwIn";
    }
    if (name375 === "xyz ") {
      return "xyzIn";
    }
    if (name375 === "xy ") {
      return "xyIn";
    }
    if (name375 === "zw ") {
      return "zwIn";
    }
    if (name375 === "x ") {
      return "xIn";
    }
    if (name375 === "y ") {
      return "yIn";
    }
    if (name375 === "z ") {
      return "zIn";
    }
    if (name375 === "w ") {
      return "wIn";
    }
    return name375;
  }
  _outputRename(name375) {
    switch (name375) {
      case "x":
        return "xOut";
      case "y":
        return "yOut";
      case "z":
        return "zOut";
      case "w":
        return "wOut";
      case "xy":
        return "xyOut";
      case "zw":
        return "zwOut";
      case "xyz":
        return "xyzOut";
      case "xyzw":
        return "xyzwOut";
      default:
        return name375;
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const xInput = this.xIn;
    const yInput = this.yIn;
    const zInput = this.zIn;
    const wInput = this.wIn;
    const xyInput = this.xyIn;
    const zwInput = this.zwIn;
    const xyzInput = this.xyzIn;
    const xyzwInput = this.xyzwIn;
    const xyzwOutput = this.xyzwOut;
    const xyzOutput = this.xyzOut;
    const xyOutput = this.xyOut;
    const zwOutput = this.zwOut;
    const xOutput = this.xOut;
    const yOutput = this.yOut;
    const zOutput = this.zOut;
    const wOutput = this.wOut;
    const getData = (state2) => {
      if (xyzwInput.isConnected) {
        return xyzwInput.getConnectedValue(state2);
      }
      let x = 0;
      let y = 0;
      let z = 0;
      let w = 0;
      if (xInput.isConnected) {
        x = xInput.getConnectedValue(state2);
      }
      if (yInput.isConnected) {
        y = yInput.getConnectedValue(state2);
      }
      if (zInput.isConnected) {
        z = zInput.getConnectedValue(state2);
      }
      if (wInput.isConnected) {
        w = wInput.getConnectedValue(state2);
      }
      if (xyInput.isConnected) {
        const temp = xyInput.getConnectedValue(state2);
        if (temp) {
          x = temp.x;
          y = temp.y;
        }
      }
      if (zwInput.isConnected) {
        const temp = zwInput.getConnectedValue(state2);
        if (temp) {
          z = temp.x;
          w = temp.y;
        }
      }
      if (xyzInput.isConnected) {
        const temp = xyzInput.getConnectedValue(state2);
        if (temp) {
          x = temp.x;
          y = temp.y;
          z = temp.z;
        }
      }
      return new Vector4(x, y, z, w);
    };
    xyzwOutput._storedFunction = (state2) => getData(state2);
    xyzOutput._storedFunction = (state2) => {
      const data = getData(state2);
      return new Vector3(data.x, data.y, data.z);
    };
    xyOutput._storedFunction = (state2) => {
      const data = getData(state2);
      return new Vector2(data.x, data.y);
    };
    zwOutput._storedFunction = (state2) => {
      const data = getData(state2);
      return new Vector2(data.z, data.w);
    };
    xOutput._storedFunction = (state2) => getData(state2).x;
    yOutput._storedFunction = (state2) => getData(state2).y;
    zOutput._storedFunction = (state2) => getData(state2).z;
    wOutput._storedFunction = (state2) => getData(state2).w;
  }
}
RegisterClass("BABYLON.VectorConverterBlock", VectorConverterBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/normalizeVectorBlock.js
init_typeStore();
class NormalizeVectorBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  getClassName() {
    return "NormalizeVectorBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.output._storedFunction = null;
    if (!this.input.isConnected) {
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state2) => this.input.getConnectedValue(state2).normalize();
  }
}
RegisterClass("BABYLON.NormalizeVectorBlock", NormalizeVectorBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setMaterialIDBlock.js
init_tslib_es6();
init_typeStore();
class SetMaterialIDBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("id", NodeGeometryBlockConnectionPointTypes.Int, true, 0);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.id.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "SetMaterialIDBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get id() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    if (!this.geometry.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (state2) => {
      const vertexData = this.geometry.getConnectedValue(state2);
      if (!vertexData || !vertexData.indices || !vertexData.positions) {
        return vertexData;
      }
      const materialInfo = new VertexDataMaterialInfo;
      materialInfo.materialIndex = this.id.getConnectedValue(state2) | 0;
      materialInfo.indexStart = 0;
      materialInfo.indexCount = vertexData.indices.length;
      materialInfo.verticesStart = 0;
      materialInfo.verticesCount = vertexData.positions.length / 3;
      vertexData.materialInfos = [materialInfo];
      return vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SetMaterialIDBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.SetMaterialIDBlock", SetMaterialIDBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/latticeBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
init_math_functions();

class LatticeBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._indexVector3 = new Vector3;
    this._currentControl = new Vector3;
    this.evaluateContext = true;
    this.resolutionX = 3;
    this.resolutionY = 3;
    this.resolutionZ = 3;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("controls", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getExecutionIndex() {
    return this._currentIndexX + this.resolutionX * (this._currentIndexY + this.resolutionY * this._currentIndexZ);
  }
  getExecutionLoopIndex() {
    return this.getExecutionIndex();
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "LatticeBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get controls() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  getOverridePositionsContextualValue() {
    return this._indexVector3;
  }
  getOverrideNormalsContextualValue() {
    return this._currentControl;
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      if (this._vertexData) {
        this._vertexData = this._vertexData.clone();
      }
      if (!this._vertexData || !this._vertexData.positions) {
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      const positions = this._vertexData.positions;
      const boundingInfo2 = extractMinAndMax(positions, 0, positions.length / 3);
      const size = boundingInfo2.maximum.subtract(boundingInfo2.minimum);
      this._lattice = new Lattice({
        resolutionX: this.resolutionX,
        resolutionY: this.resolutionY,
        resolutionZ: this.resolutionZ,
        size,
        position: boundingInfo2.minimum.add(size.scale(0.5))
      });
      for (this._currentIndexX = 0;this._currentIndexX < this.resolutionX; this._currentIndexX++) {
        for (this._currentIndexY = 0;this._currentIndexY < this.resolutionY; this._currentIndexY++) {
          for (this._currentIndexZ = 0;this._currentIndexZ < this.resolutionZ; this._currentIndexZ++) {
            this._indexVector3.set(this._currentIndexX, this._currentIndexY, this._currentIndexZ);
            const latticeControl = this._lattice.data[this._currentIndexX][this._currentIndexY][this._currentIndexZ];
            this._currentControl.copyFrom(latticeControl);
            const tempVector3 = this.controls.getConnectedValue(state2);
            if (tempVector3) {
              latticeControl.set(tempVector3.x, tempVector3.y, tempVector3.z);
            }
          }
        }
      }
      this._lattice.deform(positions);
      state2.restoreExecutionContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.resolutionX = ${this.resolutionX};
`;
    codeString += `${this._codeVariableName}.resolutionY = ${this.resolutionY};
`;
    codeString += `${this._codeVariableName}.resolutionZ = ${this.resolutionZ};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.resolutionX = this.resolutionX;
    serializationObject.resolutionY = this.resolutionY;
    serializationObject.resolutionZ = this.resolutionZ;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
      this.resolutionX = serializationObject.resolutionX;
      this.resolutionY = serializationObject.resolutionY;
      this.resolutionZ = serializationObject.resolutionZ;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], LatticeBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("resolutionX", 2, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 })
], LatticeBlock.prototype, "resolutionX", undefined);
__decorate([
  editableInPropertyPage("resolutionY", 2, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 })
], LatticeBlock.prototype, "resolutionY", undefined);
__decorate([
  editableInPropertyPage("resolutionZ", 2, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 1, max: 10 })
], LatticeBlock.prototype, "resolutionZ", undefined);
RegisterClass("BABYLON.LatticeBlock", LatticeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryTrigonometryBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var GeometryTrigonometryBlockOperations;
(function(GeometryTrigonometryBlockOperations2) {
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Cos"] = 0] = "Cos";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Sin"] = 1] = "Sin";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Abs"] = 2] = "Abs";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Exp"] = 3] = "Exp";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Round"] = 4] = "Round";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Floor"] = 5] = "Floor";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Ceiling"] = 6] = "Ceiling";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Sqrt"] = 7] = "Sqrt";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Log"] = 8] = "Log";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Tan"] = 9] = "Tan";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["ArcTan"] = 10] = "ArcTan";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["ArcCos"] = 11] = "ArcCos";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["ArcSin"] = 12] = "ArcSin";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Sign"] = 13] = "Sign";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Negate"] = 14] = "Negate";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["OneMinus"] = 15] = "OneMinus";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Reciprocal"] = 16] = "Reciprocal";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["ToDegrees"] = 17] = "ToDegrees";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["ToRadians"] = 18] = "ToRadians";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Fract"] = 19] = "Fract";
  GeometryTrigonometryBlockOperations2[GeometryTrigonometryBlockOperations2["Exp2"] = 20] = "Exp2";
})(GeometryTrigonometryBlockOperations || (GeometryTrigonometryBlockOperations = {}));

class GeometryTrigonometryBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.operation = GeometryTrigonometryBlockOperations.Cos;
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryTrigonometryBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    let func = null;
    switch (this.operation) {
      case GeometryTrigonometryBlockOperations.Cos: {
        func = (value) => Math.cos(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Sin: {
        func = (value) => Math.sin(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Abs: {
        func = (value) => Math.abs(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Exp: {
        func = (value) => Math.exp(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Exp2: {
        func = (value) => Math.pow(2, value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Round: {
        func = (value) => Math.round(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Floor: {
        func = (value) => Math.floor(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Ceiling: {
        func = (value) => Math.ceil(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Sqrt: {
        func = (value) => Math.sqrt(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Log: {
        func = (value) => Math.log(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Tan: {
        func = (value) => Math.tan(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.ArcTan: {
        func = (value) => Math.atan(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.ArcCos: {
        func = (value) => Math.acos(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.ArcSin: {
        func = (value) => Math.asin(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Sign: {
        func = (value) => Math.sign(value);
        break;
      }
      case GeometryTrigonometryBlockOperations.Negate: {
        func = (value) => -value;
        break;
      }
      case GeometryTrigonometryBlockOperations.OneMinus: {
        func = (value) => 1 - value;
        break;
      }
      case GeometryTrigonometryBlockOperations.Reciprocal: {
        func = (value) => 1 / value;
        break;
      }
      case GeometryTrigonometryBlockOperations.ToRadians: {
        func = (value) => value * Math.PI / 180;
        break;
      }
      case GeometryTrigonometryBlockOperations.ToDegrees: {
        func = (value) => value * 180 / Math.PI;
        break;
      }
      case GeometryTrigonometryBlockOperations.Fract: {
        func = (value) => {
          if (value >= 0) {
            return value - Math.floor(value);
          } else {
            return value - Math.ceil(value);
          }
        };
        break;
      }
    }
    if (!func) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    switch (this.input.type) {
      case NodeGeometryBlockConnectionPointTypes.Int:
      case NodeGeometryBlockConnectionPointTypes.Float: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return func(source);
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector2: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector2(func(source.x), func(source.y));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector3: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector3(func(source.x), func(source.y), func(source.z));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector4: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector4(func(source.x), func(source.y), func(source.z), func(source.w));
        };
        break;
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.operation = this.operation;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.operation = serializationObject.operation;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${GeometryTrigonometryBlockOperations[this.operation]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Operation", 4, "ADVANCED", {
    embedded: true,
    notifiers: { rebuild: true },
    options: [
      { label: "Cos", value: GeometryTrigonometryBlockOperations.Cos },
      { label: "Sin", value: GeometryTrigonometryBlockOperations.Sin },
      { label: "Abs", value: GeometryTrigonometryBlockOperations.Abs },
      { label: "Exp", value: GeometryTrigonometryBlockOperations.Exp },
      { label: "Exp2", value: GeometryTrigonometryBlockOperations.Exp2 },
      { label: "Round", value: GeometryTrigonometryBlockOperations.Round },
      { label: "Floor", value: GeometryTrigonometryBlockOperations.Floor },
      { label: "Ceiling", value: GeometryTrigonometryBlockOperations.Ceiling },
      { label: "Sqrt", value: GeometryTrigonometryBlockOperations.Sqrt },
      { label: "Log", value: GeometryTrigonometryBlockOperations.Log },
      { label: "Tan", value: GeometryTrigonometryBlockOperations.Tan },
      { label: "ArcTan", value: GeometryTrigonometryBlockOperations.ArcTan },
      { label: "ArcCos", value: GeometryTrigonometryBlockOperations.ArcCos },
      { label: "ArcSin", value: GeometryTrigonometryBlockOperations.ArcSin },
      { label: "Sign", value: GeometryTrigonometryBlockOperations.Sign },
      { label: "Negate", value: GeometryTrigonometryBlockOperations.Negate },
      { label: "OneMinus", value: GeometryTrigonometryBlockOperations.OneMinus },
      { label: "Reciprocal", value: GeometryTrigonometryBlockOperations.Reciprocal },
      { label: "ToDegrees", value: GeometryTrigonometryBlockOperations.ToDegrees },
      { label: "ToRadians", value: GeometryTrigonometryBlockOperations.ToRadians },
      { label: "Fract", value: GeometryTrigonometryBlockOperations.Fract }
    ]
  })
], GeometryTrigonometryBlock.prototype, "operation", undefined);
RegisterClass("BABYLON.GeometryTrigonometryBlock", GeometryTrigonometryBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryTransformBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
class GeometryTransformBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._rotationMatrix = new Matrix;
    this._scalingMatrix = new Matrix;
    this._translationMatrix = new Matrix;
    this._scalingRotationMatrix = new Matrix;
    this._pivotMatrix = new Matrix;
    this._backPivotMatrix = new Matrix;
    this._transformMatrix = new Matrix;
    this.evaluateContext = true;
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true);
    this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One());
    this.registerInput("pivot", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryTransformBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get matrix() {
    return this._inputs[1];
  }
  get translation() {
    return this._inputs[2];
  }
  get rotation() {
    return this._inputs[3];
  }
  get scaling() {
    return this._inputs[4];
  }
  get pivot() {
    return this._inputs[5];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (state2) => {
      const value = this.value.getConnectedValue(state2);
      if (!value) {
        return null;
      }
      let matrix;
      if (this.matrix.isConnected) {
        matrix = this.matrix.getConnectedValue(state2);
      } else {
        const scaling = this.scaling.getConnectedValue(state2) || Vector3.OneReadOnly;
        const rotation = this.rotation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
        const translation = this.translation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
        const pivot = this.pivot.getConnectedValue(state2) || Vector3.ZeroReadOnly;
        Matrix.TranslationToRef(-pivot.x, -pivot.y, -pivot.z, this._pivotMatrix);
        Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix);
        Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix);
        Matrix.TranslationToRef(translation.x + pivot.x, translation.y + pivot.y, translation.z + pivot.z, this._translationMatrix);
        this._pivotMatrix.multiplyToRef(this._scalingMatrix, this._backPivotMatrix);
        this._backPivotMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix);
        this._scalingRotationMatrix.multiplyToRef(this._translationMatrix, this._transformMatrix);
        matrix = this._transformMatrix;
      }
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Geometry: {
          const geometry = value.clone();
          geometry.transform(matrix);
          return geometry;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2:
          return Vector2.Transform(value, matrix);
        case NodeGeometryBlockConnectionPointTypes.Vector3:
          return Vector3.TransformCoordinates(value, matrix);
        case NodeGeometryBlockConnectionPointTypes.Vector4:
          return Vector4.TransformCoordinates(value, matrix);
      }
      return null;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryTransformBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.GeometryTransformBlock", GeometryTransformBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationXBlock.js
init_typeStore();
init_math_vector();

class RotationXBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "RotationXBlock";
  }
  get angle() {
    return this._inputs[0];
  }
  get matrix() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      return Matrix.RotationX(this.angle.getConnectedValue(state2));
    };
  }
}
RegisterClass("BABYLON.RotationXBlock", RotationXBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationYBlock.js
init_typeStore();
init_math_vector();

class RotationYBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "RotationYBlock";
  }
  get angle() {
    return this._inputs[0];
  }
  get matrix() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      return Matrix.RotationY(this.angle.getConnectedValue(state2));
    };
  }
}
RegisterClass("BABYLON.RotationYBlock", RotationYBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationZBlock.js
init_typeStore();
init_math_vector();

class RotationZBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "RotationZBlock";
  }
  get angle() {
    return this._inputs[0];
  }
  get matrix() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      return Matrix.RotationZ(this.angle.getConnectedValue(state2));
    };
  }
}
RegisterClass("BABYLON.RotationZBlock", RotationZBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/scalingBlock.js
init_typeStore();
init_math_vector();

class ScalingBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Vector3, false, Vector3.One());
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "ScalingBlock";
  }
  get scale() {
    return this._inputs[0];
  }
  get matrix() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.scale.isConnected) {
      const scaleInput = new GeometryInputBlock("Scale");
      scaleInput.value = new Vector3(1, 1, 1);
      scaleInput.output.connectTo(this.scale);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      const value = this.scale.getConnectedValue(state2);
      return Matrix.Scaling(value.x, value.y, value.z);
    };
  }
}
RegisterClass("BABYLON.ScalingBlock", ScalingBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/alignBlock.js
init_typeStore();
init_math_vector();

class AlignBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("source", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Up());
    this.registerInput("target", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Left());
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "AlignBlock";
  }
  get source() {
    return this._inputs[0];
  }
  get target() {
    return this._inputs[1];
  }
  get matrix() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      const source = this.source.getConnectedValue(state2).clone();
      const target = this.target.getConnectedValue(state2).clone();
      const result = new Matrix;
      source.normalize();
      target.normalize();
      Matrix.RotationAlignToRef(source, target, result, true);
      return result;
    };
  }
}
RegisterClass("BABYLON.AlignBlock", AlignBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/translationBlock.js
init_typeStore();
init_math_vector();

class TranslationBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, false, Vector3.Zero());
    this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "TranslationBlock";
  }
  get translation() {
    return this._inputs[0];
  }
  get matrix() {
    return this._outputs[0];
  }
  autoConfigure() {
    if (!this.translation.isConnected) {
      const translationInput = new GeometryInputBlock("Translation");
      translationInput.value = new Vector3(0, 0, 0);
      translationInput.output.connectTo(this.translation);
    }
  }
  _buildBlock(state) {
    super._buildBlock(state);
    this.matrix._storedFunction = (state2) => {
      const value = this.translation.getConnectedValue(state2);
      return Matrix.Translation(value.x, value.y, value.z);
    };
  }
}
RegisterClass("BABYLON.TranslationBlock", TranslationBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnVerticesBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
init_math_constants();

class InstantiateOnVerticesBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._indexTranslation = null;
    this.evaluateContext = true;
    this.removeDuplicatedPositions = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("density", NodeGeometryBlockConnectionPointTypes.Float, true, 1, 0, 1);
    this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true);
    this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One());
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getInstanceIndex() {
    return this._currentLoopIndex;
  }
  getExecutionIndex() {
    return this._indexTranslation ? this._indexTranslation[this._currentIndex] : this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentLoopIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "InstantiateOnVerticesBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get instance() {
    return this._inputs[1];
  }
  get density() {
    return this._inputs[2];
  }
  get matrix() {
    return this._inputs[3];
  }
  get offset() {
    return this._inputs[4];
  }
  get rotation() {
    return this._inputs[5];
  }
  get scaling() {
    return this._inputs[6];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions || !this.instance.isConnected) {
        state2.restoreExecutionContext();
        state2.restoreInstancingContext();
        state2.restoreGeometryContext();
        this.output._storedValue = null;
        return;
      }
      let vertexCount = this._vertexData.positions.length / 3;
      const additionalVertexData = [];
      const currentPosition = new Vector3;
      const alreadyDone = [];
      let vertices = this._vertexData.positions;
      this._currentLoopIndex = 0;
      if (this.removeDuplicatedPositions) {
        this._indexTranslation = {};
        for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
          const x = vertices[this._currentIndex * 3];
          const y = vertices[this._currentIndex * 3 + 1];
          const z = vertices[this._currentIndex * 3 + 2];
          let found = false;
          for (let index = 0;index < alreadyDone.length; index += 3) {
            if (Math.abs(alreadyDone[index] - x) < Epsilon && Math.abs(alreadyDone[index + 1] - y) < Epsilon && Math.abs(alreadyDone[index + 2] - z) < Epsilon) {
              found = true;
              break;
            }
          }
          if (found) {
            continue;
          }
          this._indexTranslation[alreadyDone.length / 3] = this._currentIndex;
          alreadyDone.push(x, y, z);
        }
        vertices = alreadyDone;
        vertexCount = vertices.length / 3;
      } else {
        this._indexTranslation = null;
      }
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        const instanceGeometry = this.instance.getConnectedValue(state2);
        if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
          continue;
        }
        const density = this.density.getConnectedValue(state2);
        if (density < 1) {
          if (Math.random() > density) {
            continue;
          }
        }
        currentPosition.fromArray(vertices, this._currentIndex * 3);
        const clone = instanceGeometry.clone();
        if (this.matrix.isConnected) {
          const transform = this.matrix.getConnectedValue(state2);
          state2._instantiateWithPositionAndMatrix(clone, currentPosition, transform, additionalVertexData);
        } else {
          const offset = state2.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly);
          const scaling = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
          const rotation = this.rotation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
          currentPosition.addInPlace(offset);
          state2._instantiate(clone, currentPosition, rotation, scaling, additionalVertexData);
        }
        this._currentLoopIndex++;
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      } else {
        return null;
      }
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.removeDuplicatedPositions = this.removeDuplicatedPositions;
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.removeDuplicatedPositions = serializationObject.removeDuplicatedPositions;
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { notifiers: { rebuild: true } })
], InstantiateOnVerticesBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("Remove duplicated positions", 0, "ADVANCED", { notifiers: { update: true } })
], InstantiateOnVerticesBlock.prototype, "removeDuplicatedPositions", undefined);
RegisterClass("BABYLON.InstantiateOnVerticesBlock", InstantiateOnVerticesBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnFacesBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
class InstantiateOnFacesBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._currentPosition = new Vector3;
    this._currentUV = new Vector2;
    this._vertex0 = new Vector3;
    this._vertex1 = new Vector3;
    this._vertex2 = new Vector3;
    this._tempVector0 = new Vector3;
    this._tempVector1 = new Vector3;
    this._uv0 = new Vector2;
    this._uv1 = new Vector2;
    this._uv2 = new Vector2;
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256);
    this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true);
    this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One());
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getInstanceIndex() {
    return this._currentLoopIndex;
  }
  getExecutionIndex() {
    return 0;
  }
  getExecutionFaceIndex() {
    return this._currentFaceIndex;
  }
  getExecutionLoopIndex() {
    return this._currentLoopIndex;
  }
  getOverridePositionsContextualValue() {
    return this._currentPosition;
  }
  getOverrideNormalsContextualValue() {
    this._vertex1.subtractToRef(this._vertex0, this._tempVector0);
    this._vertex2.subtractToRef(this._vertex1, this._tempVector1);
    this._tempVector0.normalize();
    this._tempVector1.normalize();
    return Vector3.Cross(this._tempVector1, this._tempVector0);
  }
  getOverrideUVs1ContextualValue() {
    return this._currentUV;
  }
  getClassName() {
    return "InstantiateOnFacesBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get instance() {
    return this._inputs[1];
  }
  get count() {
    return this._inputs[2];
  }
  get matrix() {
    return this._inputs[3];
  }
  get offset() {
    return this._inputs[4];
  }
  get rotation() {
    return this._inputs[5];
  }
  get scaling() {
    return this._inputs[6];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) {
        state2.restoreExecutionContext();
        state2.restoreInstancingContext();
        state2.restoreGeometryContext();
        this.output._storedValue = null;
        return;
      }
      let instanceGeometry = null;
      const instanceCount = this.count.getConnectedValue(state2);
      const faceCount = this._vertexData.indices.length / 3;
      const instancePerFace = instanceCount / faceCount;
      let accumulatedCount = 0;
      const additionalVertexData = [];
      let totalDone = 0;
      this._currentLoopIndex = 0;
      for (this._currentFaceIndex = 0;this._currentFaceIndex < faceCount; this._currentFaceIndex++) {
        accumulatedCount += instancePerFace;
        const countPerFace = (accumulatedCount | 0) - totalDone;
        if (countPerFace < 1) {
          continue;
        }
        const faceID0 = this._vertexData.indices[this._currentFaceIndex * 3];
        const faceID1 = this._vertexData.indices[this._currentFaceIndex * 3 + 1];
        const faceID2 = this._vertexData.indices[this._currentFaceIndex * 3 + 2];
        this._vertex0.fromArray(this._vertexData.positions, faceID0 * 3);
        this._vertex1.fromArray(this._vertexData.positions, faceID1 * 3);
        this._vertex2.fromArray(this._vertexData.positions, faceID2 * 3);
        if (this._vertexData.uvs) {
          this._uv0.fromArray(this._vertexData.uvs, faceID0 * 2);
          this._uv1.fromArray(this._vertexData.uvs, faceID1 * 2);
          this._uv2.fromArray(this._vertexData.uvs, faceID2 * 2);
        }
        for (let faceDispatchCount = 0;faceDispatchCount < countPerFace; faceDispatchCount++) {
          if (totalDone >= instanceCount) {
            break;
          }
          let x = Math.random();
          let y = Math.random();
          if (x > y) {
            const temp = x;
            x = y;
            y = temp;
          }
          const s = x;
          const t = y - x;
          const u = 1 - s - t;
          this._currentPosition.set(s * this._vertex0.x + t * this._vertex1.x + u * this._vertex2.x, s * this._vertex0.y + t * this._vertex1.y + u * this._vertex2.y, s * this._vertex0.z + t * this._vertex1.z + u * this._vertex2.z);
          if (this._vertexData.uvs) {
            this._currentUV.set(s * this._uv0.x + t * this._uv1.x + u * this._uv2.x, s * this._uv0.y + t * this._uv1.y + u * this._uv2.y);
          }
          instanceGeometry = this.instance.getConnectedValue(state2);
          if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
            accumulatedCount -= instancePerFace;
            continue;
          }
          const clone = instanceGeometry.clone();
          if (this.matrix.isConnected) {
            const transform = this.matrix.getConnectedValue(state2);
            state2._instantiateWithPositionAndMatrix(clone, this._currentPosition, transform, additionalVertexData);
          } else {
            const offset = state2.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly);
            const scaling = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
            const rotation = this.rotation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
            this._currentPosition.addInPlace(offset);
            state2._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData);
          }
          totalDone++;
          this._currentLoopIndex++;
        }
      }
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      }
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      state2.restoreGeometryContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { notifiers: { rebuild: true } })
], InstantiateOnFacesBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.InstantiateOnFacesBlock", InstantiateOnFacesBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnVolumeBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
init_math_functions();

class InstantiateOnVolumeBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._currentPosition = new Vector3;
    this._vertex0 = new Vector3;
    this._vertex1 = new Vector3;
    this._vertex2 = new Vector3;
    this.evaluateContext = true;
    this.gridMode = false;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256);
    this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true);
    this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One());
    this.registerInput("gridSize", NodeGeometryBlockConnectionPointTypes.Int, true, 10);
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getInstanceIndex() {
    return this._currentLoopIndex;
  }
  getExecutionIndex() {
    return 0;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getExecutionLoopIndex() {
    return this._currentLoopIndex;
  }
  getOverridePositionsContextualValue() {
    return this._currentPosition;
  }
  getClassName() {
    return "InstantiateOnVolumeBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get instance() {
    return this._inputs[1];
  }
  get count() {
    return this._inputs[2];
  }
  get matrix() {
    return this._inputs[3];
  }
  get offset() {
    return this._inputs[4];
  }
  get rotation() {
    return this._inputs[5];
  }
  get scaling() {
    return this._inputs[6];
  }
  get gridSize() {
    return this._inputs[6];
  }
  get output() {
    return this._outputs[0];
  }
  _getValueOnGrid(step, size, min, max) {
    const cellSize = (max - min) / size;
    return min + cellSize / 2 + step * cellSize;
  }
  _getIndexinGrid(x, y, z, size) {
    return x + y * size + z * size * size;
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) {
        state2.restoreExecutionContext();
        state2.restoreInstancingContext();
        state2.restoreGeometryContext();
        this.output._storedValue = null;
        return;
      }
      let instanceGeometry = null;
      const instanceCount = this.count.getConnectedValue(state2);
      const additionalVertexData = [];
      const boundingInfo2 = extractMinAndMax(this._vertexData.positions, 0, this._vertexData.positions.length / 3);
      const min = boundingInfo2.minimum;
      const max = boundingInfo2.maximum;
      const direction = new Vector3(0.5, 0.8, 0.2);
      const faceCount = this._vertexData.indices.length / 3;
      const gridSize = this.gridSize.getConnectedValue(state2);
      this._currentLoopIndex = 0;
      let candidatesCells;
      if (this.gridMode) {
        candidatesCells = [];
        for (let index = 0;index < gridSize * gridSize * gridSize; index++) {
          candidatesCells[index] = false;
        }
      }
      for (let index = 0;index < instanceCount; index++) {
        if (this.gridMode) {
          let cellX = Math.floor(Math.random() * gridSize);
          let cellY = Math.floor(Math.random() * gridSize);
          let cellZ = Math.floor(Math.random() * gridSize);
          let cellIndex = this._getIndexinGrid(cellX, cellY, cellZ, gridSize);
          if (candidatesCells[cellIndex]) {
            let found = false;
            for (let candidateIndex = 0;candidateIndex < gridSize * gridSize * gridSize; candidateIndex++) {
              if (!candidatesCells[candidateIndex]) {
                cellZ = Math.floor(candidateIndex / (gridSize * gridSize));
                cellY = Math.floor((candidateIndex - cellZ * gridSize * gridSize) / gridSize);
                cellX = candidateIndex - cellZ * gridSize * gridSize - cellY * gridSize;
                cellIndex = this._getIndexinGrid(cellX, cellY, cellZ, gridSize);
                found = true;
                break;
              }
            }
            if (!found) {
              break;
            }
          }
          if (!candidatesCells[cellIndex]) {
            const x = this._getValueOnGrid(cellX, gridSize, min.x, max.x);
            const y = this._getValueOnGrid(cellY, gridSize, min.y, max.y);
            const z = this._getValueOnGrid(cellZ, gridSize, min.z, max.z);
            this._currentPosition.set(x, y, z);
            candidatesCells[cellIndex] = true;
          }
        } else {
          this._currentPosition.set(Math.random() * (max.x - min.x) + min.x, Math.random() * (max.y - min.y) + min.y, Math.random() * (max.z - min.z) + min.z);
        }
        const ray2 = new Ray(this._currentPosition, direction);
        let intersectionCount = 0;
        for (let currentFaceIndex = 0;currentFaceIndex < faceCount; currentFaceIndex++) {
          this._vertex0.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3] * 3);
          this._vertex1.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 1] * 3);
          this._vertex2.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 2] * 3);
          const currentIntersectInfo = ray2.intersectsTriangle(this._vertex0, this._vertex1, this._vertex2);
          if (currentIntersectInfo && currentIntersectInfo.distance > 0) {
            intersectionCount++;
          }
        }
        if (intersectionCount % 2 === 0) {
          index--;
          continue;
        }
        instanceGeometry = this.instance.getConnectedValue(state2);
        if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
          continue;
        }
        const clone = instanceGeometry.clone();
        if (this.matrix.isConnected) {
          const transform = this.matrix.getConnectedValue(state2);
          state2._instantiateWithPositionAndMatrix(clone, this._currentPosition, transform, additionalVertexData);
        } else {
          const offset = state2.adaptInput(this.offset, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.ZeroReadOnly);
          const scaling = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
          const rotation = this.rotation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
          this._currentPosition.addInPlace(offset);
          state2._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData);
        }
        this._currentLoopIndex++;
      }
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.gridMode = ${this.gridMode ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.gridMode = this.gridMode;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
    if (serializationObject.gridMode !== undefined) {
      this.gridMode = serializationObject.gridMode;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { notifiers: { rebuild: true } })
], InstantiateOnVolumeBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("Grid mode", 0, "MODES", { notifiers: { rebuild: true } })
], InstantiateOnVolumeBlock.prototype, "gridMode", undefined);
RegisterClass("BABYLON.InstantiateOnVolumeBlock", InstantiateOnVolumeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateBlock.js
init_typeStore();
init_math_vector();

// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateBaseBlock.js
init_tslib_es6();
class InstantiateBaseBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.evaluateContext = true;
    this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true);
    this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getInstanceIndex() {
    return this._currentIndex;
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "InstantiateBaseBlock";
  }
  get instance() {
    return this._inputs[0];
  }
  get count() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], InstantiateBaseBlock.prototype, "evaluateContext", undefined);

// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateBlock.js
class InstantiateBlock extends InstantiateBaseBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true);
    this.registerInput("position", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.One());
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
  }
  getInstanceIndex() {
    return this._currentIndex;
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "InstantiateBlock";
  }
  get matrix() {
    return this._inputs[2];
  }
  get position() {
    return this._inputs[3];
  }
  get rotation() {
    return this._inputs[4];
  }
  get scaling() {
    return this._inputs[5];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      const iterationCount = this.count.getConnectedValue(state2);
      const additionalVertexData = [];
      for (this._currentIndex = 0;this._currentIndex < iterationCount; this._currentIndex++) {
        const instanceGeometry = this.instance.getConnectedValue(state2);
        if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
          continue;
        }
        const clone = instanceGeometry.clone();
        if (this.matrix.isConnected) {
          const transform = this.matrix.getConnectedValue(state2);
          state2._instantiateWithMatrix(clone, transform, additionalVertexData);
        } else {
          const position = this.position.getConnectedValue(state2) || Vector3.ZeroReadOnly;
          const scaling = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
          const rotation = this.rotation.getConnectedValue(state2) || Vector3.ZeroReadOnly;
          state2._instantiate(clone, position, rotation, scaling, additionalVertexData);
        }
      }
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      }
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
}
RegisterClass("BABYLON.InstantiateBlock", InstantiateBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateLinearBlock.js
init_typeStore();
init_math_vector();
class InstantiateLinearBlock extends InstantiateBaseBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("direction", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(1, 0, 0));
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0));
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0));
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "InstantiateLinearBlock";
  }
  get direction() {
    return this._inputs[2];
  }
  get rotation() {
    return this._inputs[3];
  }
  get scaling() {
    return this._inputs[4];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      const iterationCount = this.count.getConnectedValue(state2);
      const additionalVertexData = [];
      const transformMatrix = Matrix.Identity();
      const transformOffset = Vector3.Zero();
      const rotationOffset = Vector3.Zero();
      const scaleOffset = Vector3.Zero();
      for (this._currentIndex = 0;this._currentIndex < iterationCount; this._currentIndex++) {
        const instanceGeometry = this.instance.getConnectedValue(state2);
        if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
          continue;
        }
        const clone = instanceGeometry.clone();
        const direction = this.direction.getConnectedValue(state2);
        const rotation = this.rotation.getConnectedValue(state2);
        const scale = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
        transformOffset.copyFrom(direction.clone().scale(this._currentIndex));
        rotationOffset.copyFrom(rotation.clone().scale(this._currentIndex));
        scaleOffset.copyFrom(scale.clone().scale(this._currentIndex));
        scaleOffset.addInPlaceFromFloats(1, 1, 1);
        Matrix.ComposeToRef(scaleOffset, Quaternion.FromEulerAngles(rotationOffset.x, rotationOffset.y, rotationOffset.z), transformOffset, transformMatrix);
        state2._instantiateWithMatrix(clone, transformMatrix, additionalVertexData);
      }
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      }
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
}
RegisterClass("BABYLON.InstantiateLinearBlock", InstantiateLinearBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateRadialBlock.js
init_typeStore();
init_math_vector();
class InstantiateRadialBlock extends InstantiateBaseBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Int, true, 0, 0);
    this.registerInput("angleStart", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("angleEnd", NodeGeometryBlockConnectionPointTypes.Float, true, Math.PI * 2);
    this.registerInput("transform", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0));
    this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0));
    this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, new Vector3(0, 0, 0));
    this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "InstantiateRadialBlock";
  }
  get radius() {
    return this._inputs[2];
  }
  get angleStart() {
    return this._inputs[3];
  }
  get angleEnd() {
    return this._inputs[4];
  }
  get transform() {
    return this._inputs[5];
  }
  get rotation() {
    return this._inputs[6];
  }
  get scaling() {
    return this._inputs[7];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      state2.pushInstancingContext(this);
      const iterationCount = this.count.getConnectedValue(state2);
      const additionalVertexData = [];
      const rotMatrix = Matrix.Identity();
      const radiusMatrix = Matrix.Identity();
      const transformMatrix = Matrix.Identity();
      const transformOffset = Vector3.Zero();
      const rotationOffset = Vector3.Zero();
      const scaleOffset = Vector3.Zero();
      for (this._currentIndex = 0;this._currentIndex < iterationCount; this._currentIndex++) {
        const instanceGeometry = this.instance.getConnectedValue(state2);
        if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) {
          continue;
        }
        const clone = instanceGeometry.clone();
        const radius = this.radius.getConnectedValue(state2);
        const angleStart = this.angleStart.getConnectedValue(state2);
        const angleEnd = this.angleEnd.getConnectedValue(state2);
        const transform = this.transform.getConnectedValue(state2);
        const rotation = this.rotation.getConnectedValue(state2);
        const scale = state2.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, Vector3.OneReadOnly);
        const pieSlice = angleEnd - angleStart;
        const rStep = pieSlice / iterationCount;
        const angle = angleStart + rStep * this._currentIndex;
        const angleQuat = Quaternion.FromEulerAngles(0, angle, 0);
        transformOffset.copyFrom(transform.clone().scale(this._currentIndex));
        rotationOffset.copyFrom(rotation.clone().scale(this._currentIndex));
        scaleOffset.copyFrom(scale.clone().scale(this._currentIndex));
        scaleOffset.addInPlaceFromFloats(1, 1, 1);
        Matrix.RotationYawPitchRollToRef(rotationOffset.y, rotationOffset.x, rotationOffset.z, rotMatrix);
        radiusMatrix.setTranslationFromFloats(0, 0, radius);
        Matrix.ComposeToRef(scaleOffset, angleQuat, transformOffset, transformMatrix);
        rotMatrix.multiplyToRef(radiusMatrix, radiusMatrix);
        radiusMatrix.multiplyToRef(transformMatrix, transformMatrix);
        state2._instantiateWithMatrix(clone, transformMatrix, additionalVertexData);
      }
      if (additionalVertexData.length) {
        if (additionalVertexData.length === 1) {
          this._vertexData = additionalVertexData[0];
        } else {
          const main = additionalVertexData.splice(0, 1)[0];
          this._vertexData = main.merge(additionalVertexData, true, false, true, true);
        }
      }
      state2.restoreExecutionContext();
      state2.restoreInstancingContext();
      return this._vertexData;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
}
RegisterClass("BABYLON.InstantiateRadialBlock", InstantiateRadialBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/intFloatConverterBlock.js
init_typeStore();
class IntFloatConverterBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("float ", NodeGeometryBlockConnectionPointTypes.Float, true);
    this.registerInput("int ", NodeGeometryBlockConnectionPointTypes.Int, true);
    this.registerOutput("float", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("int", NodeGeometryBlockConnectionPointTypes.Int);
  }
  getClassName() {
    return "IntFloatConverterBlock";
  }
  get floatIn() {
    return this._inputs[0];
  }
  get intIn() {
    return this._inputs[1];
  }
  get floatOut() {
    return this._outputs[0];
  }
  get intOut() {
    return this._outputs[1];
  }
  _inputRename(name375) {
    if (name375 === "float ") {
      return "floatIn";
    }
    if (name375 === "int ") {
      return "intIn";
    }
    return name375;
  }
  _buildBlock() {
    this.floatOut._storedFunction = (state) => {
      if (this.floatIn.isConnected) {
        return this.floatIn.getConnectedValue(state);
      }
      if (this.intIn.isConnected) {
        return this.intIn.getConnectedValue(state);
      }
      return 0;
    };
    this.intOut._storedFunction = (state) => {
      if (this.floatIn.isConnected) {
        return Math.floor(this.floatIn.getConnectedValue(state));
      }
      if (this.intIn.isConnected) {
        return Math.floor(this.intIn.getConnectedValue(state));
      }
      return 0;
    };
  }
}
RegisterClass("BABYLON.IntFloatConverterBlock", IntFloatConverterBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/debugBlock.js
init_typeStore();
class DebugBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.log = [];
    this._isDebug = true;
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  get buildExecutionTime() {
    return -1;
  }
  getClassName() {
    return "DebugBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    if (!this.input.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.log = [];
    const func = (state2) => {
      const input = this.input.getConnectedValue(state2);
      if (input === null || input === undefined) {
        this.log.push(["null", ""]);
        return input;
      }
      switch (this.input.type) {
        case NodeGeometryBlockConnectionPointTypes.Vector2:
          this.log.push([Vector2ToFixed(input, 4), input.toString()]);
          break;
        case NodeGeometryBlockConnectionPointTypes.Vector3:
          this.log.push([Vector3ToFixed(input, 4), input.toString()]);
          break;
        case NodeGeometryBlockConnectionPointTypes.Vector4:
          this.log.push([Vector4ToFixed(input, 4), input.toString()]);
          break;
        default:
          this.log.push([input.toString(), input.toString()]);
          break;
      }
      return input;
    };
    if (this.output.isConnected) {
      this.output._storedFunction = func;
    } else {
      this.output._storedValue = func(state);
    }
  }
}
RegisterClass("BABYLON.DebugBlock", DebugBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryInfoBlock.js
init_typeStore();
class GeometryInfoBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("id", NodeGeometryBlockConnectionPointTypes.Int);
    this.registerOutput("collectionId", NodeGeometryBlockConnectionPointTypes.Int);
    this.registerOutput("verticesCount", NodeGeometryBlockConnectionPointTypes.Int);
    this.registerOutput("facesCount", NodeGeometryBlockConnectionPointTypes.Int);
  }
  getClassName() {
    return "GeometryInfoBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  get id() {
    return this._outputs[1];
  }
  get collectionId() {
    return this._outputs[2];
  }
  get verticesCount() {
    return this._outputs[3];
  }
  get facesCount() {
    return this._outputs[4];
  }
  _buildBlock() {
    if (!this.geometry.isConnected) {
      this.id._storedValue = 0;
      this.collectionId._storedValue = 0;
      this.verticesCount._storedValue = 0;
      this.facesCount._storedValue = 0;
      this.output._storedValue = 0;
      this.id._storedFunction = null;
      this.collectionId._storedFunction = null;
      this.verticesCount._storedFunction = null;
      this.facesCount._storedFunction = null;
      this.output._storedFunction = null;
      return;
    }
    this.output._storedFunction = (state) => {
      this._currentVertexData = this.geometry.getConnectedValue(state);
      return this._currentVertexData;
    };
    this.id._storedFunction = (state) => {
      this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state);
      return this._currentVertexData.uniqueId;
    };
    this.collectionId._storedFunction = (state) => {
      this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state);
      return this._currentVertexData.metadata ? this._currentVertexData.metadata.collectionId : 0;
    };
    this.verticesCount._storedFunction = (state) => {
      this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state);
      return this._currentVertexData.positions ? this._currentVertexData.positions.length / 3 : 0;
    };
    this.facesCount._storedFunction = (state) => {
      this._currentVertexData = this._currentVertexData || this.geometry.getConnectedValue(state);
      return this._currentVertexData.indices ? this._currentVertexData.indices.length / 3 : 0;
    };
  }
}
RegisterClass("BABYLON.GeometryInfoBlock", GeometryInfoBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/mappingBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var MappingTypes;
(function(MappingTypes2) {
  MappingTypes2[MappingTypes2["Spherical"] = 0] = "Spherical";
  MappingTypes2[MappingTypes2["Cylindrical"] = 1] = "Cylindrical";
  MappingTypes2[MappingTypes2["Cubic"] = 2] = "Cubic";
})(MappingTypes || (MappingTypes = {}));

class MappingBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.mapping = MappingTypes.Spherical;
    this.registerInput("position", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerInput("normal", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerInput("center", NodeGeometryBlockConnectionPointTypes.Vector3, true, Vector3.Zero());
    this.registerOutput("uv", NodeGeometryBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "MappingBlock";
  }
  get position() {
    return this._inputs[0];
  }
  get normal() {
    return this._inputs[1];
  }
  get center() {
    return this._inputs[2];
  }
  get uv() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.position.isConnected) {
      this.uv._storedFunction = null;
      this.uv._storedValue = null;
      return;
    }
    const tempDirection = Vector3.Zero();
    const func = (state) => {
      const position = this.position.getConnectedValue(state) || Vector3.Zero();
      const normal = this.normal.getConnectedValue(state) || Vector3.Zero();
      const center = this.center.getConnectedValue(state);
      const uv = Vector2.Zero();
      switch (this.mapping) {
        case MappingTypes.Spherical: {
          position.subtractToRef(center, tempDirection);
          const len = tempDirection.length();
          if (len > 0) {
            uv.x = Math.acos(tempDirection.y / len) / Math.PI;
            if (tempDirection.x !== 0 || tempDirection.z !== 0) {
              uv.y = Math.atan2(tempDirection.x, tempDirection.z) / (Math.PI * 2);
            }
          }
          break;
        }
        case MappingTypes.Cylindrical: {
          position.subtractToRef(center, tempDirection);
          const len = tempDirection.length();
          if (len > 0) {
            uv.x = Math.atan2(tempDirection.x / len, tempDirection.z / len) / (Math.PI * 2);
            uv.y = (tempDirection.y + 1) / 2;
          }
          break;
        }
        case MappingTypes.Cubic: {
          const absX = Math.abs(normal.x);
          const absY = Math.abs(normal.y);
          const absZ = Math.abs(normal.z);
          const maxDim = Math.max(Math.abs(position.x), Math.abs(position.y), Math.abs(position.z));
          let u = 0, v = 0;
          if (absX >= absY && absX >= absZ) {
            u = position.y / maxDim - center.y;
            v = position.z / maxDim - center.z;
          } else if (absY >= absX && absY >= absZ) {
            u = position.x / maxDim - center.x;
            v = position.z / maxDim - center.z;
          } else {
            u = position.x / maxDim - center.x;
            v = position.y / maxDim - center.y;
          }
          uv.x = (u + 1) / 2;
          uv.y = (v + 1) / 2;
        }
      }
      return uv;
    };
    this.uv._storedFunction = (state) => {
      return func(state);
    };
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.mapping = BABYLON.MappingTypes.${MappingTypes[this.mapping]};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.mapping = this.mapping;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.mapping = serializationObject.mapping;
  }
}
__decorate([
  editableInPropertyPage("Mapping", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Spherical", value: MappingTypes.Spherical },
      { label: "Cylindrical", value: MappingTypes.Cylindrical },
      { label: "Cubic", value: MappingTypes.Cubic }
    ]
  })
], MappingBlock.prototype, "mapping", undefined);
RegisterClass("BABYLON.MappingBlock", MappingBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/matrixComposeBlock.js
init_typeStore();
class MatrixComposeBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("matrix0", NodeGeometryBlockConnectionPointTypes.Matrix);
    this.registerInput("matrix1", NodeGeometryBlockConnectionPointTypes.Matrix);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "MatrixComposeBlock";
  }
  get matrix0() {
    return this._inputs[0];
  }
  get matrix1() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    this.output._storedFunction = (state) => {
      if (!this.matrix0.isConnected || !this.matrix1.isConnected) {
        return null;
      }
      const matrix0 = this.matrix0.getConnectedValue(state);
      const matrix1 = this.matrix1.getConnectedValue(state);
      if (!matrix0 || !matrix1) {
        return null;
      }
      return matrix0.multiply(matrix1);
    };
  }
}
RegisterClass("BABYLON.MatrixComposeBlock", MatrixComposeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Teleport/teleportInBlock.js
init_typeStore();
class TeleportInBlock extends NodeGeometryBlock {
  get endpoints() {
    return this._endpoints;
  }
  constructor(name375) {
    super(name375);
    this._endpoints = [];
    this._isTeleportIn = true;
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
  }
  getClassName() {
    return "TeleportInBlock";
  }
  get input() {
    return this._inputs[0];
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = super._dumpCode(uniqueNames, alreadyDumped);
    for (const endpoint of this.endpoints) {
      if (alreadyDumped.indexOf(endpoint) === -1) {
        codeString += endpoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString;
  }
  isAnAncestorOfType(type) {
    if (this.getClassName() === type) {
      return true;
    }
    for (const endpoint of this.endpoints) {
      if (endpoint.isAnAncestorOfType(type)) {
        return true;
      }
    }
    return false;
  }
  isAnAncestorOf(block) {
    for (const endpoint of this.endpoints) {
      if (endpoint === block) {
        return true;
      }
      if (endpoint.isAnAncestorOf(block)) {
        return true;
      }
    }
    return false;
  }
  getDescendantOfPredicate(predicate) {
    if (predicate(this)) {
      return this;
    }
    for (const endpoint of this.endpoints) {
      const descendant = endpoint.getDescendantOfPredicate(predicate);
      if (descendant) {
        return descendant;
      }
    }
    return null;
  }
  attachToEndpoint(endpoint) {
    endpoint.detach();
    this._endpoints.push(endpoint);
    endpoint._entryPoint = this;
    endpoint._outputs[0]._typeConnectionSource = this._inputs[0];
    endpoint._tempEntryPointUniqueId = null;
    endpoint.name = "> " + this.name;
  }
  detachFromEndpoint(endpoint) {
    const index = this._endpoints.indexOf(endpoint);
    if (index !== -1) {
      this._endpoints.splice(index, 1);
      endpoint._outputs[0]._typeConnectionSource = null;
      endpoint._entryPoint = null;
    }
  }
  _buildBlock() {
    for (const endpoint of this._endpoints) {
      endpoint.output._storedFunction = (state) => {
        return this.input.getConnectedValue(state);
      };
    }
  }
}
RegisterClass("BABYLON.TeleportInBlock", TeleportInBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Teleport/teleportOutBlock.js
init_typeStore();
class TeleportOutBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this._entryPoint = null;
    this._tempEntryPointUniqueId = null;
    this._isTeleportOut = true;
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
  }
  get entryPoint() {
    return this._entryPoint;
  }
  getClassName() {
    return "TeleportOutBlock";
  }
  get output() {
    return this._outputs[0];
  }
  detach() {
    if (!this._entryPoint) {
      return;
    }
    this._entryPoint.detachFromEndpoint(this);
  }
  _buildBlock() {}
  _customBuildStep(state) {
    if (this.entryPoint) {
      this.entryPoint.build(state);
    }
  }
  _dumpCode(uniqueNames, alreadyDumped) {
    let codeString = "";
    if (this.entryPoint) {
      if (alreadyDumped.indexOf(this.entryPoint) === -1) {
        codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped);
      }
    }
    return codeString + super._dumpCode(uniqueNames, alreadyDumped);
  }
  _dumpCodeForOutputConnections(alreadyDumped) {
    let codeString = super._dumpCodeForOutputConnections(alreadyDumped);
    if (this.entryPoint) {
      codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped);
    }
    return codeString;
  }
  clone() {
    const clone = super.clone();
    if (this.entryPoint) {
      this.entryPoint.attachToEndpoint(clone);
    }
    return clone;
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode();
    if (this.entryPoint) {
      codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});
`;
    }
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.entryPoint = this.entryPoint?.uniqueId ?? "";
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this._tempEntryPointUniqueId = serializationObject.entryPoint;
  }
}
RegisterClass("BABYLON.TeleportOutBlock", TeleportOutBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Textures/geometryTextureBlock.js
init_tslib_es6();
init_typeStore();
init_textureTools();
class GeometryTextureBlock extends NodeGeometryBlock {
  get textureData() {
    return this._data;
  }
  get textureWidth() {
    return this._width;
  }
  get textureHeight() {
    return this._height;
  }
  constructor(name375) {
    super(name375);
    this._data = null;
    this.serializedCachedData = false;
    this.registerOutput("texture", NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryTextureBlock";
  }
  get texture() {
    return this._outputs[0];
  }
  _prepareImgToLoadAsync(url) {
    return new Promise((resolve3, reject) => {
      const img = new Image;
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        const imageData = ctx.getImageData(0, 0, img.width, img.height);
        const pixels = imageData.data;
        const floatArray = new Float32Array(pixels.length);
        for (let i = 0;i < pixels.length; i++) {
          floatArray[i] = pixels[i] / 255;
        }
        this._data = floatArray;
        this._width = img.width;
        this._height = img.height;
        resolve3();
      };
      img.onerror = () => {
        this._data = null;
        reject();
      };
      img.src = url;
    });
  }
  cleanData() {
    this._data = null;
  }
  loadTextureFromFileAsync(imageFile) {
    return this._prepareImgToLoadAsync(URL.createObjectURL(imageFile));
  }
  loadTextureFromUrlAsync(url) {
    return this._prepareImgToLoadAsync(url);
  }
  extractFromTextureAsync(texture2) {
    return new Promise((resolve3, reject) => {
      if (!texture2.isReady()) {
        texture2.onLoadObservable.addOnce(() => {
          return this.extractFromTextureAsync(texture2).then(resolve3).catch(reject);
        });
        return;
      }
      const size = texture2.getSize();
      TextureTools.GetTextureDataAsync(texture2, size.width, size.height).then(async (data) => {
        const floatArray = new Float32Array(data.length);
        for (let i = 0;i < data.length; i++) {
          floatArray[i] = data[i] / 255;
        }
        this._data = floatArray;
        this._width = size.width;
        this._height = size.height;
        resolve3();
      }).catch(reject);
    });
  }
  _buildBlock() {
    if (!this._data) {
      this.texture._storedValue = null;
      return;
    }
    const textureData = {
      data: this._data,
      width: this._width,
      height: this._height
    };
    this.texture._storedValue = textureData;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.width = this._width;
    serializationObject.height = this._height;
    serializationObject.serializedCachedData = this.serializedCachedData;
    if (this._data && this.serializedCachedData) {
      serializationObject.data = Array.from(this._data);
    }
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this._width = serializationObject.width;
    this._height = serializationObject.height;
    if (serializationObject.data) {
      this._data = new Float32Array(serializationObject.data);
      this.serializedCachedData = true;
    } else {
      this.serializedCachedData = !!serializationObject.serializedCachedData;
    }
  }
}
__decorate([
  editableInPropertyPage("Serialize cached data", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryTextureBlock.prototype, "serializedCachedData", undefined);
RegisterClass("BABYLON.GeometryTextureBlock", GeometryTextureBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Textures/geometryTextureFetchBlock.js
init_tslib_es6();
init_math_vector();
init_typeStore();
class GeometryTextureFetchBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.clampCoordinates = true;
    this.registerInput("texture", NodeGeometryBlockConnectionPointTypes.Texture);
    this.registerInput("coordinates", NodeGeometryBlockConnectionPointTypes.Vector2);
    this.registerOutput("rgba", NodeGeometryBlockConnectionPointTypes.Vector4);
    this.registerOutput("rgb", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("r", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("g", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("b", NodeGeometryBlockConnectionPointTypes.Float);
    this.registerOutput("a", NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "GeometryTextureFetchBlock";
  }
  get texture() {
    return this.inputs[0];
  }
  get coordinates() {
    return this.inputs[1];
  }
  get rgba() {
    return this._outputs[0];
  }
  get rgb() {
    return this._outputs[1];
  }
  get r() {
    return this._outputs[2];
  }
  get g() {
    return this._outputs[3];
  }
  get b() {
    return this._outputs[4];
  }
  get a() {
    return this._outputs[5];
  }
  _repeatClamp(num) {
    if (num >= 0) {
      return num % 1;
    } else {
      return 1 - Math.abs(num) % 1;
    }
  }
  _buildBlock() {
    const func = (state) => {
      const textureData = this.texture.getConnectedValue(state);
      if (!textureData || !textureData.data) {
        return null;
      }
      const uv = this.coordinates.getConnectedValue(state);
      if (!uv) {
        return null;
      }
      const u = this.clampCoordinates ? Math.max(0, Math.min(uv.x, 1)) : this._repeatClamp(uv.x);
      const v = this.clampCoordinates ? Math.max(0, Math.min(uv.y, 1)) : this._repeatClamp(uv.y);
      const x = Math.floor(u * (textureData.width - 1));
      const y = Math.floor(v * (textureData.height - 1));
      const index = x + textureData.width * y;
      return Vector4.FromArray(textureData.data, index * 4);
    };
    this.rgba._storedFunction = (state) => {
      return func(state);
    };
    this.rgb._storedFunction = (state) => {
      const color = func(state);
      return color ? color.toVector3() : null;
    };
    this.r._storedFunction = (state) => {
      const color = func(state);
      return color ? color.x : null;
    };
    this.g._storedFunction = (state) => {
      const color = func(state);
      return color ? color.y : null;
    };
    this.b._storedFunction = (state) => {
      const color = func(state);
      return color ? color.z : null;
    };
    this.a._storedFunction = (state) => {
      const color = func(state);
      return color ? color.w : null;
    };
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.clampCoordinates = this.clampCoordinates;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.clampCoordinates = serializationObject.clampCoordinates;
  }
}
__decorate([
  editableInPropertyPage("Clamp Coordinates", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], GeometryTextureFetchBlock.prototype, "clampCoordinates", undefined);
RegisterClass("BABYLON.GeometryTextureFetchBlock", GeometryTextureFetchBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/boundingBlock.js
init_typeStore();
init_math_functions();

class BoundingBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("min", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerOutput("max", NodeGeometryBlockConnectionPointTypes.Vector3);
  }
  getClassName() {
    return "BoundingBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get min() {
    return this._outputs[0];
  }
  get max() {
    return this._outputs[1];
  }
  _buildBlock() {
    this.min._storedFunction = (state) => {
      const geometry = this.geometry.getConnectedValue(state);
      if (!geometry) {
        return null;
      }
      const boundingInfo2 = extractMinAndMax(geometry.positions, 0, geometry.positions.length / 3);
      return boundingInfo2.minimum;
    };
    this.max._storedFunction = (state) => {
      const geometry = this.geometry.getConnectedValue(state);
      if (!geometry) {
        return null;
      }
      const boundingInfo2 = extractMinAndMax(geometry.positions, 0, geometry.positions.length / 3);
      return boundingInfo2.maximum;
    };
  }
}
RegisterClass("BABYLON.BoundingBlock", BoundingBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/booleanGeometryBlock.js
init_tslib_es6();
init_typeStore();
var BooleanGeometryOperations;
(function(BooleanGeometryOperations2) {
  BooleanGeometryOperations2[BooleanGeometryOperations2["Intersect"] = 0] = "Intersect";
  BooleanGeometryOperations2[BooleanGeometryOperations2["Subtract"] = 1] = "Subtract";
  BooleanGeometryOperations2[BooleanGeometryOperations2["Union"] = 2] = "Union";
})(BooleanGeometryOperations || (BooleanGeometryOperations = {}));

class BooleanGeometryBlock extends NodeGeometryBlock {
  get _isReadyState() {
    if (IsCSG2Ready()) {
      return null;
    }
    if (!this._csg2LoadingPromise) {
      this._csg2LoadingPromise = InitializeCSG2Async();
    }
    return this._csg2LoadingPromise;
  }
  constructor(name375) {
    super(name375);
    this.evaluateContext = false;
    this.operation = BooleanGeometryOperations.Intersect;
    this.useOldCSGEngine = false;
    this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "BooleanGeometryBlock";
  }
  get geometry0() {
    return this._inputs[0];
  }
  get geometry1() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      const vertexData0 = this.geometry0.getConnectedValue(state2);
      const vertexData1 = this.geometry1.getConnectedValue(state2);
      if (!vertexData0 || !vertexData1) {
        return null;
      }
      const vertexCount = vertexData0.positions.length / 3;
      if (!vertexData0.normals && vertexData1.normals) {
        vertexData0.normals = new Array(vertexData0.positions.length);
      }
      if (!vertexData1.normals && vertexData0.normals) {
        vertexData1.normals = new Array(vertexData1.positions.length);
      }
      if (!vertexData0.uvs && vertexData1.uvs) {
        vertexData0.uvs = new Array(vertexCount * 2);
      }
      if (!vertexData1.uvs && vertexData0.uvs) {
        vertexData1.uvs = new Array(vertexCount * 2);
      }
      if (!vertexData0.colors && vertexData1.colors) {
        vertexData0.colors = new Array(vertexCount * 4);
      }
      if (!vertexData1.colors && vertexData0.colors) {
        vertexData1.colors = new Array(vertexCount * 4);
      }
      let boolCSG;
      if (this.useOldCSGEngine) {
        const CSG0 = CSG.FromVertexData(vertexData0);
        const CSG1 = CSG.FromVertexData(vertexData1);
        switch (this.operation) {
          case BooleanGeometryOperations.Intersect:
            boolCSG = CSG0.intersect(CSG1);
            break;
          case BooleanGeometryOperations.Subtract:
            boolCSG = CSG0.subtract(CSG1);
            break;
          case BooleanGeometryOperations.Union:
            boolCSG = CSG0.union(CSG1);
            break;
        }
      } else {
        const CSG0 = CSG2.FromVertexData(vertexData0);
        const CSG1 = CSG2.FromVertexData(vertexData1);
        switch (this.operation) {
          case BooleanGeometryOperations.Intersect:
            boolCSG = CSG0.intersect(CSG1);
            break;
          case BooleanGeometryOperations.Subtract:
            boolCSG = CSG0.subtract(CSG1);
            break;
          case BooleanGeometryOperations.Union:
            boolCSG = CSG0.add(CSG1);
            break;
        }
      }
      return boolCSG.toVertexData();
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${BooleanGeometryOperations[this.operation]};
`;
    codeString += `${this._codeVariableName}.useOldCSGEngine = ${this.useOldCSGEngine ? "true" : "false"};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.operation = this.operation;
    serializationObject.useOldCSGEngine = this.useOldCSGEngine;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.evaluateContext = serializationObject.evaluateContext;
    if (serializationObject.operation) {
      this.operation = serializationObject.operation;
    }
    this.useOldCSGEngine = !!serializationObject.useOldCSGEngine;
  }
}
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], BooleanGeometryBlock.prototype, "evaluateContext", undefined);
__decorate([
  editableInPropertyPage("Operation", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Intersect", value: BooleanGeometryOperations.Intersect },
      { label: "Subtract", value: BooleanGeometryOperations.Subtract },
      { label: "Union", value: BooleanGeometryOperations.Union }
    ]
  })
], BooleanGeometryBlock.prototype, "operation", undefined);
__decorate([
  editableInPropertyPage("Use old CSG engine", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], BooleanGeometryBlock.prototype, "useOldCSGEngine", undefined);
RegisterClass("BABYLON.BooleanGeometryBlock", BooleanGeometryBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryArcTan2Block.js
init_math_vector();
init_typeStore();
class GeometryArcTan2Block extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("x", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("y", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryArcTan2Block";
  }
  get x() {
    return this._inputs[0];
  }
  get y() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.x.isConnected || !this.y.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (x, y) => {
      return Math.atan2(x, y);
    };
    this.output._storedFunction = (state) => {
      const x = this.x.getConnectedValue(state);
      const y = this.y.getConnectedValue(state);
      switch (this.x.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(x, y);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(x.x, y.x), func(x.y, y.y));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(x.x, y.x), func(x.y, y.y), func(x.z, y.z));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(x.x, y.x), func(x.y, y.y), func(x.z, y.z), func(x.w, y.w));
        }
      }
      return 0;
    };
  }
}
RegisterClass("BABYLON.GeometryArcTan2Block", GeometryArcTan2Block);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryLerpBlock.js
init_typeStore();
init_math_vector();

class GeometryLerpBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("gradient", NodeGeometryBlockConnectionPointTypes.Float, true, 0, 0, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryLerpBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get gradient() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (gradient, left, right) => {
      return (1 - gradient) * left + gradient * right;
    };
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      const gradient = this.gradient.getConnectedValue(state);
      switch (this.left.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(gradient, left, right);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(gradient, left.x, right.x), func(gradient, left.y, right.y));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z), func(gradient, left.w, right.w));
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryLerpBlock", GeometryLerpBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryNLerpBlock.js
init_math_vector();
init_typeStore();
class GeometryNLerpBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("gradient", NodeGeometryBlockConnectionPointTypes.Float, true, 0, 0, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryNLerpBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get gradient() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (gradient, left, right) => {
      return (1 - gradient) * left + gradient * right;
    };
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      const gradient = this.gradient.getConnectedValue(state);
      switch (this.left.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(gradient, left, right);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          const result = new Vector2(func(gradient, left.x, right.x), func(gradient, left.y, right.y));
          result.normalize();
          return result;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          const result = new Vector3(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z));
          result.normalize();
          return result;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          const result = new Vector4(func(gradient, left.x, right.x), func(gradient, left.y, right.y), func(gradient, left.z, right.z), func(gradient, left.w, right.w));
          result.normalize();
          return result;
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryNLerpBlock", GeometryNLerpBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryStepBlock.js
init_math_vector();
init_typeStore();
class GeometryStepBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("edge", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryStepBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get edge() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (value, edge) => {
      if (value < edge) {
        return 0;
      }
      return 1;
    };
    this.output._storedFunction = (state) => {
      const source = this.value.getConnectedValue(state);
      const edge = this.edge.getConnectedValue(state);
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(source, edge);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(source.x, edge), func(source.y, edge));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(source.x, edge), func(source.y, edge), func(source.z, edge));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(source.x, edge), func(source.y, edge), func(source.z, edge), func(source.w, edge));
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryStepBlock", GeometryStepBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometrySmoothStepBlock.js
init_math_vector();
init_typeStore();
class GeometrySmoothStepBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("edge0", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("edge1", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometrySmoothStepBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get edge0() {
    return this._inputs[1];
  }
  get edge1() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (value, edge0, edge1) => {
      const x = Math.max(0, Math.min((value - edge0) / (edge1 - edge0), 1));
      return x * x * (3 - 2 * x);
    };
    this.output._storedFunction = (state) => {
      const source = this.value.getConnectedValue(state);
      const edge0 = this.edge0.getConnectedValue(state);
      const edge1 = this.edge1.getConnectedValue(state);
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(source, edge0, edge1);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(source.x, edge0, edge1), func(source.y, edge0, edge1));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(source.x, edge0, edge1), func(source.y, edge0, edge1), func(source.z, edge0, edge1));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(source.x, edge0, edge1), func(source.y, edge0, edge1), func(source.z, edge0, edge1), func(source.w, edge0, edge1));
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometrySmoothStepBlock", GeometrySmoothStepBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryModBlock.js
init_math_vector();
init_typeStore();
class GeometryModBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryModBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (left, right) => {
      return left - Math.floor(left / right) * right;
    };
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      switch (this.left.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(left, right);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(left.x, right.x), func(left.y, right.y));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(left.x, right.x), func(left.y, right.y), func(left.z, right.z));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(left.x, right.x), func(left.y, right.y), func(left.z, right.z), func(left.w, right.w));
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryModBlock", GeometryModBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryPowBlock.js
init_math_vector();
init_typeStore();
class GeometryPowBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("power", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryPowBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get power() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected || !this.power.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (value, power) => {
      return Math.pow(value, power);
    };
    this.output._storedFunction = (state) => {
      const source = this.value.getConnectedValue(state);
      const power = this.power.getConnectedValue(state);
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(source, power);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(source.x, power), func(source.y, power));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(source.x, power), func(source.y, power), func(source.z, power));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(source.x, power), func(source.y, power), func(source.z, power), func(source.w, power));
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryPowBlock", GeometryPowBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryClampBlock.js
init_typeStore();
init_math_vector();

class GeometryClampBlock extends NodeGeometryBlock {
  get minimum() {
    return this.min.value;
  }
  set minimum(value) {
    this.min.value = value;
  }
  get maximum() {
    return this.max.value;
  }
  set maximum(value) {
    this.max.value = value;
  }
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("min", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("max", NodeGeometryBlockConnectionPointTypes.Float, true, 1);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryClampBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get min() {
    return this._inputs[1];
  }
  get max() {
    return this._inputs[2];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    const func = (value, min, max) => {
      return Math.max(min, Math.min(value, max));
    };
    this.output._storedFunction = (state) => {
      const value = this.value.getConnectedValue(state);
      const min = this.min.isConnected ? this.min.getConnectedValue(state) : this.minimum;
      const max = this.max.isConnected ? this.max.getConnectedValue(state) : this.maximum;
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(value, min, max);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(value.x, min, max), func(value.y, min, max));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(value.x, min, max), func(value.y, min, max), func(value.z, min, max));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(value.x, min, max), func(value.y, min, max), func(value.z, min, max), func(value.w, min, max));
        }
      }
      return 0;
    };
    return this;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.minimum = serializationObject.minimum;
    this.maximum = serializationObject.maximum;
  }
}
RegisterClass("BABYLON.GeometryClampBlock", GeometryClampBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryCrossBlock.js
init_math_vector();
init_typeStore();
class GeometryCrossBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector3);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "GeometryCrossBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      switch (this.left.type) {
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return Vector3.Cross(left, right);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return Vector3.Cross(left.toVector3(), right.toVector3());
        }
      }
      return 0;
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryCrossBlock", GeometryCrossBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryCurveBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var GeometryCurveBlockTypes;
(function(GeometryCurveBlockTypes2) {
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInSine"] = 0] = "EaseInSine";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutSine"] = 1] = "EaseOutSine";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutSine"] = 2] = "EaseInOutSine";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInQuad"] = 3] = "EaseInQuad";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutQuad"] = 4] = "EaseOutQuad";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutQuad"] = 5] = "EaseInOutQuad";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInCubic"] = 6] = "EaseInCubic";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutCubic"] = 7] = "EaseOutCubic";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutCubic"] = 8] = "EaseInOutCubic";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInQuart"] = 9] = "EaseInQuart";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutQuart"] = 10] = "EaseOutQuart";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutQuart"] = 11] = "EaseInOutQuart";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInQuint"] = 12] = "EaseInQuint";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutQuint"] = 13] = "EaseOutQuint";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutQuint"] = 14] = "EaseInOutQuint";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInExpo"] = 15] = "EaseInExpo";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutExpo"] = 16] = "EaseOutExpo";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutExpo"] = 17] = "EaseInOutExpo";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInCirc"] = 18] = "EaseInCirc";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutCirc"] = 19] = "EaseOutCirc";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutCirc"] = 20] = "EaseInOutCirc";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInBack"] = 21] = "EaseInBack";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutBack"] = 22] = "EaseOutBack";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutBack"] = 23] = "EaseInOutBack";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInElastic"] = 24] = "EaseInElastic";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseOutElastic"] = 25] = "EaseOutElastic";
  GeometryCurveBlockTypes2[GeometryCurveBlockTypes2["EaseInOutElastic"] = 26] = "EaseInOutElastic";
})(GeometryCurveBlockTypes || (GeometryCurveBlockTypes = {}));

class GeometryCurveBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.type = GeometryCurveBlockTypes.EaseInOutSine;
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
  }
  getClassName() {
    return "GeometryCurveBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.input.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    let func;
    switch (this.type) {
      case GeometryCurveBlockTypes.EaseInSine:
        func = (v) => 1 - Math.cos(v * 3.1415 / 2);
        break;
      case GeometryCurveBlockTypes.EaseOutSine:
        func = (v) => Math.sin(v * 3.1415 / 2);
        break;
      case GeometryCurveBlockTypes.EaseInOutSine:
        func = (v) => -(Math.cos(v * 3.1415) - 1) / 2;
        break;
      case GeometryCurveBlockTypes.EaseInQuad:
        func = (v) => v * v;
        break;
      case GeometryCurveBlockTypes.EaseOutQuad:
        func = (v) => (1 - v) * (1 - v);
        break;
      case GeometryCurveBlockTypes.EaseInOutQuad: {
        func = (v) => v < 0.5 ? 2 * v * v : 1 - Math.pow(-2 * v + 2, 2) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInCubic:
        func = (v) => v * v * v;
        break;
      case GeometryCurveBlockTypes.EaseOutCubic: {
        func = (v) => 1 - Math.pow(1 - v, 3);
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutCubic: {
        func = (v) => v < 0.5 ? 4 * v * v * v : 1 - Math.pow(-2 * v + 2, 3) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInQuart:
        func = (v) => v * v * v * v;
        break;
      case GeometryCurveBlockTypes.EaseOutQuart: {
        func = (v) => 1 - Math.pow(1 - v, 4);
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutQuart: {
        func = (v) => v < 0.5 ? 8 * v * v * v * v : 1 - Math.pow(-2 * v + 2, 4) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInQuint:
        func = (v) => v * v * v * v * v;
        break;
      case GeometryCurveBlockTypes.EaseOutQuint: {
        func = (v) => 1 - Math.pow(1 - v, 5);
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutQuint: {
        func = (v) => v < 0.5 ? 16 * v * v * v * v * v : 1 - Math.pow(-2 * v + 2, 5) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInExpo: {
        func = (v) => v === 0 ? 0 : Math.pow(2, 10 * v - 10);
        break;
      }
      case GeometryCurveBlockTypes.EaseOutExpo: {
        func = (v) => v === 1 ? 1 : 1 - Math.pow(2, -10 * v);
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutExpo: {
        func = (v) => v === 0 ? 0 : v === 1 ? 1 : v < 0.5 ? Math.pow(2, 20 * v - 10) / 2 : (2 - Math.pow(2, -20 * v + 10)) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInCirc: {
        func = (v) => 1 - Math.sqrt(1 - Math.pow(v, 2));
        break;
      }
      case GeometryCurveBlockTypes.EaseOutCirc: {
        func = (v) => Math.sqrt(1 - Math.pow(v - 1, 2));
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutCirc: {
        func = (v) => v < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * v, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * v + 2, 2)) + 1) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInBack: {
        func = (v) => 2.70158 * v * v * v - 1.70158 * v * v;
        break;
      }
      case GeometryCurveBlockTypes.EaseOutBack: {
        func = (v) => 2.70158 * Math.pow(v - 1, 3) + 1.70158 * Math.pow(v - 1, 2);
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutBack: {
        func = (v) => v < 0.5 ? Math.pow(2 * v, 2) * (3.5949095 * 2 * v - 2.5949095) / 2 : (Math.pow(2 * v - 2, 2) * (3.5949095 * (v * 2 - 2) + 3.5949095) + 2) / 2;
        break;
      }
      case GeometryCurveBlockTypes.EaseInElastic: {
        func = (v) => v === 0 ? 0 : v === 1 ? 1 : -Math.pow(2, 10 * v - 10) * Math.sin((v * 10 - 10.75) * (2 * 3.1415 / 3));
        break;
      }
      case GeometryCurveBlockTypes.EaseOutElastic: {
        func = (v) => v === 0 ? 0 : v === 1 ? 1 : Math.pow(2, -10 * v) * Math.sin((v * 10 - 0.75) * (2 * 3.1415 / 3)) + 1;
        break;
      }
      case GeometryCurveBlockTypes.EaseInOutElastic: {
        func = (v) => v === 0 ? 0 : v == 1 ? 1 : v < 0.5 ? -(Math.pow(2, 20 * v - 10) * Math.sin((20 * v - 11.125) * (2 * 3.1415 / 4.5))) / 2 : Math.pow(2, -20 * v + 10) * Math.sin((20 * v - 11.125) * (2 * 3.1415 / 4.5)) / 2 + 1;
        break;
      }
    }
    this.output._storedFunction = (state) => {
      const input = this.input.getConnectedValue(state);
      switch (this.input.type) {
        case NodeGeometryBlockConnectionPointTypes.Float: {
          return func(input);
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          return new Vector2(func(input.x), func(input.y));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          return new Vector3(func(input.x), func(input.y), func(input.z));
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          return new Vector4(func(input.x), func(input.y), func(input.z), func(input.w));
        }
      }
      return 0;
    };
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.curveType = this.type;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.type = serializationObject.curveType;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${GeometryCurveBlockTypes[this.type]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Type", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "EaseInSine", value: GeometryCurveBlockTypes.EaseInSine },
      { label: "EaseOutSine", value: GeometryCurveBlockTypes.EaseOutSine },
      { label: "EaseInOutSine", value: GeometryCurveBlockTypes.EaseInOutSine },
      { label: "EaseInQuad", value: GeometryCurveBlockTypes.EaseInQuad },
      { label: "EaseOutQuad", value: GeometryCurveBlockTypes.EaseOutQuad },
      { label: "EaseInOutQuad", value: GeometryCurveBlockTypes.EaseInOutQuad },
      { label: "EaseInCubic", value: GeometryCurveBlockTypes.EaseInCubic },
      { label: "EaseOutCubic", value: GeometryCurveBlockTypes.EaseOutCubic },
      { label: "EaseInOutCubic", value: GeometryCurveBlockTypes.EaseInOutCubic },
      { label: "EaseInQuart", value: GeometryCurveBlockTypes.EaseInQuart },
      { label: "EaseOutQuart", value: GeometryCurveBlockTypes.EaseOutQuart },
      { label: "EaseInOutQuart", value: GeometryCurveBlockTypes.EaseInOutQuart },
      { label: "EaseInQuint", value: GeometryCurveBlockTypes.EaseInQuint },
      { label: "EaseOutQuint", value: GeometryCurveBlockTypes.EaseOutQuint },
      { label: "EaseInOutQuint", value: GeometryCurveBlockTypes.EaseInOutQuint },
      { label: "EaseInExpo", value: GeometryCurveBlockTypes.EaseInExpo },
      { label: "EaseOutExpo", value: GeometryCurveBlockTypes.EaseOutExpo },
      { label: "EaseInOutExpo", value: GeometryCurveBlockTypes.EaseInOutExpo },
      { label: "EaseInCirc", value: GeometryCurveBlockTypes.EaseInCirc },
      { label: "EaseOutCirc", value: GeometryCurveBlockTypes.EaseOutCirc },
      { label: "EaseInOutCirc", value: GeometryCurveBlockTypes.EaseInOutCirc },
      { label: "EaseInBack", value: GeometryCurveBlockTypes.EaseInBack },
      { label: "EaseOutBack", value: GeometryCurveBlockTypes.EaseOutBack },
      { label: "EaseInOutBack", value: GeometryCurveBlockTypes.EaseInOutBack },
      { label: "EaseInElastic", value: GeometryCurveBlockTypes.EaseInElastic },
      { label: "EaseOutElastic", value: GeometryCurveBlockTypes.EaseOutElastic },
      { label: "EaseInOutElastic", value: GeometryCurveBlockTypes.EaseInOutElastic }
    ]
  })
], GeometryCurveBlock.prototype, "type", undefined);
RegisterClass("BABYLON.GeometryCurveBlock", GeometryCurveBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryDesaturateBlock.js
init_math_vector();
init_typeStore();
class GeometryDesaturateBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("color", NodeGeometryBlockConnectionPointTypes.Vector3);
    this.registerInput("level", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector3);
  }
  getClassName() {
    return "GeometryDesaturateBlock";
  }
  get color() {
    return this._inputs[0];
  }
  get level() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.color.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const color = this.color.getConnectedValue(state);
      const level = this.level.getConnectedValue(state);
      const tempMin = Math.min(color.x, color.y, color.z);
      const tempMax = Math.max(color.x, color.y, color.z);
      const tempMerge = 0.5 * (tempMin + tempMax);
      return new Vector3(color.x * (1 - level) + tempMerge * level, color.y * (1 - level) + tempMerge * level, color.z * (1 - level) + tempMerge * level);
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryDesaturateBlock", GeometryDesaturateBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryPosterizeBlock.js
init_math_vector();
init_typeStore();
class GeometryPosterizeBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("steps", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
  }
  getClassName() {
    return "GeometryPosterizeBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get steps() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected || !this.steps.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const source = this.value.getConnectedValue(state);
      const steps = this.steps.getConnectedValue(state);
      let stepVector = steps;
      if (this.steps.type === NodeGeometryBlockConnectionPointTypes.Float) {
        switch (this.value.type) {
          case NodeGeometryBlockConnectionPointTypes.Vector2:
            stepVector = new Vector2(steps, steps);
            break;
          case NodeGeometryBlockConnectionPointTypes.Vector3:
            stepVector = new Vector3(steps, steps, steps);
            break;
          case NodeGeometryBlockConnectionPointTypes.Vector4:
            stepVector = new Vector4(steps, steps, steps, steps);
            break;
        }
      }
      switch (this.value.type) {
        case NodeGeometryBlockConnectionPointTypes.Vector2:
          return new Vector2(source.x / (1 / stepVector.x) * (1 / stepVector.x), source.y / (1 / stepVector.y) * (1 / stepVector.y));
        case NodeGeometryBlockConnectionPointTypes.Vector3:
          return new Vector3(source.x / (1 / stepVector.x) * (1 / stepVector.x), source.y / (1 / stepVector.y) * (1 / stepVector.y), source.z / (1 / stepVector.z) * (1 / stepVector.z));
        case NodeGeometryBlockConnectionPointTypes.Vector4:
          return new Vector4(source.x / (1 / stepVector.x) * (1 / stepVector.x), source.y / (1 / stepVector.y) * (1 / stepVector.y), source.z / (1 / stepVector.z) * (1 / stepVector.z), source.w / (1 / stepVector.w) * (1 / stepVector.w));
        default:
          return Math.floor(source / (1 / steps) * (1 / steps));
      }
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryPosterizeBlock", GeometryPosterizeBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryReplaceColorBlock.js
init_typeStore();
class GeometryReplaceColorBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("reference", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("distance", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerInput("replacement", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._linkConnectionTypes(0, 1);
    this._linkConnectionTypes(0, 3);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[3].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[3].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "GeometryReplaceColorBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get reference() {
    return this._inputs[1];
  }
  get distance() {
    return this._inputs[2];
  }
  get replacement() {
    return this._inputs[3];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected || !this.reference.isConnected || !this.replacement.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const value = this.value.getConnectedValue(state);
      const reference = this.reference.getConnectedValue(state);
      const distance = this.distance.getConnectedValue(state);
      const replacement = this.replacement.getConnectedValue(state);
      if (value.subtract(reference).length() < distance) {
        return replacement;
      } else {
        return value;
      }
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryReplaceColorBlock", GeometryReplaceColorBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryDistanceBlock.js
init_typeStore();
class GeometryDistanceBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "GeometryDistanceBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      return left.subtract(right).length();
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryDistanceBlock", GeometryDistanceBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryDotBlock.js
init_typeStore();
class GeometryDotBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float);
    this._linkConnectionTypes(0, 1);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "GeometryDotBlock";
  }
  get left() {
    return this._inputs[0];
  }
  get right() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.left.isConnected || !this.right.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const left = this.left.getConnectedValue(state);
      const right = this.right.getConnectedValue(state);
      return left.dot(right);
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryDotBlock", GeometryDotBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryLengthBlock.js
init_typeStore();
class GeometryLengthBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
  }
  getClassName() {
    return "GeometryLengthBlock";
  }
  get value() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.value.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const value = this.value.getConnectedValue(state);
      return value.length();
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryLengthBlock", GeometryLengthBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryRotate2dBlock.js
init_math_vector();
init_typeStore();
class GeometryRotate2dBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.Vector2);
    this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, true, 0);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Vector2);
  }
  getClassName() {
    return "GeometryRotate2dBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get angle() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    if (!this.input.isConnected) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    this.output._storedFunction = (state) => {
      const input = this.input.getConnectedValue(state);
      const angle = this.angle.getConnectedValue(state);
      return new Vector2(Math.cos(angle) * input.x - Math.sin(angle) * input.y, Math.sin(angle) * input.x + Math.cos(angle) * input.y);
    };
    return this;
  }
}
RegisterClass("BABYLON.GeometryRotate2dBlock", GeometryRotate2dBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryInterceptorBlock.js
init_observable();
init_typeStore();
class GeometryInterceptorBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.onInterceptionObservable = new Observable(undefined, true);
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
  }
  get buildExecutionTime() {
    return -1;
  }
  getClassName() {
    return "GeometryInterceptorBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    const output = this._outputs[0];
    const input = this._inputs[0];
    output._storedFunction = (state2) => {
      let value = input.getConnectedValue(state2);
      if (this.customFunction) {
        value = this.customFunction(value, state2);
      }
      this.onInterceptionObservable.notifyObservers(value);
      return value;
    };
  }
}
RegisterClass("BABYLON.GeometryInterceptorBlock", GeometryInterceptorBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryEaseBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
init_easing();
var GeometryEaseBlockTypes;
(function(GeometryEaseBlockTypes2) {
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInSine"] = 0] = "EaseInSine";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutSine"] = 1] = "EaseOutSine";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutSine"] = 2] = "EaseInOutSine";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInQuad"] = 3] = "EaseInQuad";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutQuad"] = 4] = "EaseOutQuad";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutQuad"] = 5] = "EaseInOutQuad";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInCubic"] = 6] = "EaseInCubic";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutCubic"] = 7] = "EaseOutCubic";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutCubic"] = 8] = "EaseInOutCubic";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInQuart"] = 9] = "EaseInQuart";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutQuart"] = 10] = "EaseOutQuart";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutQuart"] = 11] = "EaseInOutQuart";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInQuint"] = 12] = "EaseInQuint";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutQuint"] = 13] = "EaseOutQuint";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutQuint"] = 14] = "EaseInOutQuint";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInExpo"] = 15] = "EaseInExpo";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutExpo"] = 16] = "EaseOutExpo";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutExpo"] = 17] = "EaseInOutExpo";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInCirc"] = 18] = "EaseInCirc";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutCirc"] = 19] = "EaseOutCirc";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutCirc"] = 20] = "EaseInOutCirc";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInBack"] = 21] = "EaseInBack";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutBack"] = 22] = "EaseOutBack";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutBack"] = 23] = "EaseInOutBack";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInElastic"] = 24] = "EaseInElastic";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseOutElastic"] = 25] = "EaseOutElastic";
  GeometryEaseBlockTypes2[GeometryEaseBlockTypes2["EaseInOutElastic"] = 26] = "EaseInOutElastic";
})(GeometryEaseBlockTypes || (GeometryEaseBlockTypes = {}));

class GeometryEaseBlock extends NodeGeometryBlock {
  get type() {
    return this._type;
  }
  set type(value) {
    if (this._type === value) {
      return;
    }
    this._type = value;
    switch (this._type) {
      case GeometryEaseBlockTypes.EaseInSine:
        this._easingFunction = new SineEase;
        this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutSine:
        this._easingFunction = new SineEase;
        this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutSine:
        this._easingFunction = new SineEase;
        this._easingFunction.setEasingMode(SineEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInQuad:
        this._easingFunction = new QuadraticEase;
        this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutQuad:
        this._easingFunction = new QuadraticEase;
        this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutQuad:
        this._easingFunction = new QuadraticEase;
        this._easingFunction.setEasingMode(QuadraticEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInCubic:
        this._easingFunction = new CubicEase;
        this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutCubic:
        this._easingFunction = new CubicEase;
        this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutCubic:
        this._easingFunction = new CubicEase;
        this._easingFunction.setEasingMode(CubicEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInQuart:
        this._easingFunction = new QuarticEase;
        this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutQuart:
        this._easingFunction = new QuarticEase;
        this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutQuart:
        this._easingFunction = new QuarticEase;
        this._easingFunction.setEasingMode(QuarticEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInQuint:
        this._easingFunction = new QuinticEase;
        this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutQuint:
        this._easingFunction = new QuinticEase;
        this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutQuint:
        this._easingFunction = new QuinticEase;
        this._easingFunction.setEasingMode(QuinticEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInExpo:
        this._easingFunction = new ExponentialEase;
        this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutExpo:
        this._easingFunction = new ExponentialEase;
        this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutExpo:
        this._easingFunction = new ExponentialEase;
        this._easingFunction.setEasingMode(ExponentialEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInCirc:
        this._easingFunction = new CircleEase;
        this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutCirc:
        this._easingFunction = new CircleEase;
        this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutCirc:
        this._easingFunction = new CircleEase;
        this._easingFunction.setEasingMode(CircleEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInBack:
        this._easingFunction = new BackEase;
        this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutBack:
        this._easingFunction = new BackEase;
        this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutBack:
        this._easingFunction = new BackEase;
        this._easingFunction.setEasingMode(BackEase.EASINGMODE_EASEINOUT);
        break;
      case GeometryEaseBlockTypes.EaseInElastic:
        this._easingFunction = new ElasticEase;
        this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEIN);
        break;
      case GeometryEaseBlockTypes.EaseOutElastic:
        this._easingFunction = new ElasticEase;
        this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEOUT);
        break;
      case GeometryEaseBlockTypes.EaseInOutElastic:
        this._easingFunction = new ElasticEase;
        this._easingFunction.setEasingMode(ElasticEase.EASINGMODE_EASEINOUT);
        break;
    }
  }
  constructor(name375) {
    super(name375);
    this._easingFunction = new SineEase;
    this._type = GeometryEaseBlockTypes.EaseInOutSine;
    this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[0];
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry);
    this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Texture);
  }
  getClassName() {
    return "GeometryEaseBlock";
  }
  get input() {
    return this._inputs[0];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    super._buildBlock(state);
    if (!this._easingFunction) {
      this.output._storedFunction = null;
      this.output._storedValue = null;
      return;
    }
    switch (this.input.type) {
      case NodeGeometryBlockConnectionPointTypes.Int:
      case NodeGeometryBlockConnectionPointTypes.Float: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return this._easingFunction.ease(source);
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector2: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector2(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector3: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector3(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y), this._easingFunction.ease(source.z));
        };
        break;
      }
      case NodeGeometryBlockConnectionPointTypes.Vector4: {
        this.output._storedFunction = (state2) => {
          const source = this.input.getConnectedValue(state2);
          return new Vector4(this._easingFunction.ease(source.x), this._easingFunction.ease(source.y), this._easingFunction.ease(source.z), this._easingFunction.ease(source.w));
        };
        break;
      }
    }
    return this;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.type = this.type;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.type = serializationObject.type;
  }
  _dumpPropertiesCode() {
    const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.GeometryEaseBlockTypes.${GeometryEaseBlockTypes[this.type]};
`;
    return codeString;
  }
}
__decorate([
  editableInPropertyPage("Type", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "EaseInSine", value: GeometryEaseBlockTypes.EaseInSine },
      { label: "EaseOutSine", value: GeometryEaseBlockTypes.EaseOutSine },
      { label: "EaseInOutSine", value: GeometryEaseBlockTypes.EaseInOutSine },
      { label: "EaseInQuad", value: GeometryEaseBlockTypes.EaseInQuad },
      { label: "EaseOutQuad", value: GeometryEaseBlockTypes.EaseOutQuad },
      { label: "EaseInOutQuad", value: GeometryEaseBlockTypes.EaseInOutQuad },
      { label: "EaseInCubic", value: GeometryEaseBlockTypes.EaseInCubic },
      { label: "EaseOutCubic", value: GeometryEaseBlockTypes.EaseOutCubic },
      { label: "EaseInOutCubic", value: GeometryEaseBlockTypes.EaseInOutCubic },
      { label: "EaseInQuart", value: GeometryEaseBlockTypes.EaseInQuart },
      { label: "EaseOutQuart", value: GeometryEaseBlockTypes.EaseOutQuart },
      { label: "EaseInOutQuart", value: GeometryEaseBlockTypes.EaseInOutQuart },
      { label: "EaseInQuint", value: GeometryEaseBlockTypes.EaseInQuint },
      { label: "EaseOutQuint", value: GeometryEaseBlockTypes.EaseOutQuint },
      { label: "EaseInOutQuint", value: GeometryEaseBlockTypes.EaseInOutQuint },
      { label: "EaseInExpo", value: GeometryEaseBlockTypes.EaseInExpo },
      { label: "EaseOutExpo", value: GeometryEaseBlockTypes.EaseOutExpo },
      { label: "EaseInOutExpo", value: GeometryEaseBlockTypes.EaseInOutExpo },
      { label: "EaseInCirc", value: GeometryEaseBlockTypes.EaseInCirc },
      { label: "EaseOutCirc", value: GeometryEaseBlockTypes.EaseOutCirc },
      { label: "EaseInOutCirc", value: GeometryEaseBlockTypes.EaseInOutCirc },
      { label: "EaseInBack", value: GeometryEaseBlockTypes.EaseInBack },
      { label: "EaseOutBack", value: GeometryEaseBlockTypes.EaseOutBack },
      { label: "EaseInOutBack", value: GeometryEaseBlockTypes.EaseInOutBack },
      { label: "EaseInElastic", value: GeometryEaseBlockTypes.EaseInElastic },
      { label: "EaseOutElastic", value: GeometryEaseBlockTypes.EaseOutElastic },
      { label: "EaseInOutElastic", value: GeometryEaseBlockTypes.EaseInOutElastic }
    ]
  })
], GeometryEaseBlock.prototype, "type", null);
RegisterClass("BABYLON.GeometryEaseBlock", GeometryEaseBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/aggregatorBlock.js
init_tslib_es6();
init_typeStore();
init_math_vector();
var Aggregations;
(function(Aggregations2) {
  Aggregations2[Aggregations2["Max"] = 0] = "Max";
  Aggregations2[Aggregations2["Min"] = 1] = "Min";
  Aggregations2[Aggregations2["Sum"] = 2] = "Sum";
})(Aggregations || (Aggregations = {}));

class AggregatorBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.aggregation = Aggregations.Sum;
    this.evaluateContext = true;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("source", NodeGeometryBlockConnectionPointTypes.AutoDetect);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput);
    this._outputs[0]._typeConnectionSource = this._inputs[1];
  }
  getExecutionIndex() {
    return this._currentIndex;
  }
  getExecutionLoopIndex() {
    return this._currentIndex;
  }
  getExecutionFaceIndex() {
    return 0;
  }
  getClassName() {
    return "AggregatorBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get source() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock(state) {
    const func = (state2) => {
      state2.pushExecutionContext(this);
      this._vertexData = this.geometry.getConnectedValue(state2);
      state2.pushGeometryContext(this._vertexData);
      if (!this._vertexData || !this._vertexData.positions || !this.source.isConnected) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedValue = null;
        return;
      }
      const vertexCount = this._vertexData.positions.length / 3;
      const context = [];
      for (this._currentIndex = 0;this._currentIndex < vertexCount; this._currentIndex++) {
        context.push(this.source.getConnectedValue(state2));
      }
      let func2 = null;
      switch (this.aggregation) {
        case Aggregations.Max: {
          func2 = (a, b) => Math.max(a, b);
          break;
        }
        case Aggregations.Min: {
          func2 = (a, b) => Math.min(a, b);
          break;
        }
        case Aggregations.Sum: {
          func2 = (a, b) => a + b;
          break;
        }
      }
      if (!func2) {
        state2.restoreGeometryContext();
        state2.restoreExecutionContext();
        this.output._storedFunction = null;
        this.output._storedValue = null;
        return;
      }
      let returnValue;
      switch (this.source.type) {
        case NodeGeometryBlockConnectionPointTypes.Int:
        case NodeGeometryBlockConnectionPointTypes.Float: {
          returnValue = context.reduce(func2);
          break;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector2: {
          const x = context.map((v) => v.x).reduce(func2);
          const y = context.map((v) => v.y).reduce(func2);
          returnValue = new Vector2(x, y);
          break;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector3: {
          const x = context.map((v) => v.x).reduce(func2);
          const y = context.map((v) => v.y).reduce(func2);
          const z = context.map((v) => v.z).reduce(func2);
          returnValue = new Vector3(x, y, z);
          break;
        }
        case NodeGeometryBlockConnectionPointTypes.Vector4: {
          const x = context.map((v) => v.x).reduce(func2);
          const y = context.map((v) => v.y).reduce(func2);
          const z = context.map((v) => v.z).reduce(func2);
          const w = context.map((v) => v.w).reduce(func2);
          returnValue = new Vector4(x, y, z, w);
          break;
        }
      }
      state2.restoreGeometryContext();
      state2.restoreExecutionContext();
      return returnValue;
    };
    if (this.evaluateContext) {
      this.output._storedFunction = func;
    } else {
      this.output._storedFunction = null;
      this.output._storedValue = func(state);
    }
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.aggregation = BABYLON.Aggregations.${Aggregations[this.aggregation]};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.evaluateContext = this.evaluateContext;
    serializationObject.aggregation = this.aggregation;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    if (serializationObject.evaluateContext !== undefined) {
      this.evaluateContext = serializationObject.evaluateContext;
    }
    if (serializationObject.aggregation !== undefined) {
      this.aggregation = serializationObject.aggregation;
    }
  }
}
__decorate([
  editableInPropertyPage("Aggregation", 4, "ADVANCED", {
    notifiers: { rebuild: true },
    embedded: true,
    options: [
      { label: "Max", value: Aggregations.Max },
      { label: "Min", value: Aggregations.Min },
      { label: "Sum", value: Aggregations.Sum }
    ]
  })
], AggregatorBlock.prototype, "aggregation", undefined);
__decorate([
  editableInPropertyPage("Evaluate context", 0, "ADVANCED", { notifiers: { rebuild: true } })
], AggregatorBlock.prototype, "evaluateContext", undefined);
RegisterClass("BABYLON.AggregatorBlock", AggregatorBlock);
// node_modules/@babylonjs/core/Meshes/Node/Blocks/subdivideBlock.js
init_tslib_es6();
init_typeStore();
class SubdivideBlock extends NodeGeometryBlock {
  constructor(name375) {
    super(name375);
    this.flatOnly = false;
    this.loopWeight = 1;
    this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry);
    this.registerInput("level", NodeGeometryBlockConnectionPointTypes.Int, true, 1, 0, 8);
    this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry);
  }
  getClassName() {
    return "SubdivideBlock";
  }
  get geometry() {
    return this._inputs[0];
  }
  get level() {
    return this._inputs[1];
  }
  get output() {
    return this._outputs[0];
  }
  _buildBlock() {
    this.output._storedFunction = (state) => {
      if (!this.geometry.isConnected) {
        return null;
      }
      const vertexData = this.geometry.getConnectedValue(state);
      if (!vertexData) {
        return null;
      }
      const level = this.level.getConnectedValue(state);
      return Subdivide(vertexData, level, {
        flatOnly: this.flatOnly,
        weight: this.loopWeight
      });
    };
  }
  _dumpPropertiesCode() {
    let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.flatOnly = ${this.flatOnly ? "true" : "false"};
`;
    codeString += `${this._codeVariableName}.loopWeight = ${this.loopWeight};
`;
    return codeString;
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.flatOnly = this.flatOnly;
    serializationObject.loopWeight = this.loopWeight;
    return serializationObject;
  }
  _deserialize(serializationObject) {
    super._deserialize(serializationObject);
    this.flatOnly = serializationObject.flatOnly;
    this.loopWeight = serializationObject.loopWeight;
  }
}
__decorate([
  editableInPropertyPage("Flat Only", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } })
], SubdivideBlock.prototype, "flatOnly", undefined);
__decorate([
  editableInPropertyPage("Loop weight", 1, "ADVANCED", { embedded: true, min: 0, max: 1, notifiers: { rebuild: true } })
], SubdivideBlock.prototype, "loopWeight", undefined);
RegisterClass("BABYLON.SubdivideBlock", SubdivideBlock);
// node_modules/@babylonjs/core/Meshes/GaussianSplatting/gaussianSplattingMesh.js
init_math_vector();
init_logger();
init_tools();
init_textureTools();
init_engineStore();
var unpackUnorm = (value, bits) => {
  const t = (1 << bits) - 1;
  return (value & t) / t;
};
var unpack111011 = (value, result) => {
  result.x = unpackUnorm(value >>> 21, 11);
  result.y = unpackUnorm(value >>> 11, 10);
  result.z = unpackUnorm(value, 11);
};
var unpack8888 = (value, result) => {
  result[0] = unpackUnorm(value >>> 24, 8) * 255;
  result[1] = unpackUnorm(value >>> 16, 8) * 255;
  result[2] = unpackUnorm(value >>> 8, 8) * 255;
  result[3] = unpackUnorm(value, 8) * 255;
};
var unpackRot = (value, result) => {
  const norm = 1 / (Math.sqrt(2) * 0.5);
  const a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm;
  const b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm;
  const c = (unpackUnorm(value, 10) - 0.5) * norm;
  const m = Math.sqrt(1 - (a * a + b * b + c * c));
  switch (value >>> 30) {
    case 0:
      result.set(m, a, b, c);
      break;
    case 1:
      result.set(a, m, b, c);
      break;
    case 2:
      result.set(a, b, m, c);
      break;
    case 3:
      result.set(a, b, c, m);
      break;
  }
};
var PLYType;
(function(PLYType2) {
  PLYType2[PLYType2["FLOAT"] = 0] = "FLOAT";
  PLYType2[PLYType2["INT"] = 1] = "INT";
  PLYType2[PLYType2["UINT"] = 2] = "UINT";
  PLYType2[PLYType2["DOUBLE"] = 3] = "DOUBLE";
  PLYType2[PLYType2["UCHAR"] = 4] = "UCHAR";
  PLYType2[PLYType2["UNDEFINED"] = 5] = "UNDEFINED";
})(PLYType || (PLYType = {}));
var PLYValue;
(function(PLYValue2) {
  PLYValue2[PLYValue2["MIN_X"] = 0] = "MIN_X";
  PLYValue2[PLYValue2["MIN_Y"] = 1] = "MIN_Y";
  PLYValue2[PLYValue2["MIN_Z"] = 2] = "MIN_Z";
  PLYValue2[PLYValue2["MAX_X"] = 3] = "MAX_X";
  PLYValue2[PLYValue2["MAX_Y"] = 4] = "MAX_Y";
  PLYValue2[PLYValue2["MAX_Z"] = 5] = "MAX_Z";
  PLYValue2[PLYValue2["MIN_SCALE_X"] = 6] = "MIN_SCALE_X";
  PLYValue2[PLYValue2["MIN_SCALE_Y"] = 7] = "MIN_SCALE_Y";
  PLYValue2[PLYValue2["MIN_SCALE_Z"] = 8] = "MIN_SCALE_Z";
  PLYValue2[PLYValue2["MAX_SCALE_X"] = 9] = "MAX_SCALE_X";
  PLYValue2[PLYValue2["MAX_SCALE_Y"] = 10] = "MAX_SCALE_Y";
  PLYValue2[PLYValue2["MAX_SCALE_Z"] = 11] = "MAX_SCALE_Z";
  PLYValue2[PLYValue2["PACKED_POSITION"] = 12] = "PACKED_POSITION";
  PLYValue2[PLYValue2["PACKED_ROTATION"] = 13] = "PACKED_ROTATION";
  PLYValue2[PLYValue2["PACKED_SCALE"] = 14] = "PACKED_SCALE";
  PLYValue2[PLYValue2["PACKED_COLOR"] = 15] = "PACKED_COLOR";
  PLYValue2[PLYValue2["X"] = 16] = "X";
  PLYValue2[PLYValue2["Y"] = 17] = "Y";
  PLYValue2[PLYValue2["Z"] = 18] = "Z";
  PLYValue2[PLYValue2["SCALE_0"] = 19] = "SCALE_0";
  PLYValue2[PLYValue2["SCALE_1"] = 20] = "SCALE_1";
  PLYValue2[PLYValue2["SCALE_2"] = 21] = "SCALE_2";
  PLYValue2[PLYValue2["DIFFUSE_RED"] = 22] = "DIFFUSE_RED";
  PLYValue2[PLYValue2["DIFFUSE_GREEN"] = 23] = "DIFFUSE_GREEN";
  PLYValue2[PLYValue2["DIFFUSE_BLUE"] = 24] = "DIFFUSE_BLUE";
  PLYValue2[PLYValue2["OPACITY"] = 25] = "OPACITY";
  PLYValue2[PLYValue2["F_DC_0"] = 26] = "F_DC_0";
  PLYValue2[PLYValue2["F_DC_1"] = 27] = "F_DC_1";
  PLYValue2[PLYValue2["F_DC_2"] = 28] = "F_DC_2";
  PLYValue2[PLYValue2["F_DC_3"] = 29] = "F_DC_3";
  PLYValue2[PLYValue2["ROT_0"] = 30] = "ROT_0";
  PLYValue2[PLYValue2["ROT_1"] = 31] = "ROT_1";
  PLYValue2[PLYValue2["ROT_2"] = 32] = "ROT_2";
  PLYValue2[PLYValue2["ROT_3"] = 33] = "ROT_3";
  PLYValue2[PLYValue2["MIN_COLOR_R"] = 34] = "MIN_COLOR_R";
  PLYValue2[PLYValue2["MIN_COLOR_G"] = 35] = "MIN_COLOR_G";
  PLYValue2[PLYValue2["MIN_COLOR_B"] = 36] = "MIN_COLOR_B";
  PLYValue2[PLYValue2["MAX_COLOR_R"] = 37] = "MAX_COLOR_R";
  PLYValue2[PLYValue2["MAX_COLOR_G"] = 38] = "MAX_COLOR_G";
  PLYValue2[PLYValue2["MAX_COLOR_B"] = 39] = "MAX_COLOR_B";
  PLYValue2[PLYValue2["SH_0"] = 40] = "SH_0";
  PLYValue2[PLYValue2["SH_1"] = 41] = "SH_1";
  PLYValue2[PLYValue2["SH_2"] = 42] = "SH_2";
  PLYValue2[PLYValue2["SH_3"] = 43] = "SH_3";
  PLYValue2[PLYValue2["SH_4"] = 44] = "SH_4";
  PLYValue2[PLYValue2["SH_5"] = 45] = "SH_5";
  PLYValue2[PLYValue2["SH_6"] = 46] = "SH_6";
  PLYValue2[PLYValue2["SH_7"] = 47] = "SH_7";
  PLYValue2[PLYValue2["SH_8"] = 48] = "SH_8";
  PLYValue2[PLYValue2["SH_9"] = 49] = "SH_9";
  PLYValue2[PLYValue2["SH_10"] = 50] = "SH_10";
  PLYValue2[PLYValue2["SH_11"] = 51] = "SH_11";
  PLYValue2[PLYValue2["SH_12"] = 52] = "SH_12";
  PLYValue2[PLYValue2["SH_13"] = 53] = "SH_13";
  PLYValue2[PLYValue2["SH_14"] = 54] = "SH_14";
  PLYValue2[PLYValue2["SH_15"] = 55] = "SH_15";
  PLYValue2[PLYValue2["SH_16"] = 56] = "SH_16";
  PLYValue2[PLYValue2["SH_17"] = 57] = "SH_17";
  PLYValue2[PLYValue2["SH_18"] = 58] = "SH_18";
  PLYValue2[PLYValue2["SH_19"] = 59] = "SH_19";
  PLYValue2[PLYValue2["SH_20"] = 60] = "SH_20";
  PLYValue2[PLYValue2["SH_21"] = 61] = "SH_21";
  PLYValue2[PLYValue2["SH_22"] = 62] = "SH_22";
  PLYValue2[PLYValue2["SH_23"] = 63] = "SH_23";
  PLYValue2[PLYValue2["SH_24"] = 64] = "SH_24";
  PLYValue2[PLYValue2["SH_25"] = 65] = "SH_25";
  PLYValue2[PLYValue2["SH_26"] = 66] = "SH_26";
  PLYValue2[PLYValue2["SH_27"] = 67] = "SH_27";
  PLYValue2[PLYValue2["SH_28"] = 68] = "SH_28";
  PLYValue2[PLYValue2["SH_29"] = 69] = "SH_29";
  PLYValue2[PLYValue2["SH_30"] = 70] = "SH_30";
  PLYValue2[PLYValue2["SH_31"] = 71] = "SH_31";
  PLYValue2[PLYValue2["SH_32"] = 72] = "SH_32";
  PLYValue2[PLYValue2["SH_33"] = 73] = "SH_33";
  PLYValue2[PLYValue2["SH_34"] = 74] = "SH_34";
  PLYValue2[PLYValue2["SH_35"] = 75] = "SH_35";
  PLYValue2[PLYValue2["SH_36"] = 76] = "SH_36";
  PLYValue2[PLYValue2["SH_37"] = 77] = "SH_37";
  PLYValue2[PLYValue2["SH_38"] = 78] = "SH_38";
  PLYValue2[PLYValue2["SH_39"] = 79] = "SH_39";
  PLYValue2[PLYValue2["SH_40"] = 80] = "SH_40";
  PLYValue2[PLYValue2["SH_41"] = 81] = "SH_41";
  PLYValue2[PLYValue2["SH_42"] = 82] = "SH_42";
  PLYValue2[PLYValue2["SH_43"] = 83] = "SH_43";
  PLYValue2[PLYValue2["SH_44"] = 84] = "SH_44";
  PLYValue2[PLYValue2["UNDEFINED"] = 85] = "UNDEFINED";
})(PLYValue || (PLYValue = {}));

class GaussianSplattingMesh extends Mesh {
  get shDegree() {
    return this._shDegree;
  }
  get splatsData() {
    return this._splatsData;
  }
  get covariancesATexture() {
    return this._covariancesATexture;
  }
  get covariancesBTexture() {
    return this._covariancesBTexture;
  }
  get centersTexture() {
    return this._centersTexture;
  }
  get colorsTexture() {
    return this._colorsTexture;
  }
  get shTextures() {
    return this._shTextures;
  }
  set material(value) {
    this._material = value;
    this._material.backFaceCulling = true;
    this._material.cullBackFaces = false;
    value.resetDrawCache();
  }
  get material() {
    return this._material;
  }
  constructor(name375, url = null, scene = null, keepInRam = false) {
    super(name375, scene);
    this._vertexCount = 0;
    this._worker = null;
    this._frameIdLastUpdate = -1;
    this._modelViewMatrix = Matrix.Identity();
    this._canPostToWorker = true;
    this._readyToDisplay = false;
    this._covariancesATexture = null;
    this._covariancesBTexture = null;
    this._centersTexture = null;
    this._colorsTexture = null;
    this._splatPositions = null;
    this._splatIndex = null;
    this._shTextures = null;
    this._splatsData = null;
    this._sh = null;
    this._keepInRam = false;
    this._delayedTextureUpdate = null;
    this._oldDirection = new Vector3;
    this._useRGBACovariants = false;
    this._material = null;
    this._tmpCovariances = [0, 0, 0, 0, 0, 0];
    this._sortIsDirty = false;
    this._shDegree = 0;
    const vertexData = new VertexData;
    vertexData.positions = [-3, -2, 0, 3, -2, 0, 0, 4, 0];
    vertexData.indices = [0, 1, 2];
    vertexData.applyToMesh(this);
    this.subMeshes = [];
    new SubMesh(0, 0, 3, 0, 3, this);
    this.setEnabled(false);
    this._useRGBACovariants = !this.getEngine().isWebGPU && this.getEngine().version === 1;
    this._keepInRam = keepInRam;
    if (url) {
      this.loadFileAsync(url);
    }
    this._material = new GaussianSplattingMaterial(this.name + "_material", this._scene);
  }
  getClassName() {
    return "GaussianSplattingMesh";
  }
  getTotalVertices() {
    return this._vertexCount;
  }
  isReady(completeCheck = false) {
    if (!super.isReady(completeCheck, true)) {
      return false;
    }
    if (!this._readyToDisplay) {
      this._postToWorker(true);
      return false;
    }
    return true;
  }
  _postToWorker(forced = false) {
    const frameId = this.getScene().getFrameId();
    if ((forced || frameId !== this._frameIdLastUpdate) && this._worker && this._scene.activeCamera && this._canPostToWorker) {
      const cameraMatrix = this._scene.activeCamera.getViewMatrix();
      this.getWorldMatrix().multiplyToRef(cameraMatrix, this._modelViewMatrix);
      cameraMatrix.invertToRef(TmpVectors.Matrix[0]);
      this.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], TmpVectors.Matrix[1]);
      Vector3.TransformNormalToRef(Vector3.Forward(this._scene.useRightHandedSystem), TmpVectors.Matrix[1], TmpVectors.Vector3[2]);
      TmpVectors.Vector3[2].normalize();
      const dot = Vector3.Dot(TmpVectors.Vector3[2], this._oldDirection);
      if (forced || Math.abs(dot - 1) >= 0.01) {
        this._oldDirection.copyFrom(TmpVectors.Vector3[2]);
        this._frameIdLastUpdate = frameId;
        this._canPostToWorker = false;
        this._worker.postMessage({ view: this._modelViewMatrix.m, depthMix: this._depthMix, useRightHandedSystem: this._scene.useRightHandedSystem }, [
          this._depthMix.buffer
        ]);
      }
    }
  }
  render(subMesh, enableAlphaMode, effectiveMeshReplacement) {
    this._postToWorker();
    return super.render(subMesh, enableAlphaMode, effectiveMeshReplacement);
  }
  static _TypeNameToEnum(name375) {
    switch (name375) {
      case "float":
        return 0;
      case "int":
        return 1;
        break;
      case "uint":
        return 2;
      case "double":
        return 3;
      case "uchar":
        return 4;
    }
    return 5;
  }
  static _ValueNameToEnum(name375) {
    switch (name375) {
      case "min_x":
        return 0;
      case "min_y":
        return 1;
      case "min_z":
        return 2;
      case "max_x":
        return 3;
      case "max_y":
        return 4;
      case "max_z":
        return 5;
      case "min_scale_x":
        return 6;
      case "min_scale_y":
        return 7;
      case "min_scale_z":
        return 8;
      case "max_scale_x":
        return 9;
      case "max_scale_y":
        return 10;
      case "max_scale_z":
        return 11;
      case "packed_position":
        return 12;
      case "packed_rotation":
        return 13;
      case "packed_scale":
        return 14;
      case "packed_color":
        return 15;
      case "x":
        return 16;
      case "y":
        return 17;
      case "z":
        return 18;
      case "scale_0":
        return 19;
      case "scale_1":
        return 20;
      case "scale_2":
        return 21;
      case "diffuse_red":
      case "red":
        return 22;
      case "diffuse_green":
      case "green":
        return 23;
      case "diffuse_blue":
      case "blue":
        return 24;
      case "f_dc_0":
        return 26;
      case "f_dc_1":
        return 27;
      case "f_dc_2":
        return 28;
      case "f_dc_3":
        return 29;
      case "opacity":
        return 25;
      case "rot_0":
        return 30;
      case "rot_1":
        return 31;
      case "rot_2":
        return 32;
      case "rot_3":
        return 33;
      case "min_r":
        return 34;
      case "min_g":
        return 35;
      case "min_b":
        return 36;
      case "max_r":
        return 37;
      case "max_g":
        return 38;
      case "max_b":
        return 39;
      case "f_rest_0":
        return 40;
      case "f_rest_1":
        return 41;
      case "f_rest_2":
        return 42;
      case "f_rest_3":
        return 43;
      case "f_rest_4":
        return 44;
      case "f_rest_5":
        return 45;
      case "f_rest_6":
        return 46;
      case "f_rest_7":
        return 47;
      case "f_rest_8":
        return 48;
      case "f_rest_9":
        return 49;
      case "f_rest_10":
        return 50;
      case "f_rest_11":
        return 51;
      case "f_rest_12":
        return 52;
      case "f_rest_13":
        return 53;
      case "f_rest_14":
        return 54;
      case "f_rest_15":
        return 55;
      case "f_rest_16":
        return 56;
      case "f_rest_17":
        return 57;
      case "f_rest_18":
        return 58;
      case "f_rest_19":
        return 59;
      case "f_rest_20":
        return 60;
      case "f_rest_21":
        return 61;
      case "f_rest_22":
        return 62;
      case "f_rest_23":
        return 63;
      case "f_rest_24":
        return 64;
      case "f_rest_25":
        return 65;
      case "f_rest_26":
        return 66;
      case "f_rest_27":
        return 67;
      case "f_rest_28":
        return 68;
      case "f_rest_29":
        return 69;
      case "f_rest_30":
        return 70;
      case "f_rest_31":
        return 71;
      case "f_rest_32":
        return 72;
      case "f_rest_33":
        return 73;
      case "f_rest_34":
        return 74;
      case "f_rest_35":
        return 75;
      case "f_rest_36":
        return 76;
      case "f_rest_37":
        return 77;
      case "f_rest_38":
        return 78;
      case "f_rest_39":
        return 79;
      case "f_rest_40":
        return 80;
      case "f_rest_41":
        return 81;
      case "f_rest_42":
        return 82;
      case "f_rest_43":
        return 83;
      case "f_rest_44":
        return 84;
    }
    return 85;
  }
  static ParseHeader(data) {
    const ubuf = new Uint8Array(data);
    const header = new TextDecoder().decode(ubuf.slice(0, 1024 * 10));
    const headerEnd = `end_header
`;
    const headerEndIndex = header.indexOf(headerEnd);
    if (headerEndIndex < 0 || !header) {
      return null;
    }
    const vertexCount = parseInt(/element vertex (\d+)\n/.exec(header)[1]);
    const chunkElement = /element chunk (\d+)\n/.exec(header);
    let chunkCount = 0;
    if (chunkElement) {
      chunkCount = parseInt(chunkElement[1]);
    }
    let rowVertexOffset = 0;
    let rowChunkOffset = 0;
    const offsets = {
      double: 8,
      int: 4,
      uint: 4,
      float: 4,
      short: 2,
      ushort: 2,
      uchar: 1,
      list: 0
    };
    let ElementMode;
    (function(ElementMode2) {
      ElementMode2[ElementMode2["Vertex"] = 0] = "Vertex";
      ElementMode2[ElementMode2["Chunk"] = 1] = "Chunk";
    })(ElementMode || (ElementMode = {}));
    let chunkMode = 1;
    const vertexProperties = [];
    const chunkProperties = [];
    const filtered = header.slice(0, headerEndIndex).split(`
`);
    let shDegree = 0;
    for (const prop of filtered) {
      if (prop.startsWith("property ")) {
        const [, typeName, name375] = prop.split(" ");
        const value = GaussianSplattingMesh._ValueNameToEnum(name375);
        if (value >= 84) {
          shDegree = 3;
        } else if (value >= 64) {
          shDegree = 2;
        } else if (value >= 48) {
          shDegree = 1;
        }
        const type = GaussianSplattingMesh._TypeNameToEnum(typeName);
        if (chunkMode == 1) {
          chunkProperties.push({ value, type, offset: rowChunkOffset });
          rowChunkOffset += offsets[typeName];
        } else if (chunkMode == 0) {
          vertexProperties.push({ value, type, offset: rowVertexOffset });
          rowVertexOffset += offsets[typeName];
        }
        if (!offsets[typeName]) {
          Logger.Warn(`Unsupported property type: ${typeName}.`);
        }
      } else if (prop.startsWith("element ")) {
        const [, type] = prop.split(" ");
        if (type == "chunk") {
          chunkMode = 1;
        } else if (type == "vertex") {
          chunkMode = 0;
        }
      }
    }
    const dataView = new DataView(data, headerEndIndex + headerEnd.length);
    const buffer2 = new ArrayBuffer(GaussianSplattingMesh._RowOutputLength * vertexCount);
    let shBuffer = null;
    let shCoefficientCount = 0;
    if (shDegree) {
      const shVectorCount = (shDegree + 1) * (shDegree + 1) - 1;
      shCoefficientCount = shVectorCount * 3;
      shBuffer = new ArrayBuffer(shCoefficientCount * vertexCount);
    }
    return {
      vertexCount,
      chunkCount,
      rowVertexLength: rowVertexOffset,
      rowChunkLength: rowChunkOffset,
      vertexProperties,
      chunkProperties,
      dataView,
      buffer: buffer2,
      shDegree,
      shCoefficientCount,
      shBuffer
    };
  }
  static _GetCompressedChunks(header, offset) {
    if (!header.chunkCount) {
      return null;
    }
    const dataView = header.dataView;
    const compressedChunks = new Array(header.chunkCount);
    for (let i = 0;i < header.chunkCount; i++) {
      const currentChunk = {
        min: new Vector3,
        max: new Vector3,
        minScale: new Vector3,
        maxScale: new Vector3,
        minColor: new Vector3(0, 0, 0),
        maxColor: new Vector3(1, 1, 1)
      };
      compressedChunks[i] = currentChunk;
      for (let propertyIndex = 0;propertyIndex < header.chunkProperties.length; propertyIndex++) {
        const property = header.chunkProperties[propertyIndex];
        let value;
        switch (property.type) {
          case 0:
            value = dataView.getFloat32(property.offset + offset.value, true);
            break;
          default:
            continue;
        }
        switch (property.value) {
          case 0:
            currentChunk.min.x = value;
            break;
          case 1:
            currentChunk.min.y = value;
            break;
          case 2:
            currentChunk.min.z = value;
            break;
          case 3:
            currentChunk.max.x = value;
            break;
          case 4:
            currentChunk.max.y = value;
            break;
          case 5:
            currentChunk.max.z = value;
            break;
          case 6:
            currentChunk.minScale.x = value;
            break;
          case 7:
            currentChunk.minScale.y = value;
            break;
          case 8:
            currentChunk.minScale.z = value;
            break;
          case 9:
            currentChunk.maxScale.x = value;
            break;
          case 10:
            currentChunk.maxScale.y = value;
            break;
          case 11:
            currentChunk.maxScale.z = value;
            break;
          case 34:
            currentChunk.minColor.x = value;
            break;
          case 35:
            currentChunk.minColor.y = value;
            break;
          case 36:
            currentChunk.minColor.z = value;
            break;
          case 37:
            currentChunk.maxColor.x = value;
            break;
          case 38:
            currentChunk.maxColor.y = value;
            break;
          case 39:
            currentChunk.maxColor.z = value;
            break;
        }
      }
      offset.value += header.rowChunkLength;
    }
    return compressedChunks;
  }
  static _GetSplat(header, index, compressedChunks, offset) {
    const q = TmpVectors.Quaternion[0];
    const temp3 = TmpVectors.Vector3[0];
    const rowOutputLength = GaussianSplattingMesh._RowOutputLength;
    const buffer2 = header.buffer;
    const dataView = header.dataView;
    const position = new Float32Array(buffer2, index * rowOutputLength, 3);
    const scale = new Float32Array(buffer2, index * rowOutputLength + 12, 3);
    const rgba = new Uint8ClampedArray(buffer2, index * rowOutputLength + 24, 4);
    const rot = new Uint8ClampedArray(buffer2, index * rowOutputLength + 28, 4);
    let sh = null;
    if (header.shBuffer) {
      sh = new Uint8ClampedArray(header.shBuffer, index * header.shCoefficientCount, header.shCoefficientCount);
    }
    const chunkIndex = index >> 8;
    let r0 = 255;
    let r1 = 0;
    let r2 = 0;
    let r3 = 0;
    for (let propertyIndex = 0;propertyIndex < header.vertexProperties.length; propertyIndex++) {
      const property = header.vertexProperties[propertyIndex];
      let value;
      switch (property.type) {
        case 0:
          value = dataView.getFloat32(offset.value + property.offset, true);
          break;
        case 1:
          value = dataView.getInt32(offset.value + property.offset, true);
          break;
        case 2:
          value = dataView.getUint32(offset.value + property.offset, true);
          break;
        case 3:
          value = dataView.getFloat64(offset.value + property.offset, true);
          break;
        case 4:
          value = dataView.getUint8(offset.value + property.offset);
          break;
        default:
          continue;
      }
      switch (property.value) {
        case 12:
          {
            const compressedChunk = compressedChunks[chunkIndex];
            unpack111011(value, temp3);
            position[0] = Scalar.Lerp(compressedChunk.min.x, compressedChunk.max.x, temp3.x);
            position[1] = Scalar.Lerp(compressedChunk.min.y, compressedChunk.max.y, temp3.y);
            position[2] = Scalar.Lerp(compressedChunk.min.z, compressedChunk.max.z, temp3.z);
          }
          break;
        case 13:
          {
            unpackRot(value, q);
            r0 = q.w;
            r1 = -q.z;
            r2 = q.y;
            r3 = -q.x;
          }
          break;
        case 14:
          {
            const compressedChunk = compressedChunks[chunkIndex];
            unpack111011(value, temp3);
            scale[0] = Math.exp(Scalar.Lerp(compressedChunk.minScale.x, compressedChunk.maxScale.x, temp3.x));
            scale[1] = Math.exp(Scalar.Lerp(compressedChunk.minScale.y, compressedChunk.maxScale.y, temp3.y));
            scale[2] = Math.exp(Scalar.Lerp(compressedChunk.minScale.z, compressedChunk.maxScale.z, temp3.z));
          }
          break;
        case 15:
          {
            const compressedChunk = compressedChunks[chunkIndex];
            unpack8888(value, rgba);
            rgba[0] = Scalar.Lerp(compressedChunk.minColor.x, compressedChunk.maxColor.x, rgba[0] / 255) * 255;
            rgba[1] = Scalar.Lerp(compressedChunk.minColor.y, compressedChunk.maxColor.y, rgba[1] / 255) * 255;
            rgba[2] = Scalar.Lerp(compressedChunk.minColor.z, compressedChunk.maxColor.z, rgba[2] / 255) * 255;
          }
          break;
        case 16:
          position[0] = value;
          break;
        case 17:
          position[1] = value;
          break;
        case 18:
          position[2] = value;
          break;
        case 19:
          scale[0] = Math.exp(value);
          break;
        case 20:
          scale[1] = Math.exp(value);
          break;
        case 21:
          scale[2] = Math.exp(value);
          break;
        case 22:
          rgba[0] = value;
          break;
        case 23:
          rgba[1] = value;
          break;
        case 24:
          rgba[2] = value;
          break;
        case 26:
          rgba[0] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
          break;
        case 27:
          rgba[1] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
          break;
        case 28:
          rgba[2] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
          break;
        case 29:
          rgba[3] = (0.5 + GaussianSplattingMesh._SH_C0 * value) * 255;
          break;
        case 25:
          rgba[3] = 1 / (1 + Math.exp(-value)) * 255;
          break;
        case 30:
          r0 = value;
          break;
        case 31:
          r1 = value;
          break;
        case 32:
          r2 = value;
          break;
        case 33:
          r3 = value;
          break;
      }
      if (sh && property.value >= 40 && property.value <= 84) {
        const clampedValue = Scalar.Clamp(value * 127.5 + 127.5, 0, 255);
        const shIndex = property.value - 40;
        sh[shIndex] = clampedValue;
      }
    }
    q.set(r1, r2, r3, r0);
    q.normalize();
    rot[0] = q.w * 128 + 128;
    rot[1] = q.x * 128 + 128;
    rot[2] = q.y * 128 + 128;
    rot[3] = q.z * 128 + 128;
    offset.value += header.rowVertexLength;
  }
  static *ConvertPLYWithSHToSplat(data, useCoroutine = false) {
    const header = GaussianSplattingMesh.ParseHeader(data);
    if (!header) {
      return { buffer: data };
    }
    const offset = { value: 0 };
    const compressedChunks = GaussianSplattingMesh._GetCompressedChunks(header, offset);
    for (let i = 0;i < header.vertexCount; i++) {
      GaussianSplattingMesh._GetSplat(header, i, compressedChunks, offset);
      if (i % GaussianSplattingMesh._PlyConversionBatchSize === 0 && useCoroutine) {
        yield;
      }
    }
    let sh = null;
    if (header.shDegree && header.shBuffer) {
      const textureCount = Math.ceil(header.shCoefficientCount / 16);
      let shIndexRead = 0;
      const ubuf = new Uint8Array(header.shBuffer);
      sh = [];
      const splatCount = header.vertexCount;
      const engine2 = EngineStore.LastCreatedEngine;
      if (engine2) {
        const width = engine2.getCaps().maxTextureSize;
        const height = Math.ceil(splatCount / width);
        for (let textureIndex = 0;textureIndex < textureCount; textureIndex++) {
          const texture2 = new Uint8Array(height * width * 4 * 4);
          sh.push(texture2);
        }
        for (let i = 0;i < splatCount; i++) {
          for (let shIndexWrite = 0;shIndexWrite < header.shCoefficientCount; shIndexWrite++) {
            const shValue = ubuf[shIndexRead++];
            const textureIndex = Math.floor(shIndexWrite / 16);
            const shArray = sh[textureIndex];
            const byteIndexInTexture = shIndexWrite % 16;
            const offsetPerSplat = i * 16;
            shArray[byteIndexInTexture + offsetPerSplat] = shValue;
          }
        }
      }
    }
    return { buffer: header.buffer, sh };
  }
  static *ConvertPLYToSplat(data, useCoroutine = false) {
    const header = GaussianSplattingMesh.ParseHeader(data);
    if (!header) {
      return data;
    }
    const offset = { value: 0 };
    const compressedChunks = GaussianSplattingMesh._GetCompressedChunks(header, offset);
    for (let i = 0;i < header.vertexCount; i++) {
      GaussianSplattingMesh._GetSplat(header, i, compressedChunks, offset);
      if (i % GaussianSplattingMesh._PlyConversionBatchSize === 0 && useCoroutine) {
        yield;
      }
    }
    return header.buffer;
  }
  static async ConvertPLYToSplatAsync(data) {
    return runCoroutineAsync(GaussianSplattingMesh.ConvertPLYToSplat(data, true), createYieldingScheduler());
  }
  static async ConvertPLYWithSHToSplatAsync(data) {
    return runCoroutineAsync(GaussianSplattingMesh.ConvertPLYWithSHToSplat(data, true), createYieldingScheduler());
  }
  loadDataAsync(data) {
    return this.updateDataAsync(data);
  }
  loadFileAsync(url) {
    return Tools.LoadFileAsync(url, true).then(async (plyBuffer) => {
      GaussianSplattingMesh.ConvertPLYWithSHToSplatAsync(plyBuffer).then((splatsData) => {
        this.updateDataAsync(splatsData.buffer, splatsData.sh);
      });
    });
  }
  dispose(doNotRecurse) {
    this._covariancesATexture?.dispose();
    this._covariancesBTexture?.dispose();
    this._centersTexture?.dispose();
    this._colorsTexture?.dispose();
    if (this._shTextures) {
      this._shTextures.forEach((shTexture) => {
        shTexture.dispose();
      });
    }
    this._covariancesATexture = null;
    this._covariancesBTexture = null;
    this._centersTexture = null;
    this._colorsTexture = null;
    this._shTextures = null;
    this._worker?.terminate();
    this._worker = null;
    super.dispose(doNotRecurse, true);
  }
  _copyTextures(source) {
    this._covariancesATexture = source.covariancesATexture?.clone();
    this._covariancesBTexture = source.covariancesBTexture?.clone();
    this._centersTexture = source.centersTexture?.clone();
    this._colorsTexture = source.colorsTexture?.clone();
    if (source._shTextures) {
      this._shTextures = [];
      this._shTextures.forEach((shTexture) => {
        this._shTextures?.push(shTexture.clone());
      });
    }
  }
  clone(name375 = "") {
    const newGS = new GaussianSplattingMesh(name375, undefined, this.getScene());
    newGS._copySource(this);
    newGS.makeGeometryUnique();
    newGS._vertexCount = this._vertexCount;
    newGS._copyTextures(this);
    newGS._modelViewMatrix = Matrix.Identity();
    newGS._splatPositions = this._splatPositions;
    newGS._readyToDisplay = false;
    newGS._instanciateWorker();
    const binfo = this.getBoundingInfo();
    newGS.getBoundingInfo().reConstruct(binfo.minimum, binfo.maximum, this.getWorldMatrix());
    newGS.forcedInstanceCount = newGS._vertexCount;
    newGS.setEnabled(true);
    return newGS;
  }
  _makeSplat(index, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum) {
    const matrixRotation = TmpVectors.Matrix[0];
    const matrixScale = TmpVectors.Matrix[1];
    const quaternion = TmpVectors.Quaternion[0];
    const covBSItemSize = this._useRGBACovariants ? 4 : 2;
    const x = fBuffer[8 * index + 0];
    const y = -fBuffer[8 * index + 1];
    const z = fBuffer[8 * index + 2];
    this._splatPositions[4 * index + 0] = x;
    this._splatPositions[4 * index + 1] = y;
    this._splatPositions[4 * index + 2] = z;
    minimum.minimizeInPlaceFromFloats(x, y, z);
    maximum.maximizeInPlaceFromFloats(x, y, z);
    quaternion.set((uBuffer[32 * index + 28 + 1] - 127.5) / 127.5, (uBuffer[32 * index + 28 + 2] - 127.5) / 127.5, (uBuffer[32 * index + 28 + 3] - 127.5) / 127.5, -(uBuffer[32 * index + 28 + 0] - 127.5) / 127.5);
    quaternion.toRotationMatrix(matrixRotation);
    Matrix.ScalingToRef(fBuffer[8 * index + 3 + 0] * 2, fBuffer[8 * index + 3 + 1] * 2, fBuffer[8 * index + 3 + 2] * 2, matrixScale);
    const M = matrixRotation.multiplyToRef(matrixScale, TmpVectors.Matrix[0]).m;
    const covariances = this._tmpCovariances;
    covariances[0] = M[0] * M[0] + M[1] * M[1] + M[2] * M[2];
    covariances[1] = M[0] * M[4] + M[1] * M[5] + M[2] * M[6];
    covariances[2] = M[0] * M[8] + M[1] * M[9] + M[2] * M[10];
    covariances[3] = M[4] * M[4] + M[5] * M[5] + M[6] * M[6];
    covariances[4] = M[4] * M[8] + M[5] * M[9] + M[6] * M[10];
    covariances[5] = M[8] * M[8] + M[9] * M[9] + M[10] * M[10];
    let factor = -1e4;
    for (let covIndex = 0;covIndex < 6; covIndex++) {
      factor = Math.max(factor, Math.abs(covariances[covIndex]));
    }
    this._splatPositions[4 * index + 3] = factor;
    const transform = factor;
    covA[index * 4 + 0] = ToHalfFloat(covariances[0] / transform);
    covA[index * 4 + 1] = ToHalfFloat(covariances[1] / transform);
    covA[index * 4 + 2] = ToHalfFloat(covariances[2] / transform);
    covA[index * 4 + 3] = ToHalfFloat(covariances[3] / transform);
    covB[index * covBSItemSize + 0] = ToHalfFloat(covariances[4] / transform);
    covB[index * covBSItemSize + 1] = ToHalfFloat(covariances[5] / transform);
    colorArray[index * 4 + 0] = uBuffer[32 * index + 24 + 0];
    colorArray[index * 4 + 1] = uBuffer[32 * index + 24 + 1];
    colorArray[index * 4 + 2] = uBuffer[32 * index + 24 + 2];
    colorArray[index * 4 + 3] = uBuffer[32 * index + 24 + 3];
  }
  _updateTextures(covA, covB, colorArray, sh) {
    const textureSize = this._getTextureSize(this._vertexCount);
    const createTextureFromData = (data, width, height, format) => {
      return new RawTexture(data, width, height, format, this._scene, false, false, 2, 1);
    };
    const createTextureFromDataU8 = (data, width, height, format) => {
      return new RawTexture(data, width, height, format, this._scene, false, false, 2, 0);
    };
    const createTextureFromDataU32 = (data, width, height, format) => {
      return new RawTexture(data, width, height, format, this._scene, false, false, 1, 7);
    };
    const createTextureFromDataF16 = (data, width, height, format) => {
      return new RawTexture(data, width, height, format, this._scene, false, false, 2, 2);
    };
    if (this._covariancesATexture) {
      this._delayedTextureUpdate = { covA, covB, colors: colorArray, centers: this._splatPositions, sh };
      const positions = Float32Array.from(this._splatPositions);
      const vertexCount = this._vertexCount;
      this._worker.postMessage({ positions, vertexCount }, [positions.buffer]);
      this._postToWorker(true);
    } else {
      this._covariancesATexture = createTextureFromDataF16(covA, textureSize.x, textureSize.y, 5);
      this._covariancesBTexture = createTextureFromDataF16(covB, textureSize.x, textureSize.y, this._useRGBACovariants ? 5 : 7);
      this._centersTexture = createTextureFromData(this._splatPositions, textureSize.x, textureSize.y, 5);
      this._colorsTexture = createTextureFromDataU8(colorArray, textureSize.x, textureSize.y, 5);
      if (sh) {
        this._shTextures = [];
        sh.forEach((shData) => {
          const buffer2 = new Uint32Array(shData.buffer);
          const shTexture = createTextureFromDataU32(buffer2, textureSize.x, textureSize.y, 11);
          shTexture.wrapU = 0;
          shTexture.wrapV = 0;
          this._shTextures.push(shTexture);
        });
      }
      this._instanciateWorker();
    }
  }
  *_updateData(data, isAsync, sh) {
    if (!this._covariancesATexture) {
      this._readyToDisplay = false;
    }
    const uBuffer = new Uint8Array(data);
    const fBuffer = new Float32Array(uBuffer.buffer);
    if (this._keepInRam) {
      this._splatsData = data;
      if (sh) {
        this._sh = sh;
      }
    }
    const vertexCount = uBuffer.length / GaussianSplattingMesh._RowOutputLength;
    if (vertexCount != this._vertexCount) {
      this._updateSplatIndexBuffer(vertexCount);
    }
    this._vertexCount = vertexCount;
    this._shDegree = sh ? sh.length : 0;
    const textureSize = this._getTextureSize(vertexCount);
    const textureLength = textureSize.x * textureSize.y;
    const lineCountUpdate = GaussianSplattingMesh.ProgressiveUpdateAmount ?? textureSize.y;
    const textureLengthPerUpdate = textureSize.x * lineCountUpdate;
    this._splatPositions = new Float32Array(4 * textureLength);
    const covA = new Uint16Array(textureLength * 4);
    const covB = new Uint16Array((this._useRGBACovariants ? 4 : 2) * textureLength);
    const colorArray = new Uint8Array(textureLength * 4);
    const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    if (GaussianSplattingMesh.ProgressiveUpdateAmount) {
      this._updateTextures(covA, covB, colorArray, sh);
      this.setEnabled(true);
      const partCount = Math.ceil(textureSize.y / lineCountUpdate);
      for (let partIndex = 0;partIndex < partCount; partIndex++) {
        const updateLine = partIndex * lineCountUpdate;
        const splatIndexBase = updateLine * textureSize.x;
        for (let i = 0;i < textureLengthPerUpdate; i++) {
          this._makeSplat(splatIndexBase + i, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum);
        }
        this._updateSubTextures(this._splatPositions, covA, covB, colorArray, updateLine, Math.min(lineCountUpdate, textureSize.y - updateLine));
        this.getBoundingInfo().reConstruct(minimum, maximum, this.getWorldMatrix());
        if (isAsync) {
          yield;
        }
      }
      const positions = Float32Array.from(this._splatPositions);
      const vertexCount2 = this._vertexCount;
      this._worker.postMessage({ positions, vertexCount: vertexCount2 }, [positions.buffer]);
      this._sortIsDirty = true;
    } else {
      for (let i = 0;i < vertexCount; i++) {
        this._makeSplat(i, fBuffer, uBuffer, covA, covB, colorArray, minimum, maximum);
        if (isAsync && i % GaussianSplattingMesh._SplatBatchSize === 0) {
          yield;
        }
      }
      this._updateTextures(covA, covB, colorArray, sh);
      this.getBoundingInfo().reConstruct(minimum, maximum, this.getWorldMatrix());
      this.setEnabled(true);
    }
    this._postToWorker(true);
  }
  async updateDataAsync(data, sh) {
    return runCoroutineAsync(this._updateData(data, true, sh), createYieldingScheduler());
  }
  updateData(data, sh) {
    runCoroutineSync(this._updateData(data, false, sh));
  }
  refreshBoundingInfo() {
    this.thinInstanceRefreshBoundingInfo(false);
    return this;
  }
  _updateSplatIndexBuffer(vertexCount) {
    if (!this._splatIndex || vertexCount > this._splatIndex.length) {
      this._splatIndex = new Float32Array(vertexCount);
      this.thinInstanceSetBuffer("splatIndex", this._splatIndex, 1, false);
    }
    this.forcedInstanceCount = vertexCount;
  }
  _updateSubTextures(centers, covA, covB, colors, lineStart, lineCount, sh) {
    const updateTextureFromData = (texture2, data, width, lineStart2, lineCount2) => {
      this.getEngine().updateTextureData(texture2.getInternalTexture(), data, 0, lineStart2, width, lineCount2, 0, 0, false);
    };
    const textureSize = this._getTextureSize(this._vertexCount);
    const covBSItemSize = this._useRGBACovariants ? 4 : 2;
    const texelStart = lineStart * textureSize.x;
    const texelCount = lineCount * textureSize.x;
    const covAView = new Uint16Array(covA.buffer, texelStart * 4 * Uint16Array.BYTES_PER_ELEMENT, texelCount * 4);
    const covBView = new Uint16Array(covB.buffer, texelStart * covBSItemSize * Uint16Array.BYTES_PER_ELEMENT, texelCount * covBSItemSize);
    const colorsView = new Uint8Array(colors.buffer, texelStart * 4, texelCount * 4);
    const centersView = new Float32Array(centers.buffer, texelStart * 4 * Float32Array.BYTES_PER_ELEMENT, texelCount * 4);
    updateTextureFromData(this._covariancesATexture, covAView, textureSize.x, lineStart, lineCount);
    updateTextureFromData(this._covariancesBTexture, covBView, textureSize.x, lineStart, lineCount);
    updateTextureFromData(this._centersTexture, centersView, textureSize.x, lineStart, lineCount);
    updateTextureFromData(this._colorsTexture, colorsView, textureSize.x, lineStart, lineCount);
    if (sh) {
      for (let i = 0;i < sh.length; i++) {
        const componentCount = 4;
        const shView = new Uint8Array(this._sh[i].buffer, texelStart * componentCount, texelCount * componentCount);
        updateTextureFromData(this._shTextures[i], shView, textureSize.x, lineStart, lineCount);
      }
    }
  }
  _instanciateWorker() {
    if (!this._vertexCount) {
      return;
    }
    this._updateSplatIndexBuffer(this._vertexCount);
    this._worker?.terminate();
    this._worker = new Worker(URL.createObjectURL(new Blob(["(", GaussianSplattingMesh._CreateWorker.toString(), ")(self)"], {
      type: "application/javascript"
    })));
    this._depthMix = new BigInt64Array(this._vertexCount);
    const positions = Float32Array.from(this._splatPositions);
    const vertexCount = this._vertexCount;
    this._worker.postMessage({ positions, vertexCount }, [positions.buffer]);
    this._worker.onmessage = (e) => {
      this._depthMix = e.data.depthMix;
      const indexMix = new Uint32Array(e.data.depthMix.buffer);
      if (this._splatIndex) {
        for (let j = 0;j < this._vertexCount; j++) {
          this._splatIndex[j] = indexMix[2 * j];
        }
      }
      if (this._delayedTextureUpdate) {
        const textureSize = this._getTextureSize(vertexCount);
        this._updateSubTextures(this._delayedTextureUpdate.centers, this._delayedTextureUpdate.covA, this._delayedTextureUpdate.covB, this._delayedTextureUpdate.colors, 0, textureSize.y, this._delayedTextureUpdate.sh);
        this._delayedTextureUpdate = null;
      }
      this.thinInstanceBufferUpdated("splatIndex");
      this._canPostToWorker = true;
      this._readyToDisplay = true;
      if (this._sortIsDirty) {
        this._postToWorker(true);
        this._sortIsDirty = false;
      }
    };
  }
  _getTextureSize(length) {
    const engine2 = this._scene.getEngine();
    const width = engine2.getCaps().maxTextureSize;
    let height = 1;
    if (engine2.version === 1 && !engine2.isWebGPU) {
      while (width * height < length) {
        height *= 2;
      }
    } else {
      height = Math.ceil(length / width);
    }
    if (height > width) {
      Logger.Error("GaussianSplatting texture size: (" + width + ", " + height + "), maxTextureSize: " + width);
      height = width;
    }
    return new Vector2(width, height);
  }
}
GaussianSplattingMesh._RowOutputLength = 3 * 4 + 3 * 4 + 4 + 4;
GaussianSplattingMesh._SH_C0 = 0.28209479177387814;
GaussianSplattingMesh._SplatBatchSize = 327680;
GaussianSplattingMesh._PlyConversionBatchSize = 32768;
GaussianSplattingMesh.ProgressiveUpdateAmount = 0;
GaussianSplattingMesh._CreateWorker = function(self2) {
  let vertexCount = 0;
  let positions;
  let depthMix;
  let indices;
  let floatMix;
  self2.onmessage = (e) => {
    if (e.data.positions) {
      positions = e.data.positions;
      vertexCount = e.data.vertexCount;
    } else {
      const viewProj = e.data.view;
      if (!positions || !viewProj) {
        throw new Error("positions or view is not defined!");
      }
      depthMix = e.data.depthMix;
      indices = new Uint32Array(depthMix.buffer);
      floatMix = new Float32Array(depthMix.buffer);
      for (let j = 0;j < vertexCount; j++) {
        indices[2 * j] = j;
      }
      let depthFactor = -1;
      if (e.data.useRightHandedSystem) {
        depthFactor = 1;
      }
      for (let j = 0;j < vertexCount; j++) {
        floatMix[2 * j + 1] = 1e4 + (viewProj[2] * positions[4 * j + 0] + viewProj[6] * positions[4 * j + 1] + viewProj[10] * positions[4 * j + 2]) * depthFactor;
      }
      depthMix.sort();
      self2.postMessage({ depthMix }, [depthMix.buffer]);
    }
  };
};

// node_modules/@babylonjs/core/Meshes/index.js
init_color_fragment2();
init_color_vertex2();
init_color_fragment();
init_color_vertex();
init_meshUVSpaceRenderer_vertex();
init_meshUVSpaceRenderer_fragment();
init_meshUVSpaceRendererMasker_vertex();
init_meshUVSpaceRendererMasker_fragment();
init_meshUVSpaceRendererFinaliser_fragment();
init_meshUVSpaceRendererFinaliser_vertex();
init_meshUVSpaceRenderer_vertex2();
init_meshUVSpaceRenderer_fragment2();
init_meshUVSpaceRendererMasker_vertex2();
init_meshUVSpaceRendererMasker_fragment2();
init_meshUVSpaceRendererFinaliser_fragment2();
init_meshUVSpaceRendererFinaliser_vertex2();
// node_modules/@babylonjs/core/Misc/assetsManager.js
init_tools();
init_observable();
init_texture();
init_logger();
init_engineStore();
var AssetTaskState;
(function(AssetTaskState2) {
  AssetTaskState2[AssetTaskState2["INIT"] = 0] = "INIT";
  AssetTaskState2[AssetTaskState2["RUNNING"] = 1] = "RUNNING";
  AssetTaskState2[AssetTaskState2["DONE"] = 2] = "DONE";
  AssetTaskState2[AssetTaskState2["ERROR"] = 3] = "ERROR";
})(AssetTaskState || (AssetTaskState = {}));

// node_modules/@babylonjs/core/Misc/index.js
init_basis();
init_dds();
init_decorators();
init_environmentTextureTools();

// node_modules/@babylonjs/core/Misc/meshExploder.js
init_math_vector();
// node_modules/@babylonjs/core/Misc/filesInput.js
init_logger();
init_filesInputStore();
// node_modules/@babylonjs/core/Misc/HighDynamicRange/index.js
init_hdr();
init_cubemapToSphericalPolynomial();
init_panoramaToCubemap();

// node_modules/@babylonjs/core/Misc/index.js
init_khronosTextureContainer();
init_observable();

// node_modules/@babylonjs/core/Misc/observable.extensions.js
init_observable();
Observable.prototype.notifyObserversWithPromise = async function(eventData, mask = -1, target, currentTarget, userInfo) {
  let p = Promise.resolve(eventData);
  if (!this.observers.length) {
    return p;
  }
  const state = this._eventState;
  state.mask = mask;
  state.target = target;
  state.currentTarget = currentTarget;
  state.skipNextObservers = false;
  state.userInfo = userInfo;
  this.observers.forEach((obs) => {
    if (state.skipNextObservers) {
      return;
    }
    if (obs._willBeUnregistered) {
      return;
    }
    if (obs.mask & mask) {
      if (obs.scope) {
        p = p.then((lastReturnedValue) => {
          state.lastReturnValue = lastReturnedValue;
          return obs.callback.apply(obs.scope, [eventData, state]);
        });
      } else {
        p = p.then((lastReturnedValue) => {
          state.lastReturnValue = lastReturnedValue;
          return obs.callback(eventData, state);
        });
      }
      if (obs.unregisterOnNextCall) {
        this._deferUnregister(obs);
      }
    }
  });
  await p;
  return eventData;
};

// node_modules/@babylonjs/core/Misc/index.js
init_performanceMonitor();

// node_modules/@babylonjs/core/Misc/sceneOptimizer.js
init_engineStore();
init_observable();

class SceneOptimization {
  getDescription() {
    return "";
  }
  apply(scene, optimizer) {
    return true;
  }
  constructor(priority = 0) {
    this.priority = priority;
  }
}
class MergeMeshesOptimization extends SceneOptimization {
  constructor() {
    super(...arguments);
    this._canBeMerged = (abstractMesh2) => {
      if (!(abstractMesh2 instanceof Mesh)) {
        return false;
      }
      const mesh2 = abstractMesh2;
      if (mesh2.isDisposed()) {
        return false;
      }
      if (!mesh2.isVisible || !mesh2.isEnabled()) {
        return false;
      }
      if (mesh2.instances.length > 0) {
        return false;
      }
      if (mesh2.skeleton || mesh2.hasLODLevels) {
        return false;
      }
      if (mesh2.getTotalVertices() === 0) {
        return false;
      }
      return true;
    };
  }
  static get UpdateSelectionTree() {
    return MergeMeshesOptimization._UpdateSelectionTree;
  }
  static set UpdateSelectionTree(value) {
    MergeMeshesOptimization._UpdateSelectionTree = value;
  }
  getDescription() {
    return "Merging similar meshes together";
  }
  apply(scene, optimizer, updateSelectionTree) {
    const globalPool = scene.meshes.slice(0);
    let globalLength = globalPool.length;
    for (let index = 0;index < globalLength; index++) {
      const currentPool = [];
      const current = globalPool[index];
      if (!this._canBeMerged(current)) {
        continue;
      }
      currentPool.push(current);
      for (let subIndex = index + 1;subIndex < globalLength; subIndex++) {
        const otherMesh = globalPool[subIndex];
        if (!this._canBeMerged(otherMesh)) {
          continue;
        }
        if (otherMesh.material !== current.material) {
          continue;
        }
        if (otherMesh.checkCollisions !== current.checkCollisions) {
          continue;
        }
        currentPool.push(otherMesh);
        globalLength--;
        globalPool.splice(subIndex, 1);
        subIndex--;
      }
      if (currentPool.length < 2) {
        continue;
      }
      Mesh.MergeMeshes(currentPool, undefined, true);
    }
    const sceneAsAny = scene;
    if (sceneAsAny.createOrUpdateSelectionOctree) {
      if (updateSelectionTree != null) {
        if (updateSelectionTree) {
          sceneAsAny.createOrUpdateSelectionOctree();
        }
      } else if (MergeMeshesOptimization.UpdateSelectionTree) {
        sceneAsAny.createOrUpdateSelectionOctree();
      }
    }
    return true;
  }
}
MergeMeshesOptimization._UpdateSelectionTree = false;
// node_modules/@babylonjs/core/Misc/sceneSerializer.js
init_decorators_serialization();
init_texture();
init_logger();
var serializedGeometries = [];
var SerializeGeometry = (geometry2, serializationGeometries) => {
  if (geometry2.doNotSerialize) {
    return;
  }
  serializationGeometries.vertexData.push(geometry2.serializeVerticeData());
  serializedGeometries[geometry2.id] = true;
};
var SerializeMesh = (mesh2, serializationScene) => {
  const serializationObject = {};
  const geometry2 = mesh2._geometry;
  if (geometry2) {
    if (!mesh2.getScene().getGeometryById(geometry2.id)) {
      SerializeGeometry(geometry2, serializationScene.geometries);
    }
  }
  if (mesh2.serialize) {
    mesh2.serialize(serializationObject);
  }
  return serializationObject;
};
var FinalizeSingleNode = (node, serializationObject) => {
  if (node._isMesh) {
    const mesh2 = node;
    if (mesh2.delayLoadState === 1 || mesh2.delayLoadState === 0) {
      const serializeMaterial = (material2) => {
        serializationObject.materials = serializationObject.materials || [];
        if (mesh2.material && !serializationObject.materials.some((mat) => mat.id === mesh2.material.id)) {
          serializationObject.materials.push(material2.serialize());
        }
      };
      if (mesh2.material && !mesh2.material.doNotSerialize) {
        if (mesh2.material instanceof MultiMaterial) {
          serializationObject.multiMaterials = serializationObject.multiMaterials || [];
          if (!serializationObject.multiMaterials.some((mat) => mat.id === mesh2.material.id)) {
            serializationObject.multiMaterials.push(mesh2.material.serialize());
            for (const submaterial of mesh2.material.subMaterials) {
              if (submaterial) {
                serializeMaterial(submaterial);
              }
            }
          }
        } else {
          serializeMaterial(mesh2.material);
        }
      } else if (!mesh2.material) {
        serializeMaterial(mesh2.getScene().defaultMaterial);
      }
      const geometry2 = mesh2._geometry;
      if (geometry2) {
        if (!serializationObject.geometries) {
          serializationObject.geometries = {};
          serializationObject.geometries.boxes = [];
          serializationObject.geometries.spheres = [];
          serializationObject.geometries.cylinders = [];
          serializationObject.geometries.toruses = [];
          serializationObject.geometries.grounds = [];
          serializationObject.geometries.planes = [];
          serializationObject.geometries.torusKnots = [];
          serializationObject.geometries.vertexData = [];
        }
        SerializeGeometry(geometry2, serializationObject.geometries);
      }
      if (mesh2.skeleton && !mesh2.skeleton.doNotSerialize) {
        serializationObject.skeletons = serializationObject.skeletons || [];
        serializationObject.skeletons.push(mesh2.skeleton.serialize());
      }
      serializationObject.meshes = serializationObject.meshes || [];
      serializationObject.meshes.push(SerializeMesh(mesh2, serializationObject));
    }
  } else if (node.getClassName() === "TransformNode") {
    const transformNode2 = node;
    serializationObject.transformNodes.push(transformNode2.serialize());
  } else if (node.getClassName().indexOf("Camera") !== -1) {
    const camera2 = node;
    serializationObject.cameras.push(camera2.serialize());
  } else if (node.getClassName().indexOf("Light") !== -1) {
    const light2 = node;
    serializationObject.lights.push(light2.serialize());
  }
};

class SceneSerializer {
  static ClearCache() {
    serializedGeometries = [];
  }
  static Serialize(scene) {
    return SceneSerializer._Serialize(scene);
  }
  static _Serialize(scene, checkSyncReadSupported = true) {
    const serializationObject = {};
    if (checkSyncReadSupported && !scene.getEngine()._features.supportSyncTextureRead && Texture.ForceSerializeBuffers) {
      Logger.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead.");
    }
    SceneSerializer.ClearCache();
    serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
    serializationObject.autoClear = scene.autoClear;
    serializationObject.clearColor = scene.clearColor.asArray();
    serializationObject.ambientColor = scene.ambientColor.asArray();
    serializationObject.gravity = scene.gravity.asArray();
    serializationObject.collisionsEnabled = scene.collisionsEnabled;
    serializationObject.useRightHandedSystem = scene.useRightHandedSystem;
    if (scene.fogMode !== undefined && scene.fogMode !== null) {
      serializationObject.fogMode = scene.fogMode;
    }
    if (scene.fogColor !== undefined && scene.fogColor !== null) {
      serializationObject.fogColor = scene.fogColor.asArray();
    }
    if (scene.fogStart !== undefined && scene.fogStart !== null) {
      serializationObject.fogStart = scene.fogStart;
    }
    if (scene.fogEnd !== undefined && scene.fogEnd !== null) {
      serializationObject.fogEnd = scene.fogEnd;
    }
    if (scene.fogDensity !== undefined && scene.fogDensity !== null) {
      serializationObject.fogDensity = scene.fogDensity;
    }
    if (scene.isPhysicsEnabled && scene.isPhysicsEnabled()) {
      const physicEngine = scene.getPhysicsEngine();
      if (physicEngine) {
        serializationObject.physicsEnabled = true;
        serializationObject.physicsGravity = physicEngine.gravity.asArray();
        serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
      }
    }
    if (scene.metadata) {
      serializationObject.metadata = scene.metadata;
    }
    serializationObject.morphTargetManagers = [];
    for (const abstractMesh2 of scene.meshes) {
      const manager = abstractMesh2.morphTargetManager;
      if (manager) {
        serializationObject.morphTargetManagers.push(manager.serialize());
      }
    }
    serializationObject.lights = [];
    let index;
    let light2;
    for (index = 0;index < scene.lights.length; index++) {
      light2 = scene.lights[index];
      if (!light2.doNotSerialize) {
        serializationObject.lights.push(light2.serialize());
      }
    }
    serializationObject.cameras = [];
    for (index = 0;index < scene.cameras.length; index++) {
      const camera2 = scene.cameras[index];
      if (!camera2.doNotSerialize) {
        serializationObject.cameras.push(camera2.serialize());
      }
    }
    if (scene.activeCamera) {
      serializationObject.activeCameraID = scene.activeCamera.id;
    }
    SerializationHelper.AppendSerializedAnimations(scene, serializationObject);
    if (scene.animationGroups && scene.animationGroups.length > 0) {
      serializationObject.animationGroups = [];
      for (let animationGroupIndex = 0;animationGroupIndex < scene.animationGroups.length; animationGroupIndex++) {
        const animationGroup2 = scene.animationGroups[animationGroupIndex];
        serializationObject.animationGroups.push(animationGroup2.serialize());
      }
    }
    if (scene.reflectionProbes && scene.reflectionProbes.length > 0) {
      serializationObject.reflectionProbes = [];
      for (index = 0;index < scene.reflectionProbes.length; index++) {
        const reflectionProbe = scene.reflectionProbes[index];
        serializationObject.reflectionProbes.push(reflectionProbe.serialize());
      }
    }
    serializationObject.materials = [];
    serializationObject.multiMaterials = [];
    let material2;
    for (index = 0;index < scene.materials.length; index++) {
      material2 = scene.materials[index];
      if (!material2.doNotSerialize) {
        serializationObject.materials.push(material2.serialize());
      }
    }
    serializationObject.multiMaterials = [];
    for (index = 0;index < scene.multiMaterials.length; index++) {
      const multiMaterial2 = scene.multiMaterials[index];
      serializationObject.multiMaterials.push(multiMaterial2.serialize());
    }
    if (scene.environmentTexture) {
      if (scene.environmentTexture._files) {
        serializationObject.environmentTexture = scene.environmentTexture.serialize();
      } else {
        serializationObject.environmentTexture = scene.environmentTexture.name;
        serializationObject.environmentTextureRotationY = scene.environmentTexture.rotationY;
      }
    }
    serializationObject.environmentIntensity = scene.environmentIntensity;
    serializationObject.iblIntensity = scene.iblIntensity;
    serializationObject.skeletons = [];
    for (index = 0;index < scene.skeletons.length; index++) {
      const skeleton2 = scene.skeletons[index];
      if (!skeleton2.doNotSerialize) {
        serializationObject.skeletons.push(skeleton2.serialize());
      }
    }
    serializationObject.transformNodes = [];
    for (index = 0;index < scene.transformNodes.length; index++) {
      if (!scene.transformNodes[index].doNotSerialize) {
        serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
      }
    }
    serializationObject.geometries = {};
    serializationObject.geometries.boxes = [];
    serializationObject.geometries.spheres = [];
    serializationObject.geometries.cylinders = [];
    serializationObject.geometries.toruses = [];
    serializationObject.geometries.grounds = [];
    serializationObject.geometries.planes = [];
    serializationObject.geometries.torusKnots = [];
    serializationObject.geometries.vertexData = [];
    serializedGeometries = [];
    const geometries = scene.getGeometries();
    for (index = 0;index < geometries.length; index++) {
      const geometry2 = geometries[index];
      if (geometry2.isReady()) {
        SerializeGeometry(geometry2, serializationObject.geometries);
      }
    }
    serializationObject.meshes = [];
    for (index = 0;index < scene.meshes.length; index++) {
      const abstractMesh2 = scene.meshes[index];
      if (abstractMesh2 instanceof Mesh) {
        const mesh2 = abstractMesh2;
        if (!mesh2.doNotSerialize) {
          if (mesh2.delayLoadState === 1 || mesh2.delayLoadState === 0) {
            serializationObject.meshes.push(SerializeMesh(mesh2, serializationObject));
          }
        }
      }
    }
    serializationObject.particleSystems = [];
    for (index = 0;index < scene.particleSystems.length; index++) {
      serializationObject.particleSystems.push(scene.particleSystems[index].serialize(false));
    }
    serializationObject.postProcesses = [];
    for (index = 0;index < scene.postProcesses.length; index++) {
      serializationObject.postProcesses.push(scene.postProcesses[index].serialize());
    }
    if (scene.actionManager) {
      serializationObject.actions = scene.actionManager.serialize("scene");
    }
    for (const component of scene._serializableComponents) {
      component.serialize(serializationObject);
    }
    if (scene.spriteManagers) {
      serializationObject.spriteManagers = [];
      for (index = 0;index < scene.spriteManagers.length; index++) {
        serializationObject.spriteManagers.push(scene.spriteManagers[index].serialize(true));
      }
    }
    return serializationObject;
  }
  static SerializeAsync(scene) {
    const serializationObject = SceneSerializer._Serialize(scene, false);
    const promises = [];
    this._CollectPromises(serializationObject, promises);
    return Promise.all(promises).then(() => serializationObject);
  }
  static _CollectPromises(obj, promises) {
    if (Array.isArray(obj)) {
      for (let i = 0;i < obj.length; ++i) {
        const o = obj[i];
        if (o instanceof Promise) {
          promises.push(o.then((res) => obj[i] = res));
        } else if (o instanceof Object || Array.isArray(o)) {
          this._CollectPromises(o, promises);
        }
      }
    } else if (obj instanceof Object) {
      for (const name387 in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, name387)) {
          const o = obj[name387];
          if (o instanceof Promise) {
            promises.push(o.then((res) => obj[name387] = res));
          } else if (o instanceof Object || Array.isArray(o)) {
            this._CollectPromises(o, promises);
          }
        }
      }
    }
  }
  static SerializeMesh(toSerialize, withParents = false, withChildren = false) {
    const serializationObject = {};
    serializationObject.meshes = [];
    serializationObject.transformNodes = [];
    serializationObject.cameras = [];
    serializationObject.lights = [];
    SceneSerializer.ClearCache();
    toSerialize = toSerialize instanceof Array ? toSerialize : [toSerialize];
    if (withParents || withChildren) {
      for (let i = 0;i < toSerialize.length; ++i) {
        if (withChildren) {
          toSerialize[i].getDescendants().forEach((node) => {
            if (toSerialize.indexOf(node) < 0 && !node.doNotSerialize) {
              toSerialize.push(node);
            }
          });
        }
        if (withParents && toSerialize[i].parent && toSerialize.indexOf(toSerialize[i].parent) < 0 && !toSerialize[i].parent.doNotSerialize) {
          toSerialize.push(toSerialize[i].parent);
        }
      }
    }
    toSerialize.forEach((mesh2) => {
      FinalizeSingleNode(mesh2, serializationObject);
    });
    return serializationObject;
  }
}

// node_modules/@babylonjs/core/Misc/index.js
init_smartArray();
init_tags();
init_textureTools();
init_lodCube_fragment();
init_lod_fragment();
init_lodCube_fragment2();
init_lod_fragment2();
init_tga();
init_tools();

// node_modules/@babylonjs/core/Misc/videoRecorder.js
init_tools();

class VideoRecorder {
  static IsSupported(engine2, canvas) {
    const targetCanvas = canvas ?? engine2.getRenderingCanvas();
    return !!targetCanvas && typeof targetCanvas.captureStream === "function";
  }
  get isRecording() {
    return !!this._canvas && this._isRecording;
  }
  constructor(engine2, options = {}) {
    if (!VideoRecorder.IsSupported(engine2, options.canvas)) {
      throw "Your browser does not support recording so far.";
    }
    const canvas = options.canvas ?? engine2.getRenderingCanvas();
    if (!canvas) {
      throw "The babylon engine must have a canvas to be recorded";
    }
    this._canvas = canvas;
    this._isRecording = false;
    this._options = {
      ...VideoRecorder._DefaultOptions,
      ...options
    };
    const stream = this._canvas.captureStream(this._options.fps);
    if (this._options.audioTracks) {
      for (const track of this._options.audioTracks) {
        stream.addTrack(track);
      }
    }
    this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
    this._mediaRecorder.ondataavailable = (evt) => this._handleDataAvailable(evt);
    this._mediaRecorder.onerror = (evt) => this._handleError(evt);
    this._mediaRecorder.onstop = () => this._handleStop();
  }
  stopRecording() {
    if (!this._canvas || !this._mediaRecorder) {
      return;
    }
    if (!this.isRecording) {
      return;
    }
    this._isRecording = false;
    this._mediaRecorder.stop();
  }
  startRecording(fileName = "babylonjs.webm", maxDuration = 7) {
    if (!this._canvas || !this._mediaRecorder) {
      throw "Recorder has already been disposed";
    }
    if (this.isRecording) {
      throw "Recording already in progress";
    }
    if (maxDuration > 0) {
      setTimeout(() => {
        this.stopRecording();
      }, maxDuration * 1000);
    }
    this._fileName = fileName;
    this._recordedChunks = [];
    this._resolve = null;
    this._reject = null;
    this._isRecording = true;
    this._mediaRecorder.start(this._options.recordChunckSize);
    return new Promise((resolve3, reject) => {
      this._resolve = resolve3;
      this._reject = reject;
    });
  }
  dispose() {
    this._canvas = null;
    this._mediaRecorder = null;
    this._recordedChunks = [];
    this._fileName = null;
    this._resolve = null;
    this._reject = null;
  }
  _handleDataAvailable(event) {
    if (event.data.size > 0) {
      this._recordedChunks.push(event.data);
    }
  }
  _handleError(event) {
    this.stopRecording();
    if (this._reject) {
      this._reject(event.error);
    } else {
      throw new event.error;
    }
  }
  _handleStop() {
    this.stopRecording();
    const superBuffer = new Blob(this._recordedChunks);
    if (this._resolve) {
      this._resolve(superBuffer);
    }
    window.URL.createObjectURL(superBuffer);
    if (this._fileName) {
      Tools.Download(superBuffer, this._fileName);
    }
  }
}
VideoRecorder._DefaultOptions = {
  mimeType: "video/webm",
  fps: 25,
  recordChunckSize: 3000
};

// node_modules/@babylonjs/core/Misc/index.js
init_workerPool();
init_logger();
init_typeStore();
init_filesInputStore();
init_deepCopier();
init_precisionDate();

// node_modules/@babylonjs/core/Misc/screenshotTools.js
init_texture();
init_renderTargetTexture();

// node_modules/@babylonjs/core/PostProcesses/fxaaPostProcess.js
init_texture();
init_postProcess();
init_typeStore();
init_decorators_serialization();

class FxaaPostProcess extends PostProcess {
  getClassName() {
    return "FxaaPostProcess";
  }
  constructor(name391, options, camera2 = null, samplingMode, engine2, reusable, textureType = 0) {
    super(name391, "fxaa", ["texelSize"], null, options, camera2, samplingMode || Texture.BILINEAR_SAMPLINGMODE, engine2, reusable, null, textureType, "fxaa", undefined, true);
    const defines = this._getDefines();
    this.updateEffect(defines);
    this.onApplyObservable.add((effect2) => {
      const texelSize = this.texelSize;
      effect2.setFloat2("texelSize", texelSize.x, texelSize.y);
    });
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_fxaa_fragment(), exports_fxaa_fragment)), Promise.resolve().then(() => (init_fxaa_vertex(), exports_fxaa_vertex))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_fxaa_fragment2(), exports_fxaa_fragment2)), Promise.resolve().then(() => (init_fxaa_vertex2(), exports_fxaa_vertex2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  _getDefines() {
    const engine2 = this.getEngine();
    if (!engine2) {
      return null;
    }
    const driverInfo = engine2.extractDriverInfo();
    if (driverInfo.toLowerCase().indexOf("mali") > -1) {
      return `#define MALI 1
`;
    }
    return null;
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess);

// node_modules/@babylonjs/core/Misc/screenshotTools.js
init_logger();
init_tools();
init_dumpTools();
init_textureTools();
init_timingTools();
var screenshotCanvas = null;
function CreateScreenshot(engine2, camera2, size, successCallback, mimeType = "image/png", forceDownload = false, quality, useFill = false) {
  const { height, width } = _GetScreenshotSize(engine2, camera2, size);
  if (!(height && width)) {
    Logger.Error("Invalid 'size' parameter !");
    return;
  }
  const scene = camera2.getScene();
  if (scene.activeCamera !== camera2) {
    CreateScreenshotUsingRenderTarget(engine2, camera2, size, (data) => {
      if (forceDownload) {
        const blob = new Blob([data]);
        Tools.DownloadBlob(blob);
        if (successCallback) {
          successCallback("");
        }
      } else if (successCallback) {
        successCallback(data);
      }
    }, mimeType, 1, engine2.getCreationOptions().antialias, undefined, undefined, undefined, undefined, quality);
    return;
  }
  engine2.onEndFrameObservable.addOnce(() => {
    if (!screenshotCanvas) {
      screenshotCanvas = document.createElement("canvas");
    }
    screenshotCanvas.width = width;
    screenshotCanvas.height = height;
    const renderContext = screenshotCanvas.getContext("2d");
    const renderingCanvas = engine2.getRenderingCanvas();
    if (!renderContext || !renderingCanvas) {
      Logger.Error("Failed to create screenshot. Rendering context or rendering canvas is not available.");
      return;
    }
    const srcWidth = renderingCanvas.width;
    const srcHeight = renderingCanvas.height;
    const destWidth = screenshotCanvas.width;
    const destHeight = screenshotCanvas.height;
    const scaleX = destWidth / srcWidth;
    const scaleY = destHeight / srcHeight;
    const scale = useFill ? Math.max(scaleX, scaleY) : Math.min(scaleX, scaleY);
    const newWidth = srcWidth * scale;
    const newHeight = srcHeight * scale;
    const offsetX = (destWidth - newWidth) / 2;
    const offsetY = (destHeight - newHeight) / 2;
    renderContext.drawImage(renderingCanvas, 0, 0, srcWidth, srcHeight, offsetX, offsetY, newWidth, newHeight);
    if (forceDownload) {
      Tools.EncodeScreenshotCanvasData(screenshotCanvas, undefined, mimeType, undefined, quality);
      if (successCallback) {
        successCallback("");
      }
    } else {
      Tools.EncodeScreenshotCanvasData(screenshotCanvas, successCallback, mimeType, undefined, quality);
    }
  });
}
function CreateScreenshotAsync(engine2, camera2, size, mimeType = "image/png", quality, useFill = false) {
  return new Promise((resolve3, reject) => {
    CreateScreenshot(engine2, camera2, size, (data) => {
      if (typeof data !== "undefined") {
        resolve3(data);
      } else {
        reject(new Error("Data is undefined"));
      }
    }, mimeType, undefined, quality, useFill);
  });
}
function CreateScreenshotUsingRenderTarget(engine2, camera2, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture, customDumpData) {
  const { height, width, finalWidth, finalHeight } = _GetScreenshotSize(engine2, camera2, size);
  const targetTextureSize = { width, height };
  if (!(height && width)) {
    Logger.Error("Invalid 'size' parameter !");
    return;
  }
  engine2.skipFrameRender = true;
  const originalGetRenderWidth = engine2.getRenderWidth;
  const originalGetRenderHeight = engine2.getRenderHeight;
  engine2.getRenderWidth = (useScreen = false) => {
    if (!useScreen && engine2._currentRenderTarget) {
      return engine2._currentRenderTarget.width;
    }
    return width;
  };
  engine2.getRenderHeight = (useScreen = false) => {
    if (!useScreen && engine2._currentRenderTarget) {
      return engine2._currentRenderTarget.height;
    }
    return height;
  };
  if (engine2.onResizeObservable.hasObservers()) {
    engine2.onResizeObservable.notifyObservers(engine2);
  }
  const scene = camera2.getScene();
  const texture2 = new RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, 0, false, Texture.BILINEAR_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples);
  texture2.renderList = scene.meshes.slice();
  texture2.samples = samples;
  texture2.renderSprites = renderSprites;
  texture2.activeCamera = camera2;
  texture2.forceLayerMaskCheck = useLayerMask;
  customizeTexture?.(texture2);
  const dumpDataFunc = customDumpData || DumpData;
  const renderWhenReady = () => {
    _retryWithInterval(() => texture2.isReadyForRendering() && camera2.isReady(true), () => {
      engine2.onEndFrameObservable.addOnce(() => {
        if (finalWidth === width && finalHeight === height) {
          texture2.readPixels(undefined, undefined, undefined, false).then((data) => {
            dumpDataFunc(width, height, data, successCallback, mimeType, fileName, true, undefined, quality);
            texture2.dispose();
          });
        } else {
          const importPromise = engine2.isWebGPU ? Promise.resolve().then(() => (init_pass_fragment2(), exports_pass_fragment2)) : Promise.resolve().then(() => (init_pass_fragment(), exports_pass_fragment));
          importPromise.then(() => ApplyPostProcess("pass", texture2.getInternalTexture(), scene, undefined, undefined, undefined, finalWidth, finalHeight).then((texture3) => {
            engine2._readTexturePixels(texture3, finalWidth, finalHeight, -1, 0, null, true, false, 0, 0).then((data) => {
              dumpDataFunc(finalWidth, finalHeight, data, successCallback, mimeType, fileName, true, undefined, quality);
              texture3.dispose();
            });
          }));
        }
      });
      scene.incrementRenderId();
      scene.resetCachedMaterial();
      const originalCamera = scene.activeCamera;
      const originalCameras = scene.activeCameras;
      const originalOutputRenderTarget = camera2.outputRenderTarget;
      const originalSpritesEnabled = scene.spritesEnabled;
      scene.activeCamera = camera2;
      scene.activeCameras = null;
      camera2.outputRenderTarget = texture2;
      scene.spritesEnabled = renderSprites;
      const currentMeshList = scene.meshes;
      scene.meshes = texture2.renderList || scene.meshes;
      try {
        scene.render();
      } finally {
        scene.activeCamera = originalCamera;
        scene.activeCameras = originalCameras;
        camera2.outputRenderTarget = originalOutputRenderTarget;
        scene.spritesEnabled = originalSpritesEnabled;
        scene.meshes = currentMeshList;
        engine2.getRenderWidth = originalGetRenderWidth;
        engine2.getRenderHeight = originalGetRenderHeight;
        if (engine2.onResizeObservable.hasObservers()) {
          engine2.onResizeObservable.notifyObservers(engine2);
        }
        camera2.getProjectionMatrix(true);
        engine2.skipFrameRender = false;
      }
    }, () => {
      engine2.skipFrameRender = false;
      engine2.getRenderWidth = originalGetRenderWidth;
      engine2.getRenderHeight = originalGetRenderHeight;
    });
  };
  const renderToTexture = () => {
    scene.incrementRenderId();
    scene.resetCachedMaterial();
    renderWhenReady();
  };
  if (antialiasing) {
    const fxaaPostProcess = new FxaaPostProcess("antialiasing", 1, scene.activeCamera);
    texture2.addPostProcess(fxaaPostProcess);
    fxaaPostProcess.onEffectCreatedObservable.addOnce((e) => {
      if (!e.isReady()) {
        e.onCompiled = () => {
          renderToTexture();
        };
      } else {
        renderToTexture();
      }
    });
  } else {
    renderToTexture();
  }
}
function CreateScreenshotUsingRenderTargetAsync(engine2, camera2, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture, customDumpData) {
  return new Promise((resolve3, reject) => {
    CreateScreenshotUsingRenderTarget(engine2, camera2, size, (data) => {
      if (typeof data !== "undefined") {
        resolve3(data);
      } else {
        reject(new Error("Data is undefined"));
      }
    }, mimeType, samples, antialiasing, fileName, renderSprites, enableStencilBuffer, useLayerMask, quality, customizeTexture, customDumpData);
  });
}
function _GetScreenshotSize(engine2, camera2, size) {
  let height = 0;
  let width = 0;
  let finalWidth = 0;
  let finalHeight = 0;
  if (typeof size === "object") {
    const precision = size.precision ? Math.abs(size.precision) : 1;
    if (size.width && size.height) {
      height = size.height * precision;
      width = size.width * precision;
    } else if (size.width && !size.height) {
      width = size.width * precision;
      height = Math.round(width / engine2.getAspectRatio(camera2));
    } else if (size.height && !size.width) {
      height = size.height * precision;
      width = Math.round(height * engine2.getAspectRatio(camera2));
    } else {
      width = Math.round(engine2.getRenderWidth() * precision);
      height = Math.round(width / engine2.getAspectRatio(camera2));
    }
    if (size.finalWidth && size.finalHeight) {
      finalHeight = size.finalHeight;
      finalWidth = size.finalWidth;
    } else if (size.finalWidth && !size.finalHeight) {
      finalWidth = size.finalWidth;
      finalHeight = Math.round(finalWidth / engine2.getAspectRatio(camera2));
    } else if (size.finalHeight && !size.finalWidth) {
      finalHeight = size.finalHeight;
      finalWidth = Math.round(finalHeight * engine2.getAspectRatio(camera2));
    } else {
      finalWidth = width;
      finalHeight = height;
    }
  } else if (!isNaN(size)) {
    height = size;
    width = size;
    finalWidth = size;
    finalHeight = size;
  }
  if (width) {
    width = Math.floor(width);
  }
  if (height) {
    height = Math.floor(height);
  }
  if (finalWidth) {
    finalWidth = Math.floor(finalWidth);
  }
  if (finalHeight) {
    finalHeight = Math.floor(finalHeight);
  }
  return { height: height | 0, width: width | 0, finalWidth: finalWidth | 0, finalHeight: finalHeight | 0 };
}
var initSideEffects3 = () => {
  Tools.CreateScreenshot = CreateScreenshot;
  Tools.CreateScreenshotAsync = CreateScreenshotAsync;
  Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget;
  Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync;
};
initSideEffects3();

// node_modules/@babylonjs/core/Misc/index.js
init_webRequest();

// node_modules/@babylonjs/core/Misc/iInspectable.js
var InspectableType;
(function(InspectableType2) {
  InspectableType2[InspectableType2["Checkbox"] = 0] = "Checkbox";
  InspectableType2[InspectableType2["Slider"] = 1] = "Slider";
  InspectableType2[InspectableType2["Vector3"] = 2] = "Vector3";
  InspectableType2[InspectableType2["Quaternion"] = 3] = "Quaternion";
  InspectableType2[InspectableType2["Color3"] = 4] = "Color3";
  InspectableType2[InspectableType2["String"] = 5] = "String";
  InspectableType2[InspectableType2["Button"] = 6] = "Button";
  InspectableType2[InspectableType2["Options"] = 7] = "Options";
  InspectableType2[InspectableType2["Tab"] = 8] = "Tab";
  InspectableType2[InspectableType2["FileButton"] = 9] = "FileButton";
  InspectableType2[InspectableType2["Vector2"] = 10] = "Vector2";
})(InspectableType || (InspectableType = {}));

// node_modules/@babylonjs/core/Misc/index.js
init_rgbdTextureTools();

// node_modules/@babylonjs/core/Misc/gradients.js
init_math_color();

class ColorGradient {
  constructor(gradient, color1, color2) {
    this.gradient = gradient;
    this.color1 = color1;
    this.color2 = color2;
  }
  getColorToRef(result) {
    if (!this.color2) {
      result.copyFrom(this.color1);
      return;
    }
    Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  }
}

class Color3Gradient {
  constructor(gradient, color) {
    this.gradient = gradient;
    this.color = color;
  }
}

class FactorGradient {
  constructor(gradient, factor1, factor2) {
    this.gradient = gradient;
    this.factor1 = factor1;
    this.factor2 = factor2;
  }
  getFactor() {
    if (this.factor2 === undefined || this.factor2 === this.factor1) {
      return this.factor1;
    }
    return this.factor1 + (this.factor2 - this.factor1) * Math.random();
  }
}

class GradientHelper {
  static GetCurrentGradient(ratio, gradients, updateFunc) {
    if (gradients[0].gradient > ratio) {
      updateFunc(gradients[0], gradients[0], 1);
      return;
    }
    for (let gradientIndex = 0;gradientIndex < gradients.length - 1; gradientIndex++) {
      const currentGradient = gradients[gradientIndex];
      const nextGradient = gradients[gradientIndex + 1];
      if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
        const scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
        updateFunc(currentGradient, nextGradient, scale);
        return;
      }
    }
    const lastIndex = gradients.length - 1;
    updateFunc(gradients[lastIndex], gradients[lastIndex], 1);
  }
}

// node_modules/@babylonjs/core/Misc/index.js
init_perfCounter();
init_fileTools();
init_stringTools();

// node_modules/@babylonjs/core/Misc/dataReader.js
init_stringTools();
// node_modules/@babylonjs/core/Misc/dataStorage.js
class DataStorage {
  static _GetStorage() {
    try {
      localStorage.setItem("test", "");
      localStorage.removeItem("test");
      return localStorage;
    } catch {
      const inMemoryStorage = {};
      return {
        getItem: (key) => {
          const value = inMemoryStorage[key];
          return value === undefined ? null : value;
        },
        setItem: (key, value) => {
          inMemoryStorage[key] = value;
        }
      };
    }
  }
  static ReadString(key, defaultValue) {
    const value = this._Storage.getItem(key);
    return value !== null ? value : defaultValue;
  }
  static WriteString(key, value) {
    this._Storage.setItem(key, value);
  }
  static ReadBoolean(key, defaultValue) {
    const value = this._Storage.getItem(key);
    return value !== null ? value === "true" : defaultValue;
  }
  static WriteBoolean(key, value) {
    this._Storage.setItem(key, value ? "true" : "false");
  }
  static ReadNumber(key, defaultValue) {
    const value = this._Storage.getItem(key);
    return value !== null ? parseFloat(value) : defaultValue;
  }
  static WriteNumber(key, value) {
    this._Storage.setItem(key, value.toString());
  }
}
DataStorage._Storage = DataStorage._GetStorage();
// node_modules/@babylonjs/core/Particles/thinParticleSystem.js
init_observable();
init_math_vector();
init_buffer();
init_engineStore();

// node_modules/@babylonjs/core/Particles/particle.js
init_math_vector();
init_math_color();

class Particle2 {
  constructor(particleSystem) {
    this.particleSystem = particleSystem;
    this.position = Vector3.Zero();
    this.direction = Vector3.Zero();
    this.color = new Color4(0, 0, 0, 0);
    this.colorStep = new Color4(0, 0, 0, 0);
    this.lifeTime = 1;
    this.age = 0;
    this.size = 0;
    this.scale = new Vector2(1, 1);
    this.angle = 0;
    this.angularSpeed = 0;
    this.cellIndex = 0;
    this._attachedSubEmitters = null;
    this._currentColor1 = new Color4(0, 0, 0, 0);
    this._currentColor2 = new Color4(0, 0, 0, 0);
    this._currentSize1 = 0;
    this._currentSize2 = 0;
    this._currentAngularSpeed1 = 0;
    this._currentAngularSpeed2 = 0;
    this._currentVelocity1 = 0;
    this._currentVelocity2 = 0;
    this._currentLimitVelocity1 = 0;
    this._currentLimitVelocity2 = 0;
    this._currentDrag1 = 0;
    this._currentDrag2 = 0;
    this.id = Particle2._Count++;
    if (!this.particleSystem.isAnimationSheetEnabled) {
      return;
    }
    this._updateCellInfoFromSystem();
  }
  _updateCellInfoFromSystem() {
    this.cellIndex = this.particleSystem.startSpriteCellID;
  }
  updateCellIndex() {
    let offsetAge = this.age;
    let changeSpeed = this.particleSystem.spriteCellChangeSpeed;
    if (this.particleSystem.spriteRandomStartCell) {
      if (this._randomCellOffset === undefined) {
        this._randomCellOffset = Math.random() * this.lifeTime;
      }
      if (changeSpeed === 0) {
        changeSpeed = 1;
        offsetAge = this._randomCellOffset;
      } else {
        offsetAge += this._randomCellOffset;
      }
    }
    const dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID + 1;
    let ratio;
    if (this._initialSpriteCellLoop) {
      ratio = Clamp(offsetAge * changeSpeed % this.lifeTime / this.lifeTime);
    } else {
      ratio = Clamp(offsetAge * changeSpeed / this.lifeTime);
    }
    this.cellIndex = this._initialStartSpriteCellID + ratio * dist | 0;
  }
  _inheritParticleInfoToSubEmitter(subEmitter) {
    if (subEmitter.particleSystem.emitter.position) {
      const emitterMesh = subEmitter.particleSystem.emitter;
      emitterMesh.position.copyFrom(this.position);
      if (subEmitter.inheritDirection) {
        const temp = TmpVectors.Vector3[0];
        this.direction.normalizeToRef(temp);
        emitterMesh.setDirection(temp, 0, Math.PI / 2);
      }
    } else {
      const emitterPosition = subEmitter.particleSystem.emitter;
      emitterPosition.copyFrom(this.position);
    }
    this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]);
    subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0]);
  }
  _inheritParticleInfoToSubEmitters() {
    if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
      this._attachedSubEmitters.forEach((subEmitter) => {
        this._inheritParticleInfoToSubEmitter(subEmitter);
      });
    }
  }
  _reset() {
    this.age = 0;
    this.id = Particle2._Count++;
    this._currentColorGradient = null;
    this._currentSizeGradient = null;
    this._currentAngularSpeedGradient = null;
    this._currentVelocityGradient = null;
    this._currentLimitVelocityGradient = null;
    this._currentDragGradient = null;
    this.cellIndex = this.particleSystem.startSpriteCellID;
    this._randomCellOffset = undefined;
  }
  copyTo(other) {
    other.position.copyFrom(this.position);
    if (this._initialDirection) {
      if (other._initialDirection) {
        other._initialDirection.copyFrom(this._initialDirection);
      } else {
        other._initialDirection = this._initialDirection.clone();
      }
    } else {
      other._initialDirection = null;
    }
    other.direction.copyFrom(this.direction);
    if (this._localPosition) {
      if (other._localPosition) {
        other._localPosition.copyFrom(this._localPosition);
      } else {
        other._localPosition = this._localPosition.clone();
      }
    }
    other.color.copyFrom(this.color);
    other.colorStep.copyFrom(this.colorStep);
    other.lifeTime = this.lifeTime;
    other.age = this.age;
    other._randomCellOffset = this._randomCellOffset;
    other.size = this.size;
    other.scale.copyFrom(this.scale);
    other.angle = this.angle;
    other.angularSpeed = this.angularSpeed;
    other.particleSystem = this.particleSystem;
    other.cellIndex = this.cellIndex;
    other.id = this.id;
    other._attachedSubEmitters = this._attachedSubEmitters;
    if (this._currentColorGradient) {
      other._currentColorGradient = this._currentColorGradient;
      other._currentColor1.copyFrom(this._currentColor1);
      other._currentColor2.copyFrom(this._currentColor2);
    }
    if (this._currentSizeGradient) {
      other._currentSizeGradient = this._currentSizeGradient;
      other._currentSize1 = this._currentSize1;
      other._currentSize2 = this._currentSize2;
    }
    if (this._currentAngularSpeedGradient) {
      other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
      other._currentAngularSpeed1 = this._currentAngularSpeed1;
      other._currentAngularSpeed2 = this._currentAngularSpeed2;
    }
    if (this._currentVelocityGradient) {
      other._currentVelocityGradient = this._currentVelocityGradient;
      other._currentVelocity1 = this._currentVelocity1;
      other._currentVelocity2 = this._currentVelocity2;
    }
    if (this._currentLimitVelocityGradient) {
      other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
      other._currentLimitVelocity1 = this._currentLimitVelocity1;
      other._currentLimitVelocity2 = this._currentLimitVelocity2;
    }
    if (this._currentDragGradient) {
      other._currentDragGradient = this._currentDragGradient;
      other._currentDrag1 = this._currentDrag1;
      other._currentDrag2 = this._currentDrag2;
    }
    if (this.particleSystem.isAnimationSheetEnabled) {
      other._initialStartSpriteCellID = this._initialStartSpriteCellID;
      other._initialEndSpriteCellID = this._initialEndSpriteCellID;
      other._initialSpriteCellLoop = this._initialSpriteCellLoop;
    }
    if (this.particleSystem.useRampGradients) {
      if (other.remapData && this.remapData) {
        other.remapData.copyFrom(this.remapData);
      } else {
        other.remapData = new Vector4(0, 0, 0, 0);
      }
    }
    if (this._randomNoiseCoordinates1) {
      if (other._randomNoiseCoordinates1) {
        other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
        other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
      } else {
        other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
        other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
      }
    }
  }
}
Particle2._Count = 0;

// node_modules/@babylonjs/core/Particles/thinParticleSystem.js
init_drawWrapper();
init_math_color();
init_engine_alpha();
init_materialHelper_functions();

// node_modules/@babylonjs/core/Particles/EmitterTypes/boxParticleEmitter.js
init_math_vector();
init_deepCopier();

class BoxParticleEmitter {
  constructor() {
    this.direction1 = new Vector3(0, 1, 0);
    this.direction2 = new Vector3(0, 1, 0);
    this.minEmitBox = new Vector3(-0.5, -0.5, -0.5);
    this.maxEmitBox = new Vector3(0.5, 0.5, 0.5);
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    if (isLocal) {
      directionToUpdate.x = randX;
      directionToUpdate.y = randY;
      directionToUpdate.z = randZ;
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const randX = RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
    const randY = RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
    const randZ = RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
    if (isLocal) {
      positionToUpdate.x = randX;
      positionToUpdate.y = randY;
      positionToUpdate.z = randZ;
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new BoxParticleEmitter;
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
    uboOrEffect.setVector3("minEmitBox", this.minEmitBox);
    uboOrEffect.setVector3("maxEmitBox", this.maxEmitBox);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
    ubo.addUniform("minEmitBox", 3);
    ubo.addUniform("maxEmitBox", 3);
  }
  getEffectDefines() {
    return "#define BOXEMITTER";
  }
  getClassName() {
    return "BoxParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    serializationObject.minEmitBox = this.minEmitBox.asArray();
    serializationObject.maxEmitBox = this.maxEmitBox.asArray();
    return serializationObject;
  }
  parse(serializationObject) {
    Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
    Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
    Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
    Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  }
}

// node_modules/@babylonjs/core/Particles/thinParticleSystem.js
init_imageProcessingConfiguration_functions();

class ThinParticleSystem extends BaseParticleSystem {
  set onDispose(callback) {
    if (this._onDisposeObserver) {
      this.onDisposeObservable.remove(this._onDisposeObserver);
    }
    this._onDisposeObserver = this.onDisposeObservable.add(callback);
  }
  get useRampGradients() {
    return this._useRampGradients;
  }
  set useRampGradients(value) {
    if (this._useRampGradients === value) {
      return;
    }
    this._useRampGradients = value;
    this._resetEffect();
  }
  get particles() {
    return this._particles;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  getActiveCount() {
    return this._particles.length;
  }
  getClassName() {
    return "ParticleSystem";
  }
  isStopping() {
    return this._stopped && this.isAlive();
  }
  getCustomEffect(blendMode = 0) {
    return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect;
  }
  _getCustomDrawWrapper(blendMode = 0) {
    return this._customWrappers[blendMode] ?? this._customWrappers[0];
  }
  setCustomEffect(effect2, blendMode = 0) {
    this._customWrappers[blendMode] = new DrawWrapper(this._engine);
    this._customWrappers[blendMode].effect = effect2;
    if (this._customWrappers[blendMode].drawContext) {
      this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing;
    }
  }
  get onBeforeDrawParticlesObservable() {
    if (!this._onBeforeDrawParticlesObservable) {
      this._onBeforeDrawParticlesObservable = new Observable;
    }
    return this._onBeforeDrawParticlesObservable;
  }
  get vertexShaderName() {
    return "particles";
  }
  get vertexBuffers() {
    return this._vertexBuffers;
  }
  get indexBuffer() {
    return this._indexBuffer;
  }
  constructor(name395, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) {
    super(name395);
    this._emitterInverseWorldMatrix = Matrix.Identity();
    this._inheritedVelocityOffset = new Vector3;
    this.onDisposeObservable = new Observable;
    this.onStoppedObservable = new Observable;
    this._particles = new Array;
    this._stockParticles = new Array;
    this._newPartsExcess = 0;
    this._vertexBuffers = {};
    this._scaledColorStep = new Color4(0, 0, 0, 0);
    this._colorDiff = new Color4(0, 0, 0, 0);
    this._scaledDirection = Vector3.Zero();
    this._scaledGravity = Vector3.Zero();
    this._currentRenderId = -1;
    this._useInstancing = false;
    this._started = false;
    this._stopped = false;
    this._actualFrame = 0;
    this._currentEmitRate1 = 0;
    this._currentEmitRate2 = 0;
    this._currentStartSize1 = 0;
    this._currentStartSize2 = 0;
    this.updateInAnimate = true;
    this._rawTextureWidth = 256;
    this._useRampGradients = false;
    this.isLocal = false;
    this.isGPU = false;
    this._shaderLanguage = 0;
    this._onBeforeDrawParticlesObservable = null;
    this._emitFromParticle = (particle) => {};
    this.recycleParticle = (particle) => {
      const lastParticle = this._particles.pop();
      if (lastParticle !== particle) {
        lastParticle.copyTo(particle);
      }
      this._stockParticles.push(lastParticle);
    };
    this._createParticle = () => {
      let particle;
      if (this._stockParticles.length !== 0) {
        particle = this._stockParticles.pop();
        particle._reset();
      } else {
        particle = new Particle2(this);
      }
      this._prepareParticle(particle);
      return particle;
    };
    this._shadersLoaded = false;
    this._capacity = capacity;
    this._epsilon = epsilon;
    this._isAnimationSheetEnabled = isAnimationSheetEnabled;
    if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
      this._scene = sceneOrEngine || EngineStore.LastCreatedScene;
      this._engine = this._scene.getEngine();
      this.uniqueId = this._scene.getUniqueId();
      this._scene.particleSystems.push(this);
    } else {
      this._engine = sceneOrEngine;
      this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);
    }
    if (this._engine.getCaps().vertexArrayObject) {
      this._vertexArrayObject = null;
    }
    this._initShaderSourceAsync();
    this._attachImageProcessingConfiguration(null);
    this._customWrappers = { 0: new DrawWrapper(this._engine) };
    this._customWrappers[0].effect = customEffect;
    this._drawWrappers = [];
    this._useInstancing = this._engine.getCaps().instancedArrays;
    this._createIndexBuffer();
    this._createVertexBuffers();
    this.particleEmitterType = new BoxParticleEmitter;
    let noiseTextureData = null;
    this.updateFunction = (particles) => {
      let noiseTextureSize = null;
      if (this.noiseTexture) {
        noiseTextureSize = this.noiseTexture.getSize();
        this.noiseTexture.getContent()?.then((data) => {
          noiseTextureData = data;
        });
      }
      const sameParticleArray = particles === this._particles;
      for (let index = 0;index < particles.length; index++) {
        const particle = particles[index];
        let scaledUpdateSpeed = this._scaledUpdateSpeed;
        const previousAge = particle.age;
        particle.age += scaledUpdateSpeed;
        if (particle.age > particle.lifeTime) {
          const diff = particle.age - previousAge;
          const oldDiff = particle.lifeTime - previousAge;
          scaledUpdateSpeed = oldDiff * scaledUpdateSpeed / diff;
          particle.age = particle.lifeTime;
        }
        const ratio = particle.age / particle.lifeTime;
        if (this._colorGradients && this._colorGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentColorGradient) {
              particle._currentColor1.copyFrom(particle._currentColor2);
              nextGradient.getColorToRef(particle._currentColor2);
              particle._currentColorGradient = currentGradient;
            }
            Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
          });
        } else {
          particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep);
          particle.color.addInPlace(this._scaledColorStep);
          if (particle.color.a < 0) {
            particle.color.a = 0;
          }
        }
        if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentAngularSpeedGradient) {
              particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
              particle._currentAngularSpeed2 = nextGradient.getFactor();
              particle._currentAngularSpeedGradient = currentGradient;
            }
            particle.angularSpeed = Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
          });
        }
        particle.angle += particle.angularSpeed * scaledUpdateSpeed;
        let directionScale = scaledUpdateSpeed;
        if (this._velocityGradients && this._velocityGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentVelocityGradient) {
              particle._currentVelocity1 = particle._currentVelocity2;
              particle._currentVelocity2 = nextGradient.getFactor();
              particle._currentVelocityGradient = currentGradient;
            }
            directionScale *= Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
          });
        }
        particle.direction.scaleToRef(directionScale, this._scaledDirection);
        if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentLimitVelocityGradient) {
              particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
              particle._currentLimitVelocity2 = nextGradient.getFactor();
              particle._currentLimitVelocityGradient = currentGradient;
            }
            const limitVelocity = Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
            const currentVelocity = particle.direction.length();
            if (currentVelocity > limitVelocity) {
              particle.direction.scaleInPlace(this.limitVelocityDamping);
            }
          });
        }
        if (this._dragGradients && this._dragGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentDragGradient) {
              particle._currentDrag1 = particle._currentDrag2;
              particle._currentDrag2 = nextGradient.getFactor();
              particle._currentDragGradient = currentGradient;
            }
            const drag = Lerp(particle._currentDrag1, particle._currentDrag2, scale);
            this._scaledDirection.scaleInPlace(1 - drag);
          });
        }
        if (this.isLocal && particle._localPosition) {
          particle._localPosition.addInPlace(this._scaledDirection);
          Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);
        } else {
          particle.position.addInPlace(this._scaledDirection);
        }
        if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {
          const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
          const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
          const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
          const force = TmpVectors.Vector3[0];
          const scaledForce = TmpVectors.Vector3[1];
          force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);
          force.scaleToRef(scaledUpdateSpeed, scaledForce);
          particle.direction.addInPlace(scaledForce);
        }
        this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity);
        particle.direction.addInPlace(this._scaledGravity);
        if (this._sizeGradients && this._sizeGradients.length > 0) {
          GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {
            if (currentGradient !== particle._currentSizeGradient) {
              particle._currentSize1 = particle._currentSize2;
              particle._currentSize2 = nextGradient.getFactor();
              particle._currentSizeGradient = currentGradient;
            }
            particle.size = Lerp(particle._currentSize1, particle._currentSize2, scale);
          });
        }
        if (this._useRampGradients) {
          if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {
            GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {
              const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale);
              const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale);
              particle.remapData.x = min;
              particle.remapData.y = max - min;
            });
          }
          if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {
            GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {
              const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale);
              const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale);
              particle.remapData.z = min;
              particle.remapData.w = max - min;
            });
          }
        }
        if (this._isAnimationSheetEnabled) {
          particle.updateCellIndex();
        }
        particle._inheritParticleInfoToSubEmitters();
        if (particle.age >= particle.lifeTime) {
          this._emitFromParticle(particle);
          if (particle._attachedSubEmitters) {
            particle._attachedSubEmitters.forEach((subEmitter) => {
              subEmitter.particleSystem.disposeOnStop = true;
              subEmitter.particleSystem.stop();
            });
            particle._attachedSubEmitters = null;
          }
          this.recycleParticle(particle);
          if (sameParticleArray) {
            index--;
          }
          continue;
        }
      }
    };
  }
  serialize(serializeTexture) {
    throw new Error("Method not implemented.");
  }
  clone(name395, newEmitter, cloneTexture = false) {
    throw new Error("Method not implemented.");
  }
  _addFactorGradient(factorGradients, gradient, factor, factor2) {
    const newGradient = new FactorGradient(gradient, factor, factor2);
    factorGradients.push(newGradient);
    factorGradients.sort((a, b) => {
      if (a.gradient < b.gradient) {
        return -1;
      } else if (a.gradient > b.gradient) {
        return 1;
      }
      return 0;
    });
  }
  _removeFactorGradient(factorGradients, gradient) {
    if (!factorGradients) {
      return;
    }
    let index = 0;
    for (const factorGradient of factorGradients) {
      if (factorGradient.gradient === gradient) {
        factorGradients.splice(index, 1);
        break;
      }
      index++;
    }
  }
  addLifeTimeGradient(gradient, factor, factor2) {
    if (!this._lifeTimeGradients) {
      this._lifeTimeGradients = [];
    }
    this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
    return this;
  }
  removeLifeTimeGradient(gradient) {
    this._removeFactorGradient(this._lifeTimeGradients, gradient);
    return this;
  }
  addSizeGradient(gradient, factor, factor2) {
    if (!this._sizeGradients) {
      this._sizeGradients = [];
    }
    this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
    return this;
  }
  removeSizeGradient(gradient) {
    this._removeFactorGradient(this._sizeGradients, gradient);
    return this;
  }
  addColorRemapGradient(gradient, min, max) {
    if (!this._colorRemapGradients) {
      this._colorRemapGradients = [];
    }
    this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
    return this;
  }
  removeColorRemapGradient(gradient) {
    this._removeFactorGradient(this._colorRemapGradients, gradient);
    return this;
  }
  addAlphaRemapGradient(gradient, min, max) {
    if (!this._alphaRemapGradients) {
      this._alphaRemapGradients = [];
    }
    this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
    return this;
  }
  removeAlphaRemapGradient(gradient) {
    this._removeFactorGradient(this._alphaRemapGradients, gradient);
    return this;
  }
  addAngularSpeedGradient(gradient, factor, factor2) {
    if (!this._angularSpeedGradients) {
      this._angularSpeedGradients = [];
    }
    this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
    return this;
  }
  removeAngularSpeedGradient(gradient) {
    this._removeFactorGradient(this._angularSpeedGradients, gradient);
    return this;
  }
  addVelocityGradient(gradient, factor, factor2) {
    if (!this._velocityGradients) {
      this._velocityGradients = [];
    }
    this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
    return this;
  }
  removeVelocityGradient(gradient) {
    this._removeFactorGradient(this._velocityGradients, gradient);
    return this;
  }
  addLimitVelocityGradient(gradient, factor, factor2) {
    if (!this._limitVelocityGradients) {
      this._limitVelocityGradients = [];
    }
    this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
    return this;
  }
  removeLimitVelocityGradient(gradient) {
    this._removeFactorGradient(this._limitVelocityGradients, gradient);
    return this;
  }
  addDragGradient(gradient, factor, factor2) {
    if (!this._dragGradients) {
      this._dragGradients = [];
    }
    this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
    return this;
  }
  removeDragGradient(gradient) {
    this._removeFactorGradient(this._dragGradients, gradient);
    return this;
  }
  addEmitRateGradient(gradient, factor, factor2) {
    if (!this._emitRateGradients) {
      this._emitRateGradients = [];
    }
    this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
    return this;
  }
  removeEmitRateGradient(gradient) {
    this._removeFactorGradient(this._emitRateGradients, gradient);
    return this;
  }
  addStartSizeGradient(gradient, factor, factor2) {
    if (!this._startSizeGradients) {
      this._startSizeGradients = [];
    }
    this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
    return this;
  }
  removeStartSizeGradient(gradient) {
    this._removeFactorGradient(this._startSizeGradients, gradient);
    return this;
  }
  _createRampGradientTexture() {
    if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) {
      return;
    }
    const data = new Uint8Array(this._rawTextureWidth * 4);
    const tmpColor = TmpColors.Color3[0];
    for (let x = 0;x < this._rawTextureWidth; x++) {
      const ratio = x / this._rawTextureWidth;
      GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {
        Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
        data[x * 4] = tmpColor.r * 255;
        data[x * 4 + 1] = tmpColor.g * 255;
        data[x * 4 + 2] = tmpColor.b * 255;
        data[x * 4 + 3] = 255;
      });
    }
    this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);
  }
  getRampGradients() {
    return this._rampGradients;
  }
  forceRefreshGradients() {
    this._syncRampGradientTexture();
  }
  _syncRampGradientTexture() {
    if (!this._rampGradients) {
      return;
    }
    this._rampGradients.sort((a, b) => {
      if (a.gradient < b.gradient) {
        return -1;
      } else if (a.gradient > b.gradient) {
        return 1;
      }
      return 0;
    });
    if (this._rampGradientsTexture) {
      this._rampGradientsTexture.dispose();
      this._rampGradientsTexture = null;
    }
    this._createRampGradientTexture();
  }
  addRampGradient(gradient, color) {
    if (!this._rampGradients) {
      this._rampGradients = [];
    }
    const rampGradient = new Color3Gradient(gradient, color);
    this._rampGradients.push(rampGradient);
    this._syncRampGradientTexture();
    return this;
  }
  removeRampGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
    this._rampGradientsTexture = null;
    if (this._rampGradients && this._rampGradients.length > 0) {
      this._createRampGradientTexture();
    }
    return this;
  }
  addColorGradient(gradient, color1, color2) {
    if (!this._colorGradients) {
      this._colorGradients = [];
    }
    const colorGradient = new ColorGradient(gradient, color1, color2);
    this._colorGradients.push(colorGradient);
    this._colorGradients.sort((a, b) => {
      if (a.gradient < b.gradient) {
        return -1;
      } else if (a.gradient > b.gradient) {
        return 1;
      }
      return 0;
    });
    return this;
  }
  removeColorGradient(gradient) {
    if (!this._colorGradients) {
      return this;
    }
    let index = 0;
    for (const colorGradient of this._colorGradients) {
      if (colorGradient.gradient === gradient) {
        this._colorGradients.splice(index, 1);
        break;
      }
      index++;
    }
    return this;
  }
  resetDrawCache() {
    for (const drawWrappers of this._drawWrappers) {
      if (drawWrappers) {
        for (const drawWrapper2 of drawWrappers) {
          drawWrapper2?.dispose();
        }
      }
    }
    this._drawWrappers = [];
  }
  _fetchR(u, v, width, height, pixels) {
    u = Math.abs(u) * 0.5 + 0.5;
    v = Math.abs(v) * 0.5 + 0.5;
    const wrappedU = u * width % width | 0;
    const wrappedV = v * height % height | 0;
    const position = (wrappedU + wrappedV * width) * 4;
    return pixels[position] / 255;
  }
  _reset() {
    this._resetEffect();
  }
  _resetEffect() {
    if (this._vertexBuffer) {
      this._vertexBuffer.dispose();
      this._vertexBuffer = null;
    }
    if (this._spriteBuffer) {
      this._spriteBuffer.dispose();
      this._spriteBuffer = null;
    }
    if (this._vertexArrayObject) {
      this._engine.releaseVertexArrayObject(this._vertexArrayObject);
      this._vertexArrayObject = null;
    }
    this._createVertexBuffers();
  }
  _createVertexBuffers() {
    this._vertexBufferSize = this._useInstancing ? 10 : 12;
    if (this._isAnimationSheetEnabled) {
      this._vertexBufferSize += 1;
    }
    if (!this._isBillboardBased || this.billboardMode === 8 || this.billboardMode === 9) {
      this._vertexBufferSize += 3;
    }
    if (this._useRampGradients) {
      this._vertexBufferSize += 4;
    }
    const engine2 = this._engine;
    const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4);
    this._vertexData = new Float32Array(this._capacity * vertexSize);
    this._vertexBuffer = new Buffer2(engine2, this._vertexData, true, vertexSize);
    let dataOffset = 0;
    const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
    this._vertexBuffers[VertexBuffer.PositionKind] = positions;
    dataOffset += 3;
    const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
    this._vertexBuffers[VertexBuffer.ColorKind] = colors;
    dataOffset += 4;
    const options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
    this._vertexBuffers["angle"] = options;
    dataOffset += 1;
    const size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
    this._vertexBuffers["size"] = size;
    dataOffset += 2;
    if (this._isAnimationSheetEnabled) {
      const cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
      this._vertexBuffers["cellIndex"] = cellIndexBuffer;
      dataOffset += 1;
    }
    if (!this._isBillboardBased || this.billboardMode === 8 || this.billboardMode === 9) {
      const directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
      this._vertexBuffers["direction"] = directionBuffer;
      dataOffset += 3;
    }
    if (this._useRampGradients) {
      const rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
      this._vertexBuffers["remapData"] = rampDataBuffer;
      dataOffset += 4;
    }
    let offsets;
    if (this._useInstancing) {
      const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
      this._spriteBuffer = new Buffer2(engine2, spriteData, false, 2);
      offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
    } else {
      offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
      dataOffset += 2;
    }
    this._vertexBuffers["offset"] = offsets;
    this.resetDrawCache();
  }
  _createIndexBuffer() {
    if (this._useInstancing) {
      this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]));
      return;
    }
    const indices = [];
    const indicesWireframe = [];
    let index = 0;
    for (let count = 0;count < this._capacity; count++) {
      indices.push(index);
      indices.push(index + 1);
      indices.push(index + 2);
      indices.push(index);
      indices.push(index + 2);
      indices.push(index + 3);
      indicesWireframe.push(index, index + 1, index + 1, index + 2, index + 2, index + 3, index + 3, index, index, index + 3);
      index += 4;
    }
    this._indexBuffer = this._engine.createIndexBuffer(indices);
    this._linesIndexBuffer = this._engine.createIndexBuffer(indicesWireframe);
  }
  getCapacity() {
    return this._capacity;
  }
  isAlive() {
    return this._alive;
  }
  isStarted() {
    return this._started;
  }
  _preStart() {}
  start(delay = this.startDelay) {
    if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
      throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
    }
    if (delay) {
      setTimeout(() => {
        this.start(0);
      }, delay);
      return;
    }
    this._started = true;
    this._stopped = false;
    this._actualFrame = 0;
    this._preStart();
    if (this._emitRateGradients) {
      if (this._emitRateGradients.length > 0) {
        this._currentEmitRateGradient = this._emitRateGradients[0];
        this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
        this._currentEmitRate2 = this._currentEmitRate1;
      }
      if (this._emitRateGradients.length > 1) {
        this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
      }
    }
    if (this._startSizeGradients) {
      if (this._startSizeGradients.length > 0) {
        this._currentStartSizeGradient = this._startSizeGradients[0];
        this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
        this._currentStartSize2 = this._currentStartSize1;
      }
      if (this._startSizeGradients.length > 1) {
        this._currentStartSize2 = this._startSizeGradients[1].getFactor();
      }
    }
    if (this.preWarmCycles) {
      if (this.emitter?.getClassName().indexOf("Mesh") !== -1) {
        this.emitter.computeWorldMatrix(true);
      }
      const noiseTextureAsProcedural = this.noiseTexture;
      if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) {
        noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => {
          setTimeout(() => {
            for (let index = 0;index < this.preWarmCycles; index++) {
              this.animate(true);
              noiseTextureAsProcedural.render();
            }
          });
        });
      } else {
        for (let index = 0;index < this.preWarmCycles; index++) {
          this.animate(true);
        }
      }
    }
    if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {
      this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
    }
  }
  stop(stopSubEmitters = true) {
    if (this._stopped) {
      return;
    }
    this.onStoppedObservable.notifyObservers(this);
    this._stopped = true;
    this._postStop(stopSubEmitters);
  }
  _postStop(stopSubEmitters) {}
  reset() {
    this._stockParticles.length = 0;
    this._particles.length = 0;
  }
  _appendParticleVertex(index, particle, offsetX, offsetY) {
    let offset = index * this._vertexBufferSize;
    this._vertexData[offset++] = particle.position.x + this.worldOffset.x;
    this._vertexData[offset++] = particle.position.y + this.worldOffset.y;
    this._vertexData[offset++] = particle.position.z + this.worldOffset.z;
    this._vertexData[offset++] = particle.color.r;
    this._vertexData[offset++] = particle.color.g;
    this._vertexData[offset++] = particle.color.b;
    this._vertexData[offset++] = particle.color.a;
    this._vertexData[offset++] = particle.angle;
    this._vertexData[offset++] = particle.scale.x * particle.size;
    this._vertexData[offset++] = particle.scale.y * particle.size;
    if (this._isAnimationSheetEnabled) {
      this._vertexData[offset++] = particle.cellIndex;
    }
    if (!this._isBillboardBased) {
      if (particle._initialDirection) {
        let initialDirection = particle._initialDirection;
        if (this.isLocal) {
          Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]);
          initialDirection = TmpVectors.Vector3[0];
        }
        if (initialDirection.x === 0 && initialDirection.z === 0) {
          initialDirection.x = 0.001;
        }
        this._vertexData[offset++] = initialDirection.x;
        this._vertexData[offset++] = initialDirection.y;
        this._vertexData[offset++] = initialDirection.z;
      } else {
        let direction = particle.direction;
        if (this.isLocal) {
          Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]);
          direction = TmpVectors.Vector3[0];
        }
        if (direction.x === 0 && direction.z === 0) {
          direction.x = 0.001;
        }
        this._vertexData[offset++] = direction.x;
        this._vertexData[offset++] = direction.y;
        this._vertexData[offset++] = direction.z;
      }
    } else if (this.billboardMode === 8 || this.billboardMode === 9) {
      this._vertexData[offset++] = particle.direction.x;
      this._vertexData[offset++] = particle.direction.y;
      this._vertexData[offset++] = particle.direction.z;
    }
    if (this._useRampGradients && particle.remapData) {
      this._vertexData[offset++] = particle.remapData.x;
      this._vertexData[offset++] = particle.remapData.y;
      this._vertexData[offset++] = particle.remapData.z;
      this._vertexData[offset++] = particle.remapData.w;
    }
    if (!this._useInstancing) {
      if (this._isAnimationSheetEnabled) {
        if (offsetX === 0) {
          offsetX = this._epsilon;
        } else if (offsetX === 1) {
          offsetX = 1 - this._epsilon;
        }
        if (offsetY === 0) {
          offsetY = this._epsilon;
        } else if (offsetY === 1) {
          offsetY = 1 - this._epsilon;
        }
      }
      this._vertexData[offset++] = offsetX;
      this._vertexData[offset++] = offsetY;
    }
  }
  _prepareParticle(particle) {}
  _update(newParticles) {
    this._alive = this._particles.length > 0;
    if (this.emitter.position) {
      const emitterMesh = this.emitter;
      this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
    } else {
      const emitterPosition = this.emitter;
      this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
    }
    this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix);
    this.updateFunction(this._particles);
    let particle;
    for (let index = 0;index < newParticles; index++) {
      if (this._particles.length === this._capacity) {
        break;
      }
      particle = this._createParticle();
      this._particles.push(particle);
      if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {
        const ratio = Clamp(this._actualFrame / this.targetStopDuration);
        GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => {
          const factorGradient1 = currentGradient;
          const factorGradient2 = nextGradient;
          const lifeTime1 = factorGradient1.getFactor();
          const lifeTime2 = factorGradient2.getFactor();
          const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
          particle.lifeTime = Lerp(lifeTime1, lifeTime2, gradient);
        });
      } else {
        particle.lifeTime = RandomRange(this.minLifeTime, this.maxLifeTime);
      }
      const emitPower = RandomRange(this.minEmitPower, this.maxEmitPower);
      if (this.startPositionFunction) {
        this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);
      } else {
        this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);
      }
      if (this.isLocal) {
        if (!particle._localPosition) {
          particle._localPosition = particle.position.clone();
        } else {
          particle._localPosition.copyFrom(particle.position);
        }
        Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);
      }
      if (this.startDirectionFunction) {
        this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal);
      } else {
        this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix);
      }
      if (emitPower === 0) {
        if (!particle._initialDirection) {
          particle._initialDirection = particle.direction.clone();
        } else {
          particle._initialDirection.copyFrom(particle.direction);
        }
      } else {
        particle._initialDirection = null;
      }
      particle.direction.scaleInPlace(emitPower);
      if (!this._sizeGradients || this._sizeGradients.length === 0) {
        particle.size = RandomRange(this.minSize, this.maxSize);
      } else {
        particle._currentSizeGradient = this._sizeGradients[0];
        particle._currentSize1 = particle._currentSizeGradient.getFactor();
        particle.size = particle._currentSize1;
        if (this._sizeGradients.length > 1) {
          particle._currentSize2 = this._sizeGradients[1].getFactor();
        } else {
          particle._currentSize2 = particle._currentSize1;
        }
      }
      particle.scale.copyFromFloats(RandomRange(this.minScaleX, this.maxScaleX), RandomRange(this.minScaleY, this.maxScaleY));
      if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {
        const ratio = this._actualFrame / this.targetStopDuration;
        GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {
          if (currentGradient !== this._currentStartSizeGradient) {
            this._currentStartSize1 = this._currentStartSize2;
            this._currentStartSize2 = nextGradient.getFactor();
            this._currentStartSizeGradient = currentGradient;
          }
          const value = Lerp(this._currentStartSize1, this._currentStartSize2, scale);
          particle.scale.scaleInPlace(value);
        });
      }
      if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {
        particle.angularSpeed = RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
      } else {
        particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];
        particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
        particle._currentAngularSpeed1 = particle.angularSpeed;
        if (this._angularSpeedGradients.length > 1) {
          particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();
        } else {
          particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
        }
      }
      particle.angle = RandomRange(this.minInitialRotation, this.maxInitialRotation);
      if (this._velocityGradients && this._velocityGradients.length > 0) {
        particle._currentVelocityGradient = this._velocityGradients[0];
        particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
        if (this._velocityGradients.length > 1) {
          particle._currentVelocity2 = this._velocityGradients[1].getFactor();
        } else {
          particle._currentVelocity2 = particle._currentVelocity1;
        }
      }
      if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {
        particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];
        particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
        if (this._limitVelocityGradients.length > 1) {
          particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();
        } else {
          particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
        }
      }
      if (this._dragGradients && this._dragGradients.length > 0) {
        particle._currentDragGradient = this._dragGradients[0];
        particle._currentDrag1 = particle._currentDragGradient.getFactor();
        if (this._dragGradients.length > 1) {
          particle._currentDrag2 = this._dragGradients[1].getFactor();
        } else {
          particle._currentDrag2 = particle._currentDrag1;
        }
      }
      if (!this._colorGradients || this._colorGradients.length === 0) {
        const step = RandomRange(0, 1);
        Color4.LerpToRef(this.color1, this.color2, step, particle.color);
        this.colorDead.subtractToRef(particle.color, this._colorDiff);
        this._colorDiff.scaleToRef(1 / particle.lifeTime, particle.colorStep);
      } else {
        particle._currentColorGradient = this._colorGradients[0];
        particle._currentColorGradient.getColorToRef(particle.color);
        particle._currentColor1.copyFrom(particle.color);
        if (this._colorGradients.length > 1) {
          this._colorGradients[1].getColorToRef(particle._currentColor2);
        } else {
          particle._currentColor2.copyFrom(particle.color);
        }
      }
      if (this._isAnimationSheetEnabled) {
        particle._initialStartSpriteCellID = this.startSpriteCellID;
        particle._initialEndSpriteCellID = this.endSpriteCellID;
        particle._initialSpriteCellLoop = this.spriteCellLoop;
      }
      particle.direction.addInPlace(this._inheritedVelocityOffset);
      if (this._useRampGradients) {
        particle.remapData = new Vector4(0, 1, 0, 1);
      }
      if (this.noiseTexture) {
        if (particle._randomNoiseCoordinates1) {
          particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
          particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
        } else {
          particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random());
          particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random());
        }
      }
      particle._inheritParticleInfoToSubEmitters();
    }
  }
  static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) {
    const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"];
    if (isAnimationSheetEnabled) {
      attributeNamesOrOptions.push("cellIndex");
    }
    if (!isBillboardBased) {
      attributeNamesOrOptions.push("direction");
    }
    if (useRampGradients) {
      attributeNamesOrOptions.push("remapData");
    }
    return attributeNamesOrOptions;
  }
  static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) {
    const effectCreationOption = ["invView", "view", "projection", "textureMask", "translationPivot", "eyePosition"];
    addClipPlaneUniforms(effectCreationOption);
    if (isAnimationSheetEnabled) {
      effectCreationOption.push("particlesInfos");
    }
    if (useLogarithmicDepth) {
      effectCreationOption.push("logarithmicDepthConstant");
    }
    if (applyFog) {
      effectCreationOption.push("vFogInfos");
      effectCreationOption.push("vFogColor");
    }
    return effectCreationOption;
  }
  fillDefines(defines, blendMode, fillImageProcessing = true) {
    if (this._scene) {
      prepareStringDefinesForClipPlanes(this, this._scene, defines);
      if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== 0) {
        defines.push("#define FOG");
      }
    }
    if (this._isAnimationSheetEnabled) {
      defines.push("#define ANIMATESHEET");
    }
    if (this.useLogarithmicDepth) {
      defines.push("#define LOGARITHMICDEPTH");
    }
    if (blendMode === BaseParticleSystem.BLENDMODE_MULTIPLY) {
      defines.push("#define BLENDMULTIPLYMODE");
    }
    if (this._useRampGradients) {
      defines.push("#define RAMPGRADIENT");
    }
    if (this._isBillboardBased) {
      defines.push("#define BILLBOARD");
      switch (this.billboardMode) {
        case 2:
          defines.push("#define BILLBOARDY");
          break;
        case 8:
        case 9:
          defines.push("#define BILLBOARDSTRETCHED");
          if (this.billboardMode === 9) {
            defines.push("#define BILLBOARDSTRETCHED_LOCAL");
          }
          break;
        case 7:
          defines.push("#define BILLBOARDMODE_ALL");
          break;
        default:
          break;
      }
    }
    if (fillImageProcessing && this._imageProcessingConfiguration) {
      this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
      defines.push(this._imageProcessingConfigurationDefines.toString());
    }
  }
  fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {
    attributes.push(...ThinParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== 8 && this.billboardMode !== 9, this._useRampGradients));
    uniforms.push(...ThinParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog));
    samplers.push("diffuseSampler", "rampSampler");
    if (this._imageProcessingConfiguration) {
      PrepareUniformsForImageProcessing(uniforms, this._imageProcessingConfigurationDefines);
      PrepareSamplersForImageProcessing(samplers, this._imageProcessingConfigurationDefines);
    }
  }
  _getWrapper(blendMode) {
    const customWrapper = this._getCustomDrawWrapper(blendMode);
    if (customWrapper?.effect) {
      return customWrapper;
    }
    const defines = [];
    this.fillDefines(defines, blendMode);
    const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0;
    let drawWrappers = this._drawWrappers[currentRenderPassId];
    if (!drawWrappers) {
      drawWrappers = this._drawWrappers[currentRenderPassId] = [];
    }
    let drawWrapper2 = drawWrappers[blendMode];
    if (!drawWrapper2) {
      drawWrapper2 = new DrawWrapper(this._engine);
      if (drawWrapper2.drawContext) {
        drawWrapper2.drawContext.useInstancing = this._useInstancing;
      }
      drawWrappers[blendMode] = drawWrapper2;
    }
    const join6 = defines.join(`
`);
    if (drawWrapper2.defines !== join6) {
      const attributesNamesOrOptions = [];
      const effectCreationOption = [];
      const samplers = [];
      this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers);
      drawWrapper2.setEffect(this._engine.createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join6, undefined, undefined, undefined, undefined, this._shaderLanguage), join6);
    }
    return drawWrapper2;
  }
  animate(preWarmOnly = false) {
    if (!this._started) {
      return;
    }
    if (!preWarmOnly && this._scene) {
      if (!this.isReady()) {
        return;
      }
      if (this._currentRenderId === this._scene.getFrameId()) {
        return;
      }
      this._currentRenderId = this._scene.getFrameId();
    }
    this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1);
    let newParticles;
    if (this.manualEmitCount > -1) {
      newParticles = this.manualEmitCount;
      this._newPartsExcess = 0;
      this.manualEmitCount = 0;
    } else {
      let rate = this.emitRate;
      if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
        const ratio = this._actualFrame / this.targetStopDuration;
        GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {
          if (currentGradient !== this._currentEmitRateGradient) {
            this._currentEmitRate1 = this._currentEmitRate2;
            this._currentEmitRate2 = nextGradient.getFactor();
            this._currentEmitRateGradient = currentGradient;
          }
          rate = Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);
        });
      }
      newParticles = rate * this._scaledUpdateSpeed >> 0;
      this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;
    }
    if (this._newPartsExcess > 1) {
      newParticles += this._newPartsExcess >> 0;
      this._newPartsExcess -= this._newPartsExcess >> 0;
    }
    this._alive = false;
    if (!this._stopped) {
      this._actualFrame += this._scaledUpdateSpeed;
      if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
        this.stop();
      }
    } else {
      newParticles = 0;
    }
    this._update(newParticles);
    if (this._stopped) {
      if (!this._alive) {
        this._started = false;
        if (this.onAnimationEnd) {
          this.onAnimationEnd();
        }
        if (this.disposeOnStop && this._scene) {
          this._scene._toBeDisposed.push(this);
        }
      }
    }
    if (!preWarmOnly) {
      let offset = 0;
      for (let index = 0;index < this._particles.length; index++) {
        const particle = this._particles[index];
        this._appendParticleVertices(offset, particle);
        offset += this._useInstancing ? 1 : 4;
      }
      if (this._vertexBuffer) {
        this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length);
      }
    }
    if (this.manualEmitCount === 0 && this.disposeOnStop) {
      this.stop();
    }
  }
  _appendParticleVertices(offset, particle) {
    this._appendParticleVertex(offset++, particle, 0, 0);
    if (!this._useInstancing) {
      this._appendParticleVertex(offset++, particle, 1, 0);
      this._appendParticleVertex(offset++, particle, 1, 1);
      this._appendParticleVertex(offset++, particle, 0, 1);
    }
  }
  rebuild() {
    if (this._engine.getCaps().vertexArrayObject) {
      this._vertexArrayObject = null;
    }
    this._createIndexBuffer();
    this._spriteBuffer?._rebuild();
    this._createVertexBuffers();
    this.resetDrawCache();
  }
  async _initShaderSourceAsync() {
    const engine2 = this._engine;
    if (engine2.isWebGPU && !ThinParticleSystem.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([Promise.resolve().then(() => (init_particles_vertex(), exports_particles_vertex)), Promise.resolve().then(() => (init_particles_fragment(), exports_particles_fragment))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_particles_vertex2(), exports_particles_vertex2)), Promise.resolve().then(() => (init_particles_fragment2(), exports_particles_fragment2))]);
    }
    this._shadersLoaded = true;
  }
  isReady() {
    if (!this._shadersLoaded) {
      return false;
    }
    if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
      return false;
    }
    if (this.blendMode !== BaseParticleSystem.BLENDMODE_MULTIPLYADD) {
      if (!this._getWrapper(this.blendMode).effect.isReady()) {
        return false;
      }
    } else {
      if (!this._getWrapper(BaseParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {
        return false;
      }
      if (!this._getWrapper(BaseParticleSystem.BLENDMODE_ADD).effect.isReady()) {
        return false;
      }
    }
    return true;
  }
  _render(blendMode) {
    const drawWrapper2 = this._getWrapper(blendMode);
    const effect2 = drawWrapper2.effect;
    const engine2 = this._engine;
    engine2.enableEffect(drawWrapper2);
    const viewMatrix = this.defaultViewMatrix ?? this._scene.getViewMatrix();
    effect2.setTexture("diffuseSampler", this.particleTexture);
    effect2.setMatrix("view", viewMatrix);
    effect2.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix());
    if (this._isAnimationSheetEnabled && this.particleTexture) {
      const baseSize = this.particleTexture.getBaseSize();
      effect2.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width);
    }
    effect2.setVector2("translationPivot", this.translationPivot);
    effect2.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
    if (this._isBillboardBased && this._scene) {
      const camera2 = this._scene.activeCamera;
      effect2.setVector3("eyePosition", camera2.globalPosition);
    }
    if (this._rampGradientsTexture) {
      if (!this._rampGradients || !this._rampGradients.length) {
        this._rampGradientsTexture.dispose();
        this._rampGradientsTexture = null;
      }
      effect2.setTexture("rampSampler", this._rampGradientsTexture);
    }
    const defines = effect2.defines;
    if (this._scene) {
      bindClipPlane(effect2, this, this._scene);
      if (this.applyFog) {
        BindFogParameters(this._scene, undefined, effect2);
      }
    }
    if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
      viewMatrix.invertToRef(TmpVectors.Matrix[0]);
      effect2.setMatrix("invView", TmpVectors.Matrix[0]);
    }
    if (this._vertexArrayObject !== undefined) {
      if (this._scene?.forceWireframe) {
        engine2.bindBuffers(this._vertexBuffers, this._linesIndexBufferUseInstancing, effect2);
      } else {
        if (!this._vertexArrayObject) {
          this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, null, effect2);
        }
        this._engine.bindVertexArrayObject(this._vertexArrayObject, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : this._indexBuffer);
      }
    } else {
      if (!this._indexBuffer) {
        engine2.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null, effect2);
      } else {
        engine2.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBuffer : this._indexBuffer, effect2);
      }
    }
    if (this.useLogarithmicDepth && this._scene) {
      BindLogDepth(defines, effect2, this._scene);
    }
    if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
      this._imageProcessingConfiguration.bind(effect2);
    }
    switch (blendMode) {
      case BaseParticleSystem.BLENDMODE_ADD:
        engine2.setAlphaMode(1);
        break;
      case BaseParticleSystem.BLENDMODE_ONEONE:
        engine2.setAlphaMode(6);
        break;
      case BaseParticleSystem.BLENDMODE_STANDARD:
        engine2.setAlphaMode(2);
        break;
      case BaseParticleSystem.BLENDMODE_MULTIPLY:
        engine2.setAlphaMode(4);
        break;
    }
    if (this._onBeforeDrawParticlesObservable) {
      this._onBeforeDrawParticlesObservable.notifyObservers(effect2);
    }
    if (this._useInstancing) {
      if (this._scene?.forceWireframe) {
        engine2.drawElementsType(6, 0, 10, this._particles.length);
      } else {
        engine2.drawArraysType(7, 0, 4, this._particles.length);
      }
    } else {
      if (this._scene?.forceWireframe) {
        engine2.drawElementsType(1, 0, this._particles.length * 10);
      } else {
        engine2.drawElementsType(0, 0, this._particles.length * 6);
      }
    }
    return this._particles.length;
  }
  render() {
    if (!this.isReady() || !this._particles.length) {
      return 0;
    }
    const engine2 = this._engine;
    if (engine2.setState) {
      engine2.setState(false);
      if (this.forceDepthWrite) {
        engine2.setDepthWrite(true);
      }
    }
    let outparticles = 0;
    if (this.blendMode === BaseParticleSystem.BLENDMODE_MULTIPLYADD) {
      outparticles = this._render(BaseParticleSystem.BLENDMODE_MULTIPLY) + this._render(BaseParticleSystem.BLENDMODE_ADD);
    } else {
      outparticles = this._render(this.blendMode);
    }
    this._engine.unbindInstanceAttributes();
    this._engine.setAlphaMode(0);
    return outparticles;
  }
  _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) {}
  dispose(disposeTexture = true, disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) {
    this.resetDrawCache();
    if (this._vertexBuffer) {
      this._vertexBuffer.dispose();
      this._vertexBuffer = null;
    }
    if (this._spriteBuffer) {
      this._spriteBuffer.dispose();
      this._spriteBuffer = null;
    }
    if (this._indexBuffer) {
      this._engine._releaseBuffer(this._indexBuffer);
      this._indexBuffer = null;
    }
    if (this._linesIndexBuffer) {
      this._engine._releaseBuffer(this._linesIndexBuffer);
      this._linesIndexBuffer = null;
    }
    if (this._linesIndexBufferUseInstancing) {
      this._engine._releaseBuffer(this._linesIndexBufferUseInstancing);
      this._linesIndexBufferUseInstancing = null;
    }
    if (this._vertexArrayObject) {
      this._engine.releaseVertexArrayObject(this._vertexArrayObject);
      this._vertexArrayObject = null;
    }
    if (disposeTexture && this.particleTexture) {
      this.particleTexture.dispose();
      this.particleTexture = null;
    }
    if (disposeTexture && this.noiseTexture) {
      this.noiseTexture.dispose();
      this.noiseTexture = null;
    }
    if (this._rampGradientsTexture) {
      this._rampGradientsTexture.dispose();
      this._rampGradientsTexture = null;
    }
    this._onDispose(disposeAttachedSubEmitters, disposeEndSubEmitters);
    if (this._onBeforeDrawParticlesObservable) {
      this._onBeforeDrawParticlesObservable.clear();
    }
    if (this._scene) {
      const index = this._scene.particleSystems.indexOf(this);
      if (index > -1) {
        this._scene.particleSystems.splice(index, 1);
      }
      this._scene._activeParticleSystems.dispose();
    }
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
    this.onStoppedObservable.clear();
    this.reset();
  }
}
ThinParticleSystem.ForceGLSL = false;

// node_modules/@babylonjs/core/Particles/subEmitter.js
init_math_vector();
init_devTools();
init_typeStore();
var SubEmitterType;
(function(SubEmitterType2) {
  SubEmitterType2[SubEmitterType2["ATTACHED"] = 0] = "ATTACHED";
  SubEmitterType2[SubEmitterType2["END"] = 1] = "END";
})(SubEmitterType || (SubEmitterType = {}));

class SubEmitter {
  constructor(particleSystem) {
    this.particleSystem = particleSystem;
    this.type = 1;
    this.inheritDirection = false;
    this.inheritedVelocityAmount = 0;
    if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
      const internalClass = GetClass("BABYLON.AbstractMesh");
      particleSystem.emitter = new internalClass("SubemitterSystemEmitter", particleSystem.getScene());
      particleSystem._disposeEmitterOnDispose = true;
    }
  }
  clone() {
    let emitter = this.particleSystem.emitter;
    if (!emitter) {
      emitter = new Vector3;
    } else if (emitter instanceof Vector3) {
      emitter = emitter.clone();
    } else if (emitter.getClassName().indexOf("Mesh") !== -1) {
      const internalClass = GetClass("BABYLON.Mesh");
      emitter = new internalClass("", emitter.getScene());
      emitter.isVisible = false;
    }
    const clone = new SubEmitter(this.particleSystem.clone(this.particleSystem.name, emitter));
    clone.particleSystem.name += "Clone";
    clone.type = this.type;
    clone.inheritDirection = this.inheritDirection;
    clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
    clone.particleSystem._disposeEmitterOnDispose = true;
    clone.particleSystem.disposeOnStop = true;
    return clone;
  }
  serialize(serializeTexture = false) {
    const serializationObject = {};
    serializationObject.type = this.type;
    serializationObject.inheritDirection = this.inheritDirection;
    serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
    serializationObject.particleSystem = this.particleSystem.serialize(serializeTexture);
    return serializationObject;
  }
  static _ParseParticleSystem(system, sceneOrEngine, rootUrl, doNotStart = false) {
    throw _WarnImport("ParseParticle");
  }
  static Parse(serializationObject, sceneOrEngine, rootUrl) {
    const system = serializationObject.particleSystem;
    const subEmitter = new SubEmitter(SubEmitter._ParseParticleSystem(system, sceneOrEngine, rootUrl, true));
    subEmitter.type = serializationObject.type;
    subEmitter.inheritDirection = serializationObject.inheritDirection;
    subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
    subEmitter.particleSystem._isSubEmitter = true;
    return subEmitter;
  }
  dispose() {
    this.particleSystem.dispose();
  }
}

// node_modules/@babylonjs/core/Particles/particleSystem.js
init_math_color();
init_math_vector();
init_abstractEngine();
init_typeStore();
init_decorators_serialization();

// node_modules/@babylonjs/core/Particles/EmitterTypes/meshParticleEmitter.js
init_deepCopier();
init_math_vector();
init_buffer();

class MeshParticleEmitter {
  get mesh() {
    return this._mesh;
  }
  set mesh(value) {
    if (this._mesh === value) {
      return;
    }
    this._mesh = value;
    if (value) {
      this._indices = value.getIndices();
      this._positions = value.getVerticesData(VertexBuffer.PositionKind);
      this._normals = value.getVerticesData(VertexBuffer.NormalKind);
    } else {
      this._indices = null;
      this._positions = null;
      this._normals = null;
    }
  }
  constructor(mesh2 = null) {
    this._indices = null;
    this._positions = null;
    this._normals = null;
    this._storedNormal = Vector3.Zero();
    this._mesh = null;
    this.direction1 = new Vector3(0, 1, 0);
    this.direction2 = new Vector3(0, 1, 0);
    this.useMeshNormalsForDirection = true;
    this.mesh = mesh2;
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    if (this.useMeshNormalsForDirection && this._normals) {
      Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate);
      return;
    }
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    if (isLocal) {
      directionToUpdate.copyFromFloats(randX, randY, randZ);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    if (!this._indices || !this._positions) {
      return;
    }
    const randomFaceIndex = 3 * Math.random() * (this._indices.length / 3) | 0;
    const bu = Math.random();
    const bv = Math.random() * (1 - bu);
    const bw = 1 - bu - bv;
    const faceIndexA = this._indices[randomFaceIndex];
    const faceIndexB = this._indices[randomFaceIndex + 1];
    const faceIndexC = this._indices[randomFaceIndex + 2];
    const vertexA = TmpVectors.Vector3[0];
    const vertexB = TmpVectors.Vector3[1];
    const vertexC = TmpVectors.Vector3[2];
    const randomVertex = TmpVectors.Vector3[3];
    Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA);
    Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB);
    Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC);
    randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;
    randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;
    randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;
    if (isLocal) {
      positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z);
    } else {
      Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate);
    }
    if (this.useMeshNormalsForDirection && this._normals) {
      Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA);
      Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB);
      Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC);
      this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;
      this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;
      this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;
    }
  }
  clone() {
    const newOne = new MeshParticleEmitter(this.mesh);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
  }
  getEffectDefines() {
    return "";
  }
  getClassName() {
    return "MeshParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    serializationObject.meshId = this.mesh?.id;
    serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection;
    return serializationObject;
  }
  parse(serializationObject, scene) {
    Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
    Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
    if (serializationObject.meshId && scene) {
      this.mesh = scene.getLastMeshById(serializationObject.meshId);
    }
    this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection;
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/customParticleEmitter.js
init_deepCopier();
init_math_vector();

class CustomParticleEmitter {
  constructor() {
    this.particlePositionGenerator = () => {};
    this.particleDestinationGenerator = () => {};
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    const tmpVector = TmpVectors.Vector3[0];
    if (this.particleDestinationGenerator) {
      this.particleDestinationGenerator(-1, particle, tmpVector);
      const diffVector = TmpVectors.Vector3[1];
      tmpVector.subtractToRef(particle.position, diffVector);
      diffVector.scaleToRef(1 / particle.lifeTime, tmpVector);
    } else {
      tmpVector.set(0, 0, 0);
    }
    if (isLocal) {
      directionToUpdate.copyFrom(tmpVector);
      return;
    }
    Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const tmpVector = TmpVectors.Vector3[0];
    if (this.particlePositionGenerator) {
      this.particlePositionGenerator(-1, particle, tmpVector);
    } else {
      tmpVector.set(0, 0, 0);
    }
    if (isLocal) {
      positionToUpdate.copyFrom(tmpVector);
      return;
    }
    Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new CustomParticleEmitter;
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {}
  buildUniformLayout(ubo) {}
  getEffectDefines() {
    return "#define CUSTOMEMITTER";
  }
  getClassName() {
    return "CustomParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.particlePositionGenerator = this.particlePositionGenerator;
    serializationObject.particleDestinationGenerator = this.particleDestinationGenerator;
    return serializationObject;
  }
  parse(serializationObject) {
    if (serializationObject.particlePositionGenerator) {
      this.particlePositionGenerator = serializationObject.particlePositionGenerator;
    }
    if (serializationObject.particleDestinationGenerator) {
      this.particleDestinationGenerator = serializationObject.particleDestinationGenerator;
    }
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/pointParticleEmitter.js
init_deepCopier();
init_math_vector();

class PointParticleEmitter {
  constructor() {
    this.direction1 = new Vector3(0, 1, 0);
    this.direction2 = new Vector3(0, 1, 0);
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    if (isLocal) {
      directionToUpdate.copyFromFloats(randX, randY, randZ);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    if (isLocal) {
      positionToUpdate.copyFromFloats(0, 0, 0);
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new PointParticleEmitter;
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
  }
  getEffectDefines() {
    return "#define POINTEMITTER";
  }
  getClassName() {
    return "PointParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    return serializationObject;
  }
  parse(serializationObject) {
    Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
    Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/hemisphericParticleEmitter.js
init_deepCopier();
init_math_vector();

class HemisphericParticleEmitter {
  constructor(radius = 1, radiusRange = 1, directionRandomizer = 0) {
    this.radius = radius;
    this.radiusRange = radiusRange;
    this.directionRandomizer = directionRandomizer;
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
    const randX = RandomRange(0, this.directionRandomizer);
    const randY = RandomRange(0, this.directionRandomizer);
    const randZ = RandomRange(0, this.directionRandomizer);
    direction.x += randX;
    direction.y += randY;
    direction.z += randZ;
    direction.normalize();
    if (isLocal) {
      directionToUpdate.copyFrom(direction);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange);
    const v = RandomRange(0, 1);
    const phi = RandomRange(0, 2 * Math.PI);
    const theta = Math.acos(2 * v - 1);
    const randX = randRadius * Math.cos(phi) * Math.sin(theta);
    const randY = randRadius * Math.cos(theta);
    const randZ = randRadius * Math.sin(phi) * Math.sin(theta);
    if (isLocal) {
      positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ);
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("directionRandomizer", 1);
  }
  getEffectDefines() {
    return "#define HEMISPHERICEMITTER";
  }
  getClassName() {
    return "HemisphericParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.radius = this.radius;
    serializationObject.radiusRange = this.radiusRange;
    serializationObject.directionRandomizer = this.directionRandomizer;
    return serializationObject;
  }
  parse(serializationObject) {
    this.radius = serializationObject.radius;
    this.radiusRange = serializationObject.radiusRange;
    this.directionRandomizer = serializationObject.directionRandomizer;
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/sphereParticleEmitter.js
init_math_vector();
init_deepCopier();

class SphereParticleEmitter {
  constructor(radius = 1, radiusRange = 1, directionRandomizer = 0) {
    this.radius = radius;
    this.radiusRange = radiusRange;
    this.directionRandomizer = directionRandomizer;
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
    const randX = RandomRange(0, this.directionRandomizer);
    const randY = RandomRange(0, this.directionRandomizer);
    const randZ = RandomRange(0, this.directionRandomizer);
    direction.x += randX;
    direction.y += randY;
    direction.z += randZ;
    direction.normalize();
    if (isLocal) {
      directionToUpdate.copyFrom(direction);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange);
    const v = RandomRange(0, 1);
    const phi = RandomRange(0, 2 * Math.PI);
    const theta = Math.acos(2 * v - 1);
    const randX = randRadius * Math.cos(phi) * Math.sin(theta);
    const randY = randRadius * Math.cos(theta);
    const randZ = randRadius * Math.sin(phi) * Math.sin(theta);
    if (isLocal) {
      positionToUpdate.copyFromFloats(randX, randY, randZ);
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("directionRandomizer", 1);
  }
  getEffectDefines() {
    return "#define SPHEREEMITTER";
  }
  getClassName() {
    return "SphereParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.radius = this.radius;
    serializationObject.radiusRange = this.radiusRange;
    serializationObject.directionRandomizer = this.directionRandomizer;
    return serializationObject;
  }
  parse(serializationObject) {
    this.radius = serializationObject.radius;
    this.radiusRange = serializationObject.radiusRange;
    this.directionRandomizer = serializationObject.directionRandomizer;
  }
}

class SphereDirectedParticleEmitter extends SphereParticleEmitter {
  constructor(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    super(radius);
    this.direction1 = direction1;
    this.direction2 = direction2;
  }
  startDirectionFunction(worldMatrix, directionToUpdate) {
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  clone() {
    const newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
  }
  getEffectDefines() {
    return `#define SPHEREEMITTER
#define DIRECTEDSPHEREEMITTER`;
  }
  getClassName() {
    return "SphereDirectedParticleEmitter";
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    return serializationObject;
  }
  parse(serializationObject) {
    super.parse(serializationObject);
    this.direction1.copyFrom(serializationObject.direction1);
    this.direction2.copyFrom(serializationObject.direction2);
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/cylinderParticleEmitter.js
init_math_vector();
init_deepCopier();

class CylinderParticleEmitter {
  constructor(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
    this.radius = radius;
    this.height = height;
    this.radiusRange = radiusRange;
    this.directionRandomizer = directionRandomizer;
    this._tempVector = Vector3.Zero();
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) {
    particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector);
    this._tempVector.normalize();
    Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector);
    const randY = RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
    let angle = Math.atan2(this._tempVector.x, this._tempVector.z);
    angle += RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
    this._tempVector.y = randY;
    this._tempVector.x = Math.sin(angle);
    this._tempVector.z = Math.cos(angle);
    this._tempVector.normalize();
    if (isLocal) {
      directionToUpdate.copyFrom(this._tempVector);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate);
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const yPos = RandomRange(-this.height / 2, this.height / 2);
    const angle = RandomRange(0, 2 * Math.PI);
    const radiusDistribution = RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
    const positionRadius = Math.sqrt(radiusDistribution) * this.radius;
    const xPos = positionRadius * Math.cos(angle);
    const zPos = positionRadius * Math.sin(angle);
    if (isLocal) {
      positionToUpdate.copyFromFloats(xPos, yPos, zPos);
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("height", this.height);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("height", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("directionRandomizer", 1);
  }
  getEffectDefines() {
    return "#define CYLINDEREMITTER";
  }
  getClassName() {
    return "CylinderParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.radius = this.radius;
    serializationObject.height = this.height;
    serializationObject.radiusRange = this.radiusRange;
    serializationObject.directionRandomizer = this.directionRandomizer;
    return serializationObject;
  }
  parse(serializationObject) {
    this.radius = serializationObject.radius;
    this.height = serializationObject.height;
    this.radiusRange = serializationObject.radiusRange;
    this.directionRandomizer = serializationObject.directionRandomizer;
  }
}

class CylinderDirectedParticleEmitter extends CylinderParticleEmitter {
  constructor(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    super(radius, height, radiusRange);
    this.direction1 = direction1;
    this.direction2 = direction2;
  }
  startDirectionFunction(worldMatrix, directionToUpdate, _particle, isLocal) {
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    if (isLocal) {
      directionToUpdate.copyFromFloats(randX, randY, randZ);
      return;
    }
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  clone() {
    const newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("height", this.height);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("height", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
  }
  getEffectDefines() {
    return `#define CYLINDEREMITTER
#define DIRECTEDCYLINDEREMITTER`;
  }
  getClassName() {
    return "CylinderDirectedParticleEmitter";
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    return serializationObject;
  }
  parse(serializationObject) {
    super.parse(serializationObject);
    Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
    Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  }
}

// node_modules/@babylonjs/core/Particles/EmitterTypes/coneParticleEmitter.js
init_deepCopier();
init_math_vector();

class ConeParticleEmitter {
  get radius() {
    return this._radius;
  }
  set radius(value) {
    this._radius = value;
    this._buildHeight();
  }
  get angle() {
    return this._angle;
  }
  set angle(value) {
    this._angle = value;
    this._buildHeight();
  }
  _buildHeight() {
    if (this._angle !== 0) {
      this._height = this._radius / Math.tan(this._angle / 2);
    } else {
      this._height = 1;
    }
  }
  constructor(radius = 1, angle = Math.PI, directionRandomizer = 0) {
    this.directionRandomizer = directionRandomizer;
    this.radiusRange = 1;
    this.heightRange = 1;
    this.emitFromSpawnPointOnly = false;
    this.angle = angle;
    this.radius = radius;
  }
  startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {
    if (isLocal) {
      TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize();
    } else {
      particle.position.subtractToRef(worldMatrix.getTranslation(), TmpVectors.Vector3[0]).normalize();
    }
    const randX = RandomRange(0, this.directionRandomizer);
    const randY = RandomRange(0, this.directionRandomizer);
    const randZ = RandomRange(0, this.directionRandomizer);
    directionToUpdate.x = TmpVectors.Vector3[0].x + randX;
    directionToUpdate.y = TmpVectors.Vector3[0].y + randY;
    directionToUpdate.z = TmpVectors.Vector3[0].z + randZ;
    directionToUpdate.normalize();
  }
  startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {
    const s = RandomRange(0, Math.PI * 2);
    let h;
    if (!this.emitFromSpawnPointOnly) {
      h = RandomRange(0, this.heightRange);
      h = 1 - h * h;
    } else {
      h = 0.0001;
    }
    let radius = this._radius - RandomRange(0, this._radius * this.radiusRange);
    radius = radius * h;
    const randX = radius * Math.sin(s);
    const randZ = radius * Math.cos(s);
    const randY = h * this._height;
    if (isLocal) {
      positionToUpdate.x = randX;
      positionToUpdate.y = randY;
      positionToUpdate.z = randZ;
      return;
    }
    Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  }
  clone() {
    const newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat2("radius", this._radius, this.radiusRange);
    uboOrEffect.setFloat("coneAngle", this._angle);
    uboOrEffect.setFloat2("height", this._height, this.heightRange);
    uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 2);
    ubo.addUniform("coneAngle", 1);
    ubo.addUniform("height", 2);
    ubo.addUniform("directionRandomizer", 1);
  }
  getEffectDefines() {
    let defines = "#define CONEEMITTER";
    if (this.emitFromSpawnPointOnly) {
      defines += `
#define CONEEMITTERSPAWNPOINT`;
    }
    return defines;
  }
  getClassName() {
    return "ConeParticleEmitter";
  }
  serialize() {
    const serializationObject = {};
    serializationObject.type = this.getClassName();
    serializationObject.radius = this._radius;
    serializationObject.angle = this._angle;
    serializationObject.directionRandomizer = this.directionRandomizer;
    serializationObject.radiusRange = this.radiusRange;
    serializationObject.heightRange = this.heightRange;
    serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly;
    return serializationObject;
  }
  parse(serializationObject) {
    this.radius = serializationObject.radius;
    this.angle = serializationObject.angle;
    this.directionRandomizer = serializationObject.directionRandomizer;
    this.radiusRange = serializationObject.radiusRange !== undefined ? serializationObject.radiusRange : 1;
    this.heightRange = serializationObject.radiusRange !== undefined ? serializationObject.heightRange : 1;
    this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== undefined ? serializationObject.emitFromSpawnPointOnly : false;
  }
}

class ConeDirectedParticleEmitter extends ConeParticleEmitter {
  constructor(radius = 1, angle = Math.PI, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    super(radius, angle);
    this.direction1 = direction1;
    this.direction2 = direction2;
  }
  startDirectionFunction(worldMatrix, directionToUpdate) {
    const randX = RandomRange(this.direction1.x, this.direction2.x);
    const randY = RandomRange(this.direction1.y, this.direction2.y);
    const randZ = RandomRange(this.direction1.z, this.direction2.z);
    Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  }
  clone() {
    const newOne = new ConeDirectedParticleEmitter(this.radius, this.angle, this.direction1, this.direction2);
    DeepCopier.DeepCopy(this, newOne);
    return newOne;
  }
  applyToShader(uboOrEffect) {
    uboOrEffect.setFloat("radius", this.radius);
    uboOrEffect.setFloat("radiusRange", this.radiusRange);
    uboOrEffect.setVector3("direction1", this.direction1);
    uboOrEffect.setVector3("direction2", this.direction2);
  }
  buildUniformLayout(ubo) {
    ubo.addUniform("radius", 1);
    ubo.addUniform("radiusRange", 1);
    ubo.addUniform("direction1", 3);
    ubo.addUniform("direction2", 3);
  }
  getEffectDefines() {
    return `#define CONEEMITTER
#define DIRECTEDCONEEMITTER`;
  }
  getClassName() {
    return "ConeDirectedParticleEmitter";
  }
  serialize() {
    const serializationObject = super.serialize();
    serializationObject.direction1 = this.direction1.asArray();
    serializationObject.direction2 = this.direction2.asArray();
    return serializationObject;
  }
  parse(serializationObject) {
    super.parse(serializationObject);
    this.direction1.copyFrom(serializationObject.direction1);
    this.direction2.copyFrom(serializationObject.direction2);
  }
}

// node_modules/@babylonjs/core/Particles/particleSystem.functions.js
init_math_vector();
function CreatePointEmitter(direction1, direction2) {
  const particleEmitter = new PointParticleEmitter;
  particleEmitter.direction1 = direction1;
  particleEmitter.direction2 = direction2;
  return particleEmitter;
}
function CreateHemisphericEmitter(radius = 1, radiusRange = 1) {
  return new HemisphericParticleEmitter(radius, radiusRange);
}
function CreateSphereEmitter(radius = 1, radiusRange = 1) {
  return new SphereParticleEmitter(radius, radiusRange);
}
function CreateDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
  return new SphereDirectedParticleEmitter(radius, direction1, direction2);
}
function CreateCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
  return new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
}
function CreateDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
  return new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
}
function CreateConeEmitter(radius = 1, angle = Math.PI / 4) {
  return new ConeParticleEmitter(radius, angle);
}
function CreateDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
  return new ConeDirectedParticleEmitter(radius, angle, direction1, direction2);
}

// node_modules/@babylonjs/core/Particles/particleSystem.js
class ParticleSystem extends ThinParticleSystem {
  constructor() {
    super(...arguments);
    this._disposeEmitterOnDispose = false;
    this._emitFromParticle = (particle) => {
      if (!this._subEmitters || this._subEmitters.length === 0) {
        return;
      }
      const templateIndex = Math.floor(Math.random() * this._subEmitters.length);
      this._subEmitters[templateIndex].forEach((subEmitter) => {
        if (subEmitter.type === 1) {
          const subSystem = subEmitter.clone();
          particle._inheritParticleInfoToSubEmitter(subSystem);
          subSystem.particleSystem._rootParticleSystem = this;
          this.activeSubSystems.push(subSystem.particleSystem);
          subSystem.particleSystem.start();
        }
      });
    };
  }
  createPointEmitter(direction1, direction2) {
    const particleEmitter = CreatePointEmitter(direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createHemisphericEmitter(radius = 1, radiusRange = 1) {
    const particleEmitter = CreateHemisphericEmitter(radius, radiusRange);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createSphereEmitter(radius = 1, radiusRange = 1) {
    const particleEmitter = CreateSphereEmitter(radius, radiusRange);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
    const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createConeEmitter(radius = 1, angle = Math.PI / 4) {
    const particleEmitter = CreateConeEmitter(radius, angle);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {
    const particleEmitter = new BoxParticleEmitter;
    this.particleEmitterType = particleEmitter;
    this.direction1 = direction1;
    this.direction2 = direction2;
    this.minEmitBox = minEmitBox;
    this.maxEmitBox = maxEmitBox;
    return particleEmitter;
  }
  _prepareSubEmitterInternalArray() {
    this._subEmitters = new Array;
    if (this.subEmitters) {
      this.subEmitters.forEach((subEmitter) => {
        if (subEmitter instanceof ParticleSystem) {
          this._subEmitters.push([new SubEmitter(subEmitter)]);
        } else if (subEmitter instanceof SubEmitter) {
          this._subEmitters.push([subEmitter]);
        } else if (subEmitter instanceof Array) {
          this._subEmitters.push(subEmitter);
        }
      });
    }
  }
  _stopSubEmitters() {
    if (!this.activeSubSystems) {
      return;
    }
    this.activeSubSystems.forEach((subSystem) => {
      subSystem.stop(true);
    });
    this.activeSubSystems = [];
  }
  _removeFromRoot() {
    if (!this._rootParticleSystem) {
      return;
    }
    const index = this._rootParticleSystem.activeSubSystems.indexOf(this);
    if (index !== -1) {
      this._rootParticleSystem.activeSubSystems.splice(index, 1);
    }
    this._rootParticleSystem = null;
  }
  _preStart() {
    this._prepareSubEmitterInternalArray();
    if (this._subEmitters && this._subEmitters.length != 0) {
      this.activeSubSystems = [];
    }
  }
  _postStop(stopSubEmitters) {
    if (stopSubEmitters) {
      this._stopSubEmitters();
    }
  }
  _prepareParticle(particle) {
    if (this._subEmitters && this._subEmitters.length > 0) {
      const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)];
      particle._attachedSubEmitters = [];
      subEmitters.forEach((subEmitter) => {
        if (subEmitter.type === 0) {
          const newEmitter = subEmitter.clone();
          particle._attachedSubEmitters.push(newEmitter);
          newEmitter.particleSystem.start();
        }
      });
    }
  }
  _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) {
    this._removeFromRoot();
    if (this.subEmitters && !this._subEmitters) {
      this._prepareSubEmitterInternalArray();
    }
    if (disposeAttachedSubEmitters) {
      this.particles?.forEach((particle) => {
        if (particle._attachedSubEmitters) {
          for (let i = particle._attachedSubEmitters.length - 1;i >= 0; i -= 1) {
            particle._attachedSubEmitters[i].dispose();
          }
        }
      });
    }
    if (disposeEndSubEmitters) {
      if (this.activeSubSystems) {
        for (let i = this.activeSubSystems.length - 1;i >= 0; i -= 1) {
          this.activeSubSystems[i].dispose();
        }
      }
    }
    if (this._subEmitters && this._subEmitters.length) {
      for (let index = 0;index < this._subEmitters.length; index++) {
        for (const subEmitter of this._subEmitters[index]) {
          subEmitter.dispose();
        }
      }
      this._subEmitters = [];
      this.subEmitters = [];
    }
    if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
      this.emitter.dispose(true);
    }
  }
  static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) {
    let scene;
    if (sceneOrEngine instanceof AbstractEngine) {
      scene = null;
    } else {
      scene = sceneOrEngine;
    }
    const internalClass = GetClass("BABYLON.Texture");
    if (internalClass && scene) {
      if (parsedParticleSystem.texture) {
        particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl);
      } else if (parsedParticleSystem.textureName) {
        particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
        particleSystem.particleTexture.name = parsedParticleSystem.textureName;
      }
    }
    if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
      particleSystem.emitter = Vector3.Zero();
    } else if (parsedParticleSystem.emitterId && scene) {
      particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId);
    } else {
      particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);
    }
    particleSystem.isLocal = !!parsedParticleSystem.isLocal;
    if (parsedParticleSystem.renderingGroupId !== undefined) {
      particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
    }
    if (parsedParticleSystem.isBillboardBased !== undefined) {
      particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
    }
    if (parsedParticleSystem.billboardMode !== undefined) {
      particleSystem.billboardMode = parsedParticleSystem.billboardMode;
    }
    if (parsedParticleSystem.useLogarithmicDepth !== undefined) {
      particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth;
    }
    if (parsedParticleSystem.animations) {
      for (let animationIndex = 0;animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
        const parsedAnimation = parsedParticleSystem.animations[animationIndex];
        const internalClass2 = GetClass("BABYLON.Animation");
        if (internalClass2) {
          particleSystem.animations.push(internalClass2.Parse(parsedAnimation));
        }
      }
      particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
      particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
      particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
      particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
    }
    if (parsedParticleSystem.autoAnimate && scene) {
      scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1);
    }
    particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
    particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
    particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
    particleSystem.minSize = parsedParticleSystem.minSize;
    particleSystem.maxSize = parsedParticleSystem.maxSize;
    if (parsedParticleSystem.minScaleX) {
      particleSystem.minScaleX = parsedParticleSystem.minScaleX;
      particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
      particleSystem.minScaleY = parsedParticleSystem.minScaleY;
      particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
    }
    if (parsedParticleSystem.preWarmCycles !== undefined) {
      particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
      particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
    }
    if (parsedParticleSystem.minInitialRotation !== undefined) {
      particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
      particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
    }
    particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
    particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
    particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
    particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
    particleSystem.emitRate = parsedParticleSystem.emitRate;
    particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);
    if (parsedParticleSystem.noiseStrength) {
      particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength);
    }
    particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);
    particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);
    particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);
    particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
    particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
    particleSystem.blendMode = parsedParticleSystem.blendMode;
    if (parsedParticleSystem.colorGradients) {
      for (const colorGradient of parsedParticleSystem.colorGradients) {
        particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);
      }
    }
    if (parsedParticleSystem.rampGradients) {
      for (const rampGradient of parsedParticleSystem.rampGradients) {
        particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color));
      }
      particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
    }
    if (parsedParticleSystem.colorRemapGradients) {
      for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) {
        particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
      }
    }
    if (parsedParticleSystem.alphaRemapGradients) {
      for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) {
        particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
      }
    }
    if (parsedParticleSystem.sizeGradients) {
      for (const sizeGradient of parsedParticleSystem.sizeGradients) {
        particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
      }
    }
    if (parsedParticleSystem.angularSpeedGradients) {
      for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {
        particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
      }
    }
    if (parsedParticleSystem.velocityGradients) {
      for (const velocityGradient of parsedParticleSystem.velocityGradients) {
        particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
      }
    }
    if (parsedParticleSystem.dragGradients) {
      for (const dragGradient of parsedParticleSystem.dragGradients) {
        particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
      }
    }
    if (parsedParticleSystem.emitRateGradients) {
      for (const emitRateGradient of parsedParticleSystem.emitRateGradients) {
        particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
      }
    }
    if (parsedParticleSystem.startSizeGradients) {
      for (const startSizeGradient of parsedParticleSystem.startSizeGradients) {
        particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
      }
    }
    if (parsedParticleSystem.lifeTimeGradients) {
      for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) {
        particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
      }
    }
    if (parsedParticleSystem.limitVelocityGradients) {
      for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) {
        particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
      }
      particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
    }
    if (parsedParticleSystem.noiseTexture && scene) {
      const internalClass2 = GetClass("BABYLON.ProceduralTexture");
      particleSystem.noiseTexture = internalClass2.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
    }
    let emitterType;
    if (parsedParticleSystem.particleEmitterType) {
      switch (parsedParticleSystem.particleEmitterType.type) {
        case "SphereParticleEmitter":
          emitterType = new SphereParticleEmitter;
          break;
        case "SphereDirectedParticleEmitter":
          emitterType = new SphereDirectedParticleEmitter;
          break;
        case "ConeEmitter":
        case "ConeParticleEmitter":
          emitterType = new ConeParticleEmitter;
          break;
        case "ConeDirectedParticleEmitter":
          emitterType = new ConeDirectedParticleEmitter;
          break;
        case "CylinderParticleEmitter":
          emitterType = new CylinderParticleEmitter;
          break;
        case "CylinderDirectedParticleEmitter":
          emitterType = new CylinderDirectedParticleEmitter;
          break;
        case "HemisphericParticleEmitter":
          emitterType = new HemisphericParticleEmitter;
          break;
        case "PointParticleEmitter":
          emitterType = new PointParticleEmitter;
          break;
        case "MeshParticleEmitter":
          emitterType = new MeshParticleEmitter;
          break;
        case "CustomParticleEmitter":
          emitterType = new CustomParticleEmitter;
          break;
        case "BoxEmitter":
        case "BoxParticleEmitter":
        default:
          emitterType = new BoxParticleEmitter;
          break;
      }
      emitterType.parse(parsedParticleSystem.particleEmitterType, scene);
    } else {
      emitterType = new BoxParticleEmitter;
      emitterType.parse(parsedParticleSystem, scene);
    }
    particleSystem.particleEmitterType = emitterType;
    particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
    particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
    particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop ?? true;
    particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
    particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
    particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
    particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
    particleSystem.disposeOnStop = parsedParticleSystem.disposeOnStop ?? false;
    particleSystem.manualEmitCount = parsedParticleSystem.manualEmitCount ?? -1;
  }
  static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {
    const name395 = parsedParticleSystem.name;
    let custom = null;
    let program = null;
    let engine2;
    let scene;
    if (sceneOrEngine instanceof AbstractEngine) {
      engine2 = sceneOrEngine;
    } else {
      scene = sceneOrEngine;
      engine2 = scene.getEngine();
    }
    if (parsedParticleSystem.customShader && engine2.createEffectForParticles) {
      program = parsedParticleSystem.customShader;
      const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(`
`) : "";
      custom = engine2.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
    }
    const particleSystem = new ParticleSystem(name395, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled);
    particleSystem.customShader = program;
    particleSystem._rootUrl = rootUrl;
    if (parsedParticleSystem.id) {
      particleSystem.id = parsedParticleSystem.id;
    }
    if (parsedParticleSystem.subEmitters) {
      particleSystem.subEmitters = [];
      for (const cell of parsedParticleSystem.subEmitters) {
        const cellArray = [];
        for (const sub of cell) {
          cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl));
        }
        particleSystem.subEmitters.push(cellArray);
      }
    }
    ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);
    if (parsedParticleSystem.textureMask) {
      particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);
    }
    if (parsedParticleSystem.worldOffset) {
      particleSystem.worldOffset = Vector3.FromArray(parsedParticleSystem.worldOffset);
    }
    if (parsedParticleSystem.preventAutoStart) {
      particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
    }
    if (!doNotStart && !particleSystem.preventAutoStart) {
      particleSystem.start();
    }
    return particleSystem;
  }
  serialize(serializeTexture = false) {
    const serializationObject = {};
    ParticleSystem._Serialize(serializationObject, this, serializeTexture);
    serializationObject.textureMask = this.textureMask.asArray();
    serializationObject.customShader = this.customShader;
    serializationObject.preventAutoStart = this.preventAutoStart;
    serializationObject.worldOffset = this.worldOffset.asArray();
    if (this.subEmitters) {
      serializationObject.subEmitters = [];
      if (!this._subEmitters) {
        this._prepareSubEmitterInternalArray();
      }
      for (const subs of this._subEmitters) {
        const cell = [];
        for (const sub of subs) {
          cell.push(sub.serialize(serializeTexture));
        }
        serializationObject.subEmitters.push(cell);
      }
    }
    return serializationObject;
  }
  static _Serialize(serializationObject, particleSystem, serializeTexture) {
    serializationObject.name = particleSystem.name;
    serializationObject.id = particleSystem.id;
    serializationObject.capacity = particleSystem.getCapacity();
    serializationObject.disposeOnStop = particleSystem.disposeOnStop;
    serializationObject.manualEmitCount = particleSystem.manualEmitCount;
    if (particleSystem.emitter.position) {
      const emitterMesh = particleSystem.emitter;
      serializationObject.emitterId = emitterMesh.id;
    } else {
      const emitterPosition = particleSystem.emitter;
      serializationObject.emitter = emitterPosition.asArray();
    }
    if (particleSystem.particleEmitterType) {
      serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
    }
    if (particleSystem.particleTexture) {
      if (serializeTexture) {
        serializationObject.texture = particleSystem.particleTexture.serialize();
      } else {
        serializationObject.textureName = particleSystem.particleTexture.name;
        serializationObject.invertY = !!particleSystem.particleTexture._invertY;
      }
    }
    serializationObject.isLocal = particleSystem.isLocal;
    SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject);
    serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
    serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
    serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
    serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
    serializationObject.startDelay = particleSystem.startDelay;
    serializationObject.renderingGroupId = particleSystem.renderingGroupId;
    serializationObject.isBillboardBased = particleSystem.isBillboardBased;
    serializationObject.billboardMode = particleSystem.billboardMode;
    serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
    serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
    serializationObject.minSize = particleSystem.minSize;
    serializationObject.maxSize = particleSystem.maxSize;
    serializationObject.minScaleX = particleSystem.minScaleX;
    serializationObject.maxScaleX = particleSystem.maxScaleX;
    serializationObject.minScaleY = particleSystem.minScaleY;
    serializationObject.maxScaleY = particleSystem.maxScaleY;
    serializationObject.minEmitPower = particleSystem.minEmitPower;
    serializationObject.maxEmitPower = particleSystem.maxEmitPower;
    serializationObject.minLifeTime = particleSystem.minLifeTime;
    serializationObject.maxLifeTime = particleSystem.maxLifeTime;
    serializationObject.emitRate = particleSystem.emitRate;
    serializationObject.gravity = particleSystem.gravity.asArray();
    serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
    serializationObject.color1 = particleSystem.color1.asArray();
    serializationObject.color2 = particleSystem.color2.asArray();
    serializationObject.colorDead = particleSystem.colorDead.asArray();
    serializationObject.updateSpeed = particleSystem.updateSpeed;
    serializationObject.targetStopDuration = particleSystem.targetStopDuration;
    serializationObject.blendMode = particleSystem.blendMode;
    serializationObject.preWarmCycles = particleSystem.preWarmCycles;
    serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
    serializationObject.minInitialRotation = particleSystem.minInitialRotation;
    serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
    serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
    serializationObject.spriteCellLoop = particleSystem.spriteCellLoop;
    serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
    serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
    serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
    serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
    serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
    serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
    serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth;
    const colorGradients = particleSystem.getColorGradients();
    if (colorGradients) {
      serializationObject.colorGradients = [];
      for (const colorGradient of colorGradients) {
        const serializedGradient = {
          gradient: colorGradient.gradient,
          color1: colorGradient.color1.asArray()
        };
        if (colorGradient.color2) {
          serializedGradient.color2 = colorGradient.color2.asArray();
        } else {
          serializedGradient.color2 = colorGradient.color1.asArray();
        }
        serializationObject.colorGradients.push(serializedGradient);
      }
    }
    const rampGradients = particleSystem.getRampGradients();
    if (rampGradients) {
      serializationObject.rampGradients = [];
      for (const rampGradient of rampGradients) {
        const serializedGradient = {
          gradient: rampGradient.gradient,
          color: rampGradient.color.asArray()
        };
        serializationObject.rampGradients.push(serializedGradient);
      }
      serializationObject.useRampGradients = particleSystem.useRampGradients;
    }
    const colorRemapGradients = particleSystem.getColorRemapGradients();
    if (colorRemapGradients) {
      serializationObject.colorRemapGradients = [];
      for (const colorRemapGradient of colorRemapGradients) {
        const serializedGradient = {
          gradient: colorRemapGradient.gradient,
          factor1: colorRemapGradient.factor1
        };
        if (colorRemapGradient.factor2 !== undefined) {
          serializedGradient.factor2 = colorRemapGradient.factor2;
        } else {
          serializedGradient.factor2 = colorRemapGradient.factor1;
        }
        serializationObject.colorRemapGradients.push(serializedGradient);
      }
    }
    const alphaRemapGradients = particleSystem.getAlphaRemapGradients();
    if (alphaRemapGradients) {
      serializationObject.alphaRemapGradients = [];
      for (const alphaRemapGradient of alphaRemapGradients) {
        const serializedGradient = {
          gradient: alphaRemapGradient.gradient,
          factor1: alphaRemapGradient.factor1
        };
        if (alphaRemapGradient.factor2 !== undefined) {
          serializedGradient.factor2 = alphaRemapGradient.factor2;
        } else {
          serializedGradient.factor2 = alphaRemapGradient.factor1;
        }
        serializationObject.alphaRemapGradients.push(serializedGradient);
      }
    }
    const sizeGradients = particleSystem.getSizeGradients();
    if (sizeGradients) {
      serializationObject.sizeGradients = [];
      for (const sizeGradient of sizeGradients) {
        const serializedGradient = {
          gradient: sizeGradient.gradient,
          factor1: sizeGradient.factor1
        };
        if (sizeGradient.factor2 !== undefined) {
          serializedGradient.factor2 = sizeGradient.factor2;
        } else {
          serializedGradient.factor2 = sizeGradient.factor1;
        }
        serializationObject.sizeGradients.push(serializedGradient);
      }
    }
    const angularSpeedGradients = particleSystem.getAngularSpeedGradients();
    if (angularSpeedGradients) {
      serializationObject.angularSpeedGradients = [];
      for (const angularSpeedGradient of angularSpeedGradients) {
        const serializedGradient = {
          gradient: angularSpeedGradient.gradient,
          factor1: angularSpeedGradient.factor1
        };
        if (angularSpeedGradient.factor2 !== undefined) {
          serializedGradient.factor2 = angularSpeedGradient.factor2;
        } else {
          serializedGradient.factor2 = angularSpeedGradient.factor1;
        }
        serializationObject.angularSpeedGradients.push(serializedGradient);
      }
    }
    const velocityGradients = particleSystem.getVelocityGradients();
    if (velocityGradients) {
      serializationObject.velocityGradients = [];
      for (const velocityGradient of velocityGradients) {
        const serializedGradient = {
          gradient: velocityGradient.gradient,
          factor1: velocityGradient.factor1
        };
        if (velocityGradient.factor2 !== undefined) {
          serializedGradient.factor2 = velocityGradient.factor2;
        } else {
          serializedGradient.factor2 = velocityGradient.factor1;
        }
        serializationObject.velocityGradients.push(serializedGradient);
      }
    }
    const dragGradients = particleSystem.getDragGradients();
    if (dragGradients) {
      serializationObject.dragGradients = [];
      for (const dragGradient of dragGradients) {
        const serializedGradient = {
          gradient: dragGradient.gradient,
          factor1: dragGradient.factor1
        };
        if (dragGradient.factor2 !== undefined) {
          serializedGradient.factor2 = dragGradient.factor2;
        } else {
          serializedGradient.factor2 = dragGradient.factor1;
        }
        serializationObject.dragGradients.push(serializedGradient);
      }
    }
    const emitRateGradients = particleSystem.getEmitRateGradients();
    if (emitRateGradients) {
      serializationObject.emitRateGradients = [];
      for (const emitRateGradient of emitRateGradients) {
        const serializedGradient = {
          gradient: emitRateGradient.gradient,
          factor1: emitRateGradient.factor1
        };
        if (emitRateGradient.factor2 !== undefined) {
          serializedGradient.factor2 = emitRateGradient.factor2;
        } else {
          serializedGradient.factor2 = emitRateGradient.factor1;
        }
        serializationObject.emitRateGradients.push(serializedGradient);
      }
    }
    const startSizeGradients = particleSystem.getStartSizeGradients();
    if (startSizeGradients) {
      serializationObject.startSizeGradients = [];
      for (const startSizeGradient of startSizeGradients) {
        const serializedGradient = {
          gradient: startSizeGradient.gradient,
          factor1: startSizeGradient.factor1
        };
        if (startSizeGradient.factor2 !== undefined) {
          serializedGradient.factor2 = startSizeGradient.factor2;
        } else {
          serializedGradient.factor2 = startSizeGradient.factor1;
        }
        serializationObject.startSizeGradients.push(serializedGradient);
      }
    }
    const lifeTimeGradients = particleSystem.getLifeTimeGradients();
    if (lifeTimeGradients) {
      serializationObject.lifeTimeGradients = [];
      for (const lifeTimeGradient of lifeTimeGradients) {
        const serializedGradient = {
          gradient: lifeTimeGradient.gradient,
          factor1: lifeTimeGradient.factor1
        };
        if (lifeTimeGradient.factor2 !== undefined) {
          serializedGradient.factor2 = lifeTimeGradient.factor2;
        } else {
          serializedGradient.factor2 = lifeTimeGradient.factor1;
        }
        serializationObject.lifeTimeGradients.push(serializedGradient);
      }
    }
    const limitVelocityGradients = particleSystem.getLimitVelocityGradients();
    if (limitVelocityGradients) {
      serializationObject.limitVelocityGradients = [];
      for (const limitVelocityGradient of limitVelocityGradients) {
        const serializedGradient = {
          gradient: limitVelocityGradient.gradient,
          factor1: limitVelocityGradient.factor1
        };
        if (limitVelocityGradient.factor2 !== undefined) {
          serializedGradient.factor2 = limitVelocityGradient.factor2;
        } else {
          serializedGradient.factor2 = limitVelocityGradient.factor1;
        }
        serializationObject.limitVelocityGradients.push(serializedGradient);
      }
      serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
    }
    if (particleSystem.noiseTexture) {
      serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
    }
  }
  clone(name395, newEmitter, cloneTexture = false) {
    const custom = { ...this._customWrappers };
    let program = null;
    const engine2 = this._engine;
    if (engine2.createEffectForParticles) {
      if (this.customShader != null) {
        program = this.customShader;
        const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(`
`) : "";
        const effect2 = engine2.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
        if (!custom[0]) {
          this.setCustomEffect(effect2, 0);
        } else {
          custom[0].effect = effect2;
        }
      }
    }
    const serialization = this.serialize(cloneTexture);
    const result = ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);
    result.name = name395;
    result.customShader = program;
    result._customWrappers = custom;
    if (newEmitter === undefined) {
      newEmitter = this.emitter;
    }
    if (this.noiseTexture) {
      result.noiseTexture = this.noiseTexture.clone();
    }
    result.emitter = newEmitter;
    if (!this.preventAutoStart) {
      result.start();
    }
    return result;
  }
}
ParticleSystem.BILLBOARDMODE_Y = 2;
ParticleSystem.BILLBOARDMODE_ALL = 7;
ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9;
SubEmitter._ParseParticleSystem = ParticleSystem.Parse;

// node_modules/@babylonjs/core/Misc/sceneRecorder.js
init_postProcess();
init_texture();
init_decorators_serialization();

// node_modules/@babylonjs/core/Misc/index.js
init_khronosTextureContainer2();

// node_modules/@babylonjs/core/Misc/trajectoryClassifier.js
init_math_vector();
var Levenshtein;
(function(Levenshtein2) {

  class Alphabet {
    serialize() {
      const jsonObject = {};
      const characters = new Array(this._characterToIdx.size);
      this._characterToIdx.forEach((v, k) => {
        characters[v] = k;
      });
      jsonObject["characters"] = characters;
      jsonObject["insertionCosts"] = this._insertionCosts;
      jsonObject["deletionCosts"] = this._deletionCosts;
      jsonObject["substitutionCosts"] = this._substitutionCosts;
      return JSON.stringify(jsonObject);
    }
    static Deserialize(json) {
      const jsonObject = JSON.parse(json);
      const alphabet = new Alphabet(jsonObject["characters"]);
      alphabet._insertionCosts = jsonObject["insertionCosts"];
      alphabet._deletionCosts = jsonObject["deletionCosts"];
      alphabet._substitutionCosts = jsonObject["substitutionCosts"];
      return alphabet;
    }
    constructor(characters, charToInsertionCost = null, charToDeletionCost = null, charsToSubstitutionCost = null) {
      charToInsertionCost = charToInsertionCost ?? (() => 1);
      charToDeletionCost = charToDeletionCost ?? (() => 1);
      charsToSubstitutionCost = charsToSubstitutionCost ?? ((a, b) => a === b ? 0 : 1);
      this._characterToIdx = new Map;
      this._insertionCosts = new Array(characters.length);
      this._deletionCosts = new Array(characters.length);
      this._substitutionCosts = new Array(characters.length);
      let c;
      for (let outerIdx = 0;outerIdx < characters.length; ++outerIdx) {
        c = characters[outerIdx];
        this._characterToIdx.set(c, outerIdx);
        this._insertionCosts[outerIdx] = charToInsertionCost(c);
        this._deletionCosts[outerIdx] = charToDeletionCost(c);
        this._substitutionCosts[outerIdx] = new Array(characters.length);
        for (let innerIdx = outerIdx;innerIdx < characters.length; ++innerIdx) {
          this._substitutionCosts[outerIdx][innerIdx] = charsToSubstitutionCost(c, characters[innerIdx]);
        }
      }
    }
    getCharacterIdx(char) {
      return this._characterToIdx.get(char);
    }
    getInsertionCost(idx) {
      return this._insertionCosts[idx];
    }
    getDeletionCost(idx) {
      return this._deletionCosts[idx];
    }
    getSubstitutionCost(idx1, idx2) {
      const min = Math.min(idx1, idx2);
      const max = Math.max(idx1, idx2);
      return this._substitutionCosts[min][max];
    }
  }
  Levenshtein2.Alphabet = Alphabet;

  class Sequence {
    serialize() {
      return JSON.stringify(this._characters);
    }
    static Deserialize(json, alphabet) {
      const sequence = new Sequence([], alphabet);
      sequence._characters = JSON.parse(json);
      return sequence;
    }
    constructor(characters, alphabet) {
      if (characters.length > Sequence._MAX_SEQUENCE_LENGTH) {
        throw new Error("Sequences longer than " + Sequence._MAX_SEQUENCE_LENGTH + " not supported.");
      }
      this._alphabet = alphabet;
      this._characters = characters.map((c) => this._alphabet.getCharacterIdx(c));
    }
    distance(other) {
      return Sequence._Distance(this, other);
    }
    static _Distance(a, b) {
      const alphabet = a._alphabet;
      if (alphabet !== b._alphabet) {
        throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");
      }
      const aChars = a._characters;
      const bChars = b._characters;
      const aLength = aChars.length;
      const bLength = bChars.length;
      const costMatrix = Sequence._CostMatrix;
      costMatrix[0][0] = 0;
      for (let idx = 0;idx < aLength; ++idx) {
        costMatrix[idx + 1][0] = costMatrix[idx][0] + alphabet.getInsertionCost(aChars[idx]);
      }
      for (let idx = 0;idx < bLength; ++idx) {
        costMatrix[0][idx + 1] = costMatrix[0][idx] + alphabet.getInsertionCost(bChars[idx]);
      }
      for (let aIdx = 0;aIdx < aLength; ++aIdx) {
        for (let bIdx = 0;bIdx < bLength; ++bIdx) {
          Sequence._InsertionCost = costMatrix[aIdx + 1][bIdx] + alphabet.getInsertionCost(bChars[bIdx]);
          Sequence._DeletionCost = costMatrix[aIdx][bIdx + 1] + alphabet.getDeletionCost(aChars[aIdx]);
          Sequence._SubstitutionCost = costMatrix[aIdx][bIdx] + alphabet.getSubstitutionCost(aChars[aIdx], bChars[bIdx]);
          costMatrix[aIdx + 1][bIdx + 1] = Math.min(Sequence._InsertionCost, Sequence._DeletionCost, Sequence._SubstitutionCost);
        }
      }
      return costMatrix[aLength][bLength];
    }
  }
  Sequence._MAX_SEQUENCE_LENGTH = 256;
  Sequence._CostMatrix = [...Array(Sequence._MAX_SEQUENCE_LENGTH + 1)].map(() => new Array(Sequence._MAX_SEQUENCE_LENGTH + 1));
  Levenshtein2.Sequence = Sequence;
})(Levenshtein || (Levenshtein = {}));

class Trajectory {
  serialize() {
    return JSON.stringify(this);
  }
  static Deserialize(json) {
    const jsonObject = JSON.parse(json);
    const trajectory = new Trajectory(jsonObject["_segmentLength"]);
    trajectory._points = jsonObject["_points"].map((pt) => {
      return new Vector3(pt["_x"], pt["_y"], pt["_z"]);
    });
    return trajectory;
  }
  constructor(segmentLength = 0.01) {
    this._points = [];
    this._segmentLength = segmentLength;
  }
  getLength() {
    return this._points.length * this._segmentLength;
  }
  add(point) {
    let numPoints = this._points.length;
    if (numPoints === 0) {
      this._points.push(point.clone());
    } else {
      const getT = () => this._segmentLength / Vector3.Distance(this._points[numPoints - 1], point);
      for (let t = getT();t <= 1; t = getT()) {
        const newPoint = this._points[numPoints - 1].scale(1 - t);
        point.scaleAndAddToRef(t, newPoint);
        this._points.push(newPoint);
        ++numPoints;
      }
    }
  }
  resampleAtTargetResolution(targetResolution) {
    const resampled = new Trajectory(this.getLength() / targetResolution);
    this._points.forEach((pt) => {
      resampled.add(pt);
    });
    return resampled;
  }
  tokenize(tokens) {
    const tokenization = [];
    const segmentDir = new Vector3;
    for (let idx = 2;idx < this._points.length; ++idx) {
      if (Trajectory._TransformSegmentDirToRef(this._points[idx - 2], this._points[idx - 1], this._points[idx], segmentDir)) {
        tokenization.push(Trajectory._TokenizeSegment(segmentDir, tokens));
      }
    }
    return tokenization;
  }
  static _TransformSegmentDirToRef(priorVec, fromVec, toVec, result) {
    const DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD = 0.98;
    fromVec.subtractToRef(priorVec, Trajectory._ForwardDir);
    Trajectory._ForwardDir.normalize();
    fromVec.scaleToRef(-1, Trajectory._InverseFromVec);
    Trajectory._InverseFromVec.normalize();
    if (Math.abs(Vector3.Dot(Trajectory._ForwardDir, Trajectory._InverseFromVec)) > DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD) {
      return false;
    }
    Vector3.CrossToRef(Trajectory._ForwardDir, Trajectory._InverseFromVec, Trajectory._UpDir);
    Trajectory._UpDir.normalize();
    Matrix.LookAtLHToRef(priorVec, fromVec, Trajectory._UpDir, Trajectory._LookMatrix);
    toVec.subtractToRef(fromVec, Trajectory._FromToVec);
    Trajectory._FromToVec.normalize();
    Vector3.TransformNormalToRef(Trajectory._FromToVec, Trajectory._LookMatrix, result);
    return true;
  }
  static _TokenizeSegment(segment, tokens) {
    Trajectory._BestMatch = 0;
    Trajectory._Score = Vector3.Dot(segment, tokens[0]);
    Trajectory._BestScore = Trajectory._Score;
    for (let idx = 1;idx < tokens.length; ++idx) {
      Trajectory._Score = Vector3.Dot(segment, tokens[idx]);
      if (Trajectory._Score > Trajectory._BestScore) {
        Trajectory._BestMatch = idx;
        Trajectory._BestScore = Trajectory._Score;
      }
    }
    return Trajectory._BestMatch;
  }
}
Trajectory._ForwardDir = new Vector3;
Trajectory._InverseFromVec = new Vector3;
Trajectory._UpDir = new Vector3;
Trajectory._FromToVec = new Vector3;
Trajectory._LookMatrix = new Matrix;
class TrajectoryDescriptor {
  serialize() {
    return JSON.stringify(this._sequences.map((sequence) => sequence.serialize()));
  }
  static Deserialize(json, alphabet) {
    const descriptor = new TrajectoryDescriptor;
    descriptor._sequences = JSON.parse(json).map((s) => Levenshtein.Sequence.Deserialize(s, alphabet));
    return descriptor;
  }
  static CreateFromTrajectory(trajectory, vector3Alphabet, levenshteinAlphabet) {
    return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(trajectory, vector3Alphabet), levenshteinAlphabet);
  }
  static CreateFromTokenizationPyramid(pyramid, levenshteinAlphabet) {
    const descriptor = new TrajectoryDescriptor;
    descriptor._sequences = pyramid.map((tokens) => new Levenshtein.Sequence(tokens, levenshteinAlphabet));
    return descriptor;
  }
  constructor() {
    this._sequences = [];
  }
  static _GetTokenizationPyramid(trajectory, alphabet, targetResolution = TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION) {
    const pyramid = [];
    for (let res = targetResolution;res > 4; res = Math.floor(res / 2)) {
      pyramid.push(trajectory.resampleAtTargetResolution(res).tokenize(alphabet.chars));
    }
    return pyramid;
  }
  distance(other) {
    let totalDistance = 0;
    let weight;
    for (let idx = 0;idx < this._sequences.length; ++idx) {
      weight = Math.pow(2, idx);
      totalDistance += weight * this._sequences[idx].distance(other._sequences[idx]);
    }
    return totalDistance;
  }
}
TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION = 32;

class TrajectoryClass {
  serialize() {
    const jsonObject = {};
    jsonObject.descriptors = this._descriptors.map((desc) => desc.serialize());
    jsonObject.centroidIdx = this._centroidIdx;
    jsonObject.averageDistance = this._averageDistance;
    return JSON.stringify(jsonObject);
  }
  static Deserialize(json, alphabet) {
    const jsonObject = JSON.parse(json);
    const described = new TrajectoryClass;
    described._descriptors = jsonObject.descriptors.map((s) => TrajectoryDescriptor.Deserialize(s, alphabet));
    described._centroidIdx = jsonObject.centroidIdx;
    described._averageDistance = jsonObject.averageDistance;
    return described;
  }
  constructor(descriptors = []) {
    this._descriptors = descriptors;
    this._centroidIdx = -1;
    this._averageDistance = 0;
    this._refreshDescription();
  }
  add(descriptor) {
    this._descriptors.push(descriptor);
    this._refreshDescription();
  }
  getMatchCost(descriptor) {
    return descriptor.distance(this._descriptors[this._centroidIdx]) / this._averageDistance;
  }
  getMatchMinimumDistance(descriptor) {
    return Math.min(...this._descriptors.map((desc) => desc.distance(descriptor)));
  }
  _refreshDescription() {
    this._centroidIdx = -1;
    let sum;
    const distances = this._descriptors.map((a) => {
      sum = 0;
      this._descriptors.forEach((b) => {
        sum += a.distance(b);
      });
      return sum;
    });
    for (let idx = 0;idx < distances.length; ++idx) {
      if (this._centroidIdx < 0 || distances[idx] < distances[this._centroidIdx]) {
        this._centroidIdx = idx;
      }
    }
    this._averageDistance = 0;
    this._descriptors.forEach((desc) => {
      this._averageDistance += desc.distance(this._descriptors[this._centroidIdx]);
    });
    if (this._descriptors.length > 0) {
      this._averageDistance = Math.max(this._averageDistance / this._descriptors.length, TrajectoryClass._MIN_AVERAGE_DISTANCE);
    }
  }
}
TrajectoryClass._MIN_AVERAGE_DISTANCE = 1;

// node_modules/@babylonjs/core/Misc/index.js
init_timer();
init_copyTools();

// node_modules/@babylonjs/core/Misc/reflector.js
init_logger();
class Reflector {
  constructor(scene, hostname, port) {
    this._scene = scene;
    Logger.Log(`[Reflector] Connecting to ws://${hostname}:${port}`);
    this._webSocket = new WebSocket(`ws://${hostname}:${port}`);
    this._webSocket.onmessage = (event) => {
      const message = event.data;
      if (message.startsWith(Reflector._SERVER_PREFIX)) {
        const serverMessage = message.substring(Reflector._SERVER_PREFIX.length);
        Logger.Log(`[Reflector] Received server message: ${serverMessage.substring(0, 64)}`);
        this._handleServerMessage(serverMessage);
        return;
      } else {
        Logger.Log(`[Reflector] Received client message: ${message.substring(0, 64)}`);
        this._handleClientMessage();
      }
    };
    this._webSocket.onclose = (event) => {
      Logger.Log(`[Reflector] Disconnected ${event.code} ${event.reason}`);
    };
  }
  close() {
    this._webSocket.close();
  }
  _handleServerMessage(message) {
    switch (message) {
      case "connected": {
        SceneSerializer.SerializeAsync(this._scene).then((serialized) => {
          this._webSocket.send(`load|${JSON.stringify(serialized)}`);
        });
        break;
      }
    }
  }
  _handleClientMessage() {}
}
Reflector._SERVER_PREFIX = "$$";

// node_modules/@babylonjs/core/Misc/index.js
init_domManagement();

// node_modules/@babylonjs/core/Misc/pressureObserverWrapper.js
init_observable();
// node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollector.js
init_observable();
init_precisionDate();
init_tools();

// node_modules/@babylonjs/core/Misc/PerformanceViewer/dynamicFloat32Array.js
var growthFactor = 1.5;

class DynamicFloat32Array {
  constructor(itemCapacity) {
    this._view = new Float32Array(itemCapacity);
    this._itemLength = 0;
  }
  get itemLength() {
    return this._itemLength;
  }
  at(index) {
    if (index < 0 || index >= this._itemLength) {
      return NaN;
    }
    return this._view[index];
  }
  subarray(start, end) {
    if (start >= end || start < 0) {
      return new Float32Array(0);
    }
    if (end > this._itemLength) {
      end = this._itemLength;
    }
    return this._view.subarray(start, end);
  }
  push(item) {
    this._view[this._itemLength] = item;
    this._itemLength++;
    if (this._itemLength >= this._view.length) {
      this._growArray();
    }
  }
  _growArray() {
    const newCapacity = Math.floor(this._view.length * growthFactor);
    const view = new Float32Array(newCapacity);
    view.set(this._view);
    this._view = view;
  }
}

// node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollector.js
var InitialArraySize = 1800;
var NumberOfBitsInHexcode = 24;
var HexPadding = "0";
var TimestampColHeader = "timestamp";
var NumPointsColHeader = "numPoints";
var CarriageReturnRegex = /\r/g;
var ExportedDataSeparator = "@";

class PerformanceViewerCollector {
  static get SliceDataOffset() {
    return 2;
  }
  static get NumberOfPointsOffset() {
    return 1;
  }
  constructor(_scene, _enabledStrategyCallbacks) {
    this._scene = _scene;
    this._collectDataAtFrame = () => {
      const timestamp = PrecisionDate.Now - this._startingTimestamp;
      const numPoints = this.datasets.ids.length;
      const numberOfIndices = this.datasets.startingIndices.itemLength;
      let startingIndex = 0;
      if (numberOfIndices > 0) {
        const previousStartingIndex = this.datasets.startingIndices.at(numberOfIndices - 1);
        startingIndex = previousStartingIndex + this.datasets.data.at(previousStartingIndex + PerformanceViewerCollector.NumberOfPointsOffset) + PerformanceViewerCollector.SliceDataOffset;
      }
      this.datasets.startingIndices.push(startingIndex);
      this.datasets.data.push(timestamp);
      this.datasets.data.push(numPoints);
      this.datasets.ids.forEach((id) => {
        const strategy = this._strategies.get(id);
        if (!strategy) {
          return;
        }
        this.datasets.data.push(strategy.getData());
      });
      if (this.datasetObservable.hasObservers()) {
        const slice = [timestamp, numPoints];
        for (let i = 0;i < numPoints; i++) {
          slice.push(this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + i));
        }
        this.datasetObservable.notifyObservers(slice);
      }
    };
    this.datasets = {
      ids: [],
      data: new DynamicFloat32Array(InitialArraySize),
      startingIndices: new DynamicFloat32Array(InitialArraySize)
    };
    this._strategies = new Map;
    this._datasetMeta = new Map;
    this._eventRestoreSet = new Set;
    this._customEventObservable = new Observable;
    this.datasetObservable = new Observable;
    this.metadataObservable = new Observable((observer2) => observer2.callback(this._datasetMeta, new EventState(0)));
    if (_enabledStrategyCallbacks) {
      this.addCollectionStrategies(..._enabledStrategyCallbacks);
    }
  }
  registerEvent(name395, forceUpdate, category) {
    if (this._strategies.has(name395) && !forceUpdate) {
      return;
    }
    if (this._strategies.has(name395) && forceUpdate) {
      this._strategies.get(name395)?.dispose();
      this._strategies.delete(name395);
    }
    const strategy = (scene) => {
      let counter = 0;
      let value = 0;
      const afterRenderObserver = scene.onAfterRenderObservable.add(() => {
        value = counter;
        counter = 0;
      });
      const stringObserver = this._customEventObservable.add((eventVal) => {
        if (name395 !== eventVal.name) {
          return;
        }
        if (eventVal.value !== undefined) {
          counter = eventVal.value;
        } else {
          counter++;
        }
      });
      return {
        id: name395,
        getData: () => value,
        dispose: () => {
          scene.onAfterRenderObservable.remove(afterRenderObserver);
          this._customEventObservable.remove(stringObserver);
        }
      };
    };
    const event = {
      name: name395
    };
    this._eventRestoreSet.add(name395);
    this.addCollectionStrategies({ strategyCallback: strategy, category });
    return event;
  }
  sendEvent(event) {
    this._customEventObservable.notifyObservers(event);
  }
  _restoreStringEvents() {
    if (this._eventRestoreSet.size !== this._customEventObservable.observers.length) {
      this._eventRestoreSet.forEach((event) => {
        this.registerEvent(event, true);
      });
    }
  }
  addCollectionStrategies(...strategyCallbacks) {
    for (let { strategyCallback, category, hidden } of strategyCallbacks) {
      const strategy = strategyCallback(this._scene);
      if (this._strategies.has(strategy.id)) {
        strategy.dispose();
        continue;
      }
      this.datasets.ids.push(strategy.id);
      if (category) {
        category = category.replace(new RegExp(ExportedDataSeparator, "g"), "");
      }
      this._datasetMeta.set(strategy.id, {
        color: this._getHexColorFromId(strategy.id),
        category,
        hidden
      });
      this._strategies.set(strategy.id, strategy);
    }
    this.metadataObservable.notifyObservers(this._datasetMeta);
  }
  _getHexColorFromId(id) {
    let hash2 = 0;
    for (let i = 0;i < id.length; i++) {
      hash2 = id.charCodeAt(i) + ((hash2 << 5) - hash2);
    }
    let hex = "#";
    for (let i = 0;i < NumberOfBitsInHexcode; i += 8) {
      const octet = hash2 >> i & 255;
      const toStr = HexPadding + octet.toString(16);
      hex += toStr.substring(toStr.length - 2);
    }
    return hex;
  }
  getCurrentSlice() {
    const timestamp = PrecisionDate.Now - this._startingTimestamp;
    const numPoints = this.datasets.ids.length;
    const slice = [timestamp, numPoints];
    this.datasets.ids.forEach((id) => {
      const strategy = this._strategies.get(id);
      if (!strategy) {
        return;
      }
      if (this.datasetObservable.hasObservers()) {
        slice.push(strategy.getData());
      }
    });
    if (this.datasetObservable.hasObservers()) {
      this.datasetObservable.notifyObservers(slice);
    }
  }
  updateMetadata(id, prop, value) {
    const meta = this._datasetMeta.get(id);
    if (!meta) {
      return;
    }
    meta[prop] = value;
    this.metadataObservable.notifyObservers(this._datasetMeta);
  }
  clear(preserveStringEventsRestore) {
    this.datasets.data = new DynamicFloat32Array(InitialArraySize);
    this.datasets.ids.length = 0;
    this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);
    this._datasetMeta.clear();
    this._strategies.forEach((strategy) => strategy.dispose());
    this._strategies.clear();
    if (!preserveStringEventsRestore) {
      this._eventRestoreSet.clear();
    }
    this._hasLoadedData = false;
  }
  get hasLoadedData() {
    return this._hasLoadedData;
  }
  loadFromFileData(data, keepDatasetMeta) {
    const lines = data.replace(CarriageReturnRegex, "").split(`
`).map((line) => line.split(",").filter((s) => s.length > 0)).filter((line) => line.length > 0);
    const timestampIndex = 0;
    const numPointsIndex = PerformanceViewerCollector.NumberOfPointsOffset;
    if (lines.length < 2) {
      return false;
    }
    const parsedDatasets = {
      ids: [],
      data: new DynamicFloat32Array(InitialArraySize),
      startingIndices: new DynamicFloat32Array(InitialArraySize)
    };
    const [firstLine, ...dataLines] = lines;
    if (firstLine.length < 2 || firstLine[timestampIndex] !== TimestampColHeader || firstLine[numPointsIndex] !== NumPointsColHeader) {
      return false;
    }
    const idCategoryMap = new Map;
    for (let i = PerformanceViewerCollector.SliceDataOffset;i < firstLine.length; i++) {
      const [id, category] = firstLine[i].split(ExportedDataSeparator);
      parsedDatasets.ids.push(id);
      idCategoryMap.set(id, category);
    }
    let startingIndex = 0;
    for (const line of dataLines) {
      if (line.length < 2) {
        return false;
      }
      const timestamp = parseFloat(line[timestampIndex]);
      const numPoints = parseInt(line[numPointsIndex]);
      if (isNaN(numPoints) || isNaN(timestamp)) {
        return false;
      }
      parsedDatasets.data.push(timestamp);
      parsedDatasets.data.push(numPoints);
      if (numPoints + PerformanceViewerCollector.SliceDataOffset !== line.length) {
        return false;
      }
      for (let i = PerformanceViewerCollector.SliceDataOffset;i < line.length; i++) {
        const val = parseFloat(line[i]);
        if (isNaN(val)) {
          return false;
        }
        parsedDatasets.data.push(val);
      }
      parsedDatasets.startingIndices.push(startingIndex);
      startingIndex += line.length;
    }
    this.datasets.ids = parsedDatasets.ids;
    this.datasets.data = parsedDatasets.data;
    this.datasets.startingIndices = parsedDatasets.startingIndices;
    if (!keepDatasetMeta) {
      this._datasetMeta.clear();
    }
    this._strategies.forEach((strategy) => strategy.dispose());
    this._strategies.clear();
    if (!keepDatasetMeta) {
      for (const id of this.datasets.ids) {
        const category = idCategoryMap.get(id);
        this._datasetMeta.set(id, { category, color: this._getHexColorFromId(id) });
      }
    }
    this.metadataObservable.notifyObservers(this._datasetMeta);
    this._hasLoadedData = true;
    return true;
  }
  exportDataToCsv() {
    let csvContent = "";
    csvContent += `${TimestampColHeader},${NumPointsColHeader}`;
    for (let i = 0;i < this.datasets.ids.length; i++) {
      csvContent += `,${this.datasets.ids[i]}`;
      if (this._datasetMeta) {
        const meta = this._datasetMeta.get(this.datasets.ids[i]);
        if (meta?.category) {
          csvContent += `${ExportedDataSeparator}${meta.category}`;
        }
      }
    }
    csvContent += `
`;
    for (let i = 0;i < this.datasets.startingIndices.itemLength; i++) {
      const startingIndex = this.datasets.startingIndices.at(i);
      const timestamp = this.datasets.data.at(startingIndex);
      const numPoints = this.datasets.data.at(startingIndex + PerformanceViewerCollector.NumberOfPointsOffset);
      csvContent += `${timestamp},${numPoints}`;
      for (let offset = 0;offset < numPoints; offset++) {
        csvContent += `,${this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + offset)}`;
      }
      for (let diff = 0;diff < this.datasets.ids.length - numPoints; diff++) {
        csvContent += ",";
      }
      csvContent += `
`;
    }
    const fileName = `${new Date().toISOString()}-perfdata.csv`;
    Tools.Download(new Blob([csvContent], { type: "text/csv" }), fileName);
  }
  start(shouldPreserve) {
    if (!shouldPreserve) {
      this.datasets.data = new DynamicFloat32Array(InitialArraySize);
      this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);
      this._startingTimestamp = PrecisionDate.Now;
    } else if (this._startingTimestamp === undefined) {
      this._startingTimestamp = PrecisionDate.Now;
    }
    this._scene.onAfterRenderObservable.add(this._collectDataAtFrame);
    this._restoreStringEvents();
    this._isStarted = true;
  }
  stop() {
    this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);
    this._isStarted = false;
  }
  get isStarted() {
    return this._isStarted;
  }
  dispose() {
    this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);
    this._datasetMeta.clear();
    this._strategies.forEach((strategy) => {
      strategy.dispose();
    });
    this.datasetObservable.clear();
    this.metadataObservable.clear();
    this._isStarted = false;
    this.datasets = null;
  }
}
// node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollectionStrategies.js
init_precisionDate();
// node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerSceneExtension.js
init_scene();
Scene.prototype.getPerfCollector = function() {
  if (!this._perfCollector) {
    this._perfCollector = new PerformanceViewerCollector(this);
  }
  return this._perfCollector;
};
// node_modules/@babylonjs/core/Misc/index.js
init_guid();
init_error();

// node_modules/@babylonjs/core/Misc/snapshotRenderingHelper.js
init_materialHelper_functions();
init_logger();
// node_modules/@babylonjs/core/Misc/observableCoroutine.js
init_observable();
function CreateObservableScheduler(observable) {
  const coroutines = new Array;
  const onSteps = new Array;
  const onErrors = new Array;
  const observer2 = observable.add(() => {
    const count = coroutines.length;
    for (let i = 0;i < count; i++) {
      inlineScheduler(coroutines.shift(), onSteps.shift(), onErrors.shift());
    }
  });
  const scheduler = (coroutine, onStep, onError) => {
    coroutines.push(coroutine);
    onSteps.push(onStep);
    onErrors.push(onError);
  };
  return {
    scheduler,
    dispose: () => {
      observable.remove(observer2);
    }
  };
}
Observable.prototype.runCoroutineAsync = function(coroutine) {
  if (!this._coroutineScheduler) {
    const schedulerAndDispose = CreateObservableScheduler(this);
    this._coroutineScheduler = schedulerAndDispose.scheduler;
    this._coroutineSchedulerDispose = schedulerAndDispose.dispose;
  }
  return runCoroutineAsync(coroutine, this._coroutineScheduler);
};
Observable.prototype.cancelAllCoroutines = function() {
  if (this._coroutineSchedulerDispose) {
    this._coroutineSchedulerDispose();
  }
  this._coroutineScheduler = undefined;
  this._coroutineSchedulerDispose = undefined;
};

// node_modules/@babylonjs/core/Misc/index.js
init_dumpTools();

// node_modules/@babylonjs/core/Misc/equirectangularCapture.js
init_renderTargetTexture();
init_dumpTools();

// node_modules/@babylonjs/core/Shaders/equirectangularPanorama.fragment.js
init_shaderStore();
var name395 = "equirectangularPanoramaPixelShader";
var shader394 = `#ifdef GL_ES
precision highp float;
#endif
#define M_PI 3.1415926535897932384626433832795
varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(
- sin( longitude )*sin( latitude ),
cos( latitude ),
- cos( longitude )*sin( latitude )
);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;
if (!ShaderStore.ShadersStore[name395]) {
  ShaderStore.ShadersStore[name395] = shader394;
}

// node_modules/@babylonjs/core/Misc/index.js
init_decorators_serialization();
init_rgbdDecode_fragment2();
init_rgbdEncode_fragment();
init_rgbdDecode_fragment();
init_rgbdEncode_fragment2();
init_copyTextureToTexture_fragment2();
init_copyTextureToTexture_fragment();
// node_modules/@babylonjs/core/Navigation/Plugins/recastJSPlugin.js
init_logger();
init_math();
init_observable();
init_buffer();
// node_modules/@babylonjs/core/index.js
init_node();
// node_modules/@babylonjs/core/Offline/database.js
init_tools();
init_logger();
init_tga();
init_webRequest();
init_abstractEngine();
AbstractEngine.OfflineProviderFactory = (urlToScene, callbackManifestChecked, disableManifestCheck = false) => {
  return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
};

class Database {
  get enableSceneOffline() {
    return this._enableSceneOffline;
  }
  get enableTexturesOffline() {
    return this._enableTexturesOffline;
  }
  constructor(urlToScene, callbackManifestChecked, disableManifestCheck = false) {
    this._idbFactory = typeof indexedDB !== "undefined" ? indexedDB : undefined;
    this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
    this._db = null;
    this._enableSceneOffline = false;
    this._enableTexturesOffline = false;
    this._manifestVersionFound = 0;
    this._mustUpdateRessources = false;
    this._hasReachedQuota = false;
    if (!Database.IDBStorageEnabled) {
      callbackManifestChecked(true);
    } else {
      if (disableManifestCheck) {
        this._enableSceneOffline = true;
        this._enableTexturesOffline = true;
        this._manifestVersionFound = 1;
        Tools.SetImmediate(() => {
          callbackManifestChecked(true);
        });
      } else {
        this._checkManifestFile(callbackManifestChecked);
      }
    }
  }
  _checkManifestFile(callbackManifestChecked) {
    const noManifestFile = () => {
      this._enableSceneOffline = false;
      this._enableTexturesOffline = false;
      callbackManifestChecked(false);
    };
    const createManifestURL = () => {
      try {
        if (typeof URL === "function" && this._currentSceneUrl.indexOf("http") === 0) {
          const url = new URL(this._currentSceneUrl);
          url.pathname += ".manifest";
          return url.toString();
        }
      } catch (e) {}
      return `${this._currentSceneUrl}.manifest`;
    };
    let timeStampUsed = false;
    let manifestURL = createManifestURL();
    const xhr = new WebRequest;
    if (navigator.onLine) {
      timeStampUsed = true;
      manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
    }
    xhr.open("GET", manifestURL);
    xhr.addEventListener("load", () => {
      if (xhr.status === 200 || Database._ValidateXHRData(xhr, 1)) {
        try {
          const manifestFile = JSON.parse(xhr.response);
          this._enableSceneOffline = manifestFile.enableSceneOffline;
          this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database._IsUASupportingBlobStorage;
          if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
            this._manifestVersionFound = manifestFile.version;
          }
          callbackManifestChecked(true);
        } catch (ex) {
          noManifestFile();
        }
      } else {
        noManifestFile();
      }
    }, false);
    xhr.addEventListener("error", () => {
      if (timeStampUsed) {
        timeStampUsed = false;
        const retryManifestURL = createManifestURL();
        xhr.open("GET", retryManifestURL);
        xhr.send();
      } else {
        noManifestFile();
      }
    }, false);
    try {
      xhr.send();
    } catch (ex) {
      Logger.Error("Error on XHR send request.");
      callbackManifestChecked(false);
    }
  }
  open(successCallback, errorCallback) {
    const handleError = () => {
      this._isSupported = false;
      if (errorCallback) {
        errorCallback();
      }
    };
    if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
      this._isSupported = false;
      if (errorCallback) {
        errorCallback();
      }
    } else {
      if (!this._db) {
        this._hasReachedQuota = false;
        this._isSupported = true;
        const request = this._idbFactory.open("babylonjs", 1);
        request.onerror = () => {
          handleError();
        };
        request.onblocked = () => {
          Logger.Error("IDB request blocked. Please reload the page.");
          handleError();
        };
        request.onsuccess = () => {
          this._db = request.result;
          successCallback();
        };
        request.onupgradeneeded = (event) => {
          this._db = event.target.result;
          if (this._db) {
            try {
              this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
              this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
              this._db.createObjectStore("textures", { keyPath: "textureUrl" });
            } catch (ex) {
              Logger.Error("Error while creating object stores. Exception: " + ex.message);
              handleError();
            }
          }
        };
      } else {
        if (successCallback) {
          successCallback();
        }
      }
    }
  }
  loadImage(url, image) {
    const completeURL = Database._ReturnFullUrlLocation(url);
    const saveAndLoadImage = () => {
      if (!this._hasReachedQuota && this._db !== null) {
        this._saveImageIntoDBAsync(completeURL, image);
      } else {
        image.src = url;
      }
    };
    if (!this._mustUpdateRessources) {
      this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
    } else {
      saveAndLoadImage();
    }
  }
  _loadImageFromDBAsync(url, image, notInDBCallback) {
    if (this._isSupported && this._db !== null) {
      let texture2;
      const transaction = this._db.transaction(["textures"]);
      transaction.onabort = () => {
        image.src = url;
      };
      transaction.oncomplete = () => {
        let blobTextureURL;
        if (texture2 && typeof URL === "function") {
          blobTextureURL = URL.createObjectURL(texture2.data);
          image.onerror = () => {
            Logger.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
            image.src = url;
          };
          image.src = blobTextureURL;
        } else {
          notInDBCallback();
        }
      };
      const getRequest = transaction.objectStore("textures").get(url);
      getRequest.onsuccess = (event) => {
        texture2 = event.target.result;
      };
      getRequest.onerror = () => {
        Logger.Error("Error loading texture " + url + " from DB.");
        image.src = url;
      };
    } else {
      Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
      image.src = url;
    }
  }
  _saveImageIntoDBAsync(url, image) {
    let blob;
    if (this._isSupported) {
      const generateBlobUrl = () => {
        let blobTextureURL;
        if (blob && typeof URL === "function") {
          try {
            blobTextureURL = URL.createObjectURL(blob);
          } catch (ex) {
            blobTextureURL = URL.createObjectURL(blob);
          }
        }
        if (blobTextureURL) {
          image.src = blobTextureURL;
        }
      };
      if (Database._IsUASupportingBlobStorage) {
        const xhr = new WebRequest;
        xhr.open("GET", url);
        xhr.responseType = "blob";
        xhr.addEventListener("load", () => {
          if (xhr.status === 200 && this._db) {
            blob = xhr.response;
            const transaction = this._db.transaction(["textures"], "readwrite");
            transaction.onabort = (event) => {
              try {
                const srcElement = event.target;
                const error2 = srcElement.error;
                if (error2 && error2.name === "QuotaExceededError") {
                  this._hasReachedQuota = true;
                }
              } catch (ex) {}
              generateBlobUrl();
            };
            transaction.oncomplete = () => {
              generateBlobUrl();
            };
            const newTexture = { textureUrl: url, data: blob };
            try {
              const addRequest = transaction.objectStore("textures").put(newTexture);
              addRequest.onsuccess = () => {};
              addRequest.onerror = () => {
                generateBlobUrl();
              };
            } catch (ex) {
              if (ex.code === 25) {
                Database._IsUASupportingBlobStorage = false;
                this._enableTexturesOffline = false;
              }
              image.src = url;
            }
          } else {
            image.src = url;
          }
        }, false);
        xhr.addEventListener("error", () => {
          Logger.Error("Error in XHR request in BABYLON.Database.");
          image.src = url;
        }, false);
        xhr.send();
      } else {
        image.src = url;
      }
    } else {
      Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open.");
      image.src = url;
    }
  }
  _checkVersionFromDB(url, versionLoaded) {
    const updateVersion = () => {
      this._saveVersionIntoDBAsync(url, versionLoaded);
    };
    this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  }
  _loadVersionFromDBAsync(url, callback, updateInDBCallback) {
    if (this._isSupported && this._db) {
      let version;
      try {
        const transaction = this._db.transaction(["versions"]);
        transaction.oncomplete = () => {
          if (version) {
            if (this._manifestVersionFound !== version.data) {
              this._mustUpdateRessources = true;
              updateInDBCallback();
            } else {
              callback(version.data);
            }
          } else {
            this._mustUpdateRessources = true;
            updateInDBCallback();
          }
        };
        transaction.onabort = () => {
          callback(-1);
        };
        const getRequest = transaction.objectStore("versions").get(url);
        getRequest.onsuccess = (event) => {
          version = event.target.result;
        };
        getRequest.onerror = () => {
          Logger.Error("Error loading version for scene " + url + " from DB.");
          callback(-1);
        };
      } catch (ex) {
        Logger.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
        callback(-1);
      }
    } else {
      Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open.");
      callback(-1);
    }
  }
  _saveVersionIntoDBAsync(url, callback) {
    if (this._isSupported && !this._hasReachedQuota && this._db) {
      try {
        const transaction = this._db.transaction(["versions"], "readwrite");
        transaction.onabort = (event) => {
          try {
            const error2 = event.target["error"];
            if (error2 && error2.name === "QuotaExceededError") {
              this._hasReachedQuota = true;
            }
          } catch (ex) {}
          callback(-1);
        };
        transaction.oncomplete = () => {
          callback(this._manifestVersionFound);
        };
        const newVersion = { sceneUrl: url, data: this._manifestVersionFound };
        const addRequest = transaction.objectStore("versions").put(newVersion);
        addRequest.onsuccess = () => {};
        addRequest.onerror = () => {
          Logger.Error("Error in DB add version request in BABYLON.Database.");
        };
      } catch (ex) {
        Logger.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
        callback(-1);
      }
    } else {
      callback(-1);
    }
  }
  loadFile(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
    const completeUrl = Database._ReturnFullUrlLocation(url);
    const saveAndLoadFile = () => {
      this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
    };
    this._checkVersionFromDB(completeUrl, (version) => {
      if (version !== -1) {
        if (!this._mustUpdateRessources) {
          this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, progressCallBack);
        } else {
          this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
        }
      } else {
        if (errorCallback) {
          errorCallback();
        }
      }
    });
  }
  _loadFileAsync(url, callback, notInDBCallback, progressCallBack) {
    if (this._isSupported && this._db) {
      let targetStore;
      if (url.indexOf(".babylon") !== -1) {
        targetStore = "scenes";
      } else {
        targetStore = "textures";
      }
      let file;
      const transaction = this._db.transaction([targetStore]);
      transaction.oncomplete = () => {
        if (file) {
          if (progressCallBack) {
            const numberToLoad = file.data?.byteLength || 0;
            progressCallBack({
              total: numberToLoad,
              loaded: numberToLoad,
              lengthComputable: true
            });
          }
          callback(file.data);
        } else {
          notInDBCallback();
        }
      };
      transaction.onabort = () => {
        notInDBCallback();
      };
      const getRequest = transaction.objectStore(targetStore).get(url);
      getRequest.onsuccess = (event) => {
        file = event.target.result;
      };
      getRequest.onerror = () => {
        Logger.Error("Error loading file " + url + " from DB.");
        notInDBCallback();
      };
    } else {
      Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
      callback();
    }
  }
  _saveFileAsync(url, callback, progressCallback, useArrayBuffer, errorCallback) {
    if (this._isSupported) {
      let targetStore;
      if (url.indexOf(".babylon") !== -1) {
        targetStore = "scenes";
      } else {
        targetStore = "textures";
      }
      const xhr = new WebRequest;
      let fileData;
      xhr.open("GET", url + (url.match(/\?/) == null ? "?" : "&") + Date.now());
      if (useArrayBuffer) {
        xhr.responseType = "arraybuffer";
      }
      if (progressCallback) {
        xhr.onprogress = progressCallback;
      }
      xhr.addEventListener("load", () => {
        if (xhr.status === 200 || xhr.status < 400 && Database._ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
          fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
          if (!this._hasReachedQuota && this._db) {
            const transaction = this._db.transaction([targetStore], "readwrite");
            transaction.onabort = (event) => {
              try {
                const error2 = event.target["error"];
                if (error2 && error2.name === "QuotaExceededError") {
                  this._hasReachedQuota = true;
                }
              } catch (ex) {}
              callback(fileData);
            };
            transaction.oncomplete = () => {
              callback(fileData);
            };
            let newFile;
            if (targetStore === "scenes") {
              newFile = { sceneUrl: url, data: fileData, version: this._manifestVersionFound };
            } else {
              newFile = { textureUrl: url, data: fileData };
            }
            try {
              const addRequest = transaction.objectStore(targetStore).put(newFile);
              addRequest.onsuccess = () => {};
              addRequest.onerror = () => {
                Logger.Error("Error in DB add file request in BABYLON.Database.");
              };
            } catch (ex) {
              callback(fileData);
            }
          } else {
            callback(fileData);
          }
        } else {
          if (xhr.status >= 400 && errorCallback) {
            errorCallback(xhr);
          } else {
            callback();
          }
        }
      }, false);
      xhr.addEventListener("error", () => {
        Logger.Error("error on XHR request.");
        errorCallback && errorCallback();
      }, false);
      xhr.send();
    } else {
      Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open.");
      errorCallback && errorCallback();
    }
  }
  static _ValidateXHRData(xhr, dataType = 7) {
    try {
      if (dataType & 1) {
        if (xhr.responseText && xhr.responseText.length > 0) {
          return true;
        } else if (dataType === 1) {
          return false;
        }
      }
      if (dataType & 2) {
        const tgaHeader = GetTGAHeader(xhr.response);
        if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
          return true;
        } else if (dataType === 2) {
          return false;
        }
      }
      if (dataType & 4) {
        const ddsHeader = new Uint8Array(xhr.response, 0, 3);
        if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
          return true;
        } else {
          return false;
        }
      }
    } catch (e) {}
    return false;
  }
}
Database._IsUASupportingBlobStorage = true;
Database.IDBStorageEnabled = false;
Database._ParseURL = (url) => {
  const a = document.createElement("a");
  a.href = url;
  const urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  const fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  const absLocation = url.substring(0, url.indexOf(fileName, 0));
  return absLocation;
};
Database._ReturnFullUrlLocation = (url) => {
  if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1 && typeof window !== "undefined") {
    return Database._ParseURL(window.location.href) + url;
  } else {
    return url;
  }
};
// node_modules/@babylonjs/core/Materials/uniformBufferEffectCommonAccessor.js
class UniformBufferEffectCommonAccessor {
  _isUbo(uboOrEffect) {
    return uboOrEffect.addUniform !== undefined;
  }
  constructor(uboOrEffect) {
    if (this._isUbo(uboOrEffect)) {
      this.setMatrix3x3 = uboOrEffect.updateMatrix3x3.bind(uboOrEffect);
      this.setMatrix2x2 = uboOrEffect.updateMatrix2x2.bind(uboOrEffect);
      this.setFloat = uboOrEffect.updateFloat.bind(uboOrEffect);
      this.setFloat2 = uboOrEffect.updateFloat2.bind(uboOrEffect);
      this.setFloat3 = uboOrEffect.updateFloat3.bind(uboOrEffect);
      this.setFloat4 = uboOrEffect.updateFloat4.bind(uboOrEffect);
      this.setFloatArray = uboOrEffect.updateFloatArray.bind(uboOrEffect);
      this.setArray = uboOrEffect.updateArray.bind(uboOrEffect);
      this.setIntArray = uboOrEffect.updateIntArray.bind(uboOrEffect);
      this.setMatrix = uboOrEffect.updateMatrix.bind(uboOrEffect);
      this.setMatrices = uboOrEffect.updateMatrices.bind(uboOrEffect);
      this.setVector3 = uboOrEffect.updateVector3.bind(uboOrEffect);
      this.setVector4 = uboOrEffect.updateVector4.bind(uboOrEffect);
      this.setColor3 = uboOrEffect.updateColor3.bind(uboOrEffect);
      this.setColor4 = uboOrEffect.updateColor4.bind(uboOrEffect);
      this.setDirectColor4 = uboOrEffect.updateDirectColor4.bind(uboOrEffect);
      this.setInt = uboOrEffect.updateInt.bind(uboOrEffect);
      this.setInt2 = uboOrEffect.updateInt2.bind(uboOrEffect);
      this.setInt3 = uboOrEffect.updateInt3.bind(uboOrEffect);
      this.setInt4 = uboOrEffect.updateInt4.bind(uboOrEffect);
    } else {
      this.setMatrix3x3 = uboOrEffect.setMatrix3x3.bind(uboOrEffect);
      this.setMatrix2x2 = uboOrEffect.setMatrix2x2.bind(uboOrEffect);
      this.setFloat = uboOrEffect.setFloat.bind(uboOrEffect);
      this.setFloat2 = uboOrEffect.setFloat2.bind(uboOrEffect);
      this.setFloat3 = uboOrEffect.setFloat3.bind(uboOrEffect);
      this.setFloat4 = uboOrEffect.setFloat4.bind(uboOrEffect);
      this.setFloatArray = uboOrEffect.setFloatArray.bind(uboOrEffect);
      this.setArray = uboOrEffect.setArray.bind(uboOrEffect);
      this.setIntArray = uboOrEffect.setIntArray.bind(uboOrEffect);
      this.setMatrix = uboOrEffect.setMatrix.bind(uboOrEffect);
      this.setMatrices = uboOrEffect.setMatrices.bind(uboOrEffect);
      this.setVector3 = uboOrEffect.setVector3.bind(uboOrEffect);
      this.setVector4 = uboOrEffect.setVector4.bind(uboOrEffect);
      this.setColor3 = uboOrEffect.setColor3.bind(uboOrEffect);
      this.setColor4 = uboOrEffect.setColor4.bind(uboOrEffect);
      this.setDirectColor4 = uboOrEffect.setDirectColor4.bind(uboOrEffect);
      this.setInt = uboOrEffect.setInt.bind(uboOrEffect);
      this.setInt2 = uboOrEffect.setInt2.bind(uboOrEffect);
      this.setInt3 = uboOrEffect.setInt3.bind(uboOrEffect);
      this.setInt4 = uboOrEffect.setInt4.bind(uboOrEffect);
    }
  }
}

// node_modules/@babylonjs/core/Particles/webgl2ParticleSystem.js
init_typeStore();

// node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.fragment.js
init_shaderStore();
var name396 = "gpuUpdateParticlesPixelShader";
var shader395 = `#version 300 es
void main() {discard;}
`;
if (!ShaderStore.ShadersStore[name396]) {
  ShaderStore.ShadersStore[name396] = shader395;
}

// node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.vertex.js
init_shaderStore();
var name397 = "gpuUpdateParticlesVertexShader";
var shader396 = `#version 300 es
#define PI 3.14159
uniform float currentCount;uniform float timeDelta;uniform float stopFactor;
#ifndef LOCAL
uniform mat4 emitterWM;
#endif
uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;
#ifndef COLORGRADIENTS
uniform vec4 color1;uniform vec4 color2;
#endif
uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;
#ifdef BOXEMITTER
uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;
#endif
#ifdef POINTEMITTER
uniform vec3 direction1;uniform vec3 direction2;
#endif
#ifdef HEMISPHERICEMITTER
uniform float radius;uniform float radiusRange;uniform float directionRandomizer;
#endif
#ifdef SPHEREEMITTER
uniform float radius;uniform float radiusRange;
#ifdef DIRECTEDSPHEREEMITTER
uniform vec3 direction1;uniform vec3 direction2;
#else
uniform float directionRandomizer;
#endif
#endif
#ifdef CYLINDEREMITTER
uniform float radius;uniform float height;uniform float radiusRange;
#ifdef DIRECTEDCYLINDEREMITTER
uniform vec3 direction1;uniform vec3 direction2;
#else
uniform float directionRandomizer;
#endif
#endif
#ifdef CONEEMITTER
uniform vec2 radius;uniform float coneAngle;uniform vec2 height;
#ifdef DIRECTEDCONEEMITTER
uniform vec3 direction1;uniform vec3 direction2;
#else
uniform float directionRandomizer;
#endif
#endif
in vec3 position;
#ifdef CUSTOMEMITTER
in vec3 initialPosition;
#endif
in float age;in float life;in vec4 seed;in vec3 size;
#ifndef COLORGRADIENTS
in vec4 color;
#endif
in vec3 direction;
#ifndef BILLBOARD
in vec3 initialDirection;
#endif
#ifdef ANGULARSPEEDGRADIENTS
in float angle;
#else
in vec2 angle;
#endif
#ifdef ANIMATESHEET
in float cellIndex;
#ifdef ANIMATESHEETRANDOMSTART
in float cellStartOffset;
#endif
#endif
#ifdef NOISE
in vec3 noiseCoordinates1;in vec3 noiseCoordinates2;
#endif
out vec3 outPosition;
#ifdef CUSTOMEMITTER
out vec3 outInitialPosition;
#endif
out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;
#ifndef COLORGRADIENTS
out vec4 outColor;
#endif
out vec3 outDirection;
#ifndef BILLBOARD
out vec3 outInitialDirection;
#endif
#ifdef ANGULARSPEEDGRADIENTS
out float outAngle;
#else
out vec2 outAngle;
#endif
#ifdef ANIMATESHEET
out float outCellIndex;
#ifdef ANIMATESHEETRANDOMSTART
out float outCellStartOffset;
#endif
#endif
#ifdef NOISE
out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;
#endif
#ifdef SIZEGRADIENTS
uniform sampler2D sizeGradientSampler;
#endif 
#ifdef ANGULARSPEEDGRADIENTS
uniform sampler2D angularSpeedGradientSampler;
#endif 
#ifdef VELOCITYGRADIENTS
uniform sampler2D velocityGradientSampler;
#endif
#ifdef LIMITVELOCITYGRADIENTS
uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;
#endif
#ifdef DRAGGRADIENTS
uniform sampler2D dragGradientSampler;
#endif
#ifdef NOISE
uniform vec3 noiseStrength;uniform sampler2D noiseSampler;
#endif
#ifdef ANIMATESHEET
uniform vec4 cellInfos;
#endif
vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}
vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}
void main() {float newAge=age+timeDelta; 
if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;
#ifdef SIZEGRADIENTS 
outSize.x=texture(sizeGradientSampler,vec2(0,0)).r;
#else
outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;
#endif
outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; 
#ifndef COLORGRADIENTS
outColor=color1+(color2-color1)*randoms.b;
#endif
#ifndef ANGULARSPEEDGRADIENTS 
outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;
#else
outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;
#endif 
#ifdef POINTEMITTER
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;
#elif defined(BOXEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; 
#elif defined(HEMISPHERICEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; 
#elif defined(SPHEREEMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);
#ifdef DIRECTEDSPHEREEMITTER
newDirection=normalize(direction1+(direction2-direction1)*randoms3);
#else
newDirection=normalize(newPosition+directionRandomizer*randoms3);
#endif
#elif defined(CYLINDEREMITTER)
vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);
#ifdef DIRECTEDCYLINDEREMITTER
newDirection=direction1+(direction2-direction1)*randoms3;
#else
angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);
#endif
#elif defined(CONEEMITTER)
vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;
#ifdef CONEEMITTERSPAWNPOINT
float h=0.0001;
#else
float h=randoms2.y*height.y;h=1.-h*h; 
#endif
float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); 
vec3 randoms3=getRandomVec3(seed.z);
#ifdef DIRECTEDCONEEMITTER
newDirection=direction1+(direction2-direction1)*randoms3;
#else
if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {newDirection=normalize(newPosition+directionRandomizer*randoms3); }
#endif
#elif defined(CUSTOMEMITTER)
newPosition=initialPosition;outInitialPosition=initialPosition;
#else 
newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));
#endif
float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;
#ifdef LOCAL
outPosition=newPosition;
#else
outPosition=(emitterWM*vec4(newPosition,1.)).xyz;
#endif
#ifdef CUSTOMEMITTER
outDirection=direction;
#ifndef BILLBOARD 
outInitialDirection=direction;
#endif
#else
#ifdef LOCAL
vec3 initial=newDirection;
#else 
vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;
#endif
outDirection=initial*power;
#ifndef BILLBOARD 
outInitialDirection=initial;
#endif
#endif
#ifdef ANIMATESHEET 
outCellIndex=cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
outCellStartOffset=randoms.a*outLife;
#endif 
#endif
#ifdef NOISE
outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;
#endif
} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;
#ifdef VELOCITYGRADIENTS
directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;
#endif
#ifdef DRAGGRADIENTS
directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;
#endif
#if defined(CUSTOMEMITTER)
outPosition=position+(direction-position)*ageGradient; 
outInitialPosition=initialPosition;
#else
outPosition=position+direction*directionScale;
#endif
outLife=life;outSeed=seed;
#ifndef COLORGRADIENTS 
outColor=color;
#endif
#ifdef SIZEGRADIENTS
outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;
#else
outSize=size;
#endif 
#ifndef BILLBOARD 
outInitialDirection=initialDirection;
#endif
#ifdef CUSTOMEMITTER
outDirection=direction;
#else
vec3 updatedDirection=direction+gravity*timeDelta;
#ifdef LIMITVELOCITYGRADIENTS
float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}
#endif
outDirection=updatedDirection;
#ifdef NOISE
float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;
#endif 
#endif 
#ifdef ANGULARSPEEDGRADIENTS
float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;
#else
outAngle=vec2(angle.x+angle.y*timeDelta,angle.y);
#endif
#ifdef ANIMATESHEET 
float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;
#else
float cellStartOffset=0.;
#endif 
float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}
else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}
outCellIndex=float(int(cellInfos.x+ratio*dist));
#endif
}}`;
if (!ShaderStore.ShadersStore[name397]) {
  ShaderStore.ShadersStore[name397] = shader396;
}

// node_modules/@babylonjs/core/Particles/webgl2ParticleSystem.js
class WebGL2ParticleSystem {
  constructor(parent, engine2) {
    this._renderVAO = [];
    this._updateVAO = [];
    this.alignDataInBuffer = false;
    this._parent = parent;
    this._engine = engine2;
    this._updateEffectOptions = {
      attributes: [
        "position",
        "initialPosition",
        "age",
        "life",
        "seed",
        "size",
        "color",
        "direction",
        "initialDirection",
        "angle",
        "cellIndex",
        "cellStartOffset",
        "noiseCoordinates1",
        "noiseCoordinates2"
      ],
      uniformsNames: [
        "currentCount",
        "timeDelta",
        "emitterWM",
        "lifeTime",
        "color1",
        "color2",
        "sizeRange",
        "scaleRange",
        "gravity",
        "emitPower",
        "direction1",
        "direction2",
        "minEmitBox",
        "maxEmitBox",
        "radius",
        "directionRandomizer",
        "height",
        "coneAngle",
        "stopFactor",
        "angleRange",
        "radiusRange",
        "cellInfos",
        "noiseStrength",
        "limitVelocityDamping"
      ],
      uniformBuffersNames: [],
      samplers: [
        "randomSampler",
        "randomSampler2",
        "sizeGradientSampler",
        "angularSpeedGradientSampler",
        "velocityGradientSampler",
        "limitVelocityGradientSampler",
        "noiseSampler",
        "dragGradientSampler"
      ],
      defines: "",
      fallbacks: null,
      onCompiled: null,
      onError: null,
      indexParameters: null,
      maxSimultaneousLights: 0,
      transformFeedbackVaryings: []
    };
  }
  contextLost() {
    this._updateEffect = undefined;
    this._renderVAO.length = 0;
    this._updateVAO.length = 0;
  }
  isUpdateBufferCreated() {
    return !!this._updateEffect;
  }
  isUpdateBufferReady() {
    return this._updateEffect?.isReady() ?? false;
  }
  createUpdateBuffer(defines) {
    this._updateEffectOptions.transformFeedbackVaryings = ["outPosition"];
    this._updateEffectOptions.transformFeedbackVaryings.push("outAge");
    this._updateEffectOptions.transformFeedbackVaryings.push("outSize");
    this._updateEffectOptions.transformFeedbackVaryings.push("outLife");
    this._updateEffectOptions.transformFeedbackVaryings.push("outSeed");
    this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
    if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {
      this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition");
    }
    if (!this._parent._colorGradientsTexture) {
      this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
    }
    if (!this._parent._isBillboardBased) {
      this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
    }
    if (this._parent.noiseTexture) {
      this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
      this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
    }
    this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
    if (this._parent.isAnimationSheetEnabled) {
      this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
      if (this._parent.spriteRandomStartCell) {
        this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
      }
    }
    this._updateEffectOptions.defines = defines;
    this._updateEffect = this._engine.createEffect("gpuUpdateParticles", this._updateEffectOptions, this._engine);
    return new UniformBufferEffectCommonAccessor(this._updateEffect);
  }
  createVertexBuffers(updateBuffer, renderVertexBuffers) {
    this._updateVAO.push(this._createUpdateVAO(updateBuffer));
    this._renderVAO.push(this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._parent._getWrapper(this._parent.blendMode).effect));
    this._engine.bindArrayBuffer(null);
    this._renderVertexBuffers = renderVertexBuffers;
  }
  createParticleBuffer(data) {
    return data;
  }
  bindDrawBuffers(index, effect2, indexBuffer) {
    if (indexBuffer) {
      this._engine.bindBuffers(this._renderVertexBuffers, indexBuffer, effect2);
    } else {
      this._engine.bindVertexArrayObject(this._renderVAO[index], null);
    }
  }
  preUpdateParticleBuffer() {
    const engine2 = this._engine;
    this._engine.enableEffect(this._updateEffect);
    if (!engine2.setState) {
      throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported");
    }
  }
  updateParticleBuffer(index, targetBuffer, currentActiveCount) {
    this._updateEffect.setTexture("randomSampler", this._parent._randomTexture);
    this._updateEffect.setTexture("randomSampler2", this._parent._randomTexture2);
    if (this._parent._sizeGradientsTexture) {
      this._updateEffect.setTexture("sizeGradientSampler", this._parent._sizeGradientsTexture);
    }
    if (this._parent._angularSpeedGradientsTexture) {
      this._updateEffect.setTexture("angularSpeedGradientSampler", this._parent._angularSpeedGradientsTexture);
    }
    if (this._parent._velocityGradientsTexture) {
      this._updateEffect.setTexture("velocityGradientSampler", this._parent._velocityGradientsTexture);
    }
    if (this._parent._limitVelocityGradientsTexture) {
      this._updateEffect.setTexture("limitVelocityGradientSampler", this._parent._limitVelocityGradientsTexture);
    }
    if (this._parent._dragGradientsTexture) {
      this._updateEffect.setTexture("dragGradientSampler", this._parent._dragGradientsTexture);
    }
    if (this._parent.noiseTexture) {
      this._updateEffect.setTexture("noiseSampler", this._parent.noiseTexture);
    }
    this._engine.bindVertexArrayObject(this._updateVAO[index], null);
    const engine2 = this._engine;
    engine2.bindTransformFeedbackBuffer(targetBuffer.getBuffer());
    engine2.setRasterizerState(false);
    engine2.beginTransformFeedback(true);
    engine2.drawArraysType(3, 0, currentActiveCount);
    engine2.endTransformFeedback();
    engine2.setRasterizerState(true);
    engine2.bindTransformFeedbackBuffer(null);
  }
  releaseBuffers() {}
  releaseVertexBuffers() {
    for (let index = 0;index < this._updateVAO.length; index++) {
      this._engine.releaseVertexArrayObject(this._updateVAO[index]);
    }
    this._updateVAO.length = 0;
    for (let index = 0;index < this._renderVAO.length; index++) {
      this._engine.releaseVertexArrayObject(this._renderVAO[index]);
    }
    this._renderVAO.length = 0;
  }
  _createUpdateVAO(source) {
    const updateVertexBuffers = {};
    updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
    let offset = 3;
    updateVertexBuffers["age"] = source.createVertexBuffer("age", offset, 1);
    offset += 1;
    updateVertexBuffers["size"] = source.createVertexBuffer("size", offset, 3);
    offset += 3;
    updateVertexBuffers["life"] = source.createVertexBuffer("life", offset, 1);
    offset += 1;
    updateVertexBuffers["seed"] = source.createVertexBuffer("seed", offset, 4);
    offset += 4;
    updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
    offset += 3;
    if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {
      updateVertexBuffers["initialPosition"] = source.createVertexBuffer("initialPosition", offset, 3);
      offset += 3;
    }
    if (!this._parent._colorGradientsTexture) {
      updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
      offset += 4;
    }
    if (!this._parent._isBillboardBased) {
      updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
      offset += 3;
    }
    if (this._parent.noiseTexture) {
      updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
      offset += 3;
      updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
      offset += 3;
    }
    if (this._parent._angularSpeedGradientsTexture) {
      updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
      offset += 1;
    } else {
      updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
      offset += 2;
    }
    if (this._parent._isAnimationSheetEnabled) {
      updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
      offset += 1;
      if (this._parent.spriteRandomStartCell) {
        updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
        offset += 1;
      }
    }
    const vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
    this._engine.bindArrayBuffer(null);
    return vao;
  }
}
RegisterClass("BABYLON.WebGL2ParticleSystem", WebGL2ParticleSystem);
// node_modules/@babylonjs/core/Particles/computeShaderParticleSystem.js
init_computeShader();
init_uniformBuffer();
init_typeStore();

// node_modules/@babylonjs/core/ShadersWGSL/gpuUpdateParticles.compute.js
init_shaderStore();
var name398 = "gpuUpdateParticlesComputeShader";
var shader397 = `struct Particle {position : vec3<f32>,
age : f32,
size : vec3<f32>,
life : f32,
seed : vec4<f32>,
direction : vec3<f32>,
dummy0: f32,
#ifdef CUSTOMEMITTER
initialPosition : vec3<f32>,
dummy1: f32,
#endif
#ifndef COLORGRADIENTS
color : vec4<f32>,
#endif
#ifndef BILLBOARD
initialDirection : vec3<f32>,
dummy2: f32,
#endif
#ifdef NOISE
noiseCoordinates1 : vec3<f32>,
dummy3: f32,
noiseCoordinates2 : vec3<f32>,
dummy4: f32,
#endif
#ifdef ANGULARSPEEDGRADIENTS
angle : f32,
#else
angle : vec2<f32>,
#endif
#ifdef ANIMATESHEET
cellIndex : f32,
#ifdef ANIMATESHEETRANDOMSTART
cellStartOffset : f32,
#endif
#endif
};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32,
timeDelta : f32,
stopFactor : f32,
randomTextureSize: i32,
lifeTime : vec2<f32>,
emitPower : vec2<f32>,
#ifndef COLORGRADIENTS
color1 : vec4<f32>,
color2 : vec4<f32>,
#endif
sizeRange : vec2<f32>,
scaleRange : vec4<f32>,
angleRange : vec4<f32>,
gravity : vec3<f32>,
#ifdef LIMITVELOCITYGRADIENTS
limitVelocityDamping : f32,
#endif
#ifdef ANIMATESHEET
cellInfos : vec4<f32>,
#endif
#ifdef NOISE
noiseStrength : vec3<f32>,
#endif
#ifndef LOCAL
emitterWM : mat4x4<f32>,
#endif
#ifdef BOXEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
minEmitBox : vec3<f32>,
maxEmitBox : vec3<f32>,
#endif
#ifdef CONEEMITTER
radius : vec2<f32>,
coneAngle : f32,
height : vec2<f32>,
#ifdef DIRECTEDCONEEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#else
directionRandomizer : f32,
#endif
#endif
#ifdef CYLINDEREMITTER
radius : f32,
height : f32,
radiusRange : f32,
#ifdef DIRECTEDCYLINDEREMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#else
directionRandomizer : f32,
#endif
#endif
#ifdef HEMISPHERICEMITTER
radius : f32,
radiusRange : f32,
directionRandomizer : f32,
#endif
#ifdef POINTEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#endif
#ifdef SPHEREEMITTER
radius : f32,
radiusRange : f32,
#ifdef DIRECTEDSPHEREEMITTER
direction1 : vec3<f32>,
direction2 : vec3<f32>,
#else
directionRandomizer : f32,
#endif
#endif
};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>;
#ifdef SIZEGRADIENTS
@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>;
#endif 
#ifdef ANGULARSPEEDGRADIENTS
@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>;
#endif 
#ifdef VELOCITYGRADIENTS
@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>;
#endif
#ifdef LIMITVELOCITYGRADIENTS
@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>;
#endif
#ifdef DRAGGRADIENTS
@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>;
#endif
#ifdef NOISE
@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>;
#endif
fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;}
fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;}
let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32;
#ifdef SIZEGRADIENTS 
sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r;
#else
sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;
#endif
particlesOut.particles[index].size=vec3<f32>(
sizex,
params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,
params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);
#ifndef COLORGRADIENTS
particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;
#endif
#ifndef ANGULARSPEEDGRADIENTS 
particlesOut.particles[index].angle=vec2<f32>(
params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,
params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);
#else
particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;
#endif 
#if defined(POINTEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;
#elif defined(BOXEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; 
#elif defined(HEMISPHERICEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3);
#elif defined(SPHEREEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ);
#ifdef DIRECTEDSPHEREEMITTER
newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);
#else
newDirection=normalize(newPosition+params.directionRandomizer*randoms3);
#endif
#elif defined(CYLINDEREMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos);
#ifdef DIRECTEDCYLINDEREMITTER
newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;
#else
angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection);
#endif
#elif defined(CONEEMITTER)
let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x;
#ifdef CONEEMITTERSPAWNPOINT
let h : f32=0.0001;
#else
var h : f32=randoms2.y*params.height.y;h=1.-h*h; 
#endif
var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); 
let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);
#ifdef DIRECTEDCONEEMITTER
newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;
#else
if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {newDirection=normalize(newPosition+params.directionRandomizer*randoms3); }
#endif
#elif defined(CUSTOMEMITTER)
newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition;
#else 
newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5));
#endif
let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;
#ifdef LOCAL
particlesOut.particles[index].position=newPosition;
#else
particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz;
#endif
#ifdef CUSTOMEMITTER
particlesOut.particles[index].direction=direction;
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=direction;
#endif
#else
#ifdef LOCAL
let initial : vec3<f32>=newDirection;
#else 
let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz;
#endif
particlesOut.particles[index].direction=initial*power;
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=initial;
#endif
#endif
#ifdef ANIMATESHEET 
particlesOut.particles[index].cellIndex=params.cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
particlesOut.particles[index].cellStartOffset=randoms.a*outLife;
#endif 
#endif
#ifdef NOISE
particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;
#endif
} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life;
#ifdef VELOCITYGRADIENTS
directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;
#endif
#ifdef DRAGGRADIENTS
directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r);
#endif
let position : vec3<f32>=particlesIn.particles[index].position;
#if defined(CUSTOMEMITTER)
particlesOut.particles[index].position=position+(direction-position)*ageGradient; 
particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;
#else
particlesOut.particles[index].position=position+direction*directionScale;
#endif
particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed;
#ifndef COLORGRADIENTS 
particlesOut.particles[index].color=particlesIn.particles[index].color;
#endif
#ifdef SIZEGRADIENTS
particlesOut.particles[index].size=vec3<f32>(
textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r,
particlesIn.particles[index].size.yz);
#else
particlesOut.particles[index].size=particlesIn.particles[index].size;
#endif 
#ifndef BILLBOARD 
particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;
#endif
#ifdef CUSTOMEMITTER
particlesOut.particles[index].direction=direction;
#else
var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta;
#ifdef LIMITVELOCITYGRADIENTS
let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;}
#endif
particlesOut.particles[index].direction=updatedDirection;
#ifdef NOISE
let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;
#endif 
#endif 
#ifdef ANGULARSPEEDGRADIENTS
let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;
#else
let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y);
#endif
#ifdef ANIMATESHEET 
var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x;
#ifdef ANIMATESHEETRANDOMSTART
let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset;
#else
let cellStartOffset : f32=0.;
#endif 
var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);}
else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);}
particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));
#endif
}}
`;
if (!ShaderStore.ShadersStoreWGSL[name398]) {
  ShaderStore.ShadersStoreWGSL[name398] = shader397;
}

// node_modules/@babylonjs/core/Particles/computeShaderParticleSystem.js
class ComputeShaderParticleSystem {
  constructor(parent, engine2) {
    this._bufferComputeShader = [];
    this._renderVertexBuffers = [];
    this.alignDataInBuffer = true;
    this._parent = parent;
    this._engine = engine2;
  }
  contextLost() {
    this._updateComputeShader = undefined;
    this._bufferComputeShader.length = 0;
    this._renderVertexBuffers.length = 0;
  }
  isUpdateBufferCreated() {
    return !!this._updateComputeShader;
  }
  isUpdateBufferReady() {
    return this._updateComputeShader?.isReady() ?? false;
  }
  createUpdateBuffer(defines) {
    const bindingsMapping = {
      params: { group: 0, binding: 0 },
      particlesIn: { group: 0, binding: 1 },
      particlesOut: { group: 0, binding: 2 },
      randomTexture: { group: 0, binding: 3 },
      randomTexture2: { group: 0, binding: 4 }
    };
    if (this._parent._sizeGradientsTexture) {
      bindingsMapping["sizeGradientTexture"] = { group: 1, binding: 1 };
    }
    if (this._parent._angularSpeedGradientsTexture) {
      bindingsMapping["angularSpeedGradientTexture"] = { group: 1, binding: 3 };
    }
    if (this._parent._velocityGradientsTexture) {
      bindingsMapping["velocityGradientTexture"] = { group: 1, binding: 5 };
    }
    if (this._parent._limitVelocityGradientsTexture) {
      bindingsMapping["limitVelocityGradientTexture"] = { group: 1, binding: 7 };
    }
    if (this._parent._dragGradientsTexture) {
      bindingsMapping["dragGradientTexture"] = { group: 1, binding: 9 };
    }
    if (this._parent.noiseTexture) {
      bindingsMapping["noiseTexture"] = { group: 1, binding: 11 };
    }
    this._updateComputeShader = new ComputeShader("updateParticles", this._engine, "gpuUpdateParticles", { bindingsMapping, defines: defines.split(`
`) });
    this._simParamsComputeShader?.dispose();
    this._simParamsComputeShader = new UniformBuffer(this._engine, undefined, undefined, "ComputeShaderParticleSystemUBO");
    this._simParamsComputeShader.addUniform("currentCount", 1);
    this._simParamsComputeShader.addUniform("timeDelta", 1);
    this._simParamsComputeShader.addUniform("stopFactor", 1);
    this._simParamsComputeShader.addUniform("randomTextureSize", 1);
    this._simParamsComputeShader.addUniform("lifeTime", 2);
    this._simParamsComputeShader.addUniform("emitPower", 2);
    if (!this._parent._colorGradientsTexture) {
      this._simParamsComputeShader.addUniform("color1", 4);
      this._simParamsComputeShader.addUniform("color2", 4);
    }
    this._simParamsComputeShader.addUniform("sizeRange", 2);
    this._simParamsComputeShader.addUniform("scaleRange", 4);
    this._simParamsComputeShader.addUniform("angleRange", 4);
    this._simParamsComputeShader.addUniform("gravity", 3);
    if (this._parent._limitVelocityGradientsTexture) {
      this._simParamsComputeShader.addUniform("limitVelocityDamping", 1);
    }
    if (this._parent.isAnimationSheetEnabled) {
      this._simParamsComputeShader.addUniform("cellInfos", 4);
    }
    if (this._parent.noiseTexture) {
      this._simParamsComputeShader.addUniform("noiseStrength", 3);
    }
    if (!this._parent.isLocal) {
      this._simParamsComputeShader.addUniform("emitterWM", 16);
    }
    if (this._parent.particleEmitterType) {
      this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader);
    }
    this._updateComputeShader.setUniformBuffer("params", this._simParamsComputeShader);
    return new UniformBufferEffectCommonAccessor(this._simParamsComputeShader);
  }
  createVertexBuffers(updateBuffer, renderVertexBuffers) {
    this._renderVertexBuffers.push(renderVertexBuffers);
  }
  createParticleBuffer(data) {
    const buffer2 = new StorageBuffer(this._engine, data.length * 4, 3 | 8, "ComputeShaderParticleSystemBuffer");
    buffer2.update(data);
    this._bufferComputeShader.push(buffer2);
    return buffer2.getBuffer();
  }
  bindDrawBuffers(index, effect2, indexBuffer) {
    this._engine.bindBuffers(this._renderVertexBuffers[index], indexBuffer, effect2);
  }
  preUpdateParticleBuffer() {}
  updateParticleBuffer(index, targetBuffer, currentActiveCount) {
    this._simParamsComputeShader.update();
    this._updateComputeShader.setTexture("randomTexture", this._parent._randomTexture, false);
    this._updateComputeShader.setTexture("randomTexture2", this._parent._randomTexture2, false);
    if (this._parent._sizeGradientsTexture) {
      this._updateComputeShader.setTexture("sizeGradientTexture", this._parent._sizeGradientsTexture);
    }
    if (this._parent._angularSpeedGradientsTexture) {
      this._updateComputeShader.setTexture("angularSpeedGradientTexture", this._parent._angularSpeedGradientsTexture);
    }
    if (this._parent._velocityGradientsTexture) {
      this._updateComputeShader.setTexture("velocityGradientTexture", this._parent._velocityGradientsTexture);
    }
    if (this._parent._limitVelocityGradientsTexture) {
      this._updateComputeShader.setTexture("limitVelocityGradientTexture", this._parent._limitVelocityGradientsTexture);
    }
    if (this._parent._dragGradientsTexture) {
      this._updateComputeShader.setTexture("dragGradientTexture", this._parent._dragGradientsTexture);
    }
    if (this._parent.noiseTexture) {
      this._updateComputeShader.setTexture("noiseTexture", this._parent.noiseTexture);
    }
    this._updateComputeShader.setStorageBuffer("particlesIn", this._bufferComputeShader[index]);
    this._updateComputeShader.setStorageBuffer("particlesOut", this._bufferComputeShader[index ^ 1]);
    this._updateComputeShader.dispatch(Math.ceil(currentActiveCount / 64));
  }
  releaseBuffers() {
    for (let i = 0;i < this._bufferComputeShader.length; ++i) {
      this._bufferComputeShader[i].dispose();
    }
    this._bufferComputeShader.length = 0;
    this._simParamsComputeShader?.dispose();
    this._simParamsComputeShader = null;
    this._updateComputeShader = null;
  }
  releaseVertexBuffers() {
    this._renderVertexBuffers.length = 0;
  }
}
RegisterClass("BABYLON.ComputeShaderParticleSystem", ComputeShaderParticleSystem);
// node_modules/@babylonjs/core/Particles/gpuParticleSystem.js
init_observable();
init_math_vector();
init_math_color();
init_buffer();
init_imageProcessingConfiguration();
init_engineStore();
init_abstractEngine();
init_drawWrapper();
init_typeStore();
init_scene();

// node_modules/@babylonjs/core/Shaders/gpuRenderParticles.fragment.js
init_shaderStore();

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration2.js
init_shaderStore();
var name399 = "clipPlaneFragmentDeclaration2";
var shader398 = `#ifdef CLIPPLANE
in float fClipDistance;
#endif
#ifdef CLIPPLANE2
in float fClipDistance2;
#endif
#ifdef CLIPPLANE3
in float fClipDistance3;
#endif
#ifdef CLIPPLANE4
in float fClipDistance4;
#endif
#ifdef CLIPPLANE5
in float fClipDistance5;
#endif
#ifdef CLIPPLANE6
in float fClipDistance6;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name399]) {
  ShaderStore.IncludesShadersStore[name399] = shader398;
}

// node_modules/@babylonjs/core/Shaders/gpuRenderParticles.fragment.js
init_imageProcessingDeclaration2();
init_logDepthDeclaration2();
init_helperFunctions2();
init_imageProcessingFunctions2();
init_fogFragmentDeclaration2();
init_clipPlaneFragment2();
init_logDepthFragment2();
init_fogFragment2();
var name400 = "gpuRenderParticlesPixelShader";
var shader399 = `precision highp float;
#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;
#include<clipPlaneFragmentDeclaration2> 
#include<imageProcessingDeclaration>
#include<logDepthDeclaration>
#include<helperFunctions>
#include<imageProcessingFunctions>
#include<fogFragmentDeclaration>
void main() {
#include<clipPlaneFragment> 
vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;
#ifdef BLENDMULTIPLYMODE
float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);
#endif 
#include<logDepthFragment>
#include<fogFragment>(color,gl_FragColor)
#ifdef IMAGEPROCESSINGPOSTPROCESS
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);
#else
#ifdef IMAGEPROCESSING
gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);
#endif
#endif
}
`;
if (!ShaderStore.ShadersStore[name400]) {
  ShaderStore.ShadersStore[name400] = shader399;
}

// node_modules/@babylonjs/core/Shaders/gpuRenderParticles.vertex.js
init_shaderStore();

// node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration2.js
init_shaderStore();
var name401 = "clipPlaneVertexDeclaration2";
var shader400 = `#ifdef CLIPPLANE
uniform vec4 vClipPlane;out float fClipDistance;
#endif
#ifdef CLIPPLANE2
uniform vec4 vClipPlane2;out float fClipDistance2;
#endif
#ifdef CLIPPLANE3
uniform vec4 vClipPlane3;out float fClipDistance3;
#endif
#ifdef CLIPPLANE4
uniform vec4 vClipPlane4;out float fClipDistance4;
#endif
#ifdef CLIPPLANE5
uniform vec4 vClipPlane5;out float fClipDistance5;
#endif
#ifdef CLIPPLANE6
uniform vec4 vClipPlane6;out float fClipDistance6;
#endif
`;
if (!ShaderStore.IncludesShadersStore[name401]) {
  ShaderStore.IncludesShadersStore[name401] = shader400;
}

// node_modules/@babylonjs/core/Shaders/gpuRenderParticles.vertex.js
init_fogVertexDeclaration2();
init_logDepthDeclaration2();
init_clipPlaneVertex2();
init_fogVertex2();
init_logDepthVertex2();
var name402 = "gpuRenderParticlesVertexShader";
var shader401 = `precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;
#ifdef LOCAL
uniform mat4 emitterWM;
#endif
attribute vec3 position;attribute float age;attribute float life;attribute vec3 size;
#ifndef BILLBOARD
attribute vec3 initialDirection;
#endif
#ifdef BILLBOARDSTRETCHED
attribute vec3 direction;
#endif
attribute float angle;
#ifdef ANIMATESHEET
attribute float cellIndex;
#endif
attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;
#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)
uniform mat4 invView;
#endif
#include<clipPlaneVertexDeclaration2>
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
#ifdef COLORGRADIENTS
uniform sampler2D colorGradientSampler;
#else
uniform vec4 colorDead;attribute vec4 color;
#endif
#ifdef ANIMATESHEET
uniform vec3 sheetInfos;
#endif
#ifdef BILLBOARD
uniform vec3 eyePosition;
#endif
vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#ifdef BILLBOARDSTRETCHED
vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;
#ifdef LOCAL
return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;
#else
return (position+worldOffset)+alignedCorner;
#endif
}
#endif
void main() {
#ifdef ANIMATESHEET
float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;
#else
vUV=uv;
#endif
float ratio=min(1.0,age/life);
#ifdef COLORGRADIENTS
vColor=texture2D(colorGradientSampler,vec2(ratio,0));
#else
vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);
#endif
vec2 cornerPos=(offset-translationPivot)*size.yz*size.x;
#ifdef BILLBOARD
vec4 rotatedCorner;rotatedCorner.w=0.;
#ifdef BILLBOARDY
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));
#elif defined(BILLBOARDSTRETCHED)
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));
#else
rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;
#ifdef LOCAL
vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;
#else
vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;
#endif
vPositionW=(invView*viewPosition).xyz;
#endif
#else
vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);
#endif
gl_Position=projection*viewPosition;
#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)
vec4 worldPos=vec4(vPositionW,1.0);
#endif
#include<clipPlaneVertex>
#include<fogVertex>
#include<logDepthVertex>
}`;
if (!ShaderStore.ShadersStore[name402]) {
  ShaderStore.ShadersStore[name402] = shader401;
}

// node_modules/@babylonjs/core/Particles/gpuParticleSystem.js
init_materialHelper_functions();
class GPUParticleSystem extends BaseParticleSystem {
  static get IsSupported() {
    if (!EngineStore.LastCreatedEngine) {
      return false;
    }
    const caps = EngineStore.LastCreatedEngine.getCaps();
    return caps.supportTransformFeedbacks || caps.supportComputeShaders;
  }
  _createIndexBuffer() {
    this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]), undefined, "GPUParticleSystemLinesIndexBuffer");
  }
  getCapacity() {
    return this._capacity;
  }
  get maxActiveParticleCount() {
    return this._maxActiveParticleCount;
  }
  set maxActiveParticleCount(value) {
    this._maxActiveParticleCount = Math.min(value, this._capacity);
  }
  get activeParticleCount() {
    return this.maxActiveParticleCount;
  }
  set activeParticleCount(value) {
    this.maxActiveParticleCount = value;
  }
  createPointEmitter(direction1, direction2) {
    const particleEmitter = CreatePointEmitter(direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createHemisphericEmitter(radius = 1, radiusRange = 1) {
    const particleEmitter = CreateHemisphericEmitter(radius, radiusRange);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createSphereEmitter(radius = 1, radiusRange = 1) {
    const particleEmitter = CreateSphereEmitter(radius, radiusRange);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {
    const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createConeEmitter(radius = 1, angle = Math.PI / 4) {
    const particleEmitter = CreateConeEmitter(radius, angle);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) {
    const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2);
    this.particleEmitterType = particleEmitter;
    return particleEmitter;
  }
  createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {
    const particleEmitter = new BoxParticleEmitter;
    this.particleEmitterType = particleEmitter;
    this.direction1 = direction1;
    this.direction2 = direction2;
    this.minEmitBox = minEmitBox;
    this.maxEmitBox = maxEmitBox;
    return particleEmitter;
  }
  isReady() {
    if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady() || this._rebuildingAfterContextLost) {
      return false;
    }
    if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
      if (!this._getWrapper(this.blendMode).effect.isReady()) {
        return false;
      }
    } else {
      if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {
        return false;
      }
      if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {
        return false;
      }
    }
    if (!this._platform.isUpdateBufferCreated()) {
      this._recreateUpdateEffect();
      return false;
    }
    return this._platform.isUpdateBufferReady();
  }
  isStarted() {
    return this._started;
  }
  isStopped() {
    return this._stopped;
  }
  isStopping() {
    return false;
  }
  getActiveCount() {
    return this._currentActiveCount;
  }
  start(delay = this.startDelay) {
    if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
      throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
    }
    if (delay) {
      setTimeout(() => {
        this.start(0);
      }, delay);
      return;
    }
    this._started = true;
    this._stopped = false;
    this._preWarmDone = false;
    if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {
      this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
    }
  }
  stop() {
    if (this._stopped) {
      return;
    }
    this.onStoppedObservable.notifyObservers(this);
    this._stopped = true;
  }
  reset() {
    this._releaseBuffers();
    this._platform.releaseVertexBuffers();
    this._currentActiveCount = 0;
    this._targetIndex = 0;
  }
  getClassName() {
    return "GPUParticleSystem";
  }
  getCustomEffect(blendMode = 0) {
    return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect;
  }
  _getCustomDrawWrapper(blendMode = 0) {
    return this._customWrappers[blendMode] ?? this._customWrappers[0];
  }
  setCustomEffect(effect2, blendMode = 0) {
    this._customWrappers[blendMode] = new DrawWrapper(this._engine);
    this._customWrappers[blendMode].effect = effect2;
  }
  get onBeforeDrawParticlesObservable() {
    if (!this._onBeforeDrawParticlesObservable) {
      this._onBeforeDrawParticlesObservable = new Observable;
    }
    return this._onBeforeDrawParticlesObservable;
  }
  get vertexShaderName() {
    return "gpuRenderParticles";
  }
  get vertexBuffers() {
    return this._renderVertexBuffers[this._targetIndex ^ 1];
  }
  get indexBuffer() {
    return null;
  }
  _removeGradientAndTexture(gradient, gradients2, texture2) {
    super._removeGradientAndTexture(gradient, gradients2, texture2);
    this._releaseBuffers();
    return this;
  }
  addColorGradient(gradient, color1) {
    if (!this._colorGradients) {
      this._colorGradients = [];
    }
    const colorGradient = new ColorGradient(gradient, color1);
    this._colorGradients.push(colorGradient);
    this._refreshColorGradient(true);
    this._releaseBuffers();
    return this;
  }
  _refreshColorGradient(reorder = false) {
    if (this._colorGradients) {
      if (reorder) {
        this._colorGradients.sort((a, b) => {
          if (a.gradient < b.gradient) {
            return -1;
          } else if (a.gradient > b.gradient) {
            return 1;
          }
          return 0;
        });
      }
      if (this._colorGradientsTexture) {
        this._colorGradientsTexture.dispose();
        this._colorGradientsTexture = null;
      }
    }
  }
  forceRefreshGradients() {
    this._refreshColorGradient();
    this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture");
    this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
    this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture");
    this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
    this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture");
    this.reset();
  }
  removeColorGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
    this._colorGradientsTexture = null;
    return this;
  }
  resetDrawCache() {
    for (const blendMode in this._drawWrappers) {
      const drawWrapper2 = this._drawWrappers[blendMode];
      drawWrapper2.drawContext?.reset();
    }
  }
  _addFactorGradient(factorGradients, gradient, factor) {
    const valueGradient = new FactorGradient(gradient, factor);
    factorGradients.push(valueGradient);
    this._releaseBuffers();
  }
  addSizeGradient(gradient, factor) {
    if (!this._sizeGradients) {
      this._sizeGradients = [];
    }
    this._addFactorGradient(this._sizeGradients, gradient, factor);
    this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true);
    this._releaseBuffers();
    return this;
  }
  removeSizeGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
    this._sizeGradientsTexture = null;
    return this;
  }
  _refreshFactorGradient(factorGradients, textureName, reorder = false) {
    if (!factorGradients) {
      return;
    }
    if (reorder) {
      factorGradients.sort((a, b) => {
        if (a.gradient < b.gradient) {
          return -1;
        } else if (a.gradient > b.gradient) {
          return 1;
        }
        return 0;
      });
    }
    const that = this;
    if (that[textureName]) {
      that[textureName].dispose();
      that[textureName] = null;
    }
  }
  addAngularSpeedGradient(gradient, factor) {
    if (!this._angularSpeedGradients) {
      this._angularSpeedGradients = [];
    }
    this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
    this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true);
    this._releaseBuffers();
    return this;
  }
  removeAngularSpeedGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
    this._angularSpeedGradientsTexture = null;
    return this;
  }
  addVelocityGradient(gradient, factor) {
    if (!this._velocityGradients) {
      this._velocityGradients = [];
    }
    this._addFactorGradient(this._velocityGradients, gradient, factor);
    this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true);
    this._releaseBuffers();
    return this;
  }
  removeVelocityGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
    this._velocityGradientsTexture = null;
    return this;
  }
  addLimitVelocityGradient(gradient, factor) {
    if (!this._limitVelocityGradients) {
      this._limitVelocityGradients = [];
    }
    this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
    this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true);
    this._releaseBuffers();
    return this;
  }
  removeLimitVelocityGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
    this._limitVelocityGradientsTexture = null;
    return this;
  }
  addDragGradient(gradient, factor) {
    if (!this._dragGradients) {
      this._dragGradients = [];
    }
    this._addFactorGradient(this._dragGradients, gradient, factor);
    this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true);
    this._releaseBuffers();
    return this;
  }
  removeDragGradient(gradient) {
    this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
    this._dragGradientsTexture = null;
    return this;
  }
  addEmitRateGradient() {
    return this;
  }
  removeEmitRateGradient() {
    return this;
  }
  addStartSizeGradient() {
    return this;
  }
  removeStartSizeGradient() {
    return this;
  }
  addColorRemapGradient() {
    return this;
  }
  removeColorRemapGradient() {
    return this;
  }
  addAlphaRemapGradient() {
    return this;
  }
  removeAlphaRemapGradient() {
    return this;
  }
  addRampGradient() {
    return this;
  }
  removeRampGradient() {
    return this;
  }
  getRampGradients() {
    return null;
  }
  get useRampGradients() {
    return false;
  }
  set useRampGradients(value) {}
  addLifeTimeGradient() {
    return this;
  }
  removeLifeTimeGradient() {
    return this;
  }
  constructor(name403, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) {
    super(name403);
    this.layerMask = 268435455;
    this._accumulatedCount = 0;
    this._renderVertexBuffers = [];
    this._targetIndex = 0;
    this._currentRenderId = -1;
    this._currentRenderingCameraUniqueId = -1;
    this._started = false;
    this._stopped = false;
    this._timeDelta = 0;
    this.updateInAnimate = false;
    this._actualFrame = 0;
    this._rawTextureWidth = 256;
    this._rebuildingAfterContextLost = false;
    this.onDisposeObservable = new Observable;
    this.onStoppedObservable = new Observable;
    this.forceDepthWrite = false;
    this._preWarmDone = false;
    this.isLocal = false;
    this.isGPU = true;
    this._onBeforeDrawParticlesObservable = null;
    if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") {
      this._scene = sceneOrEngine || EngineStore.LastCreatedScene;
      this._engine = this._scene.getEngine();
      this.uniqueId = this._scene.getUniqueId();
      this._scene.particleSystems.push(this);
    } else {
      this._engine = sceneOrEngine;
      this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);
    }
    if (this._engine.getCaps().supportComputeShaders) {
      if (!GetClass("BABYLON.ComputeShaderParticleSystem")) {
        throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");
      }
      this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(this, this._engine);
    } else {
      if (!GetClass("BABYLON.WebGL2ParticleSystem")) {
        throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");
      }
      this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(this, this._engine);
    }
    this._customWrappers = { 0: new DrawWrapper(this._engine) };
    this._customWrappers[0].effect = customEffect;
    this._drawWrappers = { 0: new DrawWrapper(this._engine) };
    if (this._drawWrappers[0].drawContext) {
      this._drawWrappers[0].drawContext.useInstancing = true;
    }
    this._createIndexBuffer();
    this._attachImageProcessingConfiguration(null);
    options = options ?? {};
    if (!options.randomTextureSize) {
      delete options.randomTextureSize;
    }
    const fullOptions = {
      capacity: 50000,
      randomTextureSize: this._engine.getCaps().maxTextureSize,
      ...options
    };
    const optionsAsNumber = options;
    if (isFinite(optionsAsNumber)) {
      fullOptions.capacity = optionsAsNumber;
    }
    this._capacity = fullOptions.capacity;
    this._maxActiveParticleCount = fullOptions.capacity;
    this._currentActiveCount = 0;
    this._isAnimationSheetEnabled = isAnimationSheetEnabled;
    this.particleEmitterType = new BoxParticleEmitter;
    const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
    let d = [];
    for (let i = 0;i < maxTextureSize; ++i) {
      d.push(Math.random());
      d.push(Math.random());
      d.push(Math.random());
      d.push(Math.random());
    }
    this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);
    this._randomTexture.name = "GPUParticleSystem_random1";
    this._randomTexture.wrapU = 1;
    this._randomTexture.wrapV = 1;
    d = [];
    for (let i = 0;i < maxTextureSize; ++i) {
      d.push(Math.random());
      d.push(Math.random());
      d.push(Math.random());
      d.push(Math.random());
    }
    this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);
    this._randomTexture2.name = "GPUParticleSystem_random2";
    this._randomTexture2.wrapU = 1;
    this._randomTexture2.wrapV = 1;
    this._randomTextureSize = maxTextureSize;
  }
  _reset() {
    this._releaseBuffers();
  }
  _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) {
    const renderVertexBuffers = {};
    renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
    let offset = 3;
    renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true);
    offset += 1;
    renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true);
    offset += 3;
    renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true);
    offset += 1;
    offset += 4;
    if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
      renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
    }
    offset += 3;
    if (this._platform.alignDataInBuffer) {
      offset += 1;
    }
    if (this.particleEmitterType instanceof CustomParticleEmitter) {
      offset += 3;
      if (this._platform.alignDataInBuffer) {
        offset += 1;
      }
    }
    if (!this._colorGradientsTexture) {
      renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
      offset += 4;
    }
    if (!this._isBillboardBased) {
      renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
      offset += 3;
      if (this._platform.alignDataInBuffer) {
        offset += 1;
      }
    }
    if (this.noiseTexture) {
      renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
      offset += 3;
      if (this._platform.alignDataInBuffer) {
        offset += 1;
      }
      renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
      offset += 3;
      if (this._platform.alignDataInBuffer) {
        offset += 1;
      }
    }
    renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
    if (this._angularSpeedGradientsTexture) {
      offset++;
    } else {
      offset += 2;
    }
    if (this._isAnimationSheetEnabled) {
      renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
      offset += 1;
      if (this.spriteRandomStartCell) {
        renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
        offset += 1;
      }
    }
    renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
    renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
    this._renderVertexBuffers.push(renderVertexBuffers);
    this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers);
    this.resetDrawCache();
  }
  _initialize(force = false) {
    if (this._buffer0 && !force) {
      return;
    }
    const engine2 = this._engine;
    const data = [];
    this._attributesStrideSize = 21;
    this._targetIndex = 0;
    if (this._platform.alignDataInBuffer) {
      this._attributesStrideSize += 1;
    }
    if (this.particleEmitterType instanceof CustomParticleEmitter) {
      this._attributesStrideSize += 3;
      if (this._platform.alignDataInBuffer) {
        this._attributesStrideSize += 1;
      }
    }
    if (!this.isBillboardBased) {
      this._attributesStrideSize += 3;
      if (this._platform.alignDataInBuffer) {
        this._attributesStrideSize += 1;
      }
    }
    if (this._colorGradientsTexture) {
      this._attributesStrideSize -= 4;
    }
    if (this._angularSpeedGradientsTexture) {
      this._attributesStrideSize -= 1;
    }
    if (this._isAnimationSheetEnabled) {
      this._attributesStrideSize += 1;
      if (this.spriteRandomStartCell) {
        this._attributesStrideSize += 1;
      }
    }
    if (this.noiseTexture) {
      this._attributesStrideSize += 6;
      if (this._platform.alignDataInBuffer) {
        this._attributesStrideSize += 2;
      }
    }
    if (this._platform.alignDataInBuffer) {
      this._attributesStrideSize += 3 - (this._attributesStrideSize + 3 & 3);
    }
    const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;
    const tmpVector = TmpVectors.Vector3[0];
    let offset = 0;
    for (let particleIndex = 0;particleIndex < this._capacity; particleIndex++) {
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(0);
      data.push(Math.random());
      data.push(Math.random());
      data.push(Math.random());
      data.push(Math.random());
      if (usingCustomEmitter) {
        this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector);
        data.push(tmpVector.x);
        data.push(tmpVector.y);
        data.push(tmpVector.z);
      } else {
        data.push(0);
        data.push(0);
        data.push(0);
      }
      if (this._platform.alignDataInBuffer) {
        data.push(0);
      }
      offset += 16;
      if (usingCustomEmitter) {
        this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector);
        data.push(tmpVector.x);
        data.push(tmpVector.y);
        data.push(tmpVector.z);
        if (this._platform.alignDataInBuffer) {
          data.push(0);
        }
        offset += 4;
      }
      if (!this._colorGradientsTexture) {
        data.push(0);
        data.push(0);
        data.push(0);
        data.push(0);
        offset += 4;
      }
      if (!this.isBillboardBased) {
        data.push(0);
        data.push(0);
        data.push(0);
        if (this._platform.alignDataInBuffer) {
          data.push(0);
        }
        offset += 4;
      }
      if (this.noiseTexture) {
        data.push(Math.random());
        data.push(Math.random());
        data.push(Math.random());
        if (this._platform.alignDataInBuffer) {
          data.push(0);
        }
        data.push(Math.random());
        data.push(Math.random());
        data.push(Math.random());
        if (this._platform.alignDataInBuffer) {
          data.push(0);
        }
        offset += 8;
      }
      data.push(0);
      offset += 1;
      if (!this._angularSpeedGradientsTexture) {
        data.push(0);
        offset += 1;
      }
      if (this._isAnimationSheetEnabled) {
        data.push(0);
        offset += 1;
        if (this.spriteRandomStartCell) {
          data.push(0);
          offset += 1;
        }
      }
      if (this._platform.alignDataInBuffer) {
        let numDummies = 3 - (offset + 3 & 3);
        offset += numDummies;
        while (numDummies-- > 0) {
          data.push(0);
        }
      }
    }
    const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]);
    const bufferData1 = this._platform.createParticleBuffer(data);
    const bufferData2 = this._platform.createParticleBuffer(data);
    this._buffer0 = new Buffer2(engine2, bufferData1, false, this._attributesStrideSize);
    this._buffer1 = new Buffer2(engine2, bufferData2, false, this._attributesStrideSize);
    this._spriteBuffer = new Buffer2(engine2, spriteData, false, 4);
    this._renderVertexBuffers = [];
    this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer);
    this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer);
    this._sourceBuffer = this._buffer0;
    this._targetBuffer = this._buffer1;
  }
  _recreateUpdateEffect() {
    this._createColorGradientTexture();
    this._createSizeGradientTexture();
    this._createAngularSpeedGradientTexture();
    this._createVelocityGradientTexture();
    this._createLimitVelocityGradientTexture();
    this._createDragGradientTexture();
    let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
    if (this._isBillboardBased) {
      defines += `
#define BILLBOARD`;
    }
    if (this._colorGradientsTexture) {
      defines += `
#define COLORGRADIENTS`;
    }
    if (this._sizeGradientsTexture) {
      defines += `
#define SIZEGRADIENTS`;
    }
    if (this._angularSpeedGradientsTexture) {
      defines += `
#define ANGULARSPEEDGRADIENTS`;
    }
    if (this._velocityGradientsTexture) {
      defines += `
#define VELOCITYGRADIENTS`;
    }
    if (this._limitVelocityGradientsTexture) {
      defines += `
#define LIMITVELOCITYGRADIENTS`;
    }
    if (this._dragGradientsTexture) {
      defines += `
#define DRAGGRADIENTS`;
    }
    if (this.isAnimationSheetEnabled) {
      defines += `
#define ANIMATESHEET`;
      if (this.spriteRandomStartCell) {
        defines += `
#define ANIMATESHEETRANDOMSTART`;
      }
    }
    if (this.noiseTexture) {
      defines += `
#define NOISE`;
    }
    if (this.isLocal) {
      defines += `
#define LOCAL`;
    }
    if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) {
      return this._platform.isUpdateBufferReady();
    }
    this._cachedUpdateDefines = defines;
    this._updateBuffer = this._platform.createUpdateBuffer(defines);
    return this._platform.isUpdateBufferReady();
  }
  _getWrapper(blendMode) {
    const customWrapper = this._getCustomDrawWrapper(blendMode);
    if (customWrapper?.effect) {
      return customWrapper;
    }
    const defines = [];
    this.fillDefines(defines, blendMode);
    let drawWrapper2 = this._drawWrappers[blendMode];
    if (!drawWrapper2) {
      drawWrapper2 = new DrawWrapper(this._engine);
      if (drawWrapper2.drawContext) {
        drawWrapper2.drawContext.useInstancing = true;
      }
      this._drawWrappers[blendMode] = drawWrapper2;
    }
    const join6 = defines.join(`
`);
    if (drawWrapper2.defines !== join6) {
      const attributes = [];
      const uniforms = [];
      const samplers = [];
      this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers);
      drawWrapper2.setEffect(this._engine.createEffect("gpuRenderParticles", attributes, uniforms, samplers, join6), join6);
    }
    return drawWrapper2;
  }
  static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) {
    const attributeNamesOrOptions = [VertexBuffer.PositionKind, "age", "life", "size", "angle"];
    if (!hasColorGradients) {
      attributeNamesOrOptions.push(VertexBuffer.ColorKind);
    }
    if (isAnimationSheetEnabled) {
      attributeNamesOrOptions.push("cellIndex");
    }
    if (!isBillboardBased) {
      attributeNamesOrOptions.push("initialDirection");
    }
    if (isBillboardStretched) {
      attributeNamesOrOptions.push("direction");
    }
    attributeNamesOrOptions.push("offset", VertexBuffer.UVKind);
    return attributeNamesOrOptions;
  }
  static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) {
    const effectCreationOption = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "translationPivot", "eyePosition"];
    addClipPlaneUniforms(effectCreationOption);
    if (isAnimationSheetEnabled) {
      effectCreationOption.push("sheetInfos");
    }
    if (useLogarithmicDepth) {
      effectCreationOption.push("logarithmicDepthConstant");
    }
    if (applyFog) {
      effectCreationOption.push("vFogInfos");
      effectCreationOption.push("vFogColor");
    }
    return effectCreationOption;
  }
  fillDefines(defines, blendMode = 0, fillImageProcessing = true) {
    if (this._scene) {
      prepareStringDefinesForClipPlanes(this, this._scene, defines);
      if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE) {
        defines.push("#define FOG");
      }
    }
    if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
      defines.push("#define BLENDMULTIPLYMODE");
    }
    if (this.isLocal) {
      defines.push("#define LOCAL");
    }
    if (this.useLogarithmicDepth) {
      defines.push("#define LOGARITHMICDEPTH");
    }
    if (this._isBillboardBased) {
      defines.push("#define BILLBOARD");
      switch (this.billboardMode) {
        case ParticleSystem.BILLBOARDMODE_Y:
          defines.push("#define BILLBOARDY");
          break;
        case ParticleSystem.BILLBOARDMODE_STRETCHED:
          defines.push("#define BILLBOARDSTRETCHED");
          break;
        case ParticleSystem.BILLBOARDMODE_ALL:
          defines.push("#define BILLBOARDMODE_ALL");
          break;
        default:
          break;
      }
    }
    if (this._colorGradientsTexture) {
      defines.push("#define COLORGRADIENTS");
    }
    if (this.isAnimationSheetEnabled) {
      defines.push("#define ANIMATESHEET");
    }
    if (fillImageProcessing && this._imageProcessingConfiguration) {
      this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
      defines.push("" + this._imageProcessingConfigurationDefines.toString());
    }
  }
  fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {
    attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED));
    uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog));
    samplers.push("diffuseSampler", "colorGradientSampler");
    if (this._imageProcessingConfiguration) {
      ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
      ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
    }
  }
  animate(preWarm = false) {
    this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1);
    this._actualFrame += this._timeDelta;
    if (!this._stopped) {
      if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
        this.stop();
      }
    }
    if (this.updateInAnimate) {
      this._update();
    }
  }
  _createFactorGradientTexture(factorGradients, textureName) {
    const texture2 = this[textureName];
    if (!factorGradients || !factorGradients.length || texture2) {
      return;
    }
    const data = new Float32Array(this._rawTextureWidth);
    for (let x = 0;x < this._rawTextureWidth; x++) {
      const ratio = x / this._rawTextureWidth;
      GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {
        data[x] = Lerp(currentGradient.factor1, nextGradient.factor1, scale);
      });
    }
    this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1);
    this[textureName].name = textureName.substring(1);
  }
  _createSizeGradientTexture() {
    this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  }
  _createAngularSpeedGradientTexture() {
    this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  }
  _createVelocityGradientTexture() {
    this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  }
  _createLimitVelocityGradientTexture() {
    this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  }
  _createDragGradientTexture() {
    this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  }
  _createColorGradientTexture() {
    if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
      return;
    }
    const data = new Uint8Array(this._rawTextureWidth * 4);
    const tmpColor = TmpColors.Color4[0];
    for (let x = 0;x < this._rawTextureWidth; x++) {
      const ratio = x / this._rawTextureWidth;
      GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {
        Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
        data[x * 4] = tmpColor.r * 255;
        data[x * 4 + 1] = tmpColor.g * 255;
        data[x * 4 + 2] = tmpColor.b * 255;
        data[x * 4 + 3] = tmpColor.a * 255;
      });
    }
    this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);
    this._colorGradientsTexture.name = "colorGradients";
  }
  _render(blendMode, emitterWM) {
    const drawWrapper2 = this._getWrapper(blendMode);
    const effect2 = drawWrapper2.effect;
    this._engine.enableEffect(drawWrapper2);
    const viewMatrix = this._scene?.getViewMatrix() || Matrix.IdentityReadOnly;
    effect2.setMatrix("view", viewMatrix);
    effect2.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix());
    effect2.setTexture("diffuseSampler", this.particleTexture);
    effect2.setVector2("translationPivot", this.translationPivot);
    effect2.setVector3("worldOffset", this.worldOffset);
    if (this.isLocal) {
      effect2.setMatrix("emitterWM", emitterWM);
    }
    if (this._colorGradientsTexture) {
      effect2.setTexture("colorGradientSampler", this._colorGradientsTexture);
    } else {
      effect2.setDirectColor4("colorDead", this.colorDead);
    }
    if (this._isAnimationSheetEnabled && this.particleTexture) {
      const baseSize = this.particleTexture.getBaseSize();
      effect2.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
    }
    if (this._isBillboardBased && this._scene) {
      const camera2 = this._scene.activeCamera;
      effect2.setVector3("eyePosition", camera2.globalPosition);
    }
    const defines = effect2.defines;
    if (this._scene) {
      bindClipPlane(effect2, this, this._scene);
      if (this.applyFog) {
        BindFogParameters(this._scene, undefined, effect2);
      }
    }
    if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) {
      const invView = viewMatrix.clone();
      invView.invert();
      effect2.setMatrix("invView", invView);
    }
    if (this.useLogarithmicDepth && this._scene) {
      BindLogDepth(defines, effect2, this._scene);
    }
    if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
      this._imageProcessingConfiguration.bind(effect2);
    }
    switch (blendMode) {
      case ParticleSystem.BLENDMODE_ADD:
        this._engine.setAlphaMode(1);
        break;
      case ParticleSystem.BLENDMODE_ONEONE:
        this._engine.setAlphaMode(6);
        break;
      case ParticleSystem.BLENDMODE_STANDARD:
        this._engine.setAlphaMode(2);
        break;
      case ParticleSystem.BLENDMODE_MULTIPLY:
        this._engine.setAlphaMode(4);
        break;
    }
    this._platform.bindDrawBuffers(this._targetIndex, effect2, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null);
    if (this._onBeforeDrawParticlesObservable) {
      this._onBeforeDrawParticlesObservable.notifyObservers(effect2);
    }
    if (this._scene?.forceWireframe) {
      this._engine.drawElementsType(6, 0, 10, this._currentActiveCount);
    } else {
      this._engine.drawArraysType(7, 0, 4, this._currentActiveCount);
    }
    this._engine.setAlphaMode(0);
    if (this._scene?.forceWireframe) {
      this._engine.unbindInstanceAttributes();
    }
    return this._currentActiveCount;
  }
  _update(emitterWM) {
    if (!this.emitter || !this._targetBuffer) {
      return;
    }
    if (!this._recreateUpdateEffect() || this._rebuildingAfterContextLost) {
      return;
    }
    if (!emitterWM) {
      if (this.emitter.position) {
        const emitterMesh = this.emitter;
        emitterWM = emitterMesh.getWorldMatrix();
      } else {
        const emitterPosition = this.emitter;
        emitterWM = TmpVectors.Matrix[0];
        Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);
      }
    }
    const engine2 = this._engine;
    const depthWriteState = engine2.getDepthWrite();
    engine2.setDepthWrite(false);
    this._platform.preUpdateParticleBuffer();
    this._updateBuffer.setFloat("currentCount", this._currentActiveCount);
    this._updateBuffer.setFloat("timeDelta", this._timeDelta);
    this._updateBuffer.setFloat("stopFactor", this._stopped ? 0 : 1);
    this._updateBuffer.setInt("randomTextureSize", this._randomTextureSize);
    this._updateBuffer.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
    this._updateBuffer.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
    if (!this._colorGradientsTexture) {
      this._updateBuffer.setDirectColor4("color1", this.color1);
      this._updateBuffer.setDirectColor4("color2", this.color2);
    }
    this._updateBuffer.setFloat2("sizeRange", this.minSize, this.maxSize);
    this._updateBuffer.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
    this._updateBuffer.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
    this._updateBuffer.setVector3("gravity", this.gravity);
    if (this._limitVelocityGradientsTexture) {
      this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping);
    }
    if (this.particleEmitterType) {
      this.particleEmitterType.applyToShader(this._updateBuffer);
    }
    if (this._isAnimationSheetEnabled) {
      this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0);
    }
    if (this.noiseTexture) {
      this._updateBuffer.setVector3("noiseStrength", this.noiseStrength);
    }
    if (!this.isLocal) {
      this._updateBuffer.setMatrix("emitterWM", emitterWM);
    }
    this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);
    this._targetIndex++;
    if (this._targetIndex === 2) {
      this._targetIndex = 0;
    }
    const tmpBuffer = this._sourceBuffer;
    this._sourceBuffer = this._targetBuffer;
    this._targetBuffer = tmpBuffer;
    engine2.setDepthWrite(depthWriteState);
  }
  render(preWarm = false, forceUpdateOnly = false) {
    if (!this._started) {
      return 0;
    }
    if (!this.isReady()) {
      return 0;
    }
    if (!preWarm && this._scene) {
      if (!this._preWarmDone && this.preWarmCycles) {
        for (let index = 0;index < this.preWarmCycles; index++) {
          this.animate(true);
          this.render(true, true);
        }
        this._preWarmDone = true;
      }
      if (this._currentRenderId === this._scene.getRenderId() && (!this._scene.activeCamera || this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId)) {
        return 0;
      }
      this._currentRenderId = this._scene.getRenderId();
      if (this._scene.activeCamera) {
        this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId;
      }
    }
    this._initialize();
    if (this.manualEmitCount > -1) {
      this._accumulatedCount += this.manualEmitCount;
      this.manualEmitCount = 0;
    } else {
      this._accumulatedCount += this.emitRate * this._timeDelta;
    }
    if (this._accumulatedCount >= 1) {
      const intPart = this._accumulatedCount | 0;
      this._accumulatedCount -= intPart;
      this._currentActiveCount += intPart;
    }
    this._currentActiveCount = Math.min(this._maxActiveParticleCount, this._currentActiveCount);
    if (!this._currentActiveCount) {
      return 0;
    }
    let emitterWM;
    if (this.emitter.position) {
      const emitterMesh = this.emitter;
      emitterWM = emitterMesh.getWorldMatrix();
    } else {
      const emitterPosition = this.emitter;
      emitterWM = TmpVectors.Matrix[0];
      Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);
    }
    const engine2 = this._engine;
    if (!this.updateInAnimate) {
      this._update(emitterWM);
    }
    let outparticles = 0;
    if (!preWarm && !forceUpdateOnly) {
      engine2.setState(false);
      if (this.forceDepthWrite) {
        engine2.setDepthWrite(true);
      }
      if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
        outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM);
      } else {
        outparticles = this._render(this.blendMode, emitterWM);
      }
      this._engine.setAlphaMode(0);
    }
    return outparticles;
  }
  rebuild() {
    const checkUpdateEffect = () => {
      if (!this._recreateUpdateEffect() || !this._platform.isUpdateBufferReady()) {
        setTimeout(checkUpdateEffect, 10);
      } else {
        this._initialize(true);
        this._rebuildingAfterContextLost = false;
      }
    };
    this._createIndexBuffer();
    this._cachedUpdateDefines = "";
    this._platform.contextLost();
    this._rebuildingAfterContextLost = true;
    checkUpdateEffect();
  }
  _releaseBuffers() {
    if (this._buffer0) {
      this._buffer0.dispose();
      this._buffer0 = null;
    }
    if (this._buffer1) {
      this._buffer1.dispose();
      this._buffer1 = null;
    }
    if (this._spriteBuffer) {
      this._spriteBuffer.dispose();
      this._spriteBuffer = null;
    }
    this._platform.releaseBuffers();
  }
  dispose(disposeTexture = true) {
    for (const blendMode in this._drawWrappers) {
      const drawWrapper2 = this._drawWrappers[blendMode];
      drawWrapper2.dispose();
    }
    this._drawWrappers = {};
    if (this._scene) {
      const index = this._scene.particleSystems.indexOf(this);
      if (index > -1) {
        this._scene.particleSystems.splice(index, 1);
      }
    }
    this._releaseBuffers();
    this._platform.releaseVertexBuffers();
    for (let i = 0;i < this._renderVertexBuffers.length; ++i) {
      const rvb = this._renderVertexBuffers[i];
      for (const key in rvb) {
        rvb[key].dispose();
      }
    }
    this._renderVertexBuffers = [];
    if (this._colorGradientsTexture) {
      this._colorGradientsTexture.dispose();
      this._colorGradientsTexture = null;
    }
    if (this._sizeGradientsTexture) {
      this._sizeGradientsTexture.dispose();
      this._sizeGradientsTexture = null;
    }
    if (this._angularSpeedGradientsTexture) {
      this._angularSpeedGradientsTexture.dispose();
      this._angularSpeedGradientsTexture = null;
    }
    if (this._velocityGradientsTexture) {
      this._velocityGradientsTexture.dispose();
      this._velocityGradientsTexture = null;
    }
    if (this._limitVelocityGradientsTexture) {
      this._limitVelocityGradientsTexture.dispose();
      this._limitVelocityGradientsTexture = null;
    }
    if (this._dragGradientsTexture) {
      this._dragGradientsTexture.dispose();
      this._dragGradientsTexture = null;
    }
    if (this._randomTexture) {
      this._randomTexture.dispose();
      this._randomTexture = null;
    }
    if (this._randomTexture2) {
      this._randomTexture2.dispose();
      this._randomTexture2 = null;
    }
    if (disposeTexture && this.particleTexture) {
      this.particleTexture.dispose();
      this.particleTexture = null;
    }
    if (disposeTexture && this.noiseTexture) {
      this.noiseTexture.dispose();
      this.noiseTexture = null;
    }
    this.onStoppedObservable.clear();
    this.onDisposeObservable.notifyObservers(this);
    this.onDisposeObservable.clear();
  }
  clone(name403, newEmitter, cloneTexture = false) {
    const custom = { ...this._customWrappers };
    let program = null;
    const engine2 = this._engine;
    if (engine2.createEffectForParticles) {
      if (this.customShader != null) {
        program = this.customShader;
        const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(`
`) : "";
        custom[0] = engine2.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this);
      }
    }
    const serialization = this.serialize(cloneTexture);
    const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);
    result.name = name403;
    result.customShader = program;
    result._customWrappers = custom;
    if (newEmitter === undefined) {
      newEmitter = this.emitter;
    }
    if (this.noiseTexture) {
      result.noiseTexture = this.noiseTexture.clone();
    }
    result.emitter = newEmitter;
    return result;
  }
  serialize(serializeTexture = false) {
    const serializationObject = {};
    ParticleSystem._Serialize(serializationObject, this, serializeTexture);
    serializationObject.activeParticleCount = this.activeParticleCount;
    serializationObject.randomTextureSize = this._randomTextureSize;
    serializationObject.customShader = this.customShader;
    return serializationObject;
  }
  static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {
    const name403 = parsedParticleSystem.name;
    let engine2;
    let scene;
    if (sceneOrEngine instanceof AbstractEngine) {
      engine2 = sceneOrEngine;
    } else {
      scene = sceneOrEngine;
      engine2 = scene.getEngine();
    }
    const particleSystem = new GPUParticleSystem(name403, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled);
    particleSystem._rootUrl = rootUrl;
    if (parsedParticleSystem.customShader && engine2.createEffectForParticles) {
      const program = parsedParticleSystem.customShader;
      const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(`
`) : "";
      const custom = engine2.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem);
      particleSystem.setCustomEffect(custom, 0);
      particleSystem.customShader = program;
    }
    if (parsedParticleSystem.id) {
      particleSystem.id = parsedParticleSystem.id;
    }
    if (parsedParticleSystem.activeParticleCount) {
      particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
    }
    ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);
    if (parsedParticleSystem.preventAutoStart) {
      particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
    }
    if (!doNotStart && !particleSystem.preventAutoStart) {
      particleSystem.start();
    }
    return particleSystem;
  }
}
// node_modules/@babylonjs/core/Particles/particleHelper.js
init_tools();
init_math_color();
init_texture();
init_engineStore();

// node_modules/@babylonjs/core/Particles/particleSystemSet.js
init_math_color();
init_engineStore();
class ParticleSystemSet {
  constructor() {
    this._emitterNodeIsOwned = true;
    this.systems = [];
  }
  get emitterNode() {
    return this._emitterNode;
  }
  set emitterNode(value) {
    if (this._emitterNodeIsOwned && this._emitterNode) {
      if (this._emitterNode.dispose) {
        this._emitterNode.dispose();
      }
      this._emitterNodeIsOwned = false;
    }
    for (const system of this.systems) {
      system.emitter = value;
    }
    this._emitterNode = value;
  }
  setEmitterAsSphere(options, renderingGroupId, scene) {
    if (this._emitterNodeIsOwned && this._emitterNode) {
      if (this._emitterNode.dispose) {
        this._emitterNode.dispose();
      }
    }
    this._emitterNodeIsOwned = true;
    this._emitterCreationOptions = {
      kind: "Sphere",
      options,
      renderingGroupId
    };
    const emitterMesh = CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
    emitterMesh.renderingGroupId = renderingGroupId;
    const material2 = new StandardMaterial("emitterSphereMaterial", scene);
    material2.emissiveColor = options.color;
    emitterMesh.material = material2;
    for (const system of this.systems) {
      system.emitter = emitterMesh;
    }
    this._emitterNode = emitterMesh;
  }
  start(emitter) {
    for (const system of this.systems) {
      if (emitter) {
        system.emitter = emitter;
      }
      system.start();
    }
  }
  dispose() {
    for (const system of this.systems) {
      system.dispose();
    }
    this.systems.length = 0;
    if (this._emitterNode) {
      if (this._emitterNode.dispose) {
        this._emitterNode.dispose();
      }
      this._emitterNode = null;
    }
  }
  serialize(serializeTexture = false) {
    const result = {};
    result.systems = [];
    for (const system of this.systems) {
      result.systems.push(system.serialize(serializeTexture));
    }
    if (this._emitterNode) {
      result.emitter = this._emitterCreationOptions;
    }
    return result;
  }
  static Parse(data, scene, gpu = false, capacity) {
    const result = new ParticleSystemSet;
    const rootUrl = this.BaseAssetsUrl + "/textures/";
    scene = scene || EngineStore.LastCreatedScene;
    for (const system of data.systems) {
      result.systems.push(gpu ? GPUParticleSystem.Parse(system, scene, rootUrl, true, capacity) : ParticleSystem.Parse(system, scene, rootUrl, true, capacity));
    }
    if (data.emitter) {
      const options = data.emitter.options;
      switch (data.emitter.kind) {
        case "Sphere":
          result.setEmitterAsSphere({
            diameter: options.diameter,
            segments: options.segments,
            color: Color3.FromArray(options.color)
          }, data.emitter.renderingGroupId, scene);
          break;
      }
    }
    return result;
  }
}
ParticleSystemSet.BaseAssetsUrl = "https://assets.babylonjs.com/particles";

// node_modules/@babylonjs/core/Particles/particleHelper.js
init_webRequest();

class ParticleHelper {
  static CreateDefault(emitter, capacity = 500, scene, useGPU = false) {
    let system;
    if (useGPU) {
      system = new GPUParticleSystem("default system", { capacity }, scene);
    } else {
      system = new ParticleSystem("default system", capacity, scene);
    }
    system.emitter = emitter;
    const textureUrl = Tools.GetAssetUrl("https://assets.babylonjs.com/core/textures/flare.png");
    system.particleTexture = new Texture(textureUrl, system.getScene());
    system.createConeEmitter(0.1, Math.PI / 4);
    system.color1 = new Color4(1, 1, 1, 1);
    system.color2 = new Color4(1, 1, 1, 1);
    system.colorDead = new Color4(1, 1, 1, 0);
    system.minSize = 0.1;
    system.maxSize = 0.1;
    system.minEmitPower = 2;
    system.maxEmitPower = 2;
    system.updateSpeed = 1 / 60;
    system.emitRate = 30;
    return system;
  }
  static CreateAsync(type, scene, gpu = false, capacity) {
    if (!scene) {
      scene = EngineStore.LastCreatedScene;
    }
    const token = {};
    scene.addPendingData(token);
    return new Promise((resolve3, reject) => {
      if (gpu && !GPUParticleSystem.IsSupported) {
        scene.removePendingData(token);
        return reject("Particle system with GPU is not supported.");
      }
      Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${type}.json`, (data) => {
        scene.removePendingData(token);
        const newData = JSON.parse(data.toString());
        return resolve3(ParticleSystemSet.Parse(newData, scene, gpu, capacity));
      }, undefined, undefined, undefined, () => {
        scene.removePendingData(token);
        return reject(`An error occurred with the creation of your particle system. Check if your type '${type}' exists.`);
      });
    });
  }
  static ExportSet(systems) {
    const set = new ParticleSystemSet;
    for (const system of systems) {
      set.systems.push(system);
    }
    return set;
  }
  static ParseFromFileAsync(name403, url, scene, gpu = false, rootUrl = "", capacity) {
    return new Promise((resolve3, reject) => {
      const request = new WebRequest;
      request.addEventListener("readystatechange", () => {
        if (request.readyState == 4) {
          if (request.status == 200) {
            const serializationObject = JSON.parse(request.responseText);
            let output;
            if (gpu) {
              output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);
            } else {
              output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);
            }
            if (name403) {
              output.name = name403;
            }
            resolve3(output);
          } else {
            reject("Unable to load the particle system");
          }
        }
      });
      request.open("GET", url);
      request.send();
    });
  }
  static ParseFromSnippetAsync(snippetId, scene, gpu = false, rootUrl = "", capacity) {
    if (snippetId === "_BLANK") {
      const system = this.CreateDefault(null);
      system.start();
      return Promise.resolve(system);
    }
    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);
            const serializationObject = JSON.parse(snippet.particleSystem);
            let output;
            if (gpu) {
              output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);
            } else {
              output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);
            }
            output.snippetId = snippetId;
            resolve3(output);
          } else {
            reject("Unable to load the snippet " + snippetId);
          }
        }
      });
      request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
      request.send();
    });
  }
}
ParticleHelper.BaseAssetsUrl = ParticleSystemSet.BaseAssetsUrl;
ParticleHelper.SnippetUrl = `https://snippet.babylonjs.com`;
ParticleHelper.CreateFromSnippetAsync = ParticleHelper.ParseFromSnippetAsync;
// node_modules/@babylonjs/core/Particles/particleSystemComponent.js
init_sceneComponent();
init_abstractEngine();
AddParser(SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedData, scene, container, rootUrl) => {
  const individualParser = GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);
  if (!individualParser) {
    return;
  }
  if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
    for (let index = 0, cache = parsedData.particleSystems.length;index < cache; index++) {
      const parsedParticleSystem = parsedData.particleSystems[index];
      container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
    }
  }
});
AddIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedParticleSystem, scene, rootUrl) => {
  if (parsedParticleSystem.activeParticleCount) {
    const ps = GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
    return ps;
  } else {
    const ps = ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
    return ps;
  }
});
AbstractEngine.prototype.createEffectForParticles = function(fragmentName, uniformsNames = [], samplers = [], defines = "", fallbacks, onCompiled, onError, particleSystem, shaderLanguage2 = 0, vertexName) {
  let attributesNamesOrOptions = [];
  let effectCreationOption = [];
  const allSamplers = [];
  if (particleSystem) {
    particleSystem.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, allSamplers);
  } else {
    attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions();
    effectCreationOption = ParticleSystem._GetEffectCreationOptions();
  }
  if (defines.indexOf(" BILLBOARD") === -1) {
    defines += `
#define BILLBOARD
`;
  }
  if (particleSystem?.isAnimationSheetEnabled) {
    if (defines.indexOf(" ANIMATESHEET") === -1) {
      defines += `
#define ANIMATESHEET
`;
    }
  }
  if (samplers.indexOf("diffuseSampler") === -1) {
    samplers.push("diffuseSampler");
  }
  return this.createEffect({
    vertex: vertexName ?? particleSystem?.vertexShaderName ?? "particles",
    fragmentElement: fragmentName
  }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), allSamplers.concat(samplers), defines, fallbacks, onCompiled, onError, undefined, shaderLanguage2, async () => {
    if (shaderLanguage2 === 0) {
      await Promise.resolve().then(() => (init_particles_vertex2(), exports_particles_vertex2));
    } else {
      await Promise.resolve().then(() => (init_particles_vertex(), exports_particles_vertex));
    }
  });
};
Mesh.prototype.getEmittedParticleSystems = function() {
  const results = [];
  for (let index = 0;index < this.getScene().particleSystems.length; index++) {
    const particleSystem = this.getScene().particleSystems[index];
    if (particleSystem.emitter === this) {
      results.push(particleSystem);
    }
  }
  return results;
};
Mesh.prototype.getHierarchyEmittedParticleSystems = function() {
  const results = [];
  const descendants = this.getDescendants();
  descendants.push(this);
  for (let index = 0;index < this.getScene().particleSystems.length; index++) {
    const particleSystem = this.getScene().particleSystems[index];
    const emitter = particleSystem.emitter;
    if (emitter.position && descendants.indexOf(emitter) !== -1) {
      results.push(particleSystem);
    }
  }
  return results;
};
// node_modules/@babylonjs/core/Particles/solidParticle.js
init_math_vector();
init_math_color();
// node_modules/@babylonjs/core/Particles/solidParticleSystem.js
init_math_vector();
init_math_color();
init_buffer();
init_engineStore();
init_math_axis();
// node_modules/@babylonjs/core/Particles/cloudPoint.js
init_math();
// node_modules/@babylonjs/core/Particles/pointsCloudSystem.js
init_math();
init_math_vector();
init_logger();
init_buffer();
init_engineStore();
init_baseTexture();
var PointColor;
(function(PointColor2) {
  PointColor2[PointColor2["Color"] = 2] = "Color";
  PointColor2[PointColor2["UV"] = 1] = "UV";
  PointColor2[PointColor2["Random"] = 0] = "Random";
  PointColor2[PointColor2["Stated"] = 3] = "Stated";
})(PointColor || (PointColor = {}));

// node_modules/@babylonjs/core/Particles/index.js
init_particles_fragment2();
init_particles_vertex2();
init_particles_fragment();
init_particles_vertex();
// node_modules/@babylonjs/core/Physics/v1/physicsEngineComponent.js
Object.defineProperty(AbstractMesh.prototype, "physicsImpostor", {
  get: function() {
    return this._physicsImpostor;
  },
  set: function(value) {
    if (this._physicsImpostor === value) {
      return;
    }
    if (this._disposePhysicsObserver) {
      this.onDisposeObservable.remove(this._disposePhysicsObserver);
    }
    this._physicsImpostor = value;
    if (value) {
      this._disposePhysicsObserver = this.onDisposeObservable.add(() => {
        if (this.physicsImpostor) {
          this.physicsImpostor.dispose();
          /*!doNotRecurse*/
          this.physicsImpostor = null;
        }
      });
    }
  },
  enumerable: true,
  configurable: true
});
AbstractMesh.prototype.getPhysicsImpostor = function() {
  return this.physicsImpostor;
};
AbstractMesh.prototype.applyImpulse = function(force, contactPoint) {
  if (!this.physicsImpostor) {
    return this;
  }
  this.physicsImpostor.applyImpulse(force, contactPoint);
  return this;
};
AbstractMesh.prototype.setPhysicsLinkWith = function(otherMesh, pivot1, pivot2, options) {
  if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
    return this;
  }
  this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {
    mainPivot: pivot1,
    connectedPivot: pivot2,
    nativeParams: options
  });
  return this;
};
// node_modules/@babylonjs/core/Physics/v2/physicsEngine.js
init_math_vector();
init_devTools();

class PhysicsEngine2 {
  getPluginVersion() {
    return this._physicsPlugin.getPluginVersion();
  }
  static DefaultPluginFactory() {
    throw _WarnImport("");
  }
  constructor(gravity, _physicsPlugin = PhysicsEngine2.DefaultPluginFactory()) {
    this._physicsPlugin = _physicsPlugin;
    this._physicsBodies = [];
    this._subTimeStep = 0;
    gravity = gravity || new Vector3(0, -9.807, 0);
    this.setGravity(gravity);
    this.setTimeStep();
  }
  setGravity(gravity) {
    this.gravity = gravity;
    this._physicsPlugin.setGravity(this.gravity);
  }
  setTimeStep(newTimeStep = 1 / 60) {
    this._physicsPlugin.setTimeStep(newTimeStep);
  }
  getTimeStep() {
    return this._physicsPlugin.getTimeStep();
  }
  setSubTimeStep(subTimeStep = 0) {
    this._subTimeStep = subTimeStep;
  }
  getSubTimeStep() {
    return this._subTimeStep;
  }
  dispose() {
    this._physicsPlugin.dispose();
  }
  getPhysicsPluginName() {
    return this._physicsPlugin.name;
  }
  setVelocityLimits(maxLinearVelocity, maxAngularVelocity) {
    this._physicsPlugin.setVelocityLimits(maxLinearVelocity, maxAngularVelocity);
  }
  getMaxLinearVelocity() {
    return this._physicsPlugin.getMaxLinearVelocity();
  }
  getMaxAngularVelocity() {
    return this._physicsPlugin.getMaxAngularVelocity();
  }
  _step(delta) {
    if (delta > 0.1) {
      delta = 0.1;
    } else if (delta <= 0) {
      delta = 1 / 60;
    }
    this._physicsPlugin.executeStep(delta, this._physicsBodies);
  }
  addBody(physicsBody) {
    this._physicsBodies.push(physicsBody);
  }
  removeBody(physicsBody) {
    const index = this._physicsBodies.indexOf(physicsBody);
    if (index > -1) {
      this._physicsBodies.splice(index, 1);
    }
  }
  getBodies() {
    return this._physicsBodies;
  }
  getPhysicsPlugin() {
    return this._physicsPlugin;
  }
  raycastToRef(from, to, result, query) {
    this._physicsPlugin.raycast(from, to, result, query);
  }
  raycast(from, to, query) {
    const result = new PhysicsRaycastResult;
    this._physicsPlugin.raycast(from, to, result, query);
    return result;
  }
}
// node_modules/@babylonjs/core/Physics/v2/IPhysicsEnginePlugin.js
var PhysicsConstraintAxisLimitMode;
(function(PhysicsConstraintAxisLimitMode2) {
  PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["FREE"] = 0] = "FREE";
  PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["LIMITED"] = 1] = "LIMITED";
  PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["LOCKED"] = 2] = "LOCKED";
})(PhysicsConstraintAxisLimitMode || (PhysicsConstraintAxisLimitMode = {}));
var PhysicsConstraintAxis;
(function(PhysicsConstraintAxis2) {
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_X"] = 0] = "LINEAR_X";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_Y"] = 1] = "LINEAR_Y";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_Z"] = 2] = "LINEAR_Z";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_X"] = 3] = "ANGULAR_X";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_Y"] = 4] = "ANGULAR_Y";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_Z"] = 5] = "ANGULAR_Z";
  PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_DISTANCE"] = 6] = "LINEAR_DISTANCE";
})(PhysicsConstraintAxis || (PhysicsConstraintAxis = {}));
var PhysicsConstraintType;
(function(PhysicsConstraintType2) {
  PhysicsConstraintType2[PhysicsConstraintType2["BALL_AND_SOCKET"] = 1] = "BALL_AND_SOCKET";
  PhysicsConstraintType2[PhysicsConstraintType2["DISTANCE"] = 2] = "DISTANCE";
  PhysicsConstraintType2[PhysicsConstraintType2["HINGE"] = 3] = "HINGE";
  PhysicsConstraintType2[PhysicsConstraintType2["SLIDER"] = 4] = "SLIDER";
  PhysicsConstraintType2[PhysicsConstraintType2["LOCK"] = 5] = "LOCK";
  PhysicsConstraintType2[PhysicsConstraintType2["PRISMATIC"] = 6] = "PRISMATIC";
  PhysicsConstraintType2[PhysicsConstraintType2["SIX_DOF"] = 7] = "SIX_DOF";
})(PhysicsConstraintType || (PhysicsConstraintType = {}));
var PhysicsShapeType;
(function(PhysicsShapeType2) {
  PhysicsShapeType2[PhysicsShapeType2["SPHERE"] = 0] = "SPHERE";
  PhysicsShapeType2[PhysicsShapeType2["CAPSULE"] = 1] = "CAPSULE";
  PhysicsShapeType2[PhysicsShapeType2["CYLINDER"] = 2] = "CYLINDER";
  PhysicsShapeType2[PhysicsShapeType2["BOX"] = 3] = "BOX";
  PhysicsShapeType2[PhysicsShapeType2["CONVEX_HULL"] = 4] = "CONVEX_HULL";
  PhysicsShapeType2[PhysicsShapeType2["CONTAINER"] = 5] = "CONTAINER";
  PhysicsShapeType2[PhysicsShapeType2["MESH"] = 6] = "MESH";
  PhysicsShapeType2[PhysicsShapeType2["HEIGHTFIELD"] = 7] = "HEIGHTFIELD";
})(PhysicsShapeType || (PhysicsShapeType = {}));
var PhysicsConstraintMotorType;
(function(PhysicsConstraintMotorType2) {
  PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["NONE"] = 0] = "NONE";
  PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["VELOCITY"] = 1] = "VELOCITY";
  PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["POSITION"] = 2] = "POSITION";
})(PhysicsConstraintMotorType || (PhysicsConstraintMotorType = {}));
var PhysicsEventType;
(function(PhysicsEventType2) {
  PhysicsEventType2["COLLISION_STARTED"] = "COLLISION_STARTED";
  PhysicsEventType2["COLLISION_CONTINUED"] = "COLLISION_CONTINUED";
  PhysicsEventType2["COLLISION_FINISHED"] = "COLLISION_FINISHED";
  PhysicsEventType2["TRIGGER_ENTERED"] = "TRIGGER_ENTERED";
  PhysicsEventType2["TRIGGER_EXITED"] = "TRIGGER_EXITED";
})(PhysicsEventType || (PhysicsEventType = {}));
var PhysicsMotionType;
(function(PhysicsMotionType2) {
  PhysicsMotionType2[PhysicsMotionType2["STATIC"] = 0] = "STATIC";
  PhysicsMotionType2[PhysicsMotionType2["ANIMATED"] = 1] = "ANIMATED";
  PhysicsMotionType2[PhysicsMotionType2["DYNAMIC"] = 2] = "DYNAMIC";
})(PhysicsMotionType || (PhysicsMotionType = {}));
var PhysicsPrestepType;
(function(PhysicsPrestepType2) {
  PhysicsPrestepType2[PhysicsPrestepType2["DISABLED"] = 0] = "DISABLED";
  PhysicsPrestepType2[PhysicsPrestepType2["TELEPORT"] = 1] = "TELEPORT";
  PhysicsPrestepType2[PhysicsPrestepType2["ACTION"] = 2] = "ACTION";
})(PhysicsPrestepType || (PhysicsPrestepType = {}));
var PhysicsActivationControl;
(function(PhysicsActivationControl2) {
  PhysicsActivationControl2[PhysicsActivationControl2["SIMULATION_CONTROLLED"] = 0] = "SIMULATION_CONTROLLED";
  PhysicsActivationControl2[PhysicsActivationControl2["ALWAYS_ACTIVE"] = 1] = "ALWAYS_ACTIVE";
  PhysicsActivationControl2[PhysicsActivationControl2["ALWAYS_INACTIVE"] = 2] = "ALWAYS_INACTIVE";
})(PhysicsActivationControl || (PhysicsActivationControl = {}));

// node_modules/@babylonjs/core/Physics/v2/physicsBody.js
init_math_vector();
// node_modules/@babylonjs/core/Physics/v2/physicsShape.js
init_math_vector();
// node_modules/@babylonjs/core/Physics/v2/physicsMaterial.js
var PhysicsMaterialCombineMode;
(function(PhysicsMaterialCombineMode2) {
  PhysicsMaterialCombineMode2[PhysicsMaterialCombineMode2["GEOMETRIC_MEAN"] = 0] = "GEOMETRIC_MEAN";
  PhysicsMaterialCombineMode2[PhysicsMaterialCombineMode2["MINIMUM"] = 1] = "MINIMUM";
  PhysicsMaterialCombineMode2[PhysicsMaterialCombineMode2["MAXIMUM"] = 2] = "MAXIMUM";
  PhysicsMaterialCombineMode2[PhysicsMaterialCombineMode2["ARITHMETIC_MEAN"] = 3] = "ARITHMETIC_MEAN";
  PhysicsMaterialCombineMode2[PhysicsMaterialCombineMode2["MULTIPLY"] = 4] = "MULTIPLY";
})(PhysicsMaterialCombineMode || (PhysicsMaterialCombineMode = {}));
// node_modules/@babylonjs/core/Physics/v2/physicsAggregate.js
init_logger();
init_math_vector();
// node_modules/@babylonjs/core/Physics/v2/ragdoll.js
init_math_vector();
init_math_axis();
init_logger();
// node_modules/@babylonjs/core/Physics/v2/characterController.js
init_math_vector();
init_arrayTools();
var CharacterSupportedState;
(function(CharacterSupportedState2) {
  CharacterSupportedState2[CharacterSupportedState2["UNSUPPORTED"] = 0] = "UNSUPPORTED";
  CharacterSupportedState2[CharacterSupportedState2["SLIDING"] = 1] = "SLIDING";
  CharacterSupportedState2[CharacterSupportedState2["SUPPORTED"] = 2] = "SUPPORTED";
})(CharacterSupportedState || (CharacterSupportedState = {}));
var SurfaceConstraintInteractionStatus;
(function(SurfaceConstraintInteractionStatus2) {
  SurfaceConstraintInteractionStatus2[SurfaceConstraintInteractionStatus2["OK"] = 0] = "OK";
  SurfaceConstraintInteractionStatus2[SurfaceConstraintInteractionStatus2["FAILURE_3D"] = 1] = "FAILURE_3D";
  SurfaceConstraintInteractionStatus2[SurfaceConstraintInteractionStatus2["FAILURE_2D"] = 2] = "FAILURE_2D";
})(SurfaceConstraintInteractionStatus || (SurfaceConstraintInteractionStatus = {}));
// node_modules/@babylonjs/core/Physics/v2/Plugins/havokPlugin.js
init_math_vector();
init_logger();
init_buffer();
init_arrayTools();
init_observable();
// node_modules/@babylonjs/core/Physics/joinedPhysicsEngineComponent.js
init_logger();
init_observable();
init_sceneComponent();
init_scene();
Scene.prototype.getPhysicsEngine = function() {
  return this._physicsEngine;
};
Scene.prototype.enablePhysics = function(gravity = null, plugin) {
  if (this._physicsEngine) {
    return true;
  }
  let component = this._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE);
  if (!component) {
    component = new PhysicsEngineSceneComponent(this);
    this._addComponent(component);
  }
  try {
    if (!plugin || plugin?.getPluginVersion() === 1) {
      this._physicsEngine = new PhysicsEngine(gravity, plugin);
    } else if (plugin?.getPluginVersion() === 2) {
      this._physicsEngine = new PhysicsEngine2(gravity, plugin);
    } else {
      throw new Error("Unsupported Physics plugin version.");
    }
    this._physicsTimeAccumulator = 0;
    return true;
  } catch (e) {
    Logger.Error(e.message);
    return false;
  }
};
Scene.prototype.disablePhysicsEngine = function() {
  if (!this._physicsEngine) {
    return;
  }
  this._physicsEngine.dispose();
  this._physicsEngine = null;
};
Scene.prototype.isPhysicsEnabled = function() {
  return this._physicsEngine !== undefined;
};
Scene.prototype.deleteCompoundImpostor = function(compound) {
  const mesh2 = compound.parts[0].mesh;
  if (mesh2.physicsImpostor) {
    mesh2.physicsImpostor.dispose();
    mesh2.physicsImpostor = null;
  }
};
Scene.prototype._advancePhysicsEngineStep = function(step) {
  if (this._physicsEngine) {
    const subTime = this._physicsEngine.getSubTimeStep();
    if (subTime > 0) {
      this._physicsTimeAccumulator += step;
      while (this._physicsTimeAccumulator > subTime) {
        this.onBeforePhysicsObservable.notifyObservers(this);
        this._physicsEngine._step(subTime / 1000);
        this.onAfterPhysicsObservable.notifyObservers(this);
        this._physicsTimeAccumulator -= subTime;
      }
    } else {
      this.onBeforePhysicsObservable.notifyObservers(this);
      this._physicsEngine._step(step / 1000);
      this.onAfterPhysicsObservable.notifyObservers(this);
    }
  }
};

class PhysicsEngineSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_PHYSICSENGINE;
    this.scene = scene;
    this.scene.onBeforePhysicsObservable = new Observable;
    this.scene.onAfterPhysicsObservable = new Observable;
    this.scene.getDeterministicFrameTime = () => {
      if (this.scene._physicsEngine) {
        return this.scene._physicsEngine.getTimeStep() * 1000;
      }
      return 1000 / 60;
    };
  }
  register() {}
  rebuild() {}
  dispose() {
    this.scene.onBeforePhysicsObservable.clear();
    this.scene.onAfterPhysicsObservable.clear();
    if (this.scene._physicsEngine) {
      this.scene.disablePhysicsEngine();
    }
  }
}

// node_modules/@babylonjs/core/Physics/v2/physicsEngineComponent.js
Object.defineProperty(TransformNode.prototype, "physicsBody", {
  get: function() {
    return this._physicsBody;
  },
  set: function(value) {
    if (this._physicsBody === value) {
      return;
    }
    if (this._disposePhysicsObserver) {
      this.onDisposeObservable.remove(this._disposePhysicsObserver);
    }
    this._physicsBody = value;
    if (value) {
      this._disposePhysicsObserver = this.onDisposeObservable.add(() => {
        if (this.physicsBody) {
          this.physicsBody.dispose();
          /*!doNotRecurse*/
          this.physicsBody = null;
        }
      });
    }
  },
  enumerable: true,
  configurable: true
});
TransformNode.prototype.getPhysicsBody = function() {
  return this.physicsBody;
};
TransformNode.prototype.applyImpulse = function(force, contactPoint) {
  if (!this.physicsBody) {
    throw new Error("No Physics Body for TransformNode");
  }
  this.physicsBody.applyImpulse(force, contactPoint);
  return this;
};
TransformNode.prototype.applyAngularImpulse = function(angularImpulse) {
  if (!this.physicsBody) {
    throw new Error("No Physics Body for TransformNode");
  }
  this.physicsBody.applyAngularImpulse(angularImpulse);
  return this;
};
// node_modules/@babylonjs/core/Physics/physicsHelper.js
init_logger();
init_math_vector();
class HelperTools {
  static GetContactPointToRef(mesh2, origin, direction, result, instanceIndex) {
    const engine2 = mesh2.getScene().getPhysicsEngine();
    const pluginVersion = engine2?.getPluginVersion();
    if (pluginVersion === 1) {
      const ray2 = new Ray(origin, direction);
      const hit = ray2.intersectsMesh(mesh2);
      if (hit.hit && hit.pickedPoint) {
        result.copyFrom(hit.pickedPoint);
        return true;
      }
    } else if (pluginVersion === 2) {
      mesh2.physicsBody.getObjectCenterWorldToRef(result, instanceIndex);
      return true;
    }
    return false;
  }
  static HasAppliedForces(body, instanceIndex) {
    return body.getMotionType(instanceIndex) === 0 || (body.getMassProperties(instanceIndex)?.mass ?? 0) === 0 || body.transformNode?.getTotalVertices() === 0;
  }
  static IsInsideCylinder(point, origin, radius, height) {
    const distance = TmpVectors.Vector3[0];
    point.subtractToRef(origin, distance);
    return Math.abs(distance.x) <= radius && Math.abs(distance.z) <= radius && distance.y >= 0 && distance.y <= height;
  }
}
class PhysicsUpdraftEvent {
  constructor(_scene, _origin, _options) {
    this._scene = _scene;
    this._origin = _origin;
    this._options = _options;
    this._originTop = Vector3.Zero();
    this._originDirection = Vector3.Zero();
    this._cylinderPosition = Vector3.Zero();
    this._dataFetched = false;
    this._physicsEngine = this._scene.getPhysicsEngine();
    this._options = { ...new PhysicsUpdraftEventOptions, ...this._options };
    this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
    this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
    if (this._options.updraftMode === 1) {
      this._originDirection = this._origin.subtract(this._originTop).normalize();
    }
    this._tickCallback = () => this._tick();
    if (this._physicsEngine.getPluginVersion() === 1) {
      this._prepareCylinder();
    }
  }
  getData() {
    this._dataFetched = true;
    return {
      cylinder: this._cylinder
    };
  }
  enable() {
    this._tickCallback.call(this);
    this._scene.registerBeforeRender(this._tickCallback);
  }
  disable() {
    this._scene.unregisterBeforeRender(this._tickCallback);
  }
  dispose(force = true) {
    if (!this._cylinder) {
      return;
    }
    if (force) {
      this._cylinder.dispose();
      this._cylinder = undefined;
    } else {
      setTimeout(() => {
        if (!this._dataFetched && this._cylinder) {
          this._cylinder.dispose();
          this._cylinder = undefined;
        }
      }, 0);
    }
  }
  _getHitData(center, data) {
    let direction;
    if (this._options.updraftMode === 1) {
      direction = this._originDirection;
    } else {
      direction = center.subtract(this._originTop);
    }
    const distanceFromOrigin = Vector3.Distance(this._origin, center);
    const multiplier = this._options.strength * -1;
    const force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
    data.force.copyFrom(force);
    data.contactPoint.copyFrom(center);
    data.distanceFromOrigin = distanceFromOrigin;
  }
  _getBodyHitData(body, data, instanceIndex) {
    if (HelperTools.HasAppliedForces(body)) {
      return false;
    }
    const center = body.getObjectCenterWorld(instanceIndex);
    if (!HelperTools.IsInsideCylinder(center, this._origin, this._options.radius, this._options.height)) {
      return false;
    }
    data.instanceIndex = instanceIndex;
    this._getHitData(center, data);
    return true;
  }
  _getImpostorHitData(impostor, data) {
    if (impostor.mass === 0) {
      return false;
    }
    const impostorObject = impostor.object;
    if (!this._intersectsWithCylinder(impostorObject)) {
      return false;
    }
    const center = impostor.getObjectCenter();
    this._getHitData(center, data);
    return true;
  }
  _tick() {
    const hitData = PhysicsUpdraftEvent._HitData;
    if (this._physicsEngine.getPluginVersion() === 1) {
      this._physicsEngine.getImpostors().forEach((impostor) => {
        if (!this._getImpostorHitData(impostor, hitData)) {
          return;
        }
        impostor.applyForce(hitData.force, hitData.contactPoint);
      });
    } else {
      this._physicsEngine.getBodies().forEach((body) => {
        body.iterateOverAllInstances((body2, instanceIndex) => {
          if (!this._getBodyHitData(body2, hitData, instanceIndex)) {
            return;
          }
          body2.applyForce(hitData.force, hitData.contactPoint, hitData.instanceIndex);
        });
      });
    }
  }
  _prepareCylinder() {
    if (!this._cylinder) {
      this._cylinder = CreateCylinder("updraftEventCylinder", {
        height: this._options.height,
        diameter: this._options.radius * 2
      }, this._scene);
      this._cylinder.isVisible = false;
    }
  }
  _intersectsWithCylinder(mesh2) {
    if (!this._cylinder) {
      return false;
    }
    this._cylinder.position = this._cylinderPosition;
    return this._cylinder.intersectsMesh(mesh2, true);
  }
}
PhysicsUpdraftEvent._HitData = { force: new Vector3, contactPoint: new Vector3, distanceFromOrigin: 0 };

class PhysicsVortexEvent {
  constructor(_scene, _origin, _options) {
    this._scene = _scene;
    this._origin = _origin;
    this._options = _options;
    this._originTop = Vector3.Zero();
    this._cylinderPosition = Vector3.Zero();
    this._dataFetched = false;
    this._physicsEngine = this._scene.getPhysicsEngine();
    this._options = { ...new PhysicsVortexEventOptions, ...this._options };
    this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
    this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
    this._tickCallback = () => this._tick();
    if (this._physicsEngine.getPluginVersion() === 1) {
      this._prepareCylinder();
    }
  }
  getData() {
    this._dataFetched = true;
    return {
      cylinder: this._cylinder
    };
  }
  enable() {
    this._tickCallback.call(this);
    this._scene.registerBeforeRender(this._tickCallback);
  }
  disable() {
    this._scene.unregisterBeforeRender(this._tickCallback);
  }
  dispose(force = true) {
    if (!this._cylinder) {
      return;
    }
    if (force) {
      this._cylinder.dispose();
    } else {
      setTimeout(() => {
        if (!this._dataFetched) {
          this._cylinder.dispose();
        }
      }, 0);
    }
  }
  _getHitData(mesh2, center, data) {
    const originOnPlane = PhysicsVortexEvent._OriginOnPlane;
    originOnPlane.set(this._origin.x, center.y, this._origin.z);
    const originToImpostorDirection = TmpVectors.Vector3[0];
    center.subtractToRef(originOnPlane, originToImpostorDirection);
    const contactPoint = TmpVectors.Vector3[1];
    const hasContactPoint = HelperTools.GetContactPointToRef(mesh2, originOnPlane, originToImpostorDirection, contactPoint, data.instanceIndex);
    if (!hasContactPoint) {
      return false;
    }
    const distance = Vector3.Distance(contactPoint, originOnPlane);
    const absoluteDistanceFromOrigin = distance / this._options.radius;
    const directionToOrigin = TmpVectors.Vector3[2];
    contactPoint.normalizeToRef(directionToOrigin);
    if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
      directionToOrigin.negateInPlace();
    }
    let forceX;
    let forceY;
    let forceZ;
    if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
      forceX = directionToOrigin.x * this._options.centripetalForceMultiplier;
      forceY = directionToOrigin.y * this._options.updraftForceMultiplier;
      forceZ = directionToOrigin.z * this._options.centripetalForceMultiplier;
    } else {
      const perpendicularDirection = Vector3.Cross(originOnPlane, center).normalize();
      forceX = (perpendicularDirection.x + directionToOrigin.x) * this._options.centrifugalForceMultiplier;
      forceY = this._originTop.y * this._options.updraftForceMultiplier;
      forceZ = (perpendicularDirection.z + directionToOrigin.z) * this._options.centrifugalForceMultiplier;
    }
    const force = TmpVectors.Vector3[3];
    force.set(forceX, forceY, forceZ);
    force.scaleInPlace(this._options.strength);
    data.force.copyFrom(force);
    data.contactPoint.copyFrom(center);
    data.distanceFromOrigin = absoluteDistanceFromOrigin;
    return true;
  }
  _getBodyHitData(body, data, instanceIndex) {
    if (HelperTools.HasAppliedForces(body, instanceIndex)) {
      return false;
    }
    const bodyObject = body.transformNode;
    const bodyCenter = body.getObjectCenterWorld(instanceIndex);
    if (!HelperTools.IsInsideCylinder(bodyCenter, this._origin, this._options.radius, this._options.height)) {
      return false;
    }
    data.instanceIndex = instanceIndex;
    return this._getHitData(bodyObject, bodyCenter, data);
  }
  _getImpostorHitData(impostor, data) {
    if (impostor.mass === 0) {
      return false;
    }
    if (impostor.object.getClassName() !== "Mesh" && impostor.object.getClassName() !== "InstancedMesh") {
      return false;
    }
    const impostorObject = impostor.object;
    if (!this._intersectsWithCylinder(impostorObject)) {
      return false;
    }
    const impostorObjectCenter = impostor.getObjectCenter();
    this._getHitData(impostorObject, impostorObjectCenter, data);
    return true;
  }
  _tick() {
    const hitData = PhysicsVortexEvent._HitData;
    if (this._physicsEngine.getPluginVersion() === 1) {
      this._physicsEngine.getImpostors().forEach((impostor) => {
        if (!this._getImpostorHitData(impostor, hitData)) {
          return;
        }
        impostor.applyForce(hitData.force, hitData.contactPoint);
      });
    } else {
      this._physicsEngine.getBodies().forEach((body) => {
        body.iterateOverAllInstances((body2, instanceIndex) => {
          if (!this._getBodyHitData(body2, hitData, instanceIndex)) {
            return;
          }
          body2.applyForce(hitData.force, hitData.contactPoint, hitData.instanceIndex);
        });
      });
    }
  }
  _prepareCylinder() {
    if (!this._cylinder) {
      this._cylinder = CreateCylinder("vortexEventCylinder", {
        height: this._options.height,
        diameter: this._options.radius * 2
      }, this._scene);
      this._cylinder.isVisible = false;
    }
  }
  _intersectsWithCylinder(mesh2) {
    this._cylinder.position = this._cylinderPosition;
    return this._cylinder.intersectsMesh(mesh2, true);
  }
}
PhysicsVortexEvent._OriginOnPlane = Vector3.Zero();
PhysicsVortexEvent._HitData = { force: new Vector3, contactPoint: new Vector3, distanceFromOrigin: 0 };
class PhysicsUpdraftEventOptions {
  constructor() {
    this.radius = 5;
    this.strength = 10;
    this.height = 10;
    this.updraftMode = 0;
  }
}

class PhysicsVortexEventOptions {
  constructor() {
    this.radius = 5;
    this.strength = 10;
    this.height = 10;
    this.centripetalForceThreshold = 0.7;
    this.centripetalForceMultiplier = 5;
    this.centrifugalForceMultiplier = 0.5;
    this.updraftForceMultiplier = 0.02;
  }
}
var PhysicsRadialImpulseFalloff;
(function(PhysicsRadialImpulseFalloff2) {
  PhysicsRadialImpulseFalloff2[PhysicsRadialImpulseFalloff2["Constant"] = 0] = "Constant";
  PhysicsRadialImpulseFalloff2[PhysicsRadialImpulseFalloff2["Linear"] = 1] = "Linear";
})(PhysicsRadialImpulseFalloff || (PhysicsRadialImpulseFalloff = {}));
var PhysicsUpdraftMode;
(function(PhysicsUpdraftMode2) {
  PhysicsUpdraftMode2[PhysicsUpdraftMode2["Center"] = 0] = "Center";
  PhysicsUpdraftMode2[PhysicsUpdraftMode2["Perpendicular"] = 1] = "Perpendicular";
})(PhysicsUpdraftMode || (PhysicsUpdraftMode = {}));
// node_modules/@babylonjs/core/PostProcesses/blackAndWhitePostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
init_decorators_serialization();
class BlackAndWhitePostProcess extends PostProcess {
  get degree() {
    return this._effectWrapper.degree;
  }
  set degree(value) {
    this._effectWrapper.degree = value;
  }
  getClassName() {
    return "BlackAndWhitePostProcess";
  }
  constructor(name403, options, camera2 = null, samplingMode, engine2, reusable) {
    const localOptions = {
      uniforms: ThinBlackAndWhitePostProcess.Uniforms,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      ...options
    };
    super(name403, ThinBlackAndWhitePostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlackAndWhitePostProcess(name403, engine2, localOptions) : undefined,
      ...localOptions
    });
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new BlackAndWhitePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], BlackAndWhitePostProcess.prototype, "degree", null);
RegisterClass("BABYLON.BlackAndWhitePostProcess", BlackAndWhitePostProcess);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect.js
init_tools();

class PostProcessRenderEffect {
  constructor(engine2, name403, getPostProcesses, singleInstance) {
    this._name = name403;
    this._singleInstance = singleInstance || true;
    this._getPostProcesses = getPostProcesses;
    this._cameras = {};
    this._indicesForCamera = {};
    this._postProcesses = {};
  }
  get isSupported() {
    for (const index in this._postProcesses) {
      if (Object.prototype.hasOwnProperty.call(this._postProcesses, index)) {
        const pps = this._postProcesses[index];
        for (let ppIndex = 0;ppIndex < pps.length; ppIndex++) {
          if (!pps[ppIndex].isSupported) {
            return false;
          }
        }
      }
    }
    return true;
  }
  _update() {}
  _attachCameras(cameras) {
    let cameraKey;
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    for (let i = 0;i < cams.length; i++) {
      const camera2 = cams[i];
      if (!camera2) {
        continue;
      }
      const cameraName = camera2.name;
      if (this._singleInstance) {
        cameraKey = 0;
      } else {
        cameraKey = cameraName;
      }
      if (!this._postProcesses[cameraKey]) {
        const postProcess = this._getPostProcesses();
        if (postProcess) {
          this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
        }
      }
      if (!this._indicesForCamera[cameraName]) {
        this._indicesForCamera[cameraName] = [];
      }
      this._postProcesses[cameraKey].forEach((postProcess) => {
        const index = camera2.attachPostProcess(postProcess);
        this._indicesForCamera[cameraName].push(index);
      });
      if (!this._cameras[cameraName]) {
        this._cameras[cameraName] = camera2;
      }
    }
  }
  _detachCameras(cameras) {
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    for (let i = 0;i < cams.length; i++) {
      const camera2 = cams[i];
      const cameraName = camera2.name;
      const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];
      if (postProcesses) {
        postProcesses.forEach((postProcess) => {
          camera2.detachPostProcess(postProcess);
        });
      }
      if (this._cameras[cameraName]) {
        this._cameras[cameraName] = null;
      }
      delete this._indicesForCamera[cameraName];
    }
  }
  _enable(cameras) {
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    for (let i = 0;i < cams.length; i++) {
      const camera2 = cams[i];
      const cameraName = camera2.name;
      const cameraKey = this._singleInstance ? 0 : cameraName;
      for (let j = 0;j < this._indicesForCamera[cameraName].length; j++) {
        const index = this._indicesForCamera[cameraName][j];
        const postProcess = camera2._postProcesses[index];
        if (postProcess === undefined || postProcess === null) {
          cams[i].attachPostProcess(this._postProcesses[cameraKey][j], index);
        }
      }
    }
  }
  _disable(cameras) {
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    for (let i = 0;i < cams.length; i++) {
      const camera2 = cams[i];
      const cameraName = camera2.name;
      this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => {
        camera2.detachPostProcess(postProcess);
      });
    }
  }
  getPostProcesses(camera2) {
    if (this._singleInstance) {
      return this._postProcesses[0];
    } else {
      if (!camera2) {
        return null;
      }
      return this._postProcesses[camera2.name];
    }
  }
}

// node_modules/@babylonjs/core/PostProcesses/extractHighlightsPostProcess.js
init_tslib_es6();
init_postProcess();
init_decorators();
init_typeStore();
class ExtractHighlightsPostProcess extends PostProcess {
  get threshold() {
    return this._effectWrapper.threshold;
  }
  set threshold(value) {
    this._effectWrapper.threshold = value;
  }
  get _exposure() {
    return this._effectWrapper._exposure;
  }
  set _exposure(value) {
    this._effectWrapper._exposure = value;
  }
  getClassName() {
    return "ExtractHighlightsPostProcess";
  }
  constructor(name403, options, camera2 = null, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    const localOptions = {
      uniforms: ThinExtractHighlightsPostProcess.Uniforms,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      blockCompilation,
      ...options
    };
    super(name403, ThinExtractHighlightsPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinExtractHighlightsPostProcess(name403, engine2, localOptions) : undefined,
      ...localOptions
    });
    this._inputPostProcess = null;
    this.onApplyObservable.add((effect2) => {
      this.externalTextureSamplerBinding = !!this._inputPostProcess;
      if (this._inputPostProcess) {
        effect2.setTextureFromPostProcess("textureSampler", this._inputPostProcess);
      }
    });
  }
}
__decorate([
  serialize()
], ExtractHighlightsPostProcess.prototype, "threshold", null);
RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess);

// node_modules/@babylonjs/core/PostProcesses/bloomMergePostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
class BloomMergePostProcess extends PostProcess {
  get weight() {
    return this._effectWrapper.weight;
  }
  set weight(value) {
    this._effectWrapper.weight = value;
  }
  getClassName() {
    return "BloomMergePostProcess";
  }
  constructor(name403, originalFromInput, blurred, weight, options, camera2 = null, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation;
    const localOptions = {
      uniforms: ThinBloomMergePostProcess.Uniforms,
      samplers: ThinBloomMergePostProcess.Samplers,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      ...options,
      blockCompilation: true
    };
    super(name403, ThinBloomMergePostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBloomMergePostProcess(name403, engine2, localOptions) : undefined,
      ...localOptions
    });
    this.weight = weight;
    this.externalTextureSamplerBinding = true;
    this.onApplyObservable.add((effect2) => {
      effect2.setTextureFromPostProcess("textureSampler", originalFromInput);
      effect2.setTextureFromPostProcessOutput("bloomBlur", blurred);
    });
    if (!blockCompilationFinal) {
      this.updateEffect();
    }
  }
}
__decorate([
  serialize()
], BloomMergePostProcess.prototype, "weight", null);
RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess);

// node_modules/@babylonjs/core/PostProcesses/bloomEffect.js
init_texture();
class BloomEffect extends PostProcessRenderEffect {
  get threshold() {
    return this._thinBloomEffect.threshold;
  }
  set threshold(value) {
    this._thinBloomEffect.threshold = value;
  }
  get weight() {
    return this._thinBloomEffect.weight;
  }
  set weight(value) {
    this._thinBloomEffect.weight = value;
  }
  get kernel() {
    return this._thinBloomEffect.kernel;
  }
  set kernel(value) {
    this._thinBloomEffect.kernel = value;
  }
  get bloomScale() {
    return this._thinBloomEffect.scale;
  }
  constructor(sceneOrEngine, bloomScale, bloomWeight, bloomKernel, pipelineTextureType = 0, blockCompilation = false) {
    const engine2 = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine;
    super(engine2, "bloom", () => {
      return this._effects;
    }, true);
    this._effects = [];
    this._thinBloomEffect = new ThinBloomEffect("bloom", engine2, bloomScale, blockCompilation);
    this._downscale = new ExtractHighlightsPostProcess("highlights", {
      size: 1,
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      effectWrapper: this._thinBloomEffect._downscale
    });
    this._blurX = new BlurPostProcess("horizontal blur", this._thinBloomEffect._blurX.direction, this._thinBloomEffect._blurX.kernel, {
      size: bloomScale,
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      effectWrapper: this._thinBloomEffect._blurX
    });
    this._blurX.alwaysForcePOT = true;
    this._blurX.autoClear = false;
    this._blurY = new BlurPostProcess("vertical blur", this._thinBloomEffect._blurY.direction, this._thinBloomEffect._blurY.kernel, {
      size: bloomScale,
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      effectWrapper: this._thinBloomEffect._blurY
    });
    this._blurY.alwaysForcePOT = true;
    this._blurY.autoClear = false;
    this.kernel = bloomKernel;
    this._effects = [this._downscale, this._blurX, this._blurY];
    this._merge = new BloomMergePostProcess("bloomMerge", this._downscale, this._blurY, bloomWeight, {
      size: bloomScale,
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      effectWrapper: this._thinBloomEffect._merge
    });
    this._merge.autoClear = false;
    this._effects.push(this._merge);
  }
  disposeEffects(camera2) {
    for (let effectIndex = 0;effectIndex < this._effects.length; effectIndex++) {
      this._effects[effectIndex].dispose(camera2);
    }
  }
  _updateEffects() {
    for (let effectIndex = 0;effectIndex < this._effects.length; effectIndex++) {
      this._effects[effectIndex].updateEffect();
    }
  }
  _isReady() {
    return this._thinBloomEffect.isReady();
  }
}
// node_modules/@babylonjs/core/PostProcesses/chromaticAberrationPostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
init_decorators_serialization();
class ChromaticAberrationPostProcess extends PostProcess {
  get aberrationAmount() {
    return this._effectWrapper.aberrationAmount;
  }
  set aberrationAmount(value) {
    this._effectWrapper.aberrationAmount = value;
  }
  get radialIntensity() {
    return this._effectWrapper.radialIntensity;
  }
  set radialIntensity(value) {
    this._effectWrapper.radialIntensity = value;
  }
  get direction() {
    return this._effectWrapper.direction;
  }
  set direction(value) {
    this._effectWrapper.direction = value;
  }
  get centerPosition() {
    return this._effectWrapper.centerPosition;
  }
  set centerPosition(value) {
    this._effectWrapper.centerPosition = value;
  }
  get screenWidth() {
    return this._effectWrapper.screenWidth;
  }
  set screenWidth(value) {
    this._effectWrapper.screenWidth = value;
  }
  get screenHeight() {
    return this._effectWrapper.screenHeight;
  }
  set screenHeight(value) {
    this._effectWrapper.screenHeight = value;
  }
  getClassName() {
    return "ChromaticAberrationPostProcess";
  }
  constructor(name403, screenWidth, screenHeight, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    const localOptions = {
      uniforms: ThinChromaticAberrationPostProcess.Uniforms,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      blockCompilation,
      ...options
    };
    super(name403, ThinChromaticAberrationPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinChromaticAberrationPostProcess(name403, engine2, localOptions) : undefined,
      ...localOptions
    });
    this.screenWidth = screenWidth;
    this.screenHeight = screenHeight;
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new ChromaticAberrationPostProcess(parsedPostProcess.name, parsedPostProcess.screenWidth, parsedPostProcess.screenHeight, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "aberrationAmount", null);
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "radialIntensity", null);
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "direction", null);
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "centerPosition", null);
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "screenWidth", null);
__decorate([
  serialize()
], ChromaticAberrationPostProcess.prototype, "screenHeight", null);
RegisterClass("BABYLON.ChromaticAberrationPostProcess", ChromaticAberrationPostProcess);
// node_modules/@babylonjs/core/PostProcesses/circleOfConfusionPostProcess.js
init_tslib_es6();
init_postProcess();
init_logger();
init_typeStore();
init_decorators();
class CircleOfConfusionPostProcess extends PostProcess {
  get lensSize() {
    return this._effectWrapper.lensSize;
  }
  set lensSize(value) {
    this._effectWrapper.lensSize = value;
  }
  get fStop() {
    return this._effectWrapper.fStop;
  }
  set fStop(value) {
    this._effectWrapper.fStop = value;
  }
  get focusDistance() {
    return this._effectWrapper.focusDistance;
  }
  set focusDistance(value) {
    this._effectWrapper.focusDistance = value;
  }
  get focalLength() {
    return this._effectWrapper.focalLength;
  }
  set focalLength(value) {
    this._effectWrapper.focalLength = value;
  }
  getClassName() {
    return "CircleOfConfusionPostProcess";
  }
  constructor(name403, depthTexture, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    const localOptions = {
      uniforms: ThinCircleOfConfusionPostProcess.Uniforms,
      samplers: ThinCircleOfConfusionPostProcess.Samplers,
      defines: typeof options === "object" && options.depthNotNormalized ? ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : undefined,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      blockCompilation,
      ...options
    };
    super(name403, ThinCircleOfConfusionPostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinCircleOfConfusionPostProcess(name403, engine2, localOptions) : undefined,
      ...localOptions
    });
    this._depthTexture = null;
    this._depthTexture = depthTexture;
    this.onApplyObservable.add((effect2) => {
      if (!this._depthTexture) {
        Logger.Warn("No depth texture set on CircleOfConfusionPostProcess");
        return;
      }
      effect2.setTexture("depthSampler", this._depthTexture);
      this._effectWrapper.camera = this._depthTexture.activeCamera;
    });
  }
  set depthTexture(value) {
    this._depthTexture = value;
  }
}
__decorate([
  serialize()
], CircleOfConfusionPostProcess.prototype, "lensSize", null);
__decorate([
  serialize()
], CircleOfConfusionPostProcess.prototype, "fStop", null);
__decorate([
  serialize()
], CircleOfConfusionPostProcess.prototype, "focusDistance", null);
__decorate([
  serialize()
], CircleOfConfusionPostProcess.prototype, "focalLength", null);
RegisterClass("BABYLON.CircleOfConfusionPostProcess", CircleOfConfusionPostProcess);
// node_modules/@babylonjs/core/PostProcesses/colorCorrectionPostProcess.js
init_tslib_es6();
init_postProcess();
init_texture();
init_typeStore();
init_decorators();
init_decorators_serialization();

class ColorCorrectionPostProcess extends PostProcess {
  getClassName() {
    return "ColorCorrectionPostProcess";
  }
  constructor(name405, colorTableUrl, options, camera2, samplingMode, engine2, reusable) {
    super(name405, "colorCorrection", null, ["colorTable"], options, camera2, samplingMode, engine2, reusable);
    const scene = camera2?.getScene() || null;
    this._colorTableTexture = new Texture(colorTableUrl, scene, true, false, Texture.TRILINEAR_SAMPLINGMODE);
    this._colorTableTexture.anisotropicFilteringLevel = 1;
    this._colorTableTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._colorTableTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
    this.colorTableUrl = colorTableUrl;
    this.onApply = (effect2) => {
      effect2.setTexture("colorTable", this._colorTableTexture);
    };
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_colorCorrection_fragment(), exports_colorCorrection_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_colorCorrection_fragment2(), exports_colorCorrection_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new ColorCorrectionPostProcess(parsedPostProcess.name, parsedPostProcess.colorTableUrl, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], ColorCorrectionPostProcess.prototype, "colorTableUrl", undefined);
RegisterClass("BABYLON.ColorCorrectionPostProcess", ColorCorrectionPostProcess);
// node_modules/@babylonjs/core/PostProcesses/convolutionPostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
init_decorators_serialization();

class ConvolutionPostProcess extends PostProcess {
  getClassName() {
    return "ConvolutionPostProcess";
  }
  constructor(name407, kernel, options, camera2, samplingMode, engine2, reusable, textureType = 0) {
    super(name407, "convolution", ["kernel", "screenSize"], null, options, camera2, samplingMode, engine2, reusable, null, textureType);
    this.kernel = kernel;
    this.onApply = (effect2) => {
      effect2.setFloat2("screenSize", this.width, this.height);
      effect2.setArray("kernel", this.kernel);
    };
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_convolution_fragment(), exports_convolution_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_convolution_fragment2(), exports_convolution_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new ConvolutionPostProcess(parsedPostProcess.name, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType);
    }, parsedPostProcess, scene, rootUrl);
  }
}
ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
__decorate([
  serialize()
], ConvolutionPostProcess.prototype, "kernel", undefined);
RegisterClass("BABYLON.ConvolutionPostProcess", ConvolutionPostProcess);
// node_modules/@babylonjs/core/PostProcesses/depthOfFieldBlurPostProcess.js
init_texture();
init_typeStore();

class DepthOfFieldBlurPostProcess extends BlurPostProcess {
  getClassName() {
    return "DepthOfFieldBlurPostProcess";
  }
  constructor(name407, _scene, direction, kernel, options, camera2, circleOfConfusion, imageToBlur = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine2, reusable, textureType = 0, blockCompilation = false, textureFormat = 5) {
    super(name407, direction, kernel, {
      camera: camera2,
      engine: engine2,
      reusable,
      textureType,
      defines: `#define DOF 1
`,
      blockCompilation,
      textureFormat,
      ...options,
      samplingMode: samplingMode = 2
    });
    this.externalTextureSamplerBinding = !!imageToBlur;
    this.onApplyObservable.add((effect2) => {
      if (imageToBlur != null) {
        effect2.setTextureFromPostProcess("textureSampler", imageToBlur);
      }
      effect2.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
    });
  }
}
RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess);
// node_modules/@babylonjs/core/PostProcesses/depthOfFieldEffect.js
init_texture();

// node_modules/@babylonjs/core/PostProcesses/depthOfFieldMergePostProcess.js
init_postProcess();
class DepthOfFieldMergePostProcess extends PostProcess {
  getClassName() {
    return "DepthOfFieldMergePostProcess";
  }
  constructor(name407, originalFromInput, circleOfConfusion, _blurSteps, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation;
    const localOptions = {
      samplers: ThinDepthOfFieldMergePostProcess.Samplers,
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      ...options,
      blockCompilation: true
    };
    super(name407, ThinDepthOfFieldMergePostProcess.FragmentUrl, {
      effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinDepthOfFieldMergePostProcess(name407, engine2, localOptions) : undefined,
      ...localOptions
    });
    this._blurSteps = _blurSteps;
    this.externalTextureSamplerBinding = true;
    this.onApplyObservable.add((effect2) => {
      effect2.setTextureFromPostProcess("textureSampler", originalFromInput);
      effect2.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
      _blurSteps.forEach((step, index) => {
        effect2.setTextureFromPostProcessOutput("blurStep" + (_blurSteps.length - index - 1), step);
      });
    });
    if (!blockCompilationFinal) {
      this.updateEffect();
    }
  }
  updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError) {
    if (!defines) {
      defines = "";
      defines += "#define BLUR_LEVEL " + (this._blurSteps.length - 1) + `
`;
    }
    super.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError);
  }
}

// node_modules/@babylonjs/core/PostProcesses/depthOfFieldEffect.js
var DepthOfFieldEffectBlurLevel;
(function(DepthOfFieldEffectBlurLevel2) {
  DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Low"] = 0] = "Low";
  DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Medium"] = 1] = "Medium";
  DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["High"] = 2] = "High";
})(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {}));

class DepthOfFieldEffect extends PostProcessRenderEffect {
  set focalLength(value) {
    this._thinDepthOfFieldEffect.focalLength = value;
  }
  get focalLength() {
    return this._thinDepthOfFieldEffect.focalLength;
  }
  set fStop(value) {
    this._thinDepthOfFieldEffect.fStop = value;
  }
  get fStop() {
    return this._thinDepthOfFieldEffect.fStop;
  }
  set focusDistance(value) {
    this._thinDepthOfFieldEffect.focusDistance = value;
  }
  get focusDistance() {
    return this._thinDepthOfFieldEffect.focusDistance;
  }
  set lensSize(value) {
    this._thinDepthOfFieldEffect.lensSize = value;
  }
  get lensSize() {
    return this._thinDepthOfFieldEffect.lensSize;
  }
  constructor(sceneOrEngine, depthTexture, blurLevel = 0, pipelineTextureType = 0, blockCompilation = false, depthNotNormalized = false) {
    const engine2 = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine;
    super(engine2, "depth of field", () => {
      return this._effects;
    }, true);
    this._effects = [];
    this._thinDepthOfFieldEffect = new ThinDepthOfFieldEffect("Depth of Field", engine2, blurLevel, false, blockCompilation);
    const circleOfConfusionTextureFormat = engine2.isWebGPU || engine2.version > 1 ? 6 : 5;
    this._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, {
      size: 1,
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      depthNotNormalized,
      effectWrapper: this._thinDepthOfFieldEffect._circleOfConfusion
    }, null);
    this._depthOfFieldBlurY = [];
    this._depthOfFieldBlurX = [];
    const blurCount = this._thinDepthOfFieldEffect._depthOfFieldBlurX.length;
    for (let i = 0;i < blurCount; i++) {
      const [thinBlurY, ratioY] = this._thinDepthOfFieldEffect._depthOfFieldBlurY[i];
      const blurY = new DepthOfFieldBlurPostProcess("vertical blur", null, thinBlurY.direction, thinBlurY.kernel, {
        size: ratioY,
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: engine2,
        textureType: pipelineTextureType,
        blockCompilation,
        textureFormat: i == 0 ? circleOfConfusionTextureFormat : 5,
        effectWrapper: thinBlurY
      }, null, this._circleOfConfusion, i == 0 ? this._circleOfConfusion : null);
      blurY.autoClear = false;
      const [thinBlurX, ratioX] = this._thinDepthOfFieldEffect._depthOfFieldBlurX[i];
      const blurX = new DepthOfFieldBlurPostProcess("horizontal blur", null, thinBlurX.direction, thinBlurX.kernel, {
        size: ratioX,
        samplingMode: Texture.BILINEAR_SAMPLINGMODE,
        engine: engine2,
        textureType: pipelineTextureType,
        blockCompilation,
        effectWrapper: thinBlurX
      }, null, this._circleOfConfusion, null);
      blurX.autoClear = false;
      this._depthOfFieldBlurY.push(blurY);
      this._depthOfFieldBlurX.push(blurX);
    }
    this._effects = [this._circleOfConfusion];
    for (let i = 0;i < this._depthOfFieldBlurX.length; i++) {
      this._effects.push(this._depthOfFieldBlurY[i]);
      this._effects.push(this._depthOfFieldBlurX[i]);
    }
    this._dofMerge = new DepthOfFieldMergePostProcess("dofMerge", this._circleOfConfusion, this._circleOfConfusion, this._depthOfFieldBlurX, {
      size: this._thinDepthOfFieldEffect._depthOfFieldBlurX[blurCount - 1][1],
      samplingMode: Texture.BILINEAR_SAMPLINGMODE,
      engine: engine2,
      textureType: pipelineTextureType,
      blockCompilation,
      effectWrapper: this._thinDepthOfFieldEffect._dofMerge
    }, null);
    this._dofMerge.autoClear = false;
    this._effects.push(this._dofMerge);
  }
  getClassName() {
    return "DepthOfFieldEffect";
  }
  set depthTexture(value) {
    this._circleOfConfusion.depthTexture = value;
  }
  disposeEffects(camera2) {
    for (let effectIndex = 0;effectIndex < this._effects.length; effectIndex++) {
      this._effects[effectIndex].dispose(camera2);
    }
  }
  _updateEffects() {
    for (let effectIndex = 0;effectIndex < this._effects.length; effectIndex++) {
      this._effects[effectIndex].updateEffect();
    }
  }
  _isReady() {
    return this._thinDepthOfFieldEffect.isReady();
  }
}
// node_modules/@babylonjs/core/PostProcesses/displayPassPostProcess.js
init_postProcess();
init_typeStore();
init_decorators_serialization();

class DisplayPassPostProcess extends PostProcess {
  getClassName() {
    return "DisplayPassPostProcess";
  }
  constructor(name409, options, camera2, samplingMode, engine2, reusable) {
    super(name409, "displayPass", ["passSampler"], ["passSampler"], options, camera2, samplingMode, engine2, reusable);
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_displayPass_fragment(), exports_displayPass_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_displayPass_fragment2(), exports_displayPass_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new DisplayPassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
RegisterClass("BABYLON.DisplayPassPostProcess", DisplayPassPostProcess);
// node_modules/@babylonjs/core/PostProcesses/filterPostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
init_decorators_serialization();

class FilterPostProcess extends PostProcess {
  getClassName() {
    return "FilterPostProcess";
  }
  constructor(name411, kernelMatrix, options, camera2, samplingMode, engine2, reusable) {
    super(name411, "filter", ["kernelMatrix"], null, options, camera2, samplingMode, engine2, reusable);
    this.kernelMatrix = kernelMatrix;
    this.onApply = (effect2) => {
      effect2.setMatrix("kernelMatrix", this.kernelMatrix);
    };
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_filter_fragment(), exports_filter_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_filter_fragment2(), exports_filter_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new FilterPostProcess(parsedPostProcess.name, parsedPostProcess.kernelMatrix, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serializeAsMatrix()
], FilterPostProcess.prototype, "kernelMatrix", undefined);
RegisterClass("BABYLON.FilterPostProcess", FilterPostProcess);
// node_modules/@babylonjs/core/PostProcesses/grainPostProcess.js
init_tslib_es6();
init_postProcess();
init_typeStore();
init_decorators();
init_decorators_serialization();

class GrainPostProcess extends PostProcess {
  getClassName() {
    return "GrainPostProcess";
  }
  constructor(name413, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    super(name413, "grain", ["intensity", "animatedSeed"], [], options, camera2, samplingMode, engine2, reusable, null, textureType, undefined, null, blockCompilation);
    this.intensity = 30;
    this.animated = false;
    this.onApplyObservable.add((effect2) => {
      effect2.setFloat("intensity", this.intensity);
      effect2.setFloat("animatedSeed", this.animated ? Math.random() + 1 : 1);
    });
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_grain_fragment(), exports_grain_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_grain_fragment2(), exports_grain_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], GrainPostProcess.prototype, "intensity", undefined);
__decorate([
  serialize()
], GrainPostProcess.prototype, "animated", undefined);
RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess);
// node_modules/@babylonjs/core/PostProcesses/highlightsPostProcess.js
init_postProcess();
// node_modules/@babylonjs/core/PostProcesses/imageProcessingPostProcess.js
init_tslib_es6();
init_decorators();
init_imageProcessingConfiguration();
init_postProcess();
init_engineStore();

class ImageProcessingPostProcess extends PostProcess {
  get imageProcessingConfiguration() {
    return this._imageProcessingConfiguration;
  }
  set imageProcessingConfiguration(value) {
    value.applyByPostProcess = true;
    this._attachImageProcessingConfiguration(value);
  }
  _attachImageProcessingConfiguration(configuration, doNotBuild = false) {
    if (configuration === this._imageProcessingConfiguration) {
      return;
    }
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (!configuration) {
      let scene = null;
      const engine2 = this.getEngine();
      const camera2 = this.getCamera();
      if (camera2) {
        scene = camera2.getScene();
      } else if (engine2 && engine2.scenes) {
        const scenes = engine2.scenes;
        scene = scenes[scenes.length - 1];
      } else {
        scene = EngineStore.LastCreatedScene;
      }
      if (scene) {
        this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
      } else {
        this._imageProcessingConfiguration = new ImageProcessingConfiguration;
      }
    } else {
      this._imageProcessingConfiguration = configuration;
    }
    if (this._imageProcessingConfiguration) {
      this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
        this._updateParameters();
      });
    }
    if (!doNotBuild) {
      this._updateParameters();
    }
  }
  get isSupported() {
    const effect2 = this.getEffect();
    return !effect2 || effect2.isSupported;
  }
  get colorCurves() {
    return this.imageProcessingConfiguration.colorCurves;
  }
  set colorCurves(value) {
    this.imageProcessingConfiguration.colorCurves = value;
  }
  get colorCurvesEnabled() {
    return this.imageProcessingConfiguration.colorCurvesEnabled;
  }
  set colorCurvesEnabled(value) {
    this.imageProcessingConfiguration.colorCurvesEnabled = value;
  }
  get colorGradingTexture() {
    return this.imageProcessingConfiguration.colorGradingTexture;
  }
  set colorGradingTexture(value) {
    this.imageProcessingConfiguration.colorGradingTexture = value;
  }
  get colorGradingEnabled() {
    return this.imageProcessingConfiguration.colorGradingEnabled;
  }
  set colorGradingEnabled(value) {
    this.imageProcessingConfiguration.colorGradingEnabled = value;
  }
  get exposure() {
    return this.imageProcessingConfiguration.exposure;
  }
  set exposure(value) {
    this.imageProcessingConfiguration.exposure = value;
  }
  get toneMappingEnabled() {
    return this._imageProcessingConfiguration.toneMappingEnabled;
  }
  set toneMappingEnabled(value) {
    this._imageProcessingConfiguration.toneMappingEnabled = value;
  }
  get toneMappingType() {
    return this._imageProcessingConfiguration.toneMappingType;
  }
  set toneMappingType(value) {
    this._imageProcessingConfiguration.toneMappingType = value;
  }
  get contrast() {
    return this.imageProcessingConfiguration.contrast;
  }
  set contrast(value) {
    this.imageProcessingConfiguration.contrast = value;
  }
  get vignetteStretch() {
    return this.imageProcessingConfiguration.vignetteStretch;
  }
  set vignetteStretch(value) {
    this.imageProcessingConfiguration.vignetteStretch = value;
  }
  get vignetteCentreX() {
    return this.imageProcessingConfiguration.vignetteCenterX;
  }
  set vignetteCentreX(value) {
    this.imageProcessingConfiguration.vignetteCenterX = value;
  }
  get vignetteCentreY() {
    return this.imageProcessingConfiguration.vignetteCenterY;
  }
  set vignetteCentreY(value) {
    this.imageProcessingConfiguration.vignetteCenterY = value;
  }
  get vignetteCenterY() {
    return this.imageProcessingConfiguration.vignetteCenterY;
  }
  set vignetteCenterY(value) {
    this.imageProcessingConfiguration.vignetteCenterY = value;
  }
  get vignetteCenterX() {
    return this.imageProcessingConfiguration.vignetteCenterX;
  }
  set vignetteCenterX(value) {
    this.imageProcessingConfiguration.vignetteCenterX = value;
  }
  get vignetteWeight() {
    return this.imageProcessingConfiguration.vignetteWeight;
  }
  set vignetteWeight(value) {
    this.imageProcessingConfiguration.vignetteWeight = value;
  }
  get vignetteColor() {
    return this.imageProcessingConfiguration.vignetteColor;
  }
  set vignetteColor(value) {
    this.imageProcessingConfiguration.vignetteColor = value;
  }
  get vignetteCameraFov() {
    return this.imageProcessingConfiguration.vignetteCameraFov;
  }
  set vignetteCameraFov(value) {
    this.imageProcessingConfiguration.vignetteCameraFov = value;
  }
  get vignetteBlendMode() {
    return this.imageProcessingConfiguration.vignetteBlendMode;
  }
  set vignetteBlendMode(value) {
    this.imageProcessingConfiguration.vignetteBlendMode = value;
  }
  get vignetteEnabled() {
    return this.imageProcessingConfiguration.vignetteEnabled;
  }
  set vignetteEnabled(value) {
    this.imageProcessingConfiguration.vignetteEnabled = value;
  }
  get ditheringIntensity() {
    return this.imageProcessingConfiguration.ditheringIntensity;
  }
  set ditheringIntensity(value) {
    this.imageProcessingConfiguration.ditheringIntensity = value;
  }
  get ditheringEnabled() {
    return this.imageProcessingConfiguration.ditheringEnabled;
  }
  set ditheringEnabled(value) {
    this.imageProcessingConfiguration.ditheringEnabled = value;
  }
  get fromLinearSpace() {
    return this._fromLinearSpace;
  }
  set fromLinearSpace(value) {
    if (this._fromLinearSpace === value) {
      return;
    }
    this._fromLinearSpace = value;
    this._updateParameters();
  }
  constructor(name415, options, camera2 = null, samplingMode, engine2, reusable, textureType = 0, imageProcessingConfiguration2) {
    super(name415, "imageProcessing", [], [], options, camera2, samplingMode, engine2, reusable, null, textureType, "postprocess", null, true);
    this._fromLinearSpace = true;
    this._defines = {
      IMAGEPROCESSING: false,
      VIGNETTE: false,
      VIGNETTEBLENDMODEMULTIPLY: false,
      VIGNETTEBLENDMODEOPAQUE: false,
      TONEMAPPING: 0,
      CONTRAST: false,
      COLORCURVES: false,
      COLORGRADING: false,
      COLORGRADING3D: false,
      FROMLINEARSPACE: false,
      SAMPLER3DGREENDEPTH: false,
      SAMPLER3DBGRMAP: false,
      DITHER: false,
      IMAGEPROCESSINGPOSTPROCESS: false,
      EXPOSURE: false,
      SKIPFINALCOLORCLAMP: false
    };
    if (imageProcessingConfiguration2) {
      imageProcessingConfiguration2.applyByPostProcess = true;
      this._attachImageProcessingConfiguration(imageProcessingConfiguration2, true);
      this._updateParameters();
    } else {
      this._attachImageProcessingConfiguration(null, true);
      this.imageProcessingConfiguration.applyByPostProcess = true;
    }
    this.onApply = (effect2) => {
      this.imageProcessingConfiguration.bind(effect2, this.aspectRatio);
    };
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.resolve().then(() => (init_imageProcessing_fragment(), exports_imageProcessing_fragment)));
    } else {
      list.push(Promise.resolve().then(() => (init_imageProcessing_fragment2(), exports_imageProcessing_fragment2)));
    }
    super._gatherImports(useWebGPU, list);
  }
  getClassName() {
    return "ImageProcessingPostProcess";
  }
  _updateParameters() {
    this._defines.FROMLINEARSPACE = this._fromLinearSpace;
    this.imageProcessingConfiguration.prepareDefines(this._defines, true);
    let defines = "";
    for (const prop in this._defines) {
      const value = this._defines[prop];
      const type = typeof value;
      switch (type) {
        case "number":
        case "string":
          defines += `#define ${prop} ${value};
`;
          break;
        default:
          if (value) {
            defines += `#define ${prop};
`;
          }
          break;
      }
    }
    const samplers = ["textureSampler"];
    const uniforms = ["scale"];
    if (ImageProcessingConfiguration) {
      ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
      ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
    }
    this.updateEffect(defines, uniforms, samplers);
  }
  dispose(camera2) {
    super.dispose(camera2);
    if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
      this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
    }
    if (this._imageProcessingConfiguration) {
      this.imageProcessingConfiguration.applyByPostProcess = false;
    }
  }
}
__decorate([
  serialize()
], ImageProcessingPostProcess.prototype, "_fromLinearSpace", undefined);
// node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js
init_tslib_es6();
init_logger();
init_math_vector();
init_postProcess();

// node_modules/@babylonjs/core/Rendering/geometryBufferRenderer.js
init_math_vector();
init_buffer();
init_texture();
init_math_color();
init_devTools();
init_geometry_fragment();
init_geometry_vertex();
init_materialHelper_functions();
var uniforms = [
  "world",
  "mBones",
  "viewProjection",
  "diffuseMatrix",
  "view",
  "previousWorld",
  "previousViewProjection",
  "mPreviousBones",
  "bumpMatrix",
  "reflectivityMatrix",
  "albedoMatrix",
  "reflectivityColor",
  "albedoColor",
  "metallic",
  "glossiness",
  "vTangentSpaceParams",
  "vBumpInfos",
  "morphTargetInfluences",
  "morphTargetCount",
  "morphTargetTextureInfo",
  "morphTargetTextureIndices",
  "boneTextureWidth"
];
addClipPlaneUniforms(uniforms);

class GeometryBufferRenderer {
  get normalsAreUnsigned() {
    return this._normalsAreUnsigned;
  }
  _linkPrePassRenderer(prePassRenderer) {
    this._linkedWithPrePass = true;
    this._prePassRenderer = prePassRenderer;
    if (this._multiRenderTarget) {
      this._multiRenderTarget.onClearObservable.clear();
      this._multiRenderTarget.onClearObservable.add(() => {});
    }
  }
  _unlinkPrePassRenderer() {
    this._linkedWithPrePass = false;
    this._createRenderTargets();
  }
  _resetLayout() {
    this._enableDepth = true;
    this._enableNormal = true;
    this._enablePosition = false;
    this._enableReflectivity = false;
    this._enableVelocity = false;
    this._enableVelocityLinear = false;
    this._enableScreenspaceDepth = false;
    this._attachmentsFromPrePass = [];
  }
  _forceTextureType(geometryBufferType, index) {
    if (geometryBufferType === GeometryBufferRenderer.POSITION_TEXTURE_TYPE) {
      this._positionIndex = index;
      this._enablePosition = true;
    } else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) {
      this._velocityIndex = index;
      this._enableVelocity = true;
    } else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE) {
      this._velocityLinearIndex = index;
      this._enableVelocityLinear = true;
    } else if (geometryBufferType === GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) {
      this._reflectivityIndex = index;
      this._enableReflectivity = true;
    } else if (geometryBufferType === GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) {
      this._depthIndex = index;
      this._enableDepth = true;
    } else if (geometryBufferType === GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) {
      this._normalIndex = index;
      this._enableNormal = true;
    } else if (geometryBufferType === GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE) {
      this._screenspaceDepthIndex = index;
      this._enableScreenspaceDepth = true;
    }
  }
  _setAttachments(attachments) {
    this._attachmentsFromPrePass = attachments;
  }
  _linkInternalTexture(internalTexture2) {
    this._multiRenderTarget.setInternalTexture(internalTexture2, 0, false);
  }
  get renderList() {
    return this._multiRenderTarget.renderList;
  }
  set renderList(meshes) {
    this._multiRenderTarget.renderList = meshes;
  }
  get isSupported() {
    return this._multiRenderTarget.isSupported;
  }
  getTextureIndex(textureType) {
    switch (textureType) {
      case GeometryBufferRenderer.POSITION_TEXTURE_TYPE:
        return this._positionIndex;
      case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:
        return this._velocityIndex;
      case GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE:
        return this._velocityLinearIndex;
      case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:
        return this._reflectivityIndex;
      case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE:
        return this._depthIndex;
      case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE:
        return this._normalIndex;
      case GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE:
        return this._screenspaceDepthIndex;
      default:
        return -1;
    }
  }
  get enableDepth() {
    return this._enableDepth;
  }
  set enableDepth(enable) {
    this._enableDepth = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get enableNormal() {
    return this._enableNormal;
  }
  set enableNormal(enable) {
    this._enableNormal = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get enablePosition() {
    return this._enablePosition;
  }
  set enablePosition(enable) {
    this._enablePosition = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get enableVelocity() {
    return this._enableVelocity;
  }
  set enableVelocity(enable) {
    this._enableVelocity = enable;
    if (!enable) {
      this._previousTransformationMatrices = {};
    }
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
    this._scene.needsPreviousWorldMatrices = enable;
  }
  get enableVelocityLinear() {
    return this._enableVelocityLinear;
  }
  set enableVelocityLinear(enable) {
    this._enableVelocityLinear = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get enableReflectivity() {
    return this._enableReflectivity;
  }
  set enableReflectivity(enable) {
    this._enableReflectivity = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get enableScreenspaceDepth() {
    return this._enableScreenspaceDepth;
  }
  set enableScreenspaceDepth(enable) {
    this._enableScreenspaceDepth = enable;
    if (!this._linkedWithPrePass) {
      this.dispose();
      this._createRenderTargets();
    }
  }
  get scene() {
    return this._scene;
  }
  get ratio() {
    return typeof this._ratioOrDimensions === "object" ? 1 : this._ratioOrDimensions;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene, ratioOrDimensions = 1, depthFormat = 15, textureTypesAndFormats) {
    this._previousTransformationMatrices = {};
    this._previousBonesTransformationMatrices = {};
    this.excludedSkinnedMeshesFromVelocity = [];
    this.renderTransparentMeshes = true;
    this.generateNormalsInWorldSpace = false;
    this._normalsAreUnsigned = false;
    this._resizeObserver = null;
    this._enableDepth = true;
    this._enableNormal = true;
    this._enablePosition = false;
    this._enableVelocity = false;
    this._enableVelocityLinear = false;
    this._enableReflectivity = false;
    this._enableScreenspaceDepth = false;
    this._clearColor = new Color4(0, 0, 0, 0);
    this._clearDepthColor = new Color4(1e8, 0, 0, 1);
    this._positionIndex = -1;
    this._velocityIndex = -1;
    this._velocityLinearIndex = -1;
    this._reflectivityIndex = -1;
    this._depthIndex = -1;
    this._normalIndex = -1;
    this._screenspaceDepthIndex = -1;
    this._linkedWithPrePass = false;
    this.useSpecificClearForDepthTexture = false;
    this._shaderLanguage = 0;
    this._shadersLoaded = false;
    this._scene = scene;
    this._ratioOrDimensions = ratioOrDimensions;
    this._useUbo = scene.getEngine().supportsUniformBuffers;
    this._depthFormat = depthFormat;
    this._textureTypesAndFormats = textureTypesAndFormats || {};
    this._initShaderSourceAsync();
    GeometryBufferRenderer._SceneComponentInitialization(this._scene);
    this._createRenderTargets();
  }
  async _initShaderSourceAsync() {
    const engine2 = this._scene.getEngine();
    if (engine2.isWebGPU && !GeometryBufferRenderer.ForceGLSL) {
      this._shaderLanguage = 1;
      await Promise.all([Promise.resolve().then(() => (init_geometry_vertex2(), exports_geometry_vertex2)), Promise.resolve().then(() => (init_geometry_fragment2(), exports_geometry_fragment2))]);
    } else {
      await Promise.all([Promise.resolve().then(() => (init_geometry_vertex(), exports_geometry_vertex)), Promise.resolve().then(() => (init_geometry_fragment(), exports_geometry_fragment))]);
    }
    this._shadersLoaded = true;
  }
  isReady(subMesh2, useInstances) {
    if (!this._shadersLoaded) {
      return false;
    }
    const material2 = subMesh2.getMaterial();
    if (material2 && material2.disableDepthWrite) {
      return false;
    }
    const defines = [];
    const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
    const mesh2 = subMesh2.getMesh();
    let uv1 = false;
    let uv2 = false;
    const color = false;
    if (material2) {
      let needUv = false;
      if (material2.needAlphaTestingForMesh(mesh2) && material2.getAlphaTestTexture()) {
        defines.push("#define ALPHATEST");
        defines.push(`#define ALPHATEST_UV${material2.getAlphaTestTexture().coordinatesIndex + 1}`);
        needUv = true;
      }
      if ((material2.bumpTexture || material2.normalTexture) && MaterialFlags.BumpTextureEnabled) {
        const texture2 = material2.bumpTexture || material2.normalTexture;
        defines.push("#define BUMP");
        defines.push(`#define BUMP_UV${texture2.coordinatesIndex + 1}`);
        needUv = true;
      }
      if (this._enableReflectivity) {
        let metallicWorkflow = false;
        if (material2.getClassName() === "PBRMetallicRoughnessMaterial") {
          if (material2.metallicRoughnessTexture) {
            defines.push("#define ORMTEXTURE");
            defines.push(`#define REFLECTIVITY_UV${material2.metallicRoughnessTexture.coordinatesIndex + 1}`);
            defines.push("#define METALLICWORKFLOW");
            needUv = true;
            metallicWorkflow = true;
          }
          if (material2.metallic != null) {
            defines.push("#define METALLIC");
            defines.push("#define METALLICWORKFLOW");
            metallicWorkflow = true;
          }
          if (material2.roughness != null) {
            defines.push("#define ROUGHNESS");
            defines.push("#define METALLICWORKFLOW");
            metallicWorkflow = true;
          }
          if (metallicWorkflow) {
            if (material2.baseTexture) {
              defines.push("#define ALBEDOTEXTURE");
              defines.push(`#define ALBEDO_UV${material2.baseTexture.coordinatesIndex + 1}`);
              if (material2.baseTexture.gammaSpace) {
                defines.push("#define GAMMAALBEDO");
              }
              needUv = true;
            }
            if (material2.baseColor) {
              defines.push("#define ALBEDOCOLOR");
            }
          }
        } else if (material2.getClassName() === "PBRSpecularGlossinessMaterial") {
          if (material2.specularGlossinessTexture) {
            defines.push("#define SPECULARGLOSSINESSTEXTURE");
            defines.push(`#define REFLECTIVITY_UV${material2.specularGlossinessTexture.coordinatesIndex + 1}`);
            needUv = true;
            if (material2.specularGlossinessTexture.gammaSpace) {
              defines.push("#define GAMMAREFLECTIVITYTEXTURE");
            }
          } else {
            if (material2.specularColor) {
              defines.push("#define REFLECTIVITYCOLOR");
            }
          }
          if (material2.glossiness != null) {
            defines.push("#define GLOSSINESS");
          }
        } else if (material2.getClassName() === "PBRMaterial") {
          if (material2.metallicTexture) {
            defines.push("#define ORMTEXTURE");
            defines.push(`#define REFLECTIVITY_UV${material2.metallicTexture.coordinatesIndex + 1}`);
            defines.push("#define METALLICWORKFLOW");
            needUv = true;
            metallicWorkflow = true;
          }
          if (material2.metallic != null) {
            defines.push("#define METALLIC");
            defines.push("#define METALLICWORKFLOW");
            metallicWorkflow = true;
          }
          if (material2.roughness != null) {
            defines.push("#define ROUGHNESS");
            defines.push("#define METALLICWORKFLOW");
            metallicWorkflow = true;
          }
          if (metallicWorkflow) {
            if (material2.albedoTexture) {
              defines.push("#define ALBEDOTEXTURE");
              defines.push(`#define ALBEDO_UV${material2.albedoTexture.coordinatesIndex + 1}`);
              if (material2.albedoTexture.gammaSpace) {
                defines.push("#define GAMMAALBEDO");
              }
              needUv = true;
            }
            if (material2.albedoColor) {
              defines.push("#define ALBEDOCOLOR");
            }
          } else {
            if (material2.reflectivityTexture) {
              defines.push("#define SPECULARGLOSSINESSTEXTURE");
              defines.push(`#define REFLECTIVITY_UV${material2.reflectivityTexture.coordinatesIndex + 1}`);
              if (material2.reflectivityTexture.gammaSpace) {
                defines.push("#define GAMMAREFLECTIVITYTEXTURE");
              }
              needUv = true;
            } else if (material2.reflectivityColor) {
              defines.push("#define REFLECTIVITYCOLOR");
            }
            if (material2.microSurface != null) {
              defines.push("#define GLOSSINESS");
            }
          }
        } else if (material2.getClassName() === "StandardMaterial") {
          if (material2.specularTexture) {
            defines.push("#define REFLECTIVITYTEXTURE");
            defines.push(`#define REFLECTIVITY_UV${material2.specularTexture.coordinatesIndex + 1}`);
            if (material2.specularTexture.gammaSpace) {
              defines.push("#define GAMMAREFLECTIVITYTEXTURE");
            }
            needUv = true;
          }
          if (material2.specularColor) {
            defines.push("#define REFLECTIVITYCOLOR");
          }
        }
      }
      if (needUv) {
        defines.push("#define NEED_UV");
        if (mesh2.isVerticesDataPresent(VertexBuffer.UVKind)) {
          attribs.push(VertexBuffer.UVKind);
          defines.push("#define UV1");
          uv1 = true;
        }
        if (mesh2.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
          attribs.push(VertexBuffer.UV2Kind);
          defines.push("#define UV2");
          uv2 = true;
        }
      }
    }
    if (this._enableDepth) {
      defines.push("#define DEPTH");
      defines.push("#define DEPTH_INDEX " + this._depthIndex);
    }
    if (this._enableNormal) {
      defines.push("#define NORMAL");
      defines.push("#define NORMAL_INDEX " + this._normalIndex);
    }
    if (this._enablePosition) {
      defines.push("#define POSITION");
      defines.push("#define POSITION_INDEX " + this._positionIndex);
    }
    if (this._enableVelocity) {
      defines.push("#define VELOCITY");
      defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
      if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh2) === -1) {
        defines.push("#define BONES_VELOCITY_ENABLED");
      }
    }
    if (this._enableVelocityLinear) {
      defines.push("#define VELOCITY_LINEAR");
      defines.push("#define VELOCITY_LINEAR_INDEX " + this._velocityLinearIndex);
      if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh2) === -1) {
        defines.push("#define BONES_VELOCITY_ENABLED");
      }
    }
    if (this._enableReflectivity) {
      defines.push("#define REFLECTIVITY");
      defines.push("#define REFLECTIVITY_INDEX " + this._reflectivityIndex);
    }
    if (this._enableScreenspaceDepth) {
      if (this._screenspaceDepthIndex !== -1) {
        defines.push("#define SCREENSPACE_DEPTH_INDEX " + this._screenspaceDepthIndex);
        defines.push("#define SCREENSPACE_DEPTH");
      }
    }
    if (this.generateNormalsInWorldSpace) {
      defines.push("#define NORMAL_WORLDSPACE");
    }
    if (this._normalsAreUnsigned) {
      defines.push("#define ENCODE_NORMAL");
    }
    if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh2.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
      defines.push("#define BONETEXTURE " + mesh2.skeleton.isUsingTextureForMatrices);
      defines.push("#define BonesPerMesh " + (mesh2.skeleton.bones.length + 1));
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
      defines.push("#define BONETEXTURE false");
      defines.push("#define BonesPerMesh 0");
    }
    const numMorphInfluencers = mesh2.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh2.morphTargetManager, defines, attribs, mesh2, true, true, false, uv1, uv2, color) : 0;
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs, this._enableVelocity || this._enableVelocityLinear);
      if (subMesh2.getRenderingMesh().hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
      }
    }
    if (this._linkedWithPrePass) {
      defines.push("#define SCENE_MRT_COUNT " + this._attachmentsFromPrePass.length);
    } else {
      defines.push("#define SCENE_MRT_COUNT " + this._multiRenderTarget.textures.length);
    }
    prepareStringDefinesForClipPlanes(material2, this._scene, defines);
    const engine2 = this._scene.getEngine();
    const drawWrapper2 = subMesh2._getDrawWrapper(undefined, true);
    const cachedDefines = drawWrapper2.defines;
    const join6 = defines.join(`
`);
    if (cachedDefines !== join6) {
      drawWrapper2.setEffect(engine2.createEffect("geometry", {
        attributes: attribs,
        uniformsNames: uniforms,
        samplers: ["diffuseSampler", "bumpSampler", "reflectivitySampler", "albedoSampler", "morphTargets", "boneSampler"],
        defines: join6,
        onCompiled: null,
        fallbacks: null,
        onError: null,
        uniformBuffersNames: ["Scene"],
        indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers },
        shaderLanguage: this.shaderLanguage
      }, engine2), join6);
    }
    return drawWrapper2.effect.isReady();
  }
  getGBuffer() {
    return this._multiRenderTarget;
  }
  get samples() {
    return this._multiRenderTarget.samples;
  }
  set samples(value) {
    this._multiRenderTarget.samples = value;
  }
  dispose() {
    if (this._resizeObserver) {
      const engine2 = this._scene.getEngine();
      engine2.onResizeObservable.remove(this._resizeObserver);
      this._resizeObserver = null;
    }
    this.getGBuffer().dispose();
  }
  _assignRenderTargetIndices() {
    const textureNames = [];
    const textureTypesAndFormats = [];
    let count = 0;
    if (this._enableDepth) {
      this._depthIndex = count;
      count++;
      textureNames.push("gBuffer_Depth");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.DEPTH_TEXTURE_TYPE]);
    }
    if (this._enableNormal) {
      this._normalIndex = count;
      count++;
      textureNames.push("gBuffer_Normal");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE]);
    }
    if (this._enablePosition) {
      this._positionIndex = count;
      count++;
      textureNames.push("gBuffer_Position");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.POSITION_TEXTURE_TYPE]);
    }
    if (this._enableVelocity) {
      this._velocityIndex = count;
      count++;
      textureNames.push("gBuffer_Velocity");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE]);
    }
    if (this._enableVelocityLinear) {
      this._velocityLinearIndex = count;
      count++;
      textureNames.push("gBuffer_VelocityLinear");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE]);
    }
    if (this._enableReflectivity) {
      this._reflectivityIndex = count;
      count++;
      textureNames.push("gBuffer_Reflectivity");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE]);
    }
    if (this._enableScreenspaceDepth) {
      this._screenspaceDepthIndex = count;
      count++;
      textureNames.push("gBuffer_ScreenspaceDepth");
      textureTypesAndFormats.push(this._textureTypesAndFormats[GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE]);
    }
    return [count, textureNames, textureTypesAndFormats];
  }
  _createRenderTargets() {
    const engine2 = this._scene.getEngine();
    const [count, textureNames, textureTypesAndFormat] = this._assignRenderTargetIndices();
    let type = 0;
    if (engine2._caps.textureFloat && engine2._caps.textureFloatLinearFiltering) {
      type = 1;
    } else if (engine2._caps.textureHalfFloat && engine2._caps.textureHalfFloatLinearFiltering) {
      type = 2;
    }
    const dimensions = this._ratioOrDimensions.width !== undefined ? this._ratioOrDimensions : { width: engine2.getRenderWidth() * this._ratioOrDimensions, height: engine2.getRenderHeight() * this._ratioOrDimensions };
    const textureTypes = [];
    const textureFormats = [];
    for (const typeAndFormat of textureTypesAndFormat) {
      if (typeAndFormat) {
        textureTypes.push(typeAndFormat.textureType);
        textureFormats.push(typeAndFormat.textureFormat);
      } else {
        textureTypes.push(type);
        textureFormats.push(5);
      }
    }
    this._normalsAreUnsigned = textureTypes[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 11 || textureTypes[GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 13;
    this._multiRenderTarget = new MultiRenderTarget("gBuffer", dimensions, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, types: textureTypes, formats: textureFormats, depthTextureFormat: this._depthFormat }, textureNames.concat("gBuffer_DepthBuffer"));
    if (!this.isSupported) {
      return;
    }
    this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._multiRenderTarget.refreshRate = 1;
    this._multiRenderTarget.renderParticles = false;
    this._multiRenderTarget.renderList = null;
    const layoutAttachmentsAll = [true];
    const layoutAttachmentsAllButDepth = [false];
    const layoutAttachmentsDepthOnly = [true];
    for (let i = 1;i < count; ++i) {
      layoutAttachmentsAll.push(true);
      layoutAttachmentsDepthOnly.push(false);
      layoutAttachmentsAllButDepth.push(true);
    }
    const attachmentsAll = engine2.buildTextureLayout(layoutAttachmentsAll);
    const attachmentsAllButDepth = engine2.buildTextureLayout(layoutAttachmentsAllButDepth);
    const attachmentsDepthOnly = engine2.buildTextureLayout(layoutAttachmentsDepthOnly);
    this._multiRenderTarget.onClearObservable.add((engine3) => {
      engine3.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll);
      engine3.clear(this._clearColor, true, true, true);
      if (this.useSpecificClearForDepthTexture) {
        engine3.bindAttachments(attachmentsDepthOnly);
        engine3.clear(this._clearDepthColor, true, true, true);
      }
      engine3.bindAttachments(attachmentsAll);
    });
    this._resizeObserver = engine2.onResizeObservable.add(() => {
      if (this._multiRenderTarget) {
        const dimensions2 = this._ratioOrDimensions.width !== undefined ? this._ratioOrDimensions : { width: engine2.getRenderWidth() * this._ratioOrDimensions, height: engine2.getRenderHeight() * this._ratioOrDimensions };
        this._multiRenderTarget.resize(dimensions2);
      }
    });
    const renderSubMesh = (subMesh2) => {
      const renderingMesh = subMesh2.getRenderingMesh();
      const effectiveMesh = subMesh2.getEffectiveMesh();
      const scene = this._scene;
      const engine3 = scene.getEngine();
      const material2 = subMesh2.getMaterial();
      if (!material2) {
        return;
      }
      effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
      if ((this._enableVelocity || this._enableVelocityLinear) && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) {
        this._previousTransformationMatrices[effectiveMesh.uniqueId] = {
          world: Matrix.Identity(),
          viewProjection: scene.getTransformMatrix()
        };
        if (renderingMesh.skeleton) {
          const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh);
          this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length));
        }
      }
      const batch = renderingMesh._getInstancesRenderList(subMesh2._id, !!subMesh2.getReplacementMesh());
      if (batch.mustReturn) {
        return;
      }
      const hardwareInstancedRendering = engine3.getCaps().instancedArrays && (batch.visibleInstances[subMesh2._id] !== null || renderingMesh.hasThinInstances);
      const world = effectiveMesh.getWorldMatrix();
      if (this.isReady(subMesh2, hardwareInstancedRendering)) {
        const drawWrapper2 = subMesh2._getDrawWrapper();
        if (!drawWrapper2) {
          return;
        }
        const effect2 = drawWrapper2.effect;
        engine3.enableEffect(drawWrapper2);
        if (!hardwareInstancedRendering) {
          renderingMesh._bind(subMesh2, effect2, material2.fillMode);
        }
        if (!this._useUbo) {
          effect2.setMatrix("viewProjection", scene.getTransformMatrix());
          effect2.setMatrix("view", scene.getViewMatrix());
        } else {
          BindSceneUniformBuffer(effect2, this._scene.getSceneUniformBuffer());
          this._scene.finalizeSceneUbo();
        }
        let sideOrientation;
        const instanceDataStorage = renderingMesh._instanceDataStorage;
        if (!instanceDataStorage.isFrozen && (material2.backFaceCulling || material2.sideOrientation !== null)) {
          const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();
          sideOrientation = material2._getEffectiveOrientation(renderingMesh);
          if (mainDeterminant < 0) {
            sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;
          }
        } else {
          sideOrientation = instanceDataStorage.sideOrientation;
        }
        material2._preBind(drawWrapper2, sideOrientation);
        if (material2.needAlphaTestingForMesh(effectiveMesh)) {
          const alphaTexture = material2.getAlphaTestTexture();
          if (alphaTexture) {
            effect2.setTexture("diffuseSampler", alphaTexture);
            effect2.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
          }
        }
        if ((material2.bumpTexture || material2.normalTexture) && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) {
          const texture2 = material2.bumpTexture || material2.normalTexture;
          effect2.setFloat3("vBumpInfos", texture2.coordinatesIndex, 1 / texture2.level, material2.parallaxScaleBias);
          effect2.setMatrix("bumpMatrix", texture2.getTextureMatrix());
          effect2.setTexture("bumpSampler", texture2);
          effect2.setFloat2("vTangentSpaceParams", material2.invertNormalMapX ? -1 : 1, material2.invertNormalMapY ? -1 : 1);
        }
        if (this._enableReflectivity) {
          if (material2.getClassName() === "PBRMetallicRoughnessMaterial") {
            if (material2.metallicRoughnessTexture !== null) {
              effect2.setTexture("reflectivitySampler", material2.metallicRoughnessTexture);
              effect2.setMatrix("reflectivityMatrix", material2.metallicRoughnessTexture.getTextureMatrix());
            }
            if (material2.metallic !== null) {
              effect2.setFloat("metallic", material2.metallic);
            }
            if (material2.roughness !== null) {
              effect2.setFloat("glossiness", 1 - material2.roughness);
            }
            if (material2.baseTexture !== null) {
              effect2.setTexture("albedoSampler", material2.baseTexture);
              effect2.setMatrix("albedoMatrix", material2.baseTexture.getTextureMatrix());
            }
            if (material2.baseColor !== null) {
              effect2.setColor3("albedoColor", material2.baseColor);
            }
          } else if (material2.getClassName() === "PBRSpecularGlossinessMaterial") {
            if (material2.specularGlossinessTexture !== null) {
              effect2.setTexture("reflectivitySampler", material2.specularGlossinessTexture);
              effect2.setMatrix("reflectivityMatrix", material2.specularGlossinessTexture.getTextureMatrix());
            } else {
              if (material2.specularColor !== null) {
                effect2.setColor3("reflectivityColor", material2.specularColor);
              }
            }
            if (material2.glossiness !== null) {
              effect2.setFloat("glossiness", material2.glossiness);
            }
          } else if (material2.getClassName() === "PBRMaterial") {
            if (material2.metallicTexture !== null) {
              effect2.setTexture("reflectivitySampler", material2.metallicTexture);
              effect2.setMatrix("reflectivityMatrix", material2.metallicTexture.getTextureMatrix());
            }
            if (material2.metallic !== null) {
              effect2.setFloat("metallic", material2.metallic);
            }
            if (material2.roughness !== null) {
              effect2.setFloat("glossiness", 1 - material2.roughness);
            }
            if (material2.roughness !== null || material2.metallic !== null || material2.metallicTexture !== null) {
              if (material2.albedoTexture !== null) {
                effect2.setTexture("albedoSampler", material2.albedoTexture);
                effect2.setMatrix("albedoMatrix", material2.albedoTexture.getTextureMatrix());
              }
              if (material2.albedoColor !== null) {
                effect2.setColor3("albedoColor", material2.albedoColor);
              }
            } else {
              if (material2.reflectivityTexture !== null) {
                effect2.setTexture("reflectivitySampler", material2.reflectivityTexture);
                effect2.setMatrix("reflectivityMatrix", material2.reflectivityTexture.getTextureMatrix());
              } else if (material2.reflectivityColor !== null) {
                effect2.setColor3("reflectivityColor", material2.reflectivityColor);
              }
              if (material2.microSurface !== null) {
                effect2.setFloat("glossiness", material2.microSurface);
              }
            }
          } else if (material2.getClassName() === "StandardMaterial") {
            if (material2.specularTexture !== null) {
              effect2.setTexture("reflectivitySampler", material2.specularTexture);
              effect2.setMatrix("reflectivityMatrix", material2.specularTexture.getTextureMatrix());
            }
            if (material2.specularColor !== null) {
              effect2.setColor3("reflectivityColor", material2.specularColor);
            }
          }
        }
        bindClipPlane(effect2, material2, this._scene);
        if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
          const skeleton2 = renderingMesh.skeleton;
          if (skeleton2.isUsingTextureForMatrices && effect2.getUniformIndex("boneTextureWidth") > -1) {
            const boneTexture = skeleton2.getTransformMatrixTexture(renderingMesh);
            effect2.setTexture("boneSampler", boneTexture);
            effect2.setFloat("boneTextureWidth", 4 * (skeleton2.bones.length + 1));
          } else {
            effect2.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh));
          }
          if (this._enableVelocity || this._enableVelocityLinear) {
            effect2.setMatrices("mPreviousBones", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]);
          }
        }
        BindMorphTargetParameters(renderingMesh, effect2);
        if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
          renderingMesh.morphTargetManager._bind(effect2);
        }
        if (this._enableVelocity || this._enableVelocityLinear) {
          effect2.setMatrix("previousWorld", this._previousTransformationMatrices[effectiveMesh.uniqueId].world);
          effect2.setMatrix("previousViewProjection", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection);
        }
        if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {
          effect2.setMatrix("world", world);
        }
        renderingMesh._processRendering(effectiveMesh, subMesh2, effect2, material2.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => {
          if (!isInstance) {
            effect2.setMatrix("world", w);
          }
        });
      }
      if (this._enableVelocity || this._enableVelocityLinear) {
        this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone();
        this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone();
        if (renderingMesh.skeleton) {
          this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]);
        }
      }
    };
    this._multiRenderTarget.customIsReadyFunction = (mesh2, refreshRate, preWarm) => {
      if ((preWarm || refreshRate === 0) && mesh2.subMeshes) {
        for (let i = 0;i < mesh2.subMeshes.length; ++i) {
          const subMesh2 = mesh2.subMeshes[i];
          const material2 = subMesh2.getMaterial();
          const renderingMesh = subMesh2.getRenderingMesh();
          if (!material2) {
            continue;
          }
          const batch = renderingMesh._getInstancesRenderList(subMesh2._id, !!subMesh2.getReplacementMesh());
          const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh2._id] !== null || renderingMesh.hasThinInstances);
          if (!this.isReady(subMesh2, hardwareInstancedRendering)) {
            return false;
          }
        }
      }
      return true;
    };
    this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {
      let index;
      if (this._linkedWithPrePass) {
        if (!this._prePassRenderer.enabled) {
          return;
        }
        this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass);
      }
      if (depthOnlySubMeshes.length) {
        engine2.setColorWrite(false);
        for (index = 0;index < depthOnlySubMeshes.length; index++) {
          renderSubMesh(depthOnlySubMeshes.data[index]);
        }
        engine2.setColorWrite(true);
      }
      for (index = 0;index < opaqueSubMeshes.length; index++) {
        renderSubMesh(opaqueSubMeshes.data[index]);
      }
      engine2.setDepthWrite(false);
      for (index = 0;index < alphaTestSubMeshes.length; index++) {
        renderSubMesh(alphaTestSubMeshes.data[index]);
      }
      if (this.renderTransparentMeshes) {
        for (index = 0;index < transparentSubMeshes.length; index++) {
          renderSubMesh(transparentSubMeshes.data[index]);
        }
      }
      engine2.setDepthWrite(true);
    };
  }
  _copyBonesTransformationMatrices(source, target) {
    for (let i = 0;i < source.length; i++) {
      target[i] = source[i];
    }
    return target;
  }
}
GeometryBufferRenderer.ForceGLSL = false;
GeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0;
GeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1;
GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2;
GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3;
GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4;
GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE = 5;
GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE = 6;
GeometryBufferRenderer._SceneComponentInitialization = (_) => {
  throw _WarnImport("GeometryBufferRendererSceneComponent");
};

// node_modules/@babylonjs/core/Rendering/motionBlurConfiguration.js
class MotionBlurConfiguration {
  constructor() {
    this.enabled = false;
    this.name = "motionBlur";
    this.texturesRequired = [2];
  }
}

// node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js
init_animatable();

// node_modules/@babylonjs/core/Rendering/geometryBufferRendererSceneComponent.js
init_scene();
init_sceneComponent();
Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  get: function() {
    return this._geometryBufferRenderer;
  },
  set: function(value) {
    if (value && value.isSupported) {
      this._geometryBufferRenderer = value;
    }
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.enableGeometryBufferRenderer = function(ratio = 1, depthFormat = 15, textureTypesAndFormats) {
  if (this._geometryBufferRenderer) {
    return this._geometryBufferRenderer;
  }
  this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio, depthFormat, textureTypesAndFormats);
  if (!this._geometryBufferRenderer.isSupported) {
    this._geometryBufferRenderer = null;
  }
  return this._geometryBufferRenderer;
};
Scene.prototype.disableGeometryBufferRenderer = function() {
  if (!this._geometryBufferRenderer) {
    return;
  }
  this._geometryBufferRenderer.dispose();
  this._geometryBufferRenderer = null;
};

class GeometryBufferRendererSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
    this.scene = scene;
  }
  register() {
    this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  }
  rebuild() {}
  dispose() {}
  _gatherRenderTargets(renderTargets) {
    if (this.scene._geometryBufferRenderer) {
      renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
    }
  }
}
GeometryBufferRenderer._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  if (!component) {
    component = new GeometryBufferRendererSceneComponent(scene);
    scene._addComponent(component);
  }
};

// node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js
init_decorators();
init_decorators_serialization();
init_typeStore();

class MotionBlurPostProcess extends PostProcess {
  get motionBlurSamples() {
    return this._motionBlurSamples;
  }
  set motionBlurSamples(samples) {
    this._motionBlurSamples = samples;
    this._updateEffect();
  }
  get isObjectBased() {
    return this._isObjectBased;
  }
  set isObjectBased(value) {
    if (this._isObjectBased === value) {
      return;
    }
    this._isObjectBased = value;
    this._applyMode();
  }
  get _geometryBufferRenderer() {
    if (!this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.geometryBufferRenderer;
  }
  get _prePassRenderer() {
    if (this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.prePassRenderer;
  }
  getClassName() {
    return "MotionBlurPostProcess";
  }
  constructor(name424, scene, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {
    super(name424, "motionBlur", ["motionStrength", "motionScale", "screenSize", "inverseViewProjection", "prevViewProjection", "projection"], ["velocitySampler", "depthSampler"], options, camera2, samplingMode, engine2, reusable, `#define GEOMETRY_SUPPORTED
#define SAMPLES 64.0
#define OBJECT_BASED`, textureType, undefined, null, blockCompilation);
    this.motionStrength = 1;
    this._motionBlurSamples = 32;
    this._isObjectBased = true;
    this._forceGeometryBuffer = false;
    this._invViewProjection = null;
    this._previousViewProjection = null;
    this._forceGeometryBuffer = forceGeometryBuffer;
    if (this._forceGeometryBuffer) {
      scene.enableGeometryBufferRenderer();
      if (this._geometryBufferRenderer) {
        this._geometryBufferRenderer.enableVelocity = this._isObjectBased;
      }
    } else {
      scene.enablePrePassRenderer();
      if (this._prePassRenderer) {
        this._prePassRenderer.markAsDirty();
        this._prePassEffectConfiguration = new MotionBlurConfiguration;
      }
    }
    this._applyMode();
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_motionBlur_fragment(), exports_motionBlur_fragment))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_motionBlur_fragment2(), exports_motionBlur_fragment2))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  excludeSkinnedMesh(skinnedMesh) {
    if (skinnedMesh.skeleton) {
      let list;
      if (this._geometryBufferRenderer) {
        list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;
      } else if (this._prePassRenderer) {
        list = this._prePassRenderer.excludedSkinnedMesh;
      } else {
        return;
      }
      list.push(skinnedMesh);
    }
  }
  removeExcludedSkinnedMesh(skinnedMesh) {
    if (skinnedMesh.skeleton) {
      let list;
      if (this._geometryBufferRenderer) {
        list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;
      } else if (this._prePassRenderer) {
        list = this._prePassRenderer.excludedSkinnedMesh;
      } else {
        return;
      }
      const index = list.indexOf(skinnedMesh);
      if (index !== -1) {
        list.splice(index, 1);
      }
    }
  }
  dispose(camera2) {
    if (this._geometryBufferRenderer) {
      this._geometryBufferRenderer._previousTransformationMatrices = {};
      this._geometryBufferRenderer._previousBonesTransformationMatrices = {};
      this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = [];
    }
    super.dispose(camera2);
  }
  _applyMode() {
    if (!this._geometryBufferRenderer && !this._prePassRenderer) {
      Logger.Warn("Multiple Render Target support needed to compute object based motion blur");
      return this.updateEffect();
    }
    if (this._geometryBufferRenderer) {
      this._geometryBufferRenderer.enableVelocity = this._isObjectBased;
    }
    this._updateEffect();
    this._invViewProjection = null;
    this._previousViewProjection = null;
    if (this.isObjectBased) {
      if (this._prePassRenderer && this._prePassEffectConfiguration) {
        this._prePassEffectConfiguration.texturesRequired[0] = 2;
      }
      this.onApply = (effect2) => this._onApplyObjectBased(effect2);
    } else {
      this._invViewProjection = Matrix.Identity();
      this._previousViewProjection = this._scene.getTransformMatrix().clone();
      if (this._prePassRenderer && this._prePassEffectConfiguration) {
        this._prePassEffectConfiguration.texturesRequired[0] = 5;
      }
      this.onApply = (effect2) => this._onApplyScreenBased(effect2);
    }
  }
  _onApplyObjectBased(effect2) {
    effect2.setVector2("screenSize", new Vector2(this.width, this.height));
    effect2.setFloat("motionScale", this._scene.getAnimationRatio());
    effect2.setFloat("motionStrength", this.motionStrength);
    if (this._geometryBufferRenderer) {
      const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
      effect2.setTexture("velocitySampler", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
    } else if (this._prePassRenderer) {
      const velocityIndex = this._prePassRenderer.getIndex(2);
      effect2.setTexture("velocitySampler", this._prePassRenderer.getRenderTarget().textures[velocityIndex]);
    }
  }
  _onApplyScreenBased(effect2) {
    const viewProjection = TmpVectors.Matrix[0];
    viewProjection.copyFrom(this._scene.getTransformMatrix());
    viewProjection.invertToRef(this._invViewProjection);
    effect2.setMatrix("inverseViewProjection", this._invViewProjection);
    effect2.setMatrix("prevViewProjection", this._previousViewProjection);
    this._previousViewProjection.copyFrom(viewProjection);
    effect2.setMatrix("projection", this._scene.getProjectionMatrix());
    effect2.setVector2("screenSize", new Vector2(this.width, this.height));
    effect2.setFloat("motionScale", this._scene.getAnimationRatio());
    effect2.setFloat("motionStrength", this.motionStrength);
    if (this._geometryBufferRenderer) {
      const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);
      effect2.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]);
    } else if (this._prePassRenderer) {
      const depthIndex = this._prePassRenderer.getIndex(5);
      effect2.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[depthIndex]);
    }
  }
  _updateEffect() {
    if (this._geometryBufferRenderer || this._prePassRenderer) {
      const defines = [
        "#define GEOMETRY_SUPPORTED",
        "#define SAMPLES " + this._motionBlurSamples.toFixed(1),
        this._isObjectBased ? "#define OBJECT_BASED" : "#define SCREEN_BASED"
      ];
      this.updateEffect(defines.join(`
`));
    }
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], MotionBlurPostProcess.prototype, "motionStrength", undefined);
__decorate([
  serialize()
], MotionBlurPostProcess.prototype, "motionBlurSamples", null);
__decorate([
  serialize()
], MotionBlurPostProcess.prototype, "isObjectBased", null);
RegisterClass("BABYLON.MotionBlurPostProcess", MotionBlurPostProcess);

// node_modules/@babylonjs/core/PostProcesses/index.js
init_passPostProcess();
init_postProcess();
init_postProcessManager();

// node_modules/@babylonjs/core/PostProcesses/refractionPostProcess.js
init_tslib_es6();
init_texture();
init_postProcess();

// node_modules/@babylonjs/core/Shaders/refraction.fragment.js
init_shaderStore();
var name424 = "refractionPixelShader";
var shader423 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}`;
if (!ShaderStore.ShadersStore[name424]) {
  ShaderStore.ShadersStore[name424] = shader423;
}

// node_modules/@babylonjs/core/PostProcesses/refractionPostProcess.js
init_typeStore();
init_decorators();
init_decorators_serialization();

class RefractionPostProcess extends PostProcess {
  get refractionTexture() {
    return this._refTexture;
  }
  set refractionTexture(value) {
    if (this._refTexture && this._ownRefractionTexture) {
      this._refTexture.dispose();
    }
    this._refTexture = value;
    this._ownRefractionTexture = false;
  }
  getClassName() {
    return "RefractionPostProcess";
  }
  constructor(name425, refractionTextureUrl, color, depth, colorLevel, options, camera2, samplingMode, engine2, reusable) {
    super(name425, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera2, samplingMode, engine2, reusable);
    this._ownRefractionTexture = true;
    this.color = color;
    this.depth = depth;
    this.colorLevel = colorLevel;
    this.refractionTextureUrl = refractionTextureUrl;
    this.onActivateObservable.add((cam) => {
      this._refTexture = this._refTexture || new Texture(refractionTextureUrl, cam.getScene());
    });
    this.onApplyObservable.add((effect2) => {
      effect2.setColor3("baseColor", this.color);
      effect2.setFloat("depth", this.depth);
      effect2.setFloat("colorLevel", this.colorLevel);
      effect2.setTexture("refractionSampler", this._refTexture);
    });
  }
  dispose(camera2) {
    if (this._refTexture && this._ownRefractionTexture) {
      this._refTexture.dispose();
      this._refTexture = null;
    }
    super.dispose(camera2);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new RefractionPostProcess(parsedPostProcess.name, parsedPostProcess.refractionTextureUrl, parsedPostProcess.color, parsedPostProcess.depth, parsedPostProcess.colorLevel, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], RefractionPostProcess.prototype, "color", undefined);
__decorate([
  serialize()
], RefractionPostProcess.prototype, "depth", undefined);
__decorate([
  serialize()
], RefractionPostProcess.prototype, "colorLevel", undefined);
__decorate([
  serialize()
], RefractionPostProcess.prototype, "refractionTextureUrl", undefined);
RegisterClass("BABYLON.RefractionPostProcess", RefractionPostProcess);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_observable();
init_logger();
init_texture();

// node_modules/@babylonjs/core/PostProcesses/sharpenPostProcess.js
init_tslib_es6();
init_postProcess();
init_sharpen_fragment();
init_typeStore();
init_decorators();
init_decorators_serialization();

class SharpenPostProcess extends PostProcess {
  getClassName() {
    return "SharpenPostProcess";
  }
  constructor(name427, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    super(name427, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera2, samplingMode, engine2, reusable, null, textureType, undefined, null, blockCompilation);
    this.colorAmount = 1;
    this.edgeAmount = 0.3;
    this.onApply = (effect2) => {
      effect2.setFloat2("screenSize", this.width, this.height);
      effect2.setFloat2("sharpnessAmounts", this.edgeAmount, this.colorAmount);
    };
  }
  _gatherImports(useWebGPU, list) {
    if (useWebGPU) {
      this._webGPUReady = true;
      list.push(Promise.all([Promise.resolve().then(() => (init_sharpen_fragment2(), exports_sharpen_fragment2))]));
    } else {
      list.push(Promise.all([Promise.resolve().then(() => (init_sharpen_fragment(), exports_sharpen_fragment))]));
    }
    super._gatherImports(useWebGPU, list);
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new SharpenPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], SharpenPostProcess.prototype, "colorAmount", undefined);
__decorate([
  serialize()
], SharpenPostProcess.prototype, "edgeAmount", undefined);
RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess);

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipeline.js
init_tslib_es6();
init_tools();
init_decorators();

class PostProcessRenderPipeline {
  get name() {
    return this._name;
  }
  get cameras() {
    return this._cameras;
  }
  get engine() {
    return this._engine;
  }
  constructor(_engine, name427) {
    this._engine = _engine;
    this._name = name427;
    this._renderEffects = {};
    this._renderEffectsForIsolatedPass = new Array;
    this._cameras = [];
  }
  getClassName() {
    return "PostProcessRenderPipeline";
  }
  get isSupported() {
    for (const renderEffectName in this._renderEffects) {
      if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) {
        if (!this._renderEffects[renderEffectName].isSupported) {
          return false;
        }
      }
    }
    return true;
  }
  addEffect(renderEffect) {
    this._renderEffects[renderEffect._name] = renderEffect;
  }
  _rebuild() {}
  _enableEffect(renderEffectName, cameras) {
    const renderEffects = this._renderEffects[renderEffectName];
    if (!renderEffects) {
      return;
    }
    renderEffects._enable(Tools.MakeArray(cameras || this._cameras));
  }
  _disableEffect(renderEffectName, cameras) {
    const renderEffects = this._renderEffects[renderEffectName];
    if (!renderEffects) {
      return;
    }
    renderEffects._disable(Tools.MakeArray(cameras || this._cameras));
  }
  _attachCameras(cameras, unique) {
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    const indicesToDelete = [];
    let i;
    for (i = 0;i < cams.length; i++) {
      const camera2 = cams[i];
      if (!camera2) {
        continue;
      }
      if (this._cameras.indexOf(camera2) === -1) {
        this._cameras.push(camera2);
      } else if (unique) {
        indicesToDelete.push(i);
      }
    }
    for (i = 0;i < indicesToDelete.length; i++) {
      cams.splice(indicesToDelete[i], 1);
    }
    for (const renderEffectName in this._renderEffects) {
      if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) {
        this._renderEffects[renderEffectName]._attachCameras(cams);
      }
    }
  }
  _detachCameras(cameras) {
    const cams = Tools.MakeArray(cameras || this._cameras);
    if (!cams) {
      return;
    }
    for (const renderEffectName in this._renderEffects) {
      if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) {
        this._renderEffects[renderEffectName]._detachCameras(cams);
      }
    }
    for (let i = 0;i < cams.length; i++) {
      this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
    }
  }
  _update() {
    for (const renderEffectName in this._renderEffects) {
      if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) {
        this._renderEffects[renderEffectName]._update();
      }
    }
    for (let i = 0;i < this._cameras.length; i++) {
      if (!this._cameras[i]) {
        continue;
      }
      const cameraName = this._cameras[i].name;
      if (this._renderEffectsForIsolatedPass[cameraName]) {
        this._renderEffectsForIsolatedPass[cameraName]._update();
      }
    }
  }
  _reset() {
    this._renderEffects = {};
    this._renderEffectsForIsolatedPass = new Array;
  }
  _enableMSAAOnFirstPostProcess(sampleCount) {
    if (!this._engine._features.supportMSAA) {
      return false;
    }
    const effectKeys = Object.keys(this._renderEffects);
    if (effectKeys.length > 0) {
      const postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
      if (postProcesses) {
        postProcesses[0].samples = sampleCount;
      }
    }
    return true;
  }
  _adaptPostProcessesToViewPort() {
    const effectKeys = Object.keys(this._renderEffects);
    for (const effectKey of effectKeys) {
      const postProcesses = this._renderEffects[effectKey].getPostProcesses();
      if (postProcesses) {
        for (const postProcess of postProcesses) {
          postProcess.adaptScaleToCurrentViewport = true;
        }
      }
    }
  }
  setPrePassRenderer(prePassRenderer) {
    return false;
  }
  dispose() {}
}
__decorate([
  serialize()
], PostProcessRenderPipeline.prototype, "_name", undefined);

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.js
init_typeStore();
init_engineStore();
init_tools();

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js
init_sceneComponent();

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManager.js
class PostProcessRenderPipelineManager {
  constructor() {
    this._renderPipelines = {};
  }
  get supportedPipelines() {
    const result = [];
    for (const renderPipelineName in this._renderPipelines) {
      if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) {
        const pipeline = this._renderPipelines[renderPipelineName];
        if (pipeline.isSupported) {
          result.push(pipeline);
        }
      }
    }
    return result;
  }
  addPipeline(renderPipeline) {
    this._renderPipelines[renderPipeline._name] = renderPipeline;
  }
  removePipeline(renderPipelineName) {
    delete this._renderPipelines[renderPipelineName];
  }
  attachCamerasToRenderPipeline(renderPipelineName, cameras, unique = false) {
    const renderPipeline = this._renderPipelines[renderPipelineName];
    if (!renderPipeline) {
      return;
    }
    renderPipeline._attachCameras(cameras, unique);
  }
  detachCamerasFromRenderPipeline(renderPipelineName, cameras) {
    const renderPipeline = this._renderPipelines[renderPipelineName];
    if (!renderPipeline) {
      return;
    }
    renderPipeline._detachCameras(cameras);
  }
  enableEffectInPipeline(renderPipelineName, renderEffectName, cameras) {
    const renderPipeline = this._renderPipelines[renderPipelineName];
    if (!renderPipeline) {
      return;
    }
    renderPipeline._enableEffect(renderEffectName, cameras);
  }
  disableEffectInPipeline(renderPipelineName, renderEffectName, cameras) {
    const renderPipeline = this._renderPipelines[renderPipelineName];
    if (!renderPipeline) {
      return;
    }
    renderPipeline._disableEffect(renderEffectName, cameras);
  }
  update() {
    for (const renderPipelineName in this._renderPipelines) {
      if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) {
        const pipeline = this._renderPipelines[renderPipelineName];
        if (!pipeline.isSupported) {
          pipeline.dispose();
          delete this._renderPipelines[renderPipelineName];
        } else {
          pipeline._update();
        }
      }
    }
  }
  _rebuild() {
    for (const renderPipelineName in this._renderPipelines) {
      if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) {
        const pipeline = this._renderPipelines[renderPipelineName];
        pipeline._rebuild();
      }
    }
  }
  dispose() {
    for (const renderPipelineName in this._renderPipelines) {
      if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) {
        const pipeline = this._renderPipelines[renderPipelineName];
        pipeline.dispose();
      }
    }
  }
}

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js
init_scene();
Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  get: function() {
    if (!this._postProcessRenderPipelineManager) {
      let component = this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
      if (!component) {
        component = new PostProcessRenderPipelineManagerSceneComponent(this);
        this._addComponent(component);
      }
      this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager;
    }
    return this._postProcessRenderPipelineManager;
  },
  enumerable: true,
  configurable: true
});

class PostProcessRenderPipelineManagerSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
    this.scene = scene;
  }
  register() {
    this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  }
  rebuild() {
    if (this.scene._postProcessRenderPipelineManager) {
      this.scene._postProcessRenderPipelineManager._rebuild();
    }
  }
  dispose() {
    if (this.scene._postProcessRenderPipelineManager) {
      this.scene._postProcessRenderPipelineManager.dispose();
    }
  }
  _gatherRenderTargets() {
    if (this.scene._postProcessRenderPipelineManager) {
      this.scene._postProcessRenderPipelineManager.update();
    }
  }
}

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.js
class DefaultRenderingPipeline extends PostProcessRenderPipeline {
  get automaticBuild() {
    return this._buildAllowed;
  }
  set automaticBuild(value) {
    this._buildAllowed = value;
  }
  get scene() {
    return this._scene;
  }
  set sharpenEnabled(enabled) {
    if (this._sharpenEnabled === enabled) {
      return;
    }
    this._sharpenEnabled = enabled;
    this._buildPipeline();
  }
  get sharpenEnabled() {
    return this._sharpenEnabled;
  }
  get bloomKernel() {
    return this._bloomKernel;
  }
  set bloomKernel(value) {
    this._bloomKernel = value;
    this.bloom.kernel = value / this._hardwareScaleLevel;
  }
  set bloomWeight(value) {
    if (this._bloomWeight === value) {
      return;
    }
    this.bloom.weight = value;
    this._bloomWeight = value;
  }
  get bloomWeight() {
    return this._bloomWeight;
  }
  set bloomThreshold(value) {
    if (this._bloomThreshold === value) {
      return;
    }
    this.bloom.threshold = value;
    this._bloomThreshold = value;
  }
  get bloomThreshold() {
    return this._bloomThreshold;
  }
  set bloomScale(value) {
    if (this._bloomScale === value) {
      return;
    }
    this._bloomScale = value;
    this._rebuildBloom();
    this._buildPipeline();
  }
  get bloomScale() {
    return this._bloomScale;
  }
  set bloomEnabled(enabled) {
    if (this._bloomEnabled === enabled) {
      return;
    }
    this._bloomEnabled = enabled;
    this._buildPipeline();
  }
  get bloomEnabled() {
    return this._bloomEnabled;
  }
  _rebuildBloom() {
    const oldBloom = this.bloom;
    this.bloom = new BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, false);
    this.bloom.threshold = oldBloom.threshold;
    for (let i = 0;i < this._cameras.length; i++) {
      oldBloom.disposeEffects(this._cameras[i]);
    }
  }
  get depthOfFieldEnabled() {
    return this._depthOfFieldEnabled;
  }
  set depthOfFieldEnabled(enabled) {
    if (this._depthOfFieldEnabled === enabled) {
      return;
    }
    this._depthOfFieldEnabled = enabled;
    this._buildPipeline();
  }
  get depthOfFieldBlurLevel() {
    return this._depthOfFieldBlurLevel;
  }
  set depthOfFieldBlurLevel(value) {
    if (this._depthOfFieldBlurLevel === value) {
      return;
    }
    this._depthOfFieldBlurLevel = value;
    const oldDof = this.depthOfField;
    this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
    this.depthOfField.focalLength = oldDof.focalLength;
    this.depthOfField.focusDistance = oldDof.focusDistance;
    this.depthOfField.fStop = oldDof.fStop;
    this.depthOfField.lensSize = oldDof.lensSize;
    for (let i = 0;i < this._cameras.length; i++) {
      oldDof.disposeEffects(this._cameras[i]);
    }
    this._buildPipeline();
  }
  set fxaaEnabled(enabled) {
    if (this._fxaaEnabled === enabled) {
      return;
    }
    this._fxaaEnabled = enabled;
    this._buildPipeline();
  }
  get fxaaEnabled() {
    return this._fxaaEnabled;
  }
  set samples(sampleCount) {
    if (this._samples === sampleCount) {
      return;
    }
    this._samples = sampleCount;
    this._buildPipeline();
  }
  get samples() {
    return this._samples;
  }
  set imageProcessingEnabled(enabled) {
    if (this._imageProcessingEnabled === enabled) {
      return;
    }
    this._scene.imageProcessingConfiguration.isEnabled = enabled;
  }
  get imageProcessingEnabled() {
    return this._imageProcessingEnabled;
  }
  set glowLayerEnabled(enabled) {
    if (enabled && !this._glowLayer) {
      this._glowLayer = new GlowLayer("", this._scene);
    } else if (!enabled && this._glowLayer) {
      this._glowLayer.dispose();
      this._glowLayer = null;
    }
  }
  get glowLayerEnabled() {
    return this._glowLayer != null;
  }
  get glowLayer() {
    return this._glowLayer;
  }
  set chromaticAberrationEnabled(enabled) {
    if (this._chromaticAberrationEnabled === enabled) {
      return;
    }
    this._chromaticAberrationEnabled = enabled;
    this._buildPipeline();
  }
  get chromaticAberrationEnabled() {
    return this._chromaticAberrationEnabled;
  }
  set grainEnabled(enabled) {
    if (this._grainEnabled === enabled) {
      return;
    }
    this._grainEnabled = enabled;
    this._buildPipeline();
  }
  get grainEnabled() {
    return this._grainEnabled;
  }
  constructor(name427 = "", hdr = true, scene = EngineStore.LastCreatedScene, cameras, automaticBuild = true) {
    super(scene.getEngine(), name427);
    this._camerasToBeAttached = [];
    this.SharpenPostProcessId = "SharpenPostProcessEffect";
    this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
    this.FxaaPostProcessId = "FxaaPostProcessEffect";
    this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
    this.GrainPostProcessId = "GrainPostProcessEffect";
    this._glowLayer = null;
    this.animations = [];
    this._imageProcessingConfigurationObserver = null;
    this._sharpenEnabled = false;
    this._bloomEnabled = false;
    this._depthOfFieldEnabled = false;
    this._depthOfFieldBlurLevel = 0;
    this._fxaaEnabled = false;
    this._imageProcessingEnabled = true;
    this._bloomScale = 0.5;
    this._chromaticAberrationEnabled = false;
    this._grainEnabled = false;
    this._buildAllowed = true;
    this.onBuildObservable = new Observable;
    this._resizeObserver = null;
    this._hardwareScaleLevel = 1;
    this._bloomKernel = 64;
    this._bloomWeight = 0.15;
    this._bloomThreshold = 0.9;
    this._samples = 1;
    this._hasCleared = false;
    this._prevPostProcess = null;
    this._prevPrevPostProcess = null;
    this._depthOfFieldSceneObserver = null;
    this._activeCameraChangedObserver = null;
    this._activeCamerasChangedObserver = null;
    this._cameras = cameras || scene.cameras;
    this._cameras = this._cameras.slice();
    this._camerasToBeAttached = this._cameras.slice();
    this._buildAllowed = automaticBuild;
    this._scene = scene;
    const caps = this._scene.getEngine().getCaps();
    this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
    if (this._hdr) {
      if (caps.textureHalfFloatRender) {
        this._defaultPipelineTextureType = 2;
      } else if (caps.textureFloatRender) {
        this._defaultPipelineTextureType = 1;
      }
    } else {
      this._defaultPipelineTextureType = 0;
    }
    scene.postProcessRenderPipelineManager.addPipeline(this);
    const engine2 = this._scene.getEngine();
    this.sharpen = new SharpenPostProcess("sharpen", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._defaultPipelineTextureType, true);
    this._sharpenEffect = new PostProcessRenderEffect(engine2, this.SharpenPostProcessId, () => {
      return this.sharpen;
    }, true);
    this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, true);
    this._hardwareScaleLevel = engine2.getHardwareScalingLevel();
    this._resizeObserver = engine2.onResizeObservable.add(() => {
      this._hardwareScaleLevel = engine2.getHardwareScalingLevel();
      this.bloomKernel = this._bloomKernel;
    });
    this.bloom = new BloomEffect(this._scene, this._bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, true);
    this.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration", engine2.getRenderWidth(), engine2.getRenderHeight(), 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._defaultPipelineTextureType, true);
    this._chromaticAberrationEffect = new PostProcessRenderEffect(engine2, this.ChromaticAberrationPostProcessId, () => {
      return this.chromaticAberration;
    }, true);
    this.grain = new GrainPostProcess("Grain", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._defaultPipelineTextureType, true);
    this._grainEffect = new PostProcessRenderEffect(engine2, this.GrainPostProcessId, () => {
      return this.grain;
    }, true);
    let avoidReentrancyAtConstructionTime = true;
    this._imageProcessingConfigurationObserver = this._scene.imageProcessingConfiguration.onUpdateParameters.add(() => {
      this.bloom._downscale._exposure = this._scene.imageProcessingConfiguration.exposure;
      if (this.imageProcessingEnabled !== this._scene.imageProcessingConfiguration.isEnabled) {
        this._imageProcessingEnabled = this._scene.imageProcessingConfiguration.isEnabled;
        if (avoidReentrancyAtConstructionTime) {
          Tools.SetImmediate(() => {
            this._buildPipeline();
          });
        } else {
          this._buildPipeline();
        }
      }
    });
    this._buildPipeline();
    avoidReentrancyAtConstructionTime = false;
  }
  getClassName() {
    return "DefaultRenderingPipeline";
  }
  prepare() {
    const previousState = this._buildAllowed;
    this._buildAllowed = true;
    this._buildPipeline();
    this._buildAllowed = previousState;
  }
  _setAutoClearAndTextureSharing(postProcess, skipTextureSharing = false) {
    if (this._hasCleared) {
      postProcess.autoClear = false;
    } else {
      postProcess.autoClear = true;
      this._scene.autoClear = false;
      this._hasCleared = true;
    }
    if (!skipTextureSharing) {
      if (this._prevPrevPostProcess) {
        postProcess.shareOutputWith(this._prevPrevPostProcess);
      } else {
        postProcess.useOwnOutput();
      }
      if (this._prevPostProcess) {
        this._prevPrevPostProcess = this._prevPostProcess;
      }
      this._prevPostProcess = postProcess;
    }
  }
  _buildPipeline() {
    if (!this._buildAllowed) {
      return;
    }
    this._scene.autoClear = true;
    const engine2 = this._scene.getEngine();
    this._disposePostProcesses();
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
      this._cameras = this._camerasToBeAttached.slice();
    }
    this._reset();
    this._prevPostProcess = null;
    this._prevPrevPostProcess = null;
    this._hasCleared = false;
    if (this.depthOfFieldEnabled) {
      if (this._cameras.length > 1) {
        for (const camera2 of this._cameras) {
          const depthRenderer = this._scene.enableDepthRenderer(camera2);
          depthRenderer.useOnlyInActiveCamera = true;
        }
        this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add((scene) => {
          if (this._cameras.indexOf(scene.activeCamera) > -1) {
            this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
          }
        });
      } else {
        this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
        const depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
        this.depthOfField.depthTexture = depthRenderer.getDepthMap();
      }
      if (!this.depthOfField._isReady()) {
        this.depthOfField._updateEffects();
      }
      this.addEffect(this.depthOfField);
      this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
    } else {
      this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
    }
    if (this.bloomEnabled) {
      if (!this.bloom._isReady()) {
        this.bloom._updateEffects();
      }
      this.addEffect(this.bloom);
      this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
    }
    if (this._imageProcessingEnabled) {
      this.imageProcessing = new ImageProcessingPostProcess("imageProcessing", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._defaultPipelineTextureType, this.scene.imageProcessingConfiguration);
      if (this._hdr) {
        this.addEffect(new PostProcessRenderEffect(engine2, this.ImageProcessingPostProcessId, () => {
          return this.imageProcessing;
        }, true));
        this._setAutoClearAndTextureSharing(this.imageProcessing);
      } else {
        this._scene.imageProcessingConfiguration.applyByPostProcess = false;
      }
      if (!this._cameras || this._cameras.length === 0) {
        this._scene.imageProcessingConfiguration.applyByPostProcess = false;
      }
      if (!this.imageProcessing.getEffect()) {
        this.imageProcessing._updateParameters();
      }
    }
    if (this.sharpenEnabled) {
      if (!this.sharpen.isReady()) {
        this.sharpen.updateEffect();
      }
      this.addEffect(this._sharpenEffect);
      this._setAutoClearAndTextureSharing(this.sharpen);
    }
    if (this.grainEnabled) {
      if (!this.grain.isReady()) {
        this.grain.updateEffect();
      }
      this.addEffect(this._grainEffect);
      this._setAutoClearAndTextureSharing(this.grain);
    }
    if (this.chromaticAberrationEnabled) {
      if (!this.chromaticAberration.isReady()) {
        this.chromaticAberration.updateEffect();
      }
      this.addEffect(this._chromaticAberrationEffect);
      this._setAutoClearAndTextureSharing(this.chromaticAberration);
    }
    if (this.fxaaEnabled) {
      this.fxaa = new FxaaPostProcess("fxaa", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine2, false, this._defaultPipelineTextureType);
      this.addEffect(new PostProcessRenderEffect(engine2, this.FxaaPostProcessId, () => {
        return this.fxaa;
      }, true));
      this._setAutoClearAndTextureSharing(this.fxaa, true);
    }
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
    }
    if (this._scene.activeCameras && this._scene.activeCameras.length > 1 || this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) {
      this._scene.autoClear = true;
    }
    if (!this._activeCameraChangedObserver) {
      this._activeCameraChangedObserver = this._scene.onActiveCameraChanged.add(() => {
        if (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) {
          this._scene.autoClear = true;
        }
      });
    }
    if (!this._activeCamerasChangedObserver) {
      this._activeCamerasChangedObserver = this._scene.onActiveCamerasChanged.add(() => {
        if (this._scene.activeCameras && this._scene.activeCameras.length > 1) {
          this._scene.autoClear = true;
        }
      });
    }
    this._adaptPostProcessesToViewPort();
    if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
      Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
    }
    this.onBuildObservable.notifyObservers(this);
  }
  _disposePostProcesses(disposeNonRecreated = false) {
    for (let i = 0;i < this._cameras.length; i++) {
      const camera2 = this._cameras[i];
      if (this.imageProcessing) {
        this.imageProcessing.dispose(camera2);
      }
      if (this.fxaa) {
        this.fxaa.dispose(camera2);
      }
      if (disposeNonRecreated) {
        if (this.sharpen) {
          this.sharpen.dispose(camera2);
        }
        if (this.depthOfField) {
          this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
          this.depthOfField.disposeEffects(camera2);
        }
        if (this.bloom) {
          this.bloom.disposeEffects(camera2);
        }
        if (this.chromaticAberration) {
          this.chromaticAberration.dispose(camera2);
        }
        if (this.grain) {
          this.grain.dispose(camera2);
        }
        if (this._glowLayer) {
          this._glowLayer.dispose();
        }
      }
    }
    this.imageProcessing = null;
    this.fxaa = null;
    if (disposeNonRecreated) {
      this.sharpen = null;
      this._sharpenEffect = null;
      this.depthOfField = null;
      this.bloom = null;
      this.chromaticAberration = null;
      this._chromaticAberrationEffect = null;
      this.grain = null;
      this._grainEffect = null;
      this._glowLayer = null;
    }
  }
  addCamera(camera2) {
    this._camerasToBeAttached.push(camera2);
    this._buildPipeline();
  }
  removeCamera(camera2) {
    const index = this._camerasToBeAttached.indexOf(camera2);
    this._camerasToBeAttached.splice(index, 1);
    this._buildPipeline();
  }
  dispose() {
    this._buildAllowed = false;
    this.onBuildObservable.clear();
    this._disposePostProcesses(true);
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
    this._scene._postProcessRenderPipelineManager.removePipeline(this.name);
    this._scene.autoClear = true;
    if (this._resizeObserver) {
      this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
      this._resizeObserver = null;
    }
    this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver);
    this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver);
    this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
    super.dispose();
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "DefaultRenderingPipeline";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new DefaultRenderingPipeline(source._name, source._name._hdr, scene), source, scene, rootUrl);
  }
}
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "bloomKernel", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "_bloomWeight", undefined);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "_bloomThreshold", undefined);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "_hdr", undefined);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "bloomWeight", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "bloomScale", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "samples", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
__decorate([
  serialize()
], DefaultRenderingPipeline.prototype, "grainEnabled", null);
RegisterClass("BABYLON.DefaultRenderingPipeline", DefaultRenderingPipeline);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/lensRenderingPipeline.js
init_texture();
init_postProcess();
init_chromaticAberration_fragment2();

// node_modules/@babylonjs/core/Shaders/lensHighlights.fragment.js
init_shaderStore();
var name427 = "lensHighlightsPixelShader";
var shader426 = `uniform sampler2D textureSampler; 
uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }
else { lum_threshold=0.5+0.44*threshold; }
luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}
float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);
#ifdef PENTAGON
blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));
#else
blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));
#endif
blurred/=39.0;gl_FragColor=blurred;}`;
if (!ShaderStore.ShadersStore[name427]) {
  ShaderStore.ShadersStore[name427] = shader426;
}

// node_modules/@babylonjs/core/Shaders/depthOfField.fragment.js
init_shaderStore();
var name428 = "depthOfFieldPixelShader";
var shader427 = `uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; 
uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;
#define PI 3.14159265
#define TWOPI 6.28318530
#define inverse_focal_length 0.1 
vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)
{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}
vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }
vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}
float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}
float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}
vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}
if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}
col/=total_weight; 
if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}
return col;}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); 
vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); 
float depth=texture2D(depthSampler,distorted_coords).r; 
float distance=near+(far-near)*depth; 
vec4 color=texture2D(textureSampler,vUV); 
float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }
float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}
float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}
else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}
if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}
if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}
`;
if (!ShaderStore.ShadersStore[name428]) {
  ShaderStore.ShadersStore[name428] = shader427;
}
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js
init_tslib_es6();
init_logger();
init_decorators();
init_decorators_serialization();
init_math_vector();
init_texture();
init_postProcess();
init_passPostProcess();
init_typeStore();
init_engineStore();

// node_modules/@babylonjs/core/Rendering/ssao2Configuration.js
class SSAO2Configuration {
  constructor() {
    this.enabled = false;
    this.name = "ssao2";
    this.texturesRequired = [6, 5];
  }
}
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js
class SSAO2RenderingPipeline extends PostProcessRenderPipeline {
  set epsilon(n) {
    this._epsilon = n;
    this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO());
  }
  get epsilon() {
    return this._epsilon;
  }
  set samples(n) {
    this._samples = n;
    this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO());
    this._sampleSphere = this._generateHemisphere();
  }
  get samples() {
    return this._samples;
  }
  set textureSamples(n) {
    this._textureSamples = n;
    if (this._prePassRenderer) {
      this._prePassRenderer.samples = n;
    } else {
      this._originalColorPostProcess.samples = n;
    }
  }
  get textureSamples() {
    return this._textureSamples;
  }
  get _geometryBufferRenderer() {
    if (!this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.geometryBufferRenderer;
  }
  get _prePassRenderer() {
    if (this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.prePassRenderer;
  }
  set bypassBlur(b) {
    const defines = this._getDefinesForBlur(this.expensiveBlur, b);
    const samplers = this._getSamplersForBlur(b);
    this._blurHPostProcess.updateEffect(defines.h, null, samplers);
    this._blurVPostProcess.updateEffect(defines.v, null, samplers);
    this._bypassBlur = b;
  }
  get bypassBlur() {
    return this._bypassBlur;
  }
  set expensiveBlur(b) {
    const defines = this._getDefinesForBlur(b, this._bypassBlur);
    this._blurHPostProcess.updateEffect(defines.h);
    this._blurVPostProcess.updateEffect(defines.v);
    this._expensiveBlur = b;
  }
  get expensiveBlur() {
    return this._expensiveBlur;
  }
  static get IsSupported() {
    const engine2 = EngineStore.LastCreatedEngine;
    if (!engine2) {
      return false;
    }
    return engine2._features.supportSSAO2;
  }
  get scene() {
    return this._scene;
  }
  constructor(name433, scene, ratio, cameras, forceGeometryBuffer = false, textureType = 0) {
    super(scene.getEngine(), name433);
    this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
    this.SSAORenderEffect = "SSAORenderEffect";
    this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
    this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
    this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
    this.totalStrength = 1;
    this.maxZ = 100;
    this.minZAspect = 0.2;
    this._epsilon = 0.02;
    this._samples = 8;
    this._textureSamples = 1;
    this._forceGeometryBuffer = false;
    this.radius = 2;
    this.base = 0;
    this._bypassBlur = false;
    this._expensiveBlur = true;
    this.bilateralSamples = 16;
    this.bilateralSoften = 0;
    this.bilateralTolerance = 0;
    this._bits = new Uint32Array(1);
    this._scene = scene;
    this._ratio = ratio;
    this._textureType = textureType;
    this._forceGeometryBuffer = forceGeometryBuffer;
    if (!this.isSupported) {
      Logger.Error("The current engine does not support SSAO 2.");
      return;
    }
    const ssaoRatio = this._ratio.ssaoRatio || ratio;
    const blurRatio = this._ratio.blurRatio || ratio;
    if (this._forceGeometryBuffer) {
      scene.enableGeometryBufferRenderer();
      if (scene.geometryBufferRenderer?.generateNormalsInWorldSpace) {
        Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!");
      }
    } else {
      scene.enablePrePassRenderer();
      if (scene.prePassRenderer?.generateNormalsInWorldSpace) {
        Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!");
      }
    }
    this._createRandomTexture();
    this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), undefined, this._textureType);
    this._originalColorPostProcess.samples = this.textureSamples;
    this._createSSAOPostProcess(1, textureType);
    this._createBlurPostProcess(ssaoRatio, blurRatio, this._textureType);
    this._createSSAOCombinePostProcess(blurRatio, this._textureType);
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => {
      return this._originalColorPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {
      return this._ssaoPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {
      return this._blurHPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {
      return this._blurVPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {
      return this._ssaoCombinePostProcess;
    }, true));
    scene.postProcessRenderPipelineManager.addPipeline(this);
    if (cameras) {
      scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name433, cameras);
    }
  }
  getClassName() {
    return "SSAO2RenderingPipeline";
  }
  dispose(disableGeometryBufferRenderer = false) {
    for (let i = 0;i < this._scene.cameras.length; i++) {
      const camera2 = this._scene.cameras[i];
      this._originalColorPostProcess.dispose(camera2);
      this._ssaoPostProcess.dispose(camera2);
      this._blurHPostProcess.dispose(camera2);
      this._blurVPostProcess.dispose(camera2);
      this._ssaoCombinePostProcess.dispose(camera2);
    }
    this._randomTexture.dispose();
    if (disableGeometryBufferRenderer) {
      this._scene.disableGeometryBufferRenderer();
    }
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
    super.dispose();
  }
  _rebuild() {
    super._rebuild();
  }
  _getSamplersForBlur(disabled) {
    return disabled ? ["textureSampler"] : ["textureSampler", "depthSampler"];
  }
  _getDefinesForBlur(bilateral, disabled) {
    let define = `#define BLUR
`;
    if (disabled) {
      define += `#define BLUR_BYPASS
`;
    }
    if (!bilateral) {
      define += `#define BLUR_LEGACY
`;
    }
    return { h: define + `#define BLUR_H
`, v: define };
  }
  _createBlurPostProcess(ssaoRatio, blurRatio, textureType) {
    const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur);
    const samplers = this._getSamplersForBlur(this.bypassBlur);
    this._blurHPostProcess = this._createBlurFilter("BlurH", samplers, ssaoRatio, defines.h, textureType, true);
    this._blurVPostProcess = this._createBlurFilter("BlurV", samplers, blurRatio, defines.v, textureType, false);
  }
  _createBlurFilter(name433, samplers, ratio, defines, textureType, horizontal) {
    const blurFilter = new PostProcess(name433, "ssao2", ["outSize", "samples", "soften", "tolerance"], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 : 0, (useWebGPU, list) => {
      if (useWebGPU) {
        list.push(Promise.resolve().then(() => (init_ssao2_fragment(), exports_ssao2_fragment)));
      } else {
        list.push(Promise.resolve().then(() => (init_ssao2_fragment2(), exports_ssao2_fragment2)));
      }
    });
    blurFilter.onApply = (effect2) => {
      if (!this._scene.activeCamera) {
        return;
      }
      const ratio2 = this._ratio.blurRatio || this._ratio;
      const ssaoCombineSize = horizontal ? this._originalColorPostProcess.width * ratio2 : this._originalColorPostProcess.height * ratio2;
      const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height;
      effect2.setFloat("outSize", ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize);
      effect2.setInt("samples", this.bilateralSamples);
      effect2.setFloat("soften", this.bilateralSoften);
      effect2.setFloat("tolerance", this.bilateralTolerance);
      if (this._geometryBufferRenderer) {
        effect2.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]);
      } else if (this._prePassRenderer) {
        effect2.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);
      }
    };
    blurFilter.samples = this.textureSamples;
    blurFilter.autoClear = false;
    return blurFilter;
  }
  _radicalInverse_VdC(i) {
    this._bits[0] = i;
    this._bits[0] = (this._bits[0] << 16 | this._bits[0] >> 16) >>> 0;
    this._bits[0] = (this._bits[0] & 1431655765) << 1 | (this._bits[0] & 2863311530) >>> 1 >>> 0;
    this._bits[0] = (this._bits[0] & 858993459) << 2 | (this._bits[0] & 3435973836) >>> 2 >>> 0;
    this._bits[0] = (this._bits[0] & 252645135) << 4 | (this._bits[0] & 4042322160) >>> 4 >>> 0;
    this._bits[0] = (this._bits[0] & 16711935) << 8 | (this._bits[0] & 4278255360) >>> 8 >>> 0;
    return this._bits[0] * 0.00000000023283064365386963;
  }
  _hammersley(i, n) {
    return [i / n, this._radicalInverse_VdC(i)];
  }
  _hemisphereSample_uniform(u, v) {
    const phi = v * 2 * Math.PI;
    const cosTheta = 1 - u * 0.85;
    const sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
    return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  }
  _generateHemisphere() {
    const numSamples = this.samples;
    const result = [];
    let vector;
    let i = 0;
    while (i < numSamples) {
      if (numSamples < 16) {
        vector = this._hemisphereSample_uniform(Math.random(), Math.random());
      } else {
        const rand = this._hammersley(i, numSamples);
        vector = this._hemisphereSample_uniform(rand[0], rand[1]);
      }
      result.push(vector.x, vector.y, vector.z);
      i++;
    }
    return result;
  }
  _getDefinesForSSAO() {
    const defines = `#define SSAO
#define SAMPLES ${this.samples}
#define EPSILON ${this.epsilon.toFixed(4)}`;
    return defines;
  }
  _createSSAOPostProcess(ratio, textureType) {
    this._sampleSphere = this._generateHemisphere();
    const defines = this._getDefinesForSSAO();
    const samplers = ["randomSampler", "depthSampler", "normalSampler"];
    this._ssaoPostProcess = new PostProcess("ssao2", "ssao2", [
      "sampleSphere",
      "samplesFactor",
      "randTextureTiles",
      "totalStrength",
      "radius",
      "base",
      "range",
      "projection",
      "near",
      "texelSize",
      "xViewport",
      "yViewport",
      "maxZ",
      "minZAspect",
      "depthProjection"
    ], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 : 0, (useWebGPU, list) => {
      if (useWebGPU) {
        list.push(Promise.resolve().then(() => (init_ssao2_fragment(), exports_ssao2_fragment)));
      } else {
        list.push(Promise.resolve().then(() => (init_ssao2_fragment2(), exports_ssao2_fragment2)));
      }
    });
    this._ssaoPostProcess.autoClear = false;
    this._ssaoPostProcess.onApply = (effect2) => {
      if (!this._scene.activeCamera) {
        return;
      }
      effect2.setArray3("sampleSphere", this._sampleSphere);
      effect2.setFloat("randTextureTiles", 32);
      effect2.setFloat("samplesFactor", 1 / this.samples);
      effect2.setFloat("totalStrength", this.totalStrength);
      effect2.setFloat2("texelSize", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height);
      effect2.setFloat("radius", this.radius);
      effect2.setFloat("maxZ", this.maxZ);
      effect2.setFloat("minZAspect", this.minZAspect);
      effect2.setFloat("base", this.base);
      effect2.setFloat("near", this._scene.activeCamera.minZ);
      if (this._scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA) {
        effect2.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION);
        effect2.setFloat("xViewport", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true));
        effect2.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2));
      } else {
        const halfWidth = this._scene.getEngine().getRenderWidth() / 2;
        const halfHeight = this._scene.getEngine().getRenderHeight() / 2;
        const orthoLeft = this._scene.activeCamera.orthoLeft ?? -halfWidth;
        const orthoRight = this._scene.activeCamera.orthoRight ?? halfWidth;
        const orthoBottom = this._scene.activeCamera.orthoBottom ?? -halfHeight;
        const orthoTop = this._scene.activeCamera.orthoTop ?? halfHeight;
        effect2.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION);
        effect2.setFloat("xViewport", (orthoRight - orthoLeft) * 0.5);
        effect2.setFloat("yViewport", (orthoTop - orthoBottom) * 0.5);
      }
      effect2.setMatrix("projection", this._scene.getProjectionMatrix());
      if (this._geometryBufferRenderer) {
        effect2.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]);
        effect2.setTexture("normalSampler", this._geometryBufferRenderer.getGBuffer().textures[1]);
      } else if (this._prePassRenderer) {
        effect2.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);
        effect2.setTexture("normalSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]);
      }
      effect2.setTexture("randomSampler", this._randomTexture);
    };
    this._ssaoPostProcess.samples = this.textureSamples;
    if (!this._forceGeometryBuffer) {
      this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration;
    }
  }
  _createSSAOCombinePostProcess(ratio, textureType) {
    this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, undefined, textureType, undefined, undefined, undefined, undefined, this._scene.getEngine().isWebGPU ? 1 : 0, (useWebGPU, list) => {
      if (useWebGPU) {
        list.push(Promise.resolve().then(() => (init_ssaoCombine_fragment(), exports_ssaoCombine_fragment)));
      } else {
        list.push(Promise.resolve().then(() => (init_ssaoCombine_fragment2(), exports_ssaoCombine_fragment2)));
      }
    });
    this._ssaoCombinePostProcess.onApply = (effect2) => {
      const viewport = this._scene.activeCamera.viewport;
      effect2.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
      effect2.setTextureFromPostProcessOutput("originalColor", this._originalColorPostProcess);
    };
    this._ssaoCombinePostProcess.autoClear = false;
    this._ssaoCombinePostProcess.samples = this.textureSamples;
  }
  _createRandomTexture() {
    const size = 128;
    const data = new Uint8Array(size * size * 4);
    const randVector = Vector2.Zero();
    for (let index = 0;index < data.length; ) {
      randVector.set(RandomRange(0, 1), RandomRange(0, 1)).normalize().scaleInPlace(255);
      data[index++] = Math.floor(randVector.x);
      data[index++] = Math.floor(randVector.y);
      data[index++] = 0;
      data[index++] = 255;
    }
    const texture2 = RawTexture.CreateRGBATexture(data, size, size, this._scene, false, false, 2);
    texture2.name = "SSAORandomTexture";
    texture2.wrapU = Texture.WRAP_ADDRESSMODE;
    texture2.wrapV = Texture.WRAP_ADDRESSMODE;
    this._randomTexture = texture2;
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "SSAO2RenderingPipeline";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio, undefined, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl);
  }
}
SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1];
SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1];
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "totalStrength", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "maxZ", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "minZAspect", undefined);
__decorate([
  serialize("epsilon")
], SSAO2RenderingPipeline.prototype, "_epsilon", undefined);
__decorate([
  serialize("samples")
], SSAO2RenderingPipeline.prototype, "_samples", undefined);
__decorate([
  serialize("textureSamples")
], SSAO2RenderingPipeline.prototype, "_textureSamples", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "_forceGeometryBuffer", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "_ratio", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "_textureType", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "radius", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "base", undefined);
__decorate([
  serialize("bypassBlur")
], SSAO2RenderingPipeline.prototype, "_bypassBlur", undefined);
__decorate([
  serialize("expensiveBlur")
], SSAO2RenderingPipeline.prototype, "_expensiveBlur", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "bilateralSamples", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "bilateralSoften", undefined);
__decorate([
  serialize()
], SSAO2RenderingPipeline.prototype, "bilateralTolerance", undefined);
RegisterClass("BABYLON.SSAO2RenderingPipeline", SSAO2RenderingPipeline);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssaoRenderingPipeline.js
init_tslib_es6();
init_math_vector();
init_texture();
init_postProcess();
init_passPostProcess();
init_decorators();
// node_modules/@babylonjs/core/Shaders/ssao.fragment.js
init_shaderStore();
var name433 = "ssaoPixelShader";
var shader432 = `uniform sampler2D textureSampler;varying vec2 vUV;
#ifdef SSAO
uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)
{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}
void main()
{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++)
{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));}
float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;}
#endif
`;
if (!ShaderStore.ShadersStore[name433]) {
  ShaderStore.ShadersStore[name433] = shader432;
}

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssaoRenderingPipeline.js
init_ssaoCombine_fragment2();

class SSAORenderingPipeline extends PostProcessRenderPipeline {
  get scene() {
    return this._scene;
  }
  constructor(name434, scene, ratio, cameras) {
    super(scene.getEngine(), name434);
    this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
    this.SSAORenderEffect = "SSAORenderEffect";
    this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
    this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
    this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
    this.totalStrength = 1;
    this.radius = 0.0001;
    this.area = 0.0075;
    this.fallOff = 0.000001;
    this.base = 0.5;
    this._firstUpdate = true;
    this._scene = scene;
    this._createRandomTexture();
    const ssaoRatio = ratio.ssaoRatio || ratio;
    const combineRatio = ratio.combineRatio || ratio;
    this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
    this._createSSAOPostProcess(ssaoRatio);
    this._createBlurPostProcess(ssaoRatio);
    this._createSSAOCombinePostProcess(combineRatio);
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => {
      return this._originalColorPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {
      return this._ssaoPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {
      return this._blurHPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {
      return this._blurVPostProcess;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {
      return this._ssaoCombinePostProcess;
    }, true));
    scene.postProcessRenderPipelineManager.addPipeline(this);
    if (cameras) {
      scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name434, cameras);
    }
  }
  _attachCameras(cameras, unique) {
    super._attachCameras(cameras, unique);
    for (const camera2 of this._cameras) {
      this._scene.enableDepthRenderer(camera2).getDepthMap();
    }
  }
  getClassName() {
    return "SSAORenderingPipeline";
  }
  dispose(disableDepthRender = false) {
    for (let i = 0;i < this._scene.cameras.length; i++) {
      const camera2 = this._scene.cameras[i];
      this._originalColorPostProcess.dispose(camera2);
      this._ssaoPostProcess.dispose(camera2);
      this._blurHPostProcess.dispose(camera2);
      this._blurVPostProcess.dispose(camera2);
      this._ssaoCombinePostProcess.dispose(camera2);
    }
    this._randomTexture.dispose();
    if (disableDepthRender) {
      this._scene.disableDepthRenderer();
    }
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
    super.dispose();
  }
  _createBlurPostProcess(ratio) {
    const size = 16;
    this._blurHPostProcess = new BlurPostProcess("BlurH", new Vector2(1, 0), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);
    this._blurVPostProcess = new BlurPostProcess("BlurV", new Vector2(0, 1), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);
    this._blurHPostProcess.onActivateObservable.add(() => {
      const dw = this._blurHPostProcess.width / this._scene.getEngine().getRenderWidth();
      this._blurHPostProcess.kernel = size * dw;
    });
    this._blurVPostProcess.onActivateObservable.add(() => {
      const dw = this._blurVPostProcess.height / this._scene.getEngine().getRenderHeight();
      this._blurVPostProcess.kernel = size * dw;
    });
  }
  _rebuild() {
    this._firstUpdate = true;
    super._rebuild();
  }
  _createSSAOPostProcess(ratio) {
    const numSamples = 16;
    const sampleSphere = [
      0.5381,
      0.1856,
      -0.4319,
      0.1379,
      0.2486,
      0.443,
      0.3371,
      0.5679,
      -0.0057,
      -0.6999,
      -0.0451,
      -0.0019,
      0.0689,
      -0.1598,
      -0.8547,
      0.056,
      0.0069,
      -0.1843,
      -0.0146,
      0.1402,
      0.0762,
      0.01,
      -0.1924,
      -0.0344,
      -0.3577,
      -0.5301,
      -0.4358,
      -0.3169,
      0.1063,
      0.0158,
      0.0103,
      -0.5869,
      0.0046,
      -0.0897,
      -0.494,
      0.3287,
      0.7119,
      -0.0154,
      -0.0918,
      -0.0533,
      0.0596,
      -0.5411,
      0.0352,
      -0.0631,
      0.546,
      -0.4776,
      0.2847,
      -0.0271
    ];
    const samplesFactor = 1 / numSamples;
    this._ssaoPostProcess = new PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff", "base", "range", "viewport"], ["randomSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + `
#define SSAO`);
    this._ssaoPostProcess.externalTextureSamplerBinding = true;
    this._ssaoPostProcess.onApply = (effect2) => {
      if (this._firstUpdate) {
        effect2.setArray3("sampleSphere", sampleSphere);
        effect2.setFloat("samplesFactor", samplesFactor);
        effect2.setFloat("randTextureTiles", 4);
      }
      effect2.setFloat("totalStrength", this.totalStrength);
      effect2.setFloat("radius", this.radius);
      effect2.setFloat("area", this.area);
      effect2.setFloat("fallOff", this.fallOff);
      effect2.setFloat("base", this.base);
      effect2.setTexture("textureSampler", this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap());
      effect2.setTexture("randomSampler", this._randomTexture);
    };
  }
  _createSSAOCombinePostProcess(ratio) {
    this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
    this._ssaoCombinePostProcess.onApply = (effect2) => {
      effect2.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(0, 0, 1, 1));
      effect2.setTextureFromPostProcess("originalColor", this._originalColorPostProcess);
    };
  }
  _createRandomTexture() {
    const size = 512;
    const data = new Uint8Array(size * size * 4);
    for (let index = 0;index < data.length; ) {
      data[index++] = Math.floor(Math.max(0, RandomRange(-1, 1)) * 255);
      data[index++] = Math.floor(Math.max(0, RandomRange(-1, 1)) * 255);
      data[index++] = Math.floor(Math.max(0, RandomRange(-1, 1)) * 255);
      data[index++] = 255;
    }
    const texture2 = RawTexture.CreateRGBATexture(data, size, size, this._scene, false, false, 2);
    texture2.name = "SSAORandomTexture";
    texture2.wrapU = Texture.WRAP_ADDRESSMODE;
    texture2.wrapV = Texture.WRAP_ADDRESSMODE;
    this._randomTexture = texture2;
  }
}
__decorate([
  serialize()
], SSAORenderingPipeline.prototype, "totalStrength", undefined);
__decorate([
  serialize()
], SSAORenderingPipeline.prototype, "radius", undefined);
__decorate([
  serialize()
], SSAORenderingPipeline.prototype, "area", undefined);
__decorate([
  serialize()
], SSAORenderingPipeline.prototype, "fallOff", undefined);
__decorate([
  serialize()
], SSAORenderingPipeline.prototype, "base", undefined);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/standardRenderingPipeline.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_logger();
init_math_vector();
init_texture();
init_postProcess();
init_typeStore();

// node_modules/@babylonjs/core/PostProcesses/screenSpaceReflectionPostProcess.js
init_tslib_es6();
init_postProcess();
init_decorators();
init_decorators_serialization();

// node_modules/@babylonjs/core/Rendering/screenSpaceReflectionsConfiguration.js
class ScreenSpaceReflectionsConfiguration {
  constructor() {
    this.enabled = false;
    this.name = "screenSpaceReflections";
    this.texturesRequired = [6, 3, 1];
  }
}

// node_modules/@babylonjs/core/Shaders/screenSpaceReflection.fragment.js
init_shaderStore();
var name434 = "screenSpaceReflectionPixelShader";
var shader433 = `uniform sampler2D textureSampler;
#ifdef SSR_SUPPORTED
uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;
#endif
uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV;
#ifdef SSR_SUPPORTED
struct ReflectionInfo {vec3 color;vec4 coords;};/**
* According to specular,see https:
*/
vec3 fresnelSchlick(float cosTheta,vec3 F0)
{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);}
/**
* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit
* by sampling multiple reflection pixels.
*/
ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)
{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++)
{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0)
hitCoord-=dir;else
hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}
projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}
/**
* Tests the given world position (hitCoord) according to the given reflection vector (dir)
* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!").
*/
ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)
{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++)
{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;
#ifdef RIGHT_HANDED_SCENE
depth*=-1.0;
#endif
if(((depth-dir.z)<threshold) && depth<=0.0)
{
#ifdef ENABLE_SMOOTH_REFLECTIONS
return smoothReflectionInfo(dir,hitCoord);
#else
info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;
#endif
}}
info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;}
vec3 hash(vec3 a)
{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}
#endif
void main()
{
#ifdef SSR_SUPPORTED
vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;}
vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0);
#ifdef RIGHT_HANDED_SCENE
reflected.z*=-1.0;
#endif
float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a);
#else
gl_FragColor=texture2D(textureSampler,vUV);
#endif
}
`;
if (!ShaderStore.ShadersStore[name434]) {
  ShaderStore.ShadersStore[name434] = shader433;
}

// node_modules/@babylonjs/core/PostProcesses/screenSpaceReflectionPostProcess.js
init_typeStore();
init_logger();

class ScreenSpaceReflectionPostProcess extends PostProcess {
  get _geometryBufferRenderer() {
    if (!this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.geometryBufferRenderer;
  }
  get _prePassRenderer() {
    if (this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.prePassRenderer;
  }
  getClassName() {
    return "ScreenSpaceReflectionPostProcess";
  }
  constructor(name435, scene, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {
    super(name435, "screenSpaceReflection", ["projection", "view", "threshold", "reflectionSpecularFalloffExponent", "strength", "stepSize", "roughnessFactor"], ["textureSampler", "normalSampler", "positionSampler", "reflectivitySampler"], options, camera2, samplingMode, engine2, reusable, `#define SSR_SUPPORTED
#define REFLECTION_SAMPLES 64
#define SMOOTH_STEPS 5
`, textureType, undefined, null, blockCompilation);
    this.threshold = 1.2;
    this.strength = 1;
    this.reflectionSpecularFalloffExponent = 3;
    this.step = 1;
    this.roughnessFactor = 0.2;
    this._forceGeometryBuffer = false;
    this._enableSmoothReflections = false;
    this._reflectionSamples = 64;
    this._smoothSteps = 5;
    this._forceGeometryBuffer = forceGeometryBuffer;
    if (this._forceGeometryBuffer) {
      const geometryBufferRenderer = scene.enableGeometryBufferRenderer();
      if (geometryBufferRenderer) {
        if (geometryBufferRenderer.isSupported) {
          geometryBufferRenderer.enablePosition = true;
          geometryBufferRenderer.enableReflectivity = true;
          if (geometryBufferRenderer.generateNormalsInWorldSpace) {
            Logger.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!");
          }
        }
      }
    } else {
      const prePassRenderer = scene.enablePrePassRenderer();
      prePassRenderer?.markAsDirty();
      if (prePassRenderer?.generateNormalsInWorldSpace) {
        Logger.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!");
      }
      this._prePassEffectConfiguration = new ScreenSpaceReflectionsConfiguration;
    }
    this._updateEffectDefines();
    this.onApply = (effect2) => {
      const geometryBufferRenderer = this._geometryBufferRenderer;
      const prePassRenderer = this._prePassRenderer;
      if (!prePassRenderer && !geometryBufferRenderer) {
        return;
      }
      if (geometryBufferRenderer) {
        const positionIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE);
        const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);
        effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]);
        effect2.setTexture("positionSampler", geometryBufferRenderer.getGBuffer().textures[positionIndex]);
        effect2.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);
      } else if (prePassRenderer) {
        const positionIndex = prePassRenderer.getIndex(1);
        const roughnessIndex = prePassRenderer.getIndex(3);
        const normalIndex = prePassRenderer.getIndex(6);
        effect2.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]);
        effect2.setTexture("positionSampler", prePassRenderer.getRenderTarget().textures[positionIndex]);
        effect2.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]);
      }
      const camera3 = scene.activeCamera;
      if (!camera3) {
        return;
      }
      const viewMatrix = camera3.getViewMatrix(true);
      const projectionMatrix = camera3.getProjectionMatrix(true);
      effect2.setMatrix("projection", projectionMatrix);
      effect2.setMatrix("view", viewMatrix);
      effect2.setFloat("threshold", this.threshold);
      effect2.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent);
      effect2.setFloat("strength", this.strength);
      effect2.setFloat("stepSize", this.step);
      effect2.setFloat("roughnessFactor", this.roughnessFactor);
    };
    this._isSceneRightHanded = scene.useRightHandedSystem;
  }
  get enableSmoothReflections() {
    return this._enableSmoothReflections;
  }
  set enableSmoothReflections(enabled) {
    if (enabled === this._enableSmoothReflections) {
      return;
    }
    this._enableSmoothReflections = enabled;
    this._updateEffectDefines();
  }
  get reflectionSamples() {
    return this._reflectionSamples;
  }
  set reflectionSamples(samples) {
    if (samples === this._reflectionSamples) {
      return;
    }
    this._reflectionSamples = samples;
    this._updateEffectDefines();
  }
  get smoothSteps() {
    return this._smoothSteps;
  }
  set smoothSteps(steps) {
    if (steps === this._smoothSteps) {
      return;
    }
    this._smoothSteps = steps;
    this._updateEffectDefines();
  }
  _updateEffectDefines() {
    const defines = [];
    if (this._geometryBufferRenderer || this._prePassRenderer) {
      defines.push("#define SSR_SUPPORTED");
    }
    if (this._enableSmoothReflections) {
      defines.push("#define ENABLE_SMOOTH_REFLECTIONS");
    }
    if (this._isSceneRightHanded) {
      defines.push("#define RIGHT_HANDED_SCENE");
    }
    defines.push("#define REFLECTION_SAMPLES " + (this._reflectionSamples >> 0));
    defines.push("#define SMOOTH_STEPS " + (this._smoothSteps >> 0));
    this.updateEffect(defines.join(`
`));
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new ScreenSpaceReflectionPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "threshold", undefined);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "strength", undefined);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "reflectionSpecularFalloffExponent", undefined);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "step", undefined);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "roughnessFactor", undefined);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "enableSmoothReflections", null);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "reflectionSamples", null);
__decorate([
  serialize()
], ScreenSpaceReflectionPostProcess.prototype, "smoothSteps", null);
RegisterClass("BABYLON.ScreenSpaceReflectionPostProcess", ScreenSpaceReflectionPostProcess);

// node_modules/@babylonjs/core/Shaders/standard.fragment.js
init_shaderStore();
init_packingFunctions2();
var name435 = "standardPixelShader";
var shader434 = `uniform sampler2D textureSampler;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
#if defined(PASS_POST_PROCESS)
void main(void)
{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}
#endif
#if defined(DOWN_SAMPLE_X4)
uniform vec2 dsOffsets[16];void main(void)
{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}
#endif
#if defined(BRIGHT_PASS)
uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)
{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);}
gl_FragColor=average;}
#endif
#if defined(TEXTURE_ADDER)
uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void)
{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;}
#endif
#if defined(VLS)
#define PI 3.1415926535897932384626433832795
uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView)
{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;}
void main(void)
{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++)
{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth)
accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}
accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}
#endif
#if defined(VLSMERGE)
uniform sampler2D originalSampler;void main(void)
{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}
#endif
#if defined(LUMINANCE)
uniform vec2 lumOffsets[4];void main()
{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)
{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));
#ifdef WEIGHTED_AVERAGE
float GreyValue=dot(color.rgb,weight);
#endif
#ifdef BRIGHTNESS
float GreyValue=max(color.r,max(color.g,color.b));
#endif
#ifdef HSL_COMPONENT
float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));
#endif
#ifdef MAGNITUDE
float GreyValue=length(color.rgb);
#endif
maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}
average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}
#endif
#if defined(LUMINANCE_DOWN_SAMPLE)
uniform vec2 dsOffsets[9];uniform float halfDestPixelSize;
#ifdef FINAL_DOWN_SAMPLER
#include<packingFunctions>
#endif
void main()
{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)
{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}
average/=9.0;
#ifdef FINAL_DOWN_SAMPLER
gl_FragColor=pack(average);
#else
gl_FragColor=vec4(average,average,0.0,1.0);
#endif
}
#endif
#if defined(HDR)
uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()
{vec4 color=texture2D(textureAdderSampler,vUV);
#ifndef AUTO_EXPOSURE
vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;
#endif
gl_FragColor=color;}
#endif
#if defined(LENS_FLARE)
#define GHOSTS 3
uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)
{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}
float noise(in vec2 p)
{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),
hash(i+vec2(1.0,0.0)),u.x),
mix(hash(i+vec2(0.0,1.0)),
hash(i+vec2(1.0,1.0)),u.x),u.y);}
float fbm(vec2 p)
{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}
vec3 pattern(vec2 uv)
{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}
float luminance(vec3 color)
{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}
vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)
{return vec4(
texture2D(tex,texcoord+direction*distortion.r).r,
texture2D(tex,texcoord+direction*distortion.g).g,
texture2D(tex,texcoord+direction*distortion.b).b,
1.0
);}
void main(void)
{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i)
{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;}
vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;}
#endif
#if defined(LENS_FLARE_COMPOSE)
uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void)
{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;}
#endif
#if defined(DEPTH_OF_FIELD)
uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void)
{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05)
factor=1.0;else if (dist<0.1)
factor=20.0*(0.1-dist);else if (dist<0.5)
factor=0.0;else
factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);}
#endif
#if defined(MOTION_BLUR)
uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void)
{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples)
break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}
gl_FragColor=result/float(nSamples);}
#endif
`;
if (!ShaderStore.ShadersStore[name435]) {
  ShaderStore.ShadersStore[name435] = shader434;
}

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/standardRenderingPipeline.js
class StandardRenderingPipeline extends PostProcessRenderPipeline {
  get exposure() {
    return this._fixedExposure;
  }
  set exposure(value) {
    this._fixedExposure = value;
    this._currentExposure = value;
  }
  get hdrAutoExposure() {
    return this._hdrAutoExposure;
  }
  set hdrAutoExposure(value) {
    this._hdrAutoExposure = value;
    if (this.hdrPostProcess) {
      const defines = ["#define HDR"];
      if (value) {
        defines.push("#define AUTO_EXPOSURE");
      }
      this.hdrPostProcess.updateEffect(defines.join(`
`));
    }
  }
  get motionStrength() {
    return this._motionStrength;
  }
  set motionStrength(strength) {
    this._motionStrength = strength;
    if (this._isObjectBasedMotionBlur && this.motionBlurPostProcess) {
      this.motionBlurPostProcess.motionStrength = strength;
    }
  }
  get objectBasedMotionBlur() {
    return this._isObjectBasedMotionBlur;
  }
  set objectBasedMotionBlur(value) {
    const shouldRebuild = this._isObjectBasedMotionBlur !== value;
    this._isObjectBasedMotionBlur = value;
    if (shouldRebuild) {
      this._buildPipeline();
    }
  }
  get BloomEnabled() {
    return this._bloomEnabled;
  }
  set BloomEnabled(enabled) {
    if (this._bloomEnabled === enabled) {
      return;
    }
    this._bloomEnabled = enabled;
    this._buildPipeline();
  }
  get DepthOfFieldEnabled() {
    return this._depthOfFieldEnabled;
  }
  set DepthOfFieldEnabled(enabled) {
    if (this._depthOfFieldEnabled === enabled) {
      return;
    }
    this._depthOfFieldEnabled = enabled;
    this._buildPipeline();
  }
  get LensFlareEnabled() {
    return this._lensFlareEnabled;
  }
  set LensFlareEnabled(enabled) {
    if (this._lensFlareEnabled === enabled) {
      return;
    }
    this._lensFlareEnabled = enabled;
    this._buildPipeline();
  }
  get HDREnabled() {
    return this._hdrEnabled;
  }
  set HDREnabled(enabled) {
    if (this._hdrEnabled === enabled) {
      return;
    }
    this._hdrEnabled = enabled;
    this._buildPipeline();
  }
  get VLSEnabled() {
    return this._vlsEnabled;
  }
  set VLSEnabled(enabled) {
    if (this._vlsEnabled === enabled) {
      return;
    }
    if (enabled) {
      const geometry2 = this._scene.enableGeometryBufferRenderer();
      if (!geometry2) {
        Logger.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
        return;
      }
    }
    this._vlsEnabled = enabled;
    this._buildPipeline();
  }
  get MotionBlurEnabled() {
    return this._motionBlurEnabled;
  }
  set MotionBlurEnabled(enabled) {
    if (this._motionBlurEnabled === enabled) {
      return;
    }
    this._motionBlurEnabled = enabled;
    this._buildPipeline();
  }
  get fxaaEnabled() {
    return this._fxaaEnabled;
  }
  set fxaaEnabled(enabled) {
    if (this._fxaaEnabled === enabled) {
      return;
    }
    this._fxaaEnabled = enabled;
    this._buildPipeline();
  }
  get screenSpaceReflectionsEnabled() {
    return this._screenSpaceReflectionsEnabled;
  }
  set screenSpaceReflectionsEnabled(enabled) {
    if (this._screenSpaceReflectionsEnabled === enabled) {
      return;
    }
    this._screenSpaceReflectionsEnabled = enabled;
    this._buildPipeline();
  }
  get volumetricLightStepsCount() {
    return this._volumetricLightStepsCount;
  }
  set volumetricLightStepsCount(count) {
    if (this.volumetricLightPostProcess) {
      this.volumetricLightPostProcess.updateEffect(`#define VLS
#define NB_STEPS ` + count.toFixed(1));
    }
    this._volumetricLightStepsCount = count;
  }
  get motionBlurSamples() {
    return this._motionBlurSamples;
  }
  set motionBlurSamples(samples) {
    if (this.motionBlurPostProcess) {
      if (this._isObjectBasedMotionBlur) {
        this.motionBlurPostProcess.motionBlurSamples = samples;
      } else {
        this.motionBlurPostProcess.updateEffect(`#define MOTION_BLUR
#define MAX_MOTION_SAMPLES ` + samples.toFixed(1));
      }
    }
    this._motionBlurSamples = samples;
  }
  get samples() {
    return this._samples;
  }
  set samples(sampleCount) {
    if (this._samples === sampleCount) {
      return;
    }
    this._samples = sampleCount;
    this._buildPipeline();
  }
  constructor(name436, scene, ratio, originalPostProcess = null, cameras) {
    super(scene.getEngine(), name436);
    this.downSampleX4PostProcess = null;
    this.brightPassPostProcess = null;
    this.blurHPostProcesses = [];
    this.blurVPostProcesses = [];
    this.textureAdderPostProcess = null;
    this.volumetricLightPostProcess = null;
    this.volumetricLightSmoothXPostProcess = null;
    this.volumetricLightSmoothYPostProcess = null;
    this.volumetricLightMergePostProces = null;
    this.volumetricLightFinalPostProcess = null;
    this.luminancePostProcess = null;
    this.luminanceDownSamplePostProcesses = [];
    this.hdrPostProcess = null;
    this.textureAdderFinalPostProcess = null;
    this.lensFlareFinalPostProcess = null;
    this.hdrFinalPostProcess = null;
    this.lensFlarePostProcess = null;
    this.lensFlareComposePostProcess = null;
    this.motionBlurPostProcess = null;
    this.depthOfFieldPostProcess = null;
    this.fxaaPostProcess = null;
    this.screenSpaceReflectionPostProcess = null;
    this.brightThreshold = 1;
    this.blurWidth = 512;
    this.horizontalBlur = false;
    this.lensTexture = null;
    this.volumetricLightCoefficient = 0.2;
    this.volumetricLightPower = 4;
    this.volumetricLightBlurScale = 64;
    this.sourceLight = null;
    this.hdrMinimumLuminance = 1;
    this.hdrDecreaseRate = 0.5;
    this.hdrIncreaseRate = 0.5;
    this.lensColorTexture = null;
    this.lensFlareStrength = 20;
    this.lensFlareGhostDispersal = 1.4;
    this.lensFlareHaloWidth = 0.7;
    this.lensFlareDistortionStrength = 16;
    this.lensFlareBlurWidth = 512;
    this.lensStarTexture = null;
    this.lensFlareDirtTexture = null;
    this.depthOfFieldDistance = 10;
    this.depthOfFieldBlurWidth = 64;
    this.animations = [];
    this._currentDepthOfFieldSource = null;
    this._fixedExposure = 1;
    this._currentExposure = 1;
    this._hdrAutoExposure = false;
    this._hdrCurrentLuminance = 1;
    this._motionStrength = 1;
    this._isObjectBasedMotionBlur = false;
    this._camerasToBeAttached = [];
    this._bloomEnabled = false;
    this._depthOfFieldEnabled = false;
    this._vlsEnabled = false;
    this._lensFlareEnabled = false;
    this._hdrEnabled = false;
    this._motionBlurEnabled = false;
    this._fxaaEnabled = false;
    this._screenSpaceReflectionsEnabled = false;
    this._motionBlurSamples = 64;
    this._volumetricLightStepsCount = 50;
    this._samples = 1;
    this._cameras = cameras || scene.cameras;
    this._cameras = this._cameras.slice();
    this._camerasToBeAttached = this._cameras.slice();
    this._scene = scene;
    this._basePostProcess = originalPostProcess;
    this._ratio = ratio;
    this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? 1 : 2;
    scene.postProcessRenderPipelineManager.addPipeline(this);
    this._buildPipeline();
  }
  _buildPipeline() {
    const ratio = this._ratio;
    const scene = this._scene;
    this._disposePostProcesses();
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
      this._cameras = this._camerasToBeAttached.slice();
    }
    this._reset();
    if (this._screenSpaceReflectionsEnabled) {
      this.screenSpaceReflectionPostProcess = new ScreenSpaceReflectionPostProcess("HDRPass", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);
      this.screenSpaceReflectionPostProcess.onApplyObservable.add(() => {
        this._currentDepthOfFieldSource = this.screenSpaceReflectionPostProcess;
      });
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRScreenSpaceReflections", () => this.screenSpaceReflectionPostProcess, true));
    }
    if (!this._basePostProcess) {
      this.originalPostProcess = new PostProcess("HDRPass", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
    } else {
      this.originalPostProcess = this._basePostProcess;
    }
    this.originalPostProcess.autoClear = !this.screenSpaceReflectionPostProcess;
    this.originalPostProcess.onApplyObservable.add(() => {
      this._currentDepthOfFieldSource = this.originalPostProcess;
    });
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", () => this.originalPostProcess, true));
    if (this._bloomEnabled) {
      this._createDownSampleX4PostProcess(scene, ratio / 4);
      this._createBrightPassPostProcess(scene, ratio / 4);
      this._createBlurPostProcesses(scene, ratio / 4, 1);
      this._createTextureAdderPostProcess(scene, ratio);
      this.textureAdderFinalPostProcess = new PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0);
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", () => {
        return this.textureAdderFinalPostProcess;
      }, true));
    }
    if (this._vlsEnabled) {
      this._createVolumetricLightPostProcess(scene, ratio);
      this.volumetricLightFinalPostProcess = new PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0);
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", () => {
        return this.volumetricLightFinalPostProcess;
      }, true));
    }
    if (this._lensFlareEnabled) {
      this._createLensFlarePostProcess(scene, ratio);
      this.lensFlareFinalPostProcess = new PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0);
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", () => {
        return this.lensFlareFinalPostProcess;
      }, true));
    }
    if (this._hdrEnabled) {
      this._createLuminancePostProcesses(scene, this._floatTextureType);
      this._createHdrPostProcess(scene, ratio);
      this.hdrFinalPostProcess = new PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0);
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", () => {
        return this.hdrFinalPostProcess;
      }, true));
    }
    if (this._depthOfFieldEnabled) {
      this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
      this._createDepthOfFieldPostProcess(scene, ratio);
    }
    if (this._motionBlurEnabled) {
      this._createMotionBlurPostProcess(scene, ratio);
    }
    if (this._fxaaEnabled) {
      this.fxaaPostProcess = new FxaaPostProcess("fxaa", 1, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", () => {
        return this.fxaaPostProcess;
      }, true));
    }
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
    }
    if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
      Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
    }
  }
  _createDownSampleX4PostProcess(scene, ratio) {
    const downSampleX4Offsets = new Array(32);
    this.downSampleX4PostProcess = new PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", this._floatTextureType);
    this.downSampleX4PostProcess.onApply = (effect2) => {
      let id = 0;
      const width = this.downSampleX4PostProcess.width;
      const height = this.downSampleX4PostProcess.height;
      for (let i = -2;i < 2; i++) {
        for (let j = -2;j < 2; j++) {
          downSampleX4Offsets[id] = (i + 0.5) * (1 / width);
          downSampleX4Offsets[id + 1] = (j + 0.5) * (1 / height);
          id += 2;
        }
      }
      effect2.setArray2("dsOffsets", downSampleX4Offsets);
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", () => {
      return this.downSampleX4PostProcess;
    }, true));
  }
  _createBrightPassPostProcess(scene, ratio) {
    const brightOffsets = new Array(8);
    this.brightPassPostProcess = new PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", this._floatTextureType);
    this.brightPassPostProcess.onApply = (effect2) => {
      const sU = 1 / this.brightPassPostProcess.width;
      const sV = 1 / this.brightPassPostProcess.height;
      brightOffsets[0] = -0.5 * sU;
      brightOffsets[1] = 0.5 * sV;
      brightOffsets[2] = 0.5 * sU;
      brightOffsets[3] = 0.5 * sV;
      brightOffsets[4] = -0.5 * sU;
      brightOffsets[5] = -0.5 * sV;
      brightOffsets[6] = 0.5 * sU;
      brightOffsets[7] = -0.5 * sV;
      effect2.setArray2("dsOffsets", brightOffsets);
      effect2.setFloat("brightThreshold", this.brightThreshold);
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", () => {
      return this.brightPassPostProcess;
    }, true));
  }
  _createBlurPostProcesses(scene, ratio, indice, blurWidthKey = "blurWidth") {
    const engine2 = scene.getEngine();
    const blurX = new BlurPostProcess("HDRBlurH" + "_" + indice, new Vector2(1, 0), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);
    const blurY = new BlurPostProcess("HDRBlurV" + "_" + indice, new Vector2(0, 1), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);
    blurX.onActivateObservable.add(() => {
      const dw = blurX.width / engine2.getRenderWidth();
      blurX.kernel = this[blurWidthKey] * dw;
    });
    blurY.onActivateObservable.add(() => {
      const dw = blurY.height / engine2.getRenderHeight();
      blurY.kernel = this.horizontalBlur ? 64 * dw : this[blurWidthKey] * dw;
    });
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, () => {
      return blurX;
    }, true));
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, () => {
      return blurY;
    }, true));
    this.blurHPostProcesses.push(blurX);
    this.blurVPostProcesses.push(blurY);
  }
  _createTextureAdderPostProcess(scene, ratio) {
    this.textureAdderPostProcess = new PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", this._floatTextureType);
    this.textureAdderPostProcess.onApply = (effect2) => {
      effect2.setTextureFromPostProcess("otherSampler", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess);
      effect2.setTexture("lensSampler", this.lensTexture);
      effect2.setFloat("exposure", this._currentExposure);
      this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", () => {
      return this.textureAdderPostProcess;
    }, true));
  }
  _createVolumetricLightPostProcess(scene, ratio) {
    const geometryRenderer = scene.enableGeometryBufferRenderer();
    geometryRenderer.enablePosition = true;
    const geometry2 = geometryRenderer.getGBuffer();
    this.volumetricLightPostProcess = new PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, `#define VLS
#define NB_STEPS ` + this._volumetricLightStepsCount.toFixed(1));
    const depthValues = Vector2.Zero();
    this.volumetricLightPostProcess.onApply = (effect2) => {
      if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) {
        const generator = this.sourceLight.getShadowGenerator();
        effect2.setTexture("shadowMapSampler", generator.getShadowMap());
        effect2.setTexture("positionSampler", geometry2.textures[2]);
        effect2.setColor3("sunColor", this.sourceLight.diffuse);
        effect2.setVector3("sunDirection", this.sourceLight.getShadowDirection());
        effect2.setVector3("cameraPosition", this._scene.activeCamera.globalPosition);
        effect2.setMatrix("shadowViewProjection", generator.getTransformMatrix());
        effect2.setFloat("scatteringCoefficient", this.volumetricLightCoefficient);
        effect2.setFloat("scatteringPower", this.volumetricLightPower);
        depthValues.x = this.sourceLight.getDepthMinZ(this._scene.activeCamera);
        depthValues.y = this.sourceLight.getDepthMaxZ(this._scene.activeCamera);
        effect2.setVector2("depthValues", depthValues);
      }
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLS", () => {
      return this.volumetricLightPostProcess;
    }, true));
    this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
    this.volumetricLightMergePostProces = new PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
    this.volumetricLightMergePostProces.onApply = (effect2) => {
      effect2.setTextureFromPostProcess("originalSampler", this._bloomEnabled ? this.textureAdderFinalPostProcess : this.originalPostProcess);
      this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess;
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", () => {
      return this.volumetricLightMergePostProces;
    }, true));
  }
  _createLuminancePostProcesses(scene, textureType) {
    let size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
    this.luminancePostProcess = new PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
    const offsets = [];
    this.luminancePostProcess.onApply = (effect2) => {
      const sU = 1 / this.luminancePostProcess.width;
      const sV = 1 / this.luminancePostProcess.height;
      offsets[0] = -0.5 * sU;
      offsets[1] = 0.5 * sV;
      offsets[2] = 0.5 * sU;
      offsets[3] = 0.5 * sV;
      offsets[4] = -0.5 * sU;
      offsets[5] = -0.5 * sV;
      offsets[6] = 0.5 * sU;
      offsets[7] = -0.5 * sV;
      effect2.setArray2("lumOffsets", offsets);
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", () => {
      return this.luminancePostProcess;
    }, true));
    for (let i = StandardRenderingPipeline.LuminanceSteps - 1;i >= 0; i--) {
      size = Math.pow(3, i);
      let defines = `#define LUMINANCE_DOWN_SAMPLE
`;
      if (i === 0) {
        defines += "#define FINAL_DOWN_SAMPLER";
      }
      const postProcess = new PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
      this.luminanceDownSamplePostProcesses.push(postProcess);
    }
    let lastLuminance = this.luminancePostProcess;
    this.luminanceDownSamplePostProcesses.forEach((pp, index) => {
      const downSampleOffsets = new Array(18);
      pp.onApply = (effect2) => {
        if (!lastLuminance) {
          return;
        }
        let id = 0;
        for (let x = -1;x < 2; x++) {
          for (let y = -1;y < 2; y++) {
            downSampleOffsets[id] = x / lastLuminance.width;
            downSampleOffsets[id + 1] = y / lastLuminance.height;
            id += 2;
          }
        }
        effect2.setArray2("dsOffsets", downSampleOffsets);
        effect2.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
        if (index === this.luminanceDownSamplePostProcesses.length - 1) {
          lastLuminance = this.luminancePostProcess;
        } else {
          lastLuminance = pp;
        }
      };
      if (index === this.luminanceDownSamplePostProcesses.length - 1) {
        pp.onAfterRender = () => {
          const pixel = scene.getEngine().readPixels(0, 0, 1, 1);
          const bit_shift = new Vector4(1 / (255 * 255 * 255), 1 / (255 * 255), 1 / 255, 1);
          pixel.then((pixel2) => {
            const data = new Uint8Array(pixel2.buffer);
            this._hdrCurrentLuminance = (data[0] * bit_shift.x + data[1] * bit_shift.y + data[2] * bit_shift.z + data[3] * bit_shift.w) / 100;
          });
        };
      }
      this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, () => {
        return pp;
      }, true));
    });
  }
  _createHdrPostProcess(scene, ratio) {
    const defines = ["#define HDR"];
    if (this._hdrAutoExposure) {
      defines.push("#define AUTO_EXPOSURE");
    }
    this.hdrPostProcess = new PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines.join(`
`), 0);
    let outputLiminance = 1;
    let time = 0;
    let lastTime = 0;
    this.hdrPostProcess.onApply = (effect2) => {
      effect2.setTextureFromPostProcess("textureAdderSampler", this._currentDepthOfFieldSource);
      time += scene.getEngine().getDeltaTime();
      if (outputLiminance < 0) {
        outputLiminance = this._hdrCurrentLuminance;
      } else {
        const dt = (lastTime - time) / 1000;
        if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) {
          outputLiminance += this.hdrDecreaseRate * dt;
        } else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) {
          outputLiminance -= this.hdrIncreaseRate * dt;
        } else {
          outputLiminance = this._hdrCurrentLuminance;
        }
      }
      if (this.hdrAutoExposure) {
        this._currentExposure = this._fixedExposure / outputLiminance;
      } else {
        outputLiminance = Clamp(outputLiminance, this.hdrMinimumLuminance, 100000000000000000000);
        effect2.setFloat("averageLuminance", outputLiminance);
      }
      lastTime = time;
      this._currentDepthOfFieldSource = this.hdrFinalPostProcess;
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDR", () => {
      return this.hdrPostProcess;
    }, true));
  }
  _createLensFlarePostProcess(scene, ratio) {
    this.lensFlarePostProcess = new PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", 0);
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", () => {
      return this.lensFlarePostProcess;
    }, true));
    this._createBlurPostProcesses(scene, ratio / 4, 2, "lensFlareBlurWidth");
    this.lensFlareComposePostProcess = new PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", 0);
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", () => {
      return this.lensFlareComposePostProcess;
    }, true));
    const resolution = new Vector2(0, 0);
    this.lensFlarePostProcess.externalTextureSamplerBinding = true;
    this.lensFlarePostProcess.onApply = (effect2) => {
      effect2.setTextureFromPostProcess("textureSampler", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess);
      effect2.setTexture("lensColorSampler", this.lensColorTexture);
      effect2.setFloat("strength", this.lensFlareStrength);
      effect2.setFloat("ghostDispersal", this.lensFlareGhostDispersal);
      effect2.setFloat("haloWidth", this.lensFlareHaloWidth);
      resolution.x = this.lensFlarePostProcess.width;
      resolution.y = this.lensFlarePostProcess.height;
      effect2.setVector2("resolution", resolution);
      effect2.setFloat("distortionStrength", this.lensFlareDistortionStrength);
    };
    const scaleBias1 = Matrix.FromValues(2, 0, -1, 0, 0, 2, -1, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    const scaleBias2 = Matrix.FromValues(0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    this.lensFlareComposePostProcess.onApply = (effect2) => {
      if (!this._scene.activeCamera) {
        return;
      }
      effect2.setTextureFromPostProcess("otherSampler", this.lensFlarePostProcess);
      effect2.setTexture("lensDirtSampler", this.lensFlareDirtTexture);
      effect2.setTexture("lensStarSampler", this.lensStarTexture);
      const camerax = this._scene.activeCamera.getViewMatrix().getRow(0);
      const cameraz = this._scene.activeCamera.getViewMatrix().getRow(2);
      let camRot = Vector3.Dot(camerax.toVector3(), new Vector3(1, 0, 0)) + Vector3.Dot(cameraz.toVector3(), new Vector3(0, 0, 1));
      camRot *= 4;
      const starRotation = Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0, 0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
      const lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
      effect2.setMatrix("lensStarMatrix", lensStarMatrix);
      this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
    };
  }
  _createDepthOfFieldPostProcess(scene, ratio) {
    this.depthOfFieldPostProcess = new PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", 0);
    this.depthOfFieldPostProcess.onApply = (effect2) => {
      effect2.setTextureFromPostProcess("otherSampler", this._currentDepthOfFieldSource);
      effect2.setTexture("depthSampler", this._getDepthTexture());
      effect2.setFloat("distance", this.depthOfFieldDistance);
    };
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", () => {
      return this.depthOfFieldPostProcess;
    }, true));
  }
  _createMotionBlurPostProcess(scene, ratio) {
    if (this._isObjectBasedMotionBlur) {
      const mb = new MotionBlurPostProcess("HDRMotionBlur", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);
      mb.motionStrength = this.motionStrength;
      mb.motionBlurSamples = this.motionBlurSamples;
      this.motionBlurPostProcess = mb;
    } else {
      this.motionBlurPostProcess = new PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, `#define MOTION_BLUR
#define MAX_MOTION_SAMPLES ` + this.motionBlurSamples.toFixed(1), 0);
      let motionScale = 0;
      let prevViewProjection = Matrix.Identity();
      const invViewProjection = Matrix.Identity();
      let viewProjection = Matrix.Identity();
      const screenSize = Vector2.Zero();
      this.motionBlurPostProcess.onApply = (effect2) => {
        viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
        viewProjection.invertToRef(invViewProjection);
        effect2.setMatrix("inverseViewProjection", invViewProjection);
        effect2.setMatrix("prevViewProjection", prevViewProjection);
        prevViewProjection = viewProjection;
        screenSize.x = this.motionBlurPostProcess.width;
        screenSize.y = this.motionBlurPostProcess.height;
        effect2.setVector2("screenSize", screenSize);
        motionScale = scene.getEngine().getFps() / 60;
        effect2.setFloat("motionScale", motionScale);
        effect2.setFloat("motionStrength", this.motionStrength);
        effect2.setTexture("depthSampler", this._getDepthTexture());
      };
    }
    this.addEffect(new PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", () => {
      return this.motionBlurPostProcess;
    }, true));
  }
  _getDepthTexture() {
    if (this._scene.getEngine().getCaps().drawBuffersExtension) {
      const renderer = this._scene.enableGeometryBufferRenderer();
      return renderer.getGBuffer().textures[0];
    }
    return this._scene.enableDepthRenderer().getDepthMap();
  }
  _disposePostProcesses() {
    for (let i = 0;i < this._cameras.length; i++) {
      const camera2 = this._cameras[i];
      if (this.originalPostProcess) {
        this.originalPostProcess.dispose(camera2);
      }
      if (this.screenSpaceReflectionPostProcess) {
        this.screenSpaceReflectionPostProcess.dispose(camera2);
      }
      if (this.downSampleX4PostProcess) {
        this.downSampleX4PostProcess.dispose(camera2);
      }
      if (this.brightPassPostProcess) {
        this.brightPassPostProcess.dispose(camera2);
      }
      if (this.textureAdderPostProcess) {
        this.textureAdderPostProcess.dispose(camera2);
      }
      if (this.volumetricLightPostProcess) {
        this.volumetricLightPostProcess.dispose(camera2);
      }
      if (this.volumetricLightSmoothXPostProcess) {
        this.volumetricLightSmoothXPostProcess.dispose(camera2);
      }
      if (this.volumetricLightSmoothYPostProcess) {
        this.volumetricLightSmoothYPostProcess.dispose(camera2);
      }
      if (this.volumetricLightMergePostProces) {
        this.volumetricLightMergePostProces.dispose(camera2);
      }
      if (this.volumetricLightFinalPostProcess) {
        this.volumetricLightFinalPostProcess.dispose(camera2);
      }
      if (this.lensFlarePostProcess) {
        this.lensFlarePostProcess.dispose(camera2);
      }
      if (this.lensFlareComposePostProcess) {
        this.lensFlareComposePostProcess.dispose(camera2);
      }
      for (let j = 0;j < this.luminanceDownSamplePostProcesses.length; j++) {
        this.luminanceDownSamplePostProcesses[j].dispose(camera2);
      }
      if (this.luminancePostProcess) {
        this.luminancePostProcess.dispose(camera2);
      }
      if (this.hdrPostProcess) {
        this.hdrPostProcess.dispose(camera2);
      }
      if (this.hdrFinalPostProcess) {
        this.hdrFinalPostProcess.dispose(camera2);
      }
      if (this.depthOfFieldPostProcess) {
        this.depthOfFieldPostProcess.dispose(camera2);
      }
      if (this.motionBlurPostProcess) {
        this.motionBlurPostProcess.dispose(camera2);
      }
      if (this.fxaaPostProcess) {
        this.fxaaPostProcess.dispose(camera2);
      }
      for (let j = 0;j < this.blurHPostProcesses.length; j++) {
        this.blurHPostProcesses[j].dispose(camera2);
      }
      for (let j = 0;j < this.blurVPostProcesses.length; j++) {
        this.blurVPostProcesses[j].dispose(camera2);
      }
    }
    this.originalPostProcess = null;
    this.downSampleX4PostProcess = null;
    this.brightPassPostProcess = null;
    this.textureAdderPostProcess = null;
    this.textureAdderFinalPostProcess = null;
    this.volumetricLightPostProcess = null;
    this.volumetricLightSmoothXPostProcess = null;
    this.volumetricLightSmoothYPostProcess = null;
    this.volumetricLightMergePostProces = null;
    this.volumetricLightFinalPostProcess = null;
    this.lensFlarePostProcess = null;
    this.lensFlareComposePostProcess = null;
    this.luminancePostProcess = null;
    this.hdrPostProcess = null;
    this.hdrFinalPostProcess = null;
    this.depthOfFieldPostProcess = null;
    this.motionBlurPostProcess = null;
    this.fxaaPostProcess = null;
    this.screenSpaceReflectionPostProcess = null;
    this.luminanceDownSamplePostProcesses.length = 0;
    this.blurHPostProcesses.length = 0;
    this.blurVPostProcesses.length = 0;
  }
  dispose() {
    this._disposePostProcesses();
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
    super.dispose();
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    if (this.sourceLight) {
      serializationObject.sourceLightId = this.sourceLight.id;
    }
    if (this.screenSpaceReflectionPostProcess) {
      serializationObject.screenSpaceReflectionPostProcess = SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess);
    }
    serializationObject.customType = "StandardRenderingPipeline";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    const p = SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);
    if (source.sourceLightId) {
      p.sourceLight = scene.getLightById(source.sourceLightId);
    }
    if (source.screenSpaceReflectionPostProcess) {
      SerializationHelper.Parse(() => p.screenSpaceReflectionPostProcess, source.screenSpaceReflectionPostProcess, scene, rootUrl);
    }
    return p;
  }
}
StandardRenderingPipeline.LuminanceSteps = 6;
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "brightThreshold", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "blurWidth", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "horizontalBlur", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "exposure", null);
__decorate([
  serializeAsTexture("lensTexture")
], StandardRenderingPipeline.prototype, "lensTexture", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "volumetricLightPower", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "hdrDecreaseRate", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "hdrIncreaseRate", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "hdrAutoExposure", null);
__decorate([
  serializeAsTexture("lensColorTexture")
], StandardRenderingPipeline.prototype, "lensColorTexture", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "lensFlareStrength", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "lensFlareBlurWidth", undefined);
__decorate([
  serializeAsTexture("lensStarTexture")
], StandardRenderingPipeline.prototype, "lensStarTexture", undefined);
__decorate([
  serializeAsTexture("lensFlareDirtTexture")
], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "depthOfFieldDistance", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "motionStrength", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "objectBasedMotionBlur", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "_ratio", undefined);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "BloomEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "HDREnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "VLSEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "screenSpaceReflectionsEnabled", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
__decorate([
  serialize()
], StandardRenderingPipeline.prototype, "samples", null);
RegisterClass("BABYLON.StandardRenderingPipeline", StandardRenderingPipeline);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_postProcess();
init_typeStore();

// node_modules/@babylonjs/core/Rendering/screenSpaceReflections2Configuration.js
class ScreenSpaceReflections2Configuration {
  constructor(useScreenspaceDepth = false) {
    this.enabled = false;
    this.name = "screenSpaceReflections2";
    this.texturesRequired = [6, 3];
    this.texturesRequired.push(useScreenspaceDepth ? 10 : 5);
  }
}

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js
class SSRRenderingPipeline extends PostProcessRenderPipeline {
  set samples(sampleCount) {
    if (this._samples === sampleCount) {
      return;
    }
    this._samples = sampleCount;
    if (this._ssrPostProcess) {
      this._ssrPostProcess.samples = this.samples;
    }
  }
  get samples() {
    return this._samples;
  }
  get maxDistance() {
    return this._thinSSRRenderingPipeline.maxDistance;
  }
  set maxDistance(distance) {
    this._thinSSRRenderingPipeline.maxDistance = distance;
  }
  get step() {
    return this._thinSSRRenderingPipeline.step;
  }
  set step(step) {
    this._thinSSRRenderingPipeline.step = step;
  }
  get thickness() {
    return this._thinSSRRenderingPipeline.thickness;
  }
  set thickness(thickness) {
    this._thinSSRRenderingPipeline.thickness = thickness;
  }
  get strength() {
    return this._thinSSRRenderingPipeline.strength;
  }
  set strength(strength) {
    this._thinSSRRenderingPipeline.strength = strength;
  }
  get reflectionSpecularFalloffExponent() {
    return this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent;
  }
  set reflectionSpecularFalloffExponent(exponent) {
    this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent = exponent;
  }
  get maxSteps() {
    return this._thinSSRRenderingPipeline.maxSteps;
  }
  set maxSteps(steps) {
    this._thinSSRRenderingPipeline.maxSteps = steps;
  }
  get roughnessFactor() {
    return this._thinSSRRenderingPipeline.roughnessFactor;
  }
  set roughnessFactor(factor) {
    this._thinSSRRenderingPipeline.roughnessFactor = factor;
  }
  get selfCollisionNumSkip() {
    return this._thinSSRRenderingPipeline.selfCollisionNumSkip;
  }
  set selfCollisionNumSkip(skip) {
    this._thinSSRRenderingPipeline.selfCollisionNumSkip = skip;
  }
  get reflectivityThreshold() {
    return this._thinSSRRenderingPipeline.reflectivityThreshold;
  }
  set reflectivityThreshold(threshold) {
    const currentThreshold = this.reflectivityThreshold;
    if (threshold === currentThreshold) {
      return;
    }
    this._thinSSRRenderingPipeline.reflectivityThreshold = threshold;
    if (threshold === 0 && currentThreshold !== 0 || threshold !== 0 && currentThreshold === 0) {
      this._buildPipeline();
    }
  }
  get ssrDownsample() {
    return this._thinSSRRenderingPipeline.ssrDownsample;
  }
  set ssrDownsample(downsample) {
    this._thinSSRRenderingPipeline.ssrDownsample = downsample;
    this._buildPipeline();
  }
  get blurDispersionStrength() {
    return this._thinSSRRenderingPipeline.blurDispersionStrength;
  }
  set blurDispersionStrength(strength) {
    const currentStrength = this.blurDispersionStrength;
    if (strength === currentStrength) {
      return;
    }
    this._thinSSRRenderingPipeline.blurDispersionStrength = strength;
    if (strength === 0 && currentStrength !== 0 || strength !== 0 && currentStrength === 0) {
      this._buildPipeline();
    }
  }
  _useBlur() {
    return this.blurDispersionStrength > 0;
  }
  get blurDownsample() {
    return this._thinSSRRenderingPipeline.blurDownsample;
  }
  set blurDownsample(downsample) {
    this._thinSSRRenderingPipeline.blurDownsample = downsample;
    this._buildPipeline();
  }
  get enableSmoothReflections() {
    return this._thinSSRRenderingPipeline.enableSmoothReflections;
  }
  set enableSmoothReflections(enabled) {
    this._thinSSRRenderingPipeline.enableSmoothReflections = enabled;
  }
  get _useScreenspaceDepth() {
    return this._thinSSRRenderingPipeline.useScreenspaceDepth;
  }
  get environmentTexture() {
    return this._thinSSRRenderingPipeline.environmentTexture;
  }
  set environmentTexture(texture2) {
    this._thinSSRRenderingPipeline.environmentTexture = texture2;
  }
  get environmentTextureIsProbe() {
    return this._thinSSRRenderingPipeline.environmentTextureIsProbe;
  }
  set environmentTextureIsProbe(isProbe) {
    this._thinSSRRenderingPipeline.environmentTextureIsProbe = isProbe;
  }
  get attenuateScreenBorders() {
    return this._thinSSRRenderingPipeline.attenuateScreenBorders;
  }
  set attenuateScreenBorders(attenuate) {
    this._thinSSRRenderingPipeline.attenuateScreenBorders = attenuate;
  }
  get attenuateIntersectionDistance() {
    return this._thinSSRRenderingPipeline.attenuateIntersectionDistance;
  }
  set attenuateIntersectionDistance(attenuate) {
    this._thinSSRRenderingPipeline.attenuateIntersectionDistance = attenuate;
  }
  get attenuateIntersectionIterations() {
    return this._thinSSRRenderingPipeline.attenuateIntersectionIterations;
  }
  set attenuateIntersectionIterations(attenuate) {
    this._thinSSRRenderingPipeline.attenuateIntersectionIterations = attenuate;
  }
  get attenuateFacingCamera() {
    return this._thinSSRRenderingPipeline.attenuateFacingCamera;
  }
  set attenuateFacingCamera(attenuate) {
    this._thinSSRRenderingPipeline.attenuateFacingCamera = attenuate;
  }
  get attenuateBackfaceReflection() {
    return this._thinSSRRenderingPipeline.attenuateBackfaceReflection;
  }
  set attenuateBackfaceReflection(attenuate) {
    this._thinSSRRenderingPipeline.attenuateBackfaceReflection = attenuate;
  }
  get clipToFrustum() {
    return this._thinSSRRenderingPipeline.clipToFrustum;
  }
  set clipToFrustum(clip) {
    this._thinSSRRenderingPipeline.clipToFrustum = clip;
  }
  get useFresnel() {
    return this._thinSSRRenderingPipeline.useFresnel;
  }
  set useFresnel(fresnel) {
    this._thinSSRRenderingPipeline.useFresnel = fresnel;
    this._buildPipeline();
  }
  get enableAutomaticThicknessComputation() {
    return this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation;
  }
  set enableAutomaticThicknessComputation(automatic) {
    this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation = automatic;
    this._buildPipeline();
  }
  get backfaceDepthRenderer() {
    return this._depthRenderer;
  }
  get backfaceDepthTextureDownsample() {
    return this._backfaceDepthTextureDownsample;
  }
  set backfaceDepthTextureDownsample(factor) {
    if (this._backfaceDepthTextureDownsample === factor) {
      return;
    }
    this._backfaceDepthTextureDownsample = factor;
    this._resizeDepthRenderer();
  }
  get backfaceForceDepthWriteTransparentMeshes() {
    return this._backfaceForceDepthWriteTransparentMeshes;
  }
  set backfaceForceDepthWriteTransparentMeshes(force) {
    if (this._backfaceForceDepthWriteTransparentMeshes === force) {
      return;
    }
    this._backfaceForceDepthWriteTransparentMeshes = force;
    if (this._depthRenderer) {
      this._depthRenderer.forceDepthWriteTransparentMeshes = force;
    }
  }
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    if (this._isEnabled === value) {
      return;
    }
    this._isEnabled = value;
    if (!value) {
      if (this._cameras !== null) {
        this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
        this._cameras = this._camerasToBeAttached.slice();
      }
    } else if (value) {
      if (!this._isDirty) {
        if (this._cameras !== null) {
          this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
        }
      } else {
        this._buildPipeline();
      }
    }
  }
  get inputTextureColorIsInGammaSpace() {
    return this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace;
  }
  set inputTextureColorIsInGammaSpace(gammaSpace) {
    this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace = gammaSpace;
    this._buildPipeline();
  }
  get generateOutputInGammaSpace() {
    return this._thinSSRRenderingPipeline.generateOutputInGammaSpace;
  }
  set generateOutputInGammaSpace(gammaSpace) {
    this._thinSSRRenderingPipeline.generateOutputInGammaSpace = gammaSpace;
    this._buildPipeline();
  }
  get debug() {
    return this._thinSSRRenderingPipeline.debug;
  }
  set debug(value) {
    this._thinSSRRenderingPipeline.debug = value;
    this._buildPipeline();
  }
  getScene() {
    return this._scene;
  }
  get _geometryBufferRenderer() {
    if (!this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.geometryBufferRenderer;
  }
  get _prePassRenderer() {
    if (this._forceGeometryBuffer) {
      return null;
    }
    return this._scene.prePassRenderer;
  }
  get scene() {
    return this._scene;
  }
  get isSupported() {
    const caps = this._scene.getEngine().getCaps();
    return caps.drawBuffersExtension && caps.texelFetch;
  }
  constructor(name436, scene, cameras, forceGeometryBuffer = false, textureType = 0, useScreenspaceDepth = false) {
    super(scene.getEngine(), name436);
    this.SSRRenderEffect = "SSRRenderEffect";
    this.SSRBlurRenderEffect = "SSRBlurRenderEffect";
    this.SSRCombineRenderEffect = "SSRCombineRenderEffect";
    this._samples = 1;
    this._backfaceDepthTextureDownsample = 0;
    this._backfaceForceDepthWriteTransparentMeshes = true;
    this._isEnabled = true;
    this._forceGeometryBuffer = false;
    this._isDirty = false;
    this._camerasToBeAttached = [];
    this._thinSSRRenderingPipeline = new ThinSSRRenderingPipeline(name436, scene);
    this._thinSSRRenderingPipeline.isSSRSupported = false;
    this._thinSSRRenderingPipeline.useScreenspaceDepth = useScreenspaceDepth;
    this._cameras = cameras || scene.cameras;
    this._cameras = this._cameras.slice();
    this._camerasToBeAttached = this._cameras.slice();
    this._scene = scene;
    this._textureType = textureType;
    this._forceGeometryBuffer = forceGeometryBuffer;
    if (this.isSupported) {
      this._createSSRPostProcess();
      scene.postProcessRenderPipelineManager.addPipeline(this);
      if (this._forceGeometryBuffer) {
        const geometryBufferRenderer = scene.enableGeometryBufferRenderer();
        if (geometryBufferRenderer) {
          geometryBufferRenderer.enableReflectivity = true;
          geometryBufferRenderer.useSpecificClearForDepthTexture = true;
          geometryBufferRenderer.enableScreenspaceDepth = this._useScreenspaceDepth;
          geometryBufferRenderer.enableDepth = !this._useScreenspaceDepth;
        }
      } else {
        const prePassRenderer = scene.enablePrePassRenderer();
        if (prePassRenderer) {
          prePassRenderer.useSpecificClearForDepthTexture = true;
          prePassRenderer.markAsDirty();
        }
      }
      this._thinSSRRenderingPipeline.isSSRSupported = !!this._geometryBufferRenderer || !!this._prePassRenderer;
      this._buildPipeline();
    }
  }
  getClassName() {
    return "SSRRenderingPipeline";
  }
  addCamera(camera2) {
    this._camerasToBeAttached.push(camera2);
    this._buildPipeline();
  }
  removeCamera(camera2) {
    const index = this._camerasToBeAttached.indexOf(camera2);
    this._camerasToBeAttached.splice(index, 1);
    this._buildPipeline();
  }
  dispose(disableGeometryBufferRenderer = false) {
    this._disposeDepthRenderer();
    this._disposeSSRPostProcess();
    this._disposeBlurPostProcesses();
    if (disableGeometryBufferRenderer) {
      this._scene.disableGeometryBufferRenderer();
    }
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
    this._thinSSRRenderingPipeline.dispose();
    super.dispose();
  }
  _getTextureSize() {
    const engine2 = this._scene.getEngine();
    const prePassRenderer = this._prePassRenderer;
    let textureSize = { width: engine2.getRenderWidth(), height: engine2.getRenderHeight() };
    if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) {
      const renderTarget = prePassRenderer.getRenderTarget();
      if (renderTarget && renderTarget.textures) {
        textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize();
      }
    } else if (this._ssrPostProcess?.inputTexture) {
      textureSize.width = this._ssrPostProcess.inputTexture.width;
      textureSize.height = this._ssrPostProcess.inputTexture.height;
    }
    return textureSize;
  }
  _buildPipeline() {
    if (!this.isSupported) {
      return;
    }
    if (!this._isEnabled) {
      this._isDirty = true;
      return;
    }
    this._isDirty = false;
    const engine2 = this._scene.getEngine();
    this._disposeDepthRenderer();
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
      this._cameras = this._camerasToBeAttached.slice();
      if (this._cameras.length > 0) {
        this._thinSSRRenderingPipeline.camera = this._cameras[0];
      }
    }
    this._reset();
    this._thinSSRRenderingPipeline.normalsAreInWorldSpace = !!(this._geometryBufferRenderer?.generateNormalsInWorldSpace ?? this._prePassRenderer?.generateNormalsInWorldSpace);
    if (this.enableAutomaticThicknessComputation) {
      const camera2 = this._cameras?.[0];
      if (camera2) {
        this._depthRendererCamera = camera2;
        this._depthRenderer = new DepthRenderer(this._scene, undefined, undefined, this._useScreenspaceDepth, 1, !this._useScreenspaceDepth, "SSRBackDepth");
        if (!this._useScreenspaceDepth) {
          this._depthRenderer.clearColor.r = 1e8;
        }
        this._depthRenderer.reverseCulling = true;
        this._depthRenderer.forceDepthWriteTransparentMeshes = this.backfaceForceDepthWriteTransparentMeshes;
        this._resizeDepthRenderer();
        camera2.customRenderTargets.push(this._depthRenderer.getDepthMap());
      }
    }
    this.addEffect(new PostProcessRenderEffect(engine2, this.SSRRenderEffect, () => {
      return this._ssrPostProcess;
    }, true));
    this._disposeBlurPostProcesses();
    if (this._useBlur()) {
      this._createBlurAndCombinerPostProcesses();
      this.addEffect(new PostProcessRenderEffect(engine2, this.SSRBlurRenderEffect, () => {
        return [this._blurPostProcessX, this._blurPostProcessY];
      }, true));
      this.addEffect(new PostProcessRenderEffect(engine2, this.SSRCombineRenderEffect, () => {
        return this._blurCombinerPostProcess;
      }, true));
    }
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
    }
  }
  _resizeDepthRenderer() {
    if (!this._depthRenderer) {
      return;
    }
    const textureSize = this._getTextureSize();
    const depthRendererSize = this._depthRenderer.getDepthMap().getSize();
    const width = Math.floor(textureSize.width / (this.backfaceDepthTextureDownsample + 1));
    const height = Math.floor(textureSize.height / (this.backfaceDepthTextureDownsample + 1));
    if (depthRendererSize.width !== width || depthRendererSize.height !== height) {
      this._depthRenderer.getDepthMap().resize({ width, height });
    }
  }
  _disposeDepthRenderer() {
    if (this._depthRenderer) {
      if (this._depthRendererCamera) {
        const idx = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()) ?? -1;
        if (idx !== -1) {
          this._depthRendererCamera.customRenderTargets.splice(idx, 1);
        }
      }
      this._depthRendererCamera = null;
      this._depthRenderer.getDepthMap().dispose();
    }
    this._depthRenderer = null;
  }
  _disposeBlurPostProcesses() {
    for (let i = 0;i < this._cameras.length; i++) {
      const camera2 = this._cameras[i];
      this._blurPostProcessX?.dispose(camera2);
      this._blurPostProcessY?.dispose(camera2);
      this._blurCombinerPostProcess?.dispose(camera2);
    }
    this._blurPostProcessX = null;
    this._blurPostProcessY = null;
    this._blurCombinerPostProcess = null;
  }
  _disposeSSRPostProcess() {
    for (let i = 0;i < this._cameras.length; i++) {
      const camera2 = this._cameras[i];
      this._ssrPostProcess?.dispose(camera2);
    }
    this._ssrPostProcess = null;
  }
  _createSSRPostProcess() {
    this._ssrPostProcess = new PostProcess("ssr", ThinSSRPostProcess.FragmentUrl, {
      uniformNames: ThinSSRPostProcess.Uniforms,
      samplerNames: ThinSSRPostProcess.Samplers,
      size: 1,
      samplingMode: 2,
      engine: this._scene.getEngine(),
      textureType: this._textureType,
      effectWrapper: this._thinSSRRenderingPipeline._ssrPostProcess
    });
    this._ssrPostProcess.onApply = (effect2) => {
      this._resizeDepthRenderer();
      const geometryBufferRenderer = this._geometryBufferRenderer;
      const prePassRenderer = this._prePassRenderer;
      if (!prePassRenderer && !geometryBufferRenderer) {
        return;
      }
      if (geometryBufferRenderer) {
        const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);
        const normalIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE);
        effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[normalIndex]);
        effect2.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);
        if (this._useScreenspaceDepth) {
          const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE);
          effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]);
        } else {
          const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);
          effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]);
        }
      } else if (prePassRenderer) {
        const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5);
        const roughnessIndex = prePassRenderer.getIndex(3);
        const normalIndex = prePassRenderer.getIndex(6);
        effect2.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]);
        effect2.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]);
        effect2.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]);
      }
      if (this.enableAutomaticThicknessComputation && this._depthRenderer) {
        effect2.setTexture("backDepthSampler", this._depthRenderer.getDepthMap());
        effect2.setFloat("backSizeFactor", this.backfaceDepthTextureDownsample + 1);
      }
      const textureSize = this._getTextureSize();
      this._thinSSRRenderingPipeline._ssrPostProcess.textureWidth = textureSize.width;
      this._thinSSRRenderingPipeline._ssrPostProcess.textureHeight = textureSize.height;
    };
    this._ssrPostProcess.samples = this.samples;
    if (!this._forceGeometryBuffer) {
      this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration(this._useScreenspaceDepth);
    }
  }
  _createBlurAndCombinerPostProcesses() {
    const engine2 = this._scene.getEngine();
    this._blurPostProcessX = new PostProcess("SSRblurX", ThinSSRBlurPostProcess.FragmentUrl, {
      uniformNames: ThinSSRBlurPostProcess.Uniforms,
      samplerNames: ThinSSRBlurPostProcess.Samplers,
      size: 1 / (this.ssrDownsample + 1),
      samplingMode: 2,
      engine: engine2,
      textureType: this._textureType,
      effectWrapper: this._thinSSRRenderingPipeline._ssrBlurXPostProcess
    });
    this._blurPostProcessX.autoClear = false;
    this._blurPostProcessX.onApplyObservable.add(() => {
      this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureWidth = this._blurPostProcessX?.inputTexture.width ?? this._scene.getEngine().getRenderWidth();
      this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureHeight = 1;
    });
    this._blurPostProcessY = new PostProcess("SSRblurY", ThinSSRBlurPostProcess.FragmentUrl, {
      uniformNames: ThinSSRBlurPostProcess.Uniforms,
      samplerNames: ThinSSRBlurPostProcess.Samplers,
      size: 1 / (this.blurDownsample + 1),
      samplingMode: 2,
      engine: engine2,
      textureType: this._textureType,
      effectWrapper: this._thinSSRRenderingPipeline._ssrBlurYPostProcess
    });
    this._blurPostProcessY.autoClear = false;
    this._blurPostProcessY.onApplyObservable.add(() => {
      this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureWidth = 1;
      this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureHeight = this._blurPostProcessY?.inputTexture.height ?? this._scene.getEngine().getRenderHeight();
    });
    this._blurCombinerPostProcess = new PostProcess("SSRblurCombiner", ThinSSRBlurCombinerPostProcess.FragmentUrl, {
      uniformNames: ThinSSRBlurCombinerPostProcess.Uniforms,
      samplerNames: ThinSSRBlurCombinerPostProcess.Samplers,
      size: 1 / (this.blurDownsample + 1),
      samplingMode: 1,
      engine: engine2,
      textureType: this._textureType,
      effectWrapper: this._thinSSRRenderingPipeline._ssrBlurCombinerPostProcess
    });
    this._blurCombinerPostProcess.autoClear = false;
    this._blurCombinerPostProcess.onApplyObservable.add((effect2) => {
      const geometryBufferRenderer = this._geometryBufferRenderer;
      const prePassRenderer = this._prePassRenderer;
      if (!prePassRenderer && !geometryBufferRenderer) {
        return;
      }
      if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) {
        const renderTarget = prePassRenderer.getRenderTarget();
        if (renderTarget && renderTarget.textures) {
          effect2.setTexture("mainSampler", renderTarget.textures[prePassRenderer.getIndex(4)]);
        }
      } else {
        effect2.setTextureFromPostProcess("mainSampler", this._ssrPostProcess);
      }
      if (geometryBufferRenderer) {
        const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);
        effect2.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);
        if (this.useFresnel) {
          effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]);
          if (this._useScreenspaceDepth) {
            const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE);
            effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]);
          } else {
            effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[0]);
          }
        }
      } else if (prePassRenderer) {
        const roughnessIndex = prePassRenderer.getIndex(3);
        effect2.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]);
        if (this.useFresnel) {
          const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5);
          const normalIndex = prePassRenderer.getIndex(6);
          effect2.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]);
          effect2.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]);
        }
      }
    });
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "SSRRenderingPipeline";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);
  }
}
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "samples", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "maxDistance", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "step", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "thickness", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "strength", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "reflectionSpecularFalloffExponent", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "maxSteps", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "roughnessFactor", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "selfCollisionNumSkip", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "reflectivityThreshold", null);
__decorate([
  serialize()
], SSRRenderingPipeline.prototype, "ssrDownsample", null);
__decorate([
  serialize("blurDispersionStrength")
], SSRRenderingPipeline.prototype, "blurDispersionStrength", null);
__decorate([
  serialize("blurDownsample")
], SSRRenderingPipeline.prototype, "blurDownsample", null);
__decorate([
  serialize("enableSmoothReflections")
], SSRRenderingPipeline.prototype, "enableSmoothReflections", null);
__decorate([
  serialize("environmentTexture")
], SSRRenderingPipeline.prototype, "environmentTexture", null);
__decorate([
  serialize("environmentTextureIsProbe")
], SSRRenderingPipeline.prototype, "environmentTextureIsProbe", null);
__decorate([
  serialize("attenuateScreenBorders")
], SSRRenderingPipeline.prototype, "attenuateScreenBorders", null);
__decorate([
  serialize("attenuateIntersectionDistance")
], SSRRenderingPipeline.prototype, "attenuateIntersectionDistance", null);
__decorate([
  serialize("attenuateIntersectionIterations")
], SSRRenderingPipeline.prototype, "attenuateIntersectionIterations", null);
__decorate([
  serialize("attenuateFacingCamera")
], SSRRenderingPipeline.prototype, "attenuateFacingCamera", null);
__decorate([
  serialize("attenuateBackfaceReflection")
], SSRRenderingPipeline.prototype, "attenuateBackfaceReflection", null);
__decorate([
  serialize("clipToFrustum")
], SSRRenderingPipeline.prototype, "clipToFrustum", null);
__decorate([
  serialize("useFresnel")
], SSRRenderingPipeline.prototype, "useFresnel", null);
__decorate([
  serialize("enableAutomaticThicknessComputation")
], SSRRenderingPipeline.prototype, "enableAutomaticThicknessComputation", null);
__decorate([
  serialize("backfaceDepthTextureDownsample")
], SSRRenderingPipeline.prototype, "_backfaceDepthTextureDownsample", undefined);
__decorate([
  serialize("backfaceForceDepthWriteTransparentMeshes")
], SSRRenderingPipeline.prototype, "_backfaceForceDepthWriteTransparentMeshes", undefined);
__decorate([
  serialize("isEnabled")
], SSRRenderingPipeline.prototype, "_isEnabled", undefined);
__decorate([
  serialize("inputTextureColorIsInGammaSpace")
], SSRRenderingPipeline.prototype, "inputTextureColorIsInGammaSpace", null);
__decorate([
  serialize("generateOutputInGammaSpace")
], SSRRenderingPipeline.prototype, "generateOutputInGammaSpace", null);
__decorate([
  serialize("debug")
], SSRRenderingPipeline.prototype, "debug", null);
RegisterClass("BABYLON.SSRRenderingPipeline", SSRRenderingPipeline);
// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/taaRenderingPipeline.js
init_tslib_es6();
init_decorators();
init_decorators_serialization();
init_postProcess();
init_typeStore();
init_passPostProcess();
class TAARenderingPipeline extends PostProcessRenderPipeline {
  set samples(samples) {
    this._taaThinPostProcess.samples = samples;
  }
  get samples() {
    return this._taaThinPostProcess.samples;
  }
  set msaaSamples(samples) {
    if (this._msaaSamples === samples) {
      return;
    }
    this._msaaSamples = samples;
    if (this._taaPostProcess) {
      this._taaPostProcess.samples = samples;
    }
  }
  get msaaSamples() {
    return this._msaaSamples;
  }
  get factor() {
    return this._taaThinPostProcess.factor;
  }
  set factor(value) {
    this._taaThinPostProcess.factor = value;
  }
  get disableOnCameraMove() {
    return this._taaThinPostProcess.disableOnCameraMove;
  }
  set disableOnCameraMove(value) {
    this._taaThinPostProcess.disableOnCameraMove = value;
  }
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    if (this._isEnabled === value) {
      return;
    }
    this._isEnabled = value;
    if (!value) {
      if (this._cameras !== null) {
        this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
        this._cameras = this._camerasToBeAttached.slice();
      }
    } else if (value) {
      if (!this._isDirty) {
        if (this._cameras !== null) {
          this._taaThinPostProcess._reset();
          this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
        }
      } else {
        this._buildPipeline();
      }
    }
  }
  get scene() {
    return this._scene;
  }
  get isSupported() {
    const caps = this._scene.getEngine().getCaps();
    return caps.texelFetch;
  }
  constructor(name436, scene, cameras, textureType = 0) {
    const engine2 = scene.getEngine();
    super(engine2, name436);
    this.TAARenderEffect = "TAARenderEffect";
    this.TAAPassEffect = "TAAPassEffect";
    this._msaaSamples = 1;
    this._isEnabled = true;
    this._isDirty = false;
    this._camerasToBeAttached = [];
    this._pingpong = 0;
    this._cameras = cameras || scene.cameras;
    this._cameras = this._cameras.slice();
    this._camerasToBeAttached = this._cameras.slice();
    this._scene = scene;
    this._textureType = textureType;
    this._taaThinPostProcess = new ThinTAAPostProcess("TAA", this._scene.getEngine());
    if (this.isSupported) {
      this._createPingPongTextures(engine2.getRenderWidth(), engine2.getRenderHeight());
      scene.postProcessRenderPipelineManager.addPipeline(this);
      this._buildPipeline();
    }
  }
  getClassName() {
    return "TAARenderingPipeline";
  }
  addCamera(camera2) {
    this._camerasToBeAttached.push(camera2);
    this._buildPipeline();
  }
  removeCamera(camera2) {
    const index = this._camerasToBeAttached.indexOf(camera2);
    this._camerasToBeAttached.splice(index, 1);
    this._buildPipeline();
  }
  dispose() {
    this._disposePostProcesses();
    this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
    this._ping.dispose();
    this._pong.dispose();
    super.dispose();
  }
  _createPingPongTextures(width, height) {
    const engine2 = this._scene.getEngine();
    this._ping?.dispose();
    this._pong?.dispose();
    this._ping = engine2.createRenderTargetTexture({ width, height }, { generateMipMaps: false, generateDepthBuffer: false, type: 2, samplingMode: 1 });
    this._pong = engine2.createRenderTargetTexture({ width, height }, { generateMipMaps: false, generateDepthBuffer: false, type: 2, samplingMode: 1 });
    this._taaThinPostProcess.textureWidth = width;
    this._taaThinPostProcess.textureHeight = height;
  }
  _buildPipeline() {
    if (!this.isSupported) {
      return;
    }
    if (!this._isEnabled) {
      this._isDirty = true;
      return;
    }
    this._isDirty = false;
    const engine2 = this._scene.getEngine();
    this._disposePostProcesses();
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
      this._cameras = this._camerasToBeAttached.slice();
    }
    this._reset();
    this._createTAAPostProcess();
    this.addEffect(new PostProcessRenderEffect(engine2, this.TAARenderEffect, () => {
      return this._taaPostProcess;
    }, true));
    this._createPassPostProcess();
    this.addEffect(new PostProcessRenderEffect(engine2, this.TAAPassEffect, () => {
      return this._passPostProcess;
    }, true));
    if (this._cameras !== null) {
      this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
    }
  }
  _disposePostProcesses() {
    for (let i = 0;i < this._cameras.length; i++) {
      const camera2 = this._cameras[i];
      this._taaPostProcess?.dispose(camera2);
      this._passPostProcess?.dispose(camera2);
      camera2.getProjectionMatrix(true);
    }
    this._taaPostProcess = null;
    this._passPostProcess = null;
  }
  _createTAAPostProcess() {
    this._taaPostProcess = new PostProcess("TAA", "taa", {
      uniforms: ["factor"],
      samplers: ["historySampler"],
      size: 1,
      engine: this._scene.getEngine(),
      textureType: this._textureType,
      effectWrapper: this._taaThinPostProcess
    });
    this._taaPostProcess.samples = this._msaaSamples;
    this._taaPostProcess.onActivateObservable.add(() => {
      this._taaThinPostProcess.camera = this._scene.activeCamera;
      if (this._taaPostProcess?.width !== this._ping.width || this._taaPostProcess?.height !== this._ping.height) {
        const engine2 = this._scene.getEngine();
        this._createPingPongTextures(engine2.getRenderWidth(), engine2.getRenderHeight());
      }
      this._taaThinPostProcess.updateProjectionMatrix();
      if (this._passPostProcess) {
        this._passPostProcess.inputTexture = this._pingpong ? this._ping : this._pong;
      }
      this._pingpong = this._pingpong ^ 1;
    });
    this._taaPostProcess.onApplyObservable.add((effect2) => {
      effect2._bindTexture("historySampler", this._pingpong ? this._ping.texture : this._pong.texture);
    });
  }
  _createPassPostProcess() {
    const engine2 = this._scene.getEngine();
    this._passPostProcess = new PassPostProcess("TAAPass", 1, null, 1, engine2);
    this._passPostProcess.inputTexture = this._ping;
    this._passPostProcess.autoClear = false;
  }
  serialize() {
    const serializationObject = SerializationHelper.Serialize(this);
    serializationObject.customType = "TAARenderingPipeline";
    return serializationObject;
  }
  static Parse(source, scene, rootUrl) {
    return SerializationHelper.Parse(() => new TAARenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);
  }
}
__decorate([
  serialize("samples")
], TAARenderingPipeline.prototype, "samples", null);
__decorate([
  serialize("msaaSamples")
], TAARenderingPipeline.prototype, "_msaaSamples", undefined);
__decorate([
  serialize()
], TAARenderingPipeline.prototype, "factor", null);
__decorate([
  serialize()
], TAARenderingPipeline.prototype, "disableOnCameraMove", null);
__decorate([
  serialize("isEnabled")
], TAARenderingPipeline.prototype, "_isEnabled", undefined);
RegisterClass("BABYLON.TAARenderingPipeline", TAARenderingPipeline);

// node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/index.js
init_taa_fragment2();
init_taa_fragment();
init_ssao2_fragment2();
init_ssaoCombine_fragment2();
init_ssao2_fragment();
init_ssaoCombine_fragment();
init_screenSpaceReflection2_fragment2();
init_screenSpaceReflection2Blur_fragment2();
init_screenSpaceReflection2BlurCombiner_fragment2();
init_screenSpaceReflection2_fragment();
init_screenSpaceReflection2Blur_fragment();
init_screenSpaceReflection2BlurCombiner_fragment();
// node_modules/@babylonjs/core/PostProcesses/tonemapPostProcess.js
init_postProcess();
var TonemappingOperator;
(function(TonemappingOperator2) {
  TonemappingOperator2[TonemappingOperator2["Hable"] = 0] = "Hable";
  TonemappingOperator2[TonemappingOperator2["Reinhard"] = 1] = "Reinhard";
  TonemappingOperator2[TonemappingOperator2["HejiDawson"] = 2] = "HejiDawson";
  TonemappingOperator2[TonemappingOperator2["Photographic"] = 3] = "Photographic";
})(TonemappingOperator || (TonemappingOperator = {}));
// node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js
init_tslib_es6();
init_decorators();
init_logger();
init_math_vector();
init_buffer();
init_texture();
init_renderTargetTexture();
init_postProcess();
init_depth_vertex();

// node_modules/@babylonjs/core/Shaders/volumetricLightScattering.fragment.js
init_shaderStore();
var name436 = "volumetricLightScatteringPixelShader";
var shader435 = `uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;}
vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),realColor.a))+(realColor*(1.5-0.4)));
#define CUSTOM_FRAGMENT_MAIN_END
}
`;
if (!ShaderStore.ShadersStore[name436]) {
  ShaderStore.ShadersStore[name436] = shader435;
}

// node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.vertex.js
init_shaderStore();
init_bonesDeclaration2();
init_bakedVertexAnimationDeclaration2();
init_morphTargetsVertexGlobalDeclaration2();
init_morphTargetsVertexDeclaration2();
init_instancesDeclaration2();
init_morphTargetsVertexGlobal2();
init_morphTargetsVertex2();
init_instancesVertex2();
init_bonesVertex2();
init_bakedVertexAnimation2();
var name437 = "volumetricLightScatteringPassVertexShader";
var shader436 = `attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)
vec2 uvUpdated=uv;
#endif
#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV2)
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
}
`;
if (!ShaderStore.ShadersStore[name437]) {
  ShaderStore.ShadersStore[name437] = shader436;
}

// node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.fragment.js
init_shaderStore();
var name438 = "volumetricLightScatteringPassPixelShader";
var shader437 = `#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;
#endif
#if defined(ALPHATEST)
uniform sampler2D diffuseSampler;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#if defined(ALPHATEST)
vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4)
discard;
#endif
gl_FragColor=vec4(0.0,0.0,0.0,1.0);}
`;
if (!ShaderStore.ShadersStore[name438]) {
  ShaderStore.ShadersStore[name438] = shader437;
}

// node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js
init_math_color();
init_typeStore();
init_materialHelper_functions();
class VolumetricLightScatteringPostProcess extends PostProcess {
  get useDiffuseColor() {
    Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
    return false;
  }
  set useDiffuseColor(useDiffuseColor) {
    Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  }
  constructor(name439, ratio, camera2, mesh2, samples = 100, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine2, reusable, scene) {
    super(name439, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera2, samplingMode, engine2, reusable, "#define NUM_SAMPLES " + samples);
    this._screenCoordinates = Vector2.Zero();
    this.customMeshPosition = Vector3.Zero();
    this.useCustomMeshPosition = false;
    this.invert = true;
    this.excludedMeshes = [];
    this.includedMeshes = [];
    this.exposure = 0.3;
    this.decay = 0.96815;
    this.weight = 0.58767;
    this.density = 0.926;
    scene = camera2?.getScene() ?? scene ?? this._scene;
    engine2 = scene.getEngine();
    this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine2.getRenderWidth(), engine2.getRenderHeight());
    this.mesh = mesh2 ?? VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
    this._createPass(scene, ratio.passRatio || ratio);
    this.onActivate = (camera3) => {
      if (!this.isSupported) {
        this.dispose(camera3);
      }
      this.onActivate = null;
    };
    this.onApplyObservable.add((effect2) => {
      this._updateMeshScreenCoordinates(scene);
      effect2.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT);
      effect2.setFloat("exposure", this.exposure);
      effect2.setFloat("decay", this.decay);
      effect2.setFloat("weight", this.weight);
      effect2.setFloat("density", this.density);
      effect2.setVector2("meshPositionOnScreen", this._screenCoordinates);
    });
  }
  getClassName() {
    return "VolumetricLightScatteringPostProcess";
  }
  _isReady(subMesh2, useInstances) {
    const mesh2 = subMesh2.getMesh();
    if (mesh2 === this.mesh && mesh2.material) {
      return mesh2.material.isReady(mesh2);
    }
    const renderingMaterial = mesh2._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];
    if (renderingMaterial) {
      return renderingMaterial.isReadyForSubMesh(mesh2, subMesh2, useInstances);
    }
    const defines = [];
    const attribs = [VertexBuffer.PositionKind];
    const material2 = subMesh2.getMaterial();
    let uv1 = false;
    let uv2 = false;
    const color = false;
    if (material2) {
      const needAlphaTesting = material2.needAlphaTestingForMesh(mesh2);
      if (needAlphaTesting) {
        defines.push("#define ALPHATEST");
      }
      if (mesh2.isVerticesDataPresent(VertexBuffer.UVKind)) {
        attribs.push(VertexBuffer.UVKind);
        defines.push("#define UV1");
        uv1 = needAlphaTesting;
      }
      if (mesh2.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
        attribs.push(VertexBuffer.UV2Kind);
        defines.push("#define UV2");
        uv2 = needAlphaTesting;
      }
    }
    const fallbacks = new EffectFallbacks;
    if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh2.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
      if (mesh2.numBoneInfluencers > 0) {
        fallbacks.addCPUSkinningFallback(0, mesh2);
      }
      const skeleton2 = mesh2.skeleton;
      if (skeleton2.isUsingTextureForMatrices) {
        defines.push("#define BONETEXTURE");
      } else {
        defines.push("#define BonesPerMesh " + (skeleton2.bones.length + 1));
      }
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
    }
    const numMorphInfluencers = mesh2.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh2.morphTargetManager, defines, attribs, mesh2, true, false, false, uv1, uv2, color) : 0;
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs);
      if (subMesh2.getRenderingMesh().hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
      }
    }
    const bvaManager = mesh2.bakedVertexAnimationManager;
    if (bvaManager && bvaManager.isEnabled) {
      defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
      if (useInstances) {
        attribs.push("bakedVertexAnimationSettingsInstanced");
      }
    }
    const drawWrapper2 = subMesh2._getDrawWrapper(undefined, true);
    const cachedDefines = drawWrapper2.defines;
    const join6 = defines.join(`
`);
    if (cachedDefines !== join6) {
      const uniforms2 = [
        "world",
        "mBones",
        "boneTextureWidth",
        "viewProjection",
        "diffuseMatrix",
        "morphTargetInfluences",
        "morphTargetCount",
        "morphTargetTextureInfo",
        "morphTargetTextureIndices",
        "bakedVertexAnimationSettings",
        "bakedVertexAnimationTextureSizeInverted",
        "bakedVertexAnimationTime",
        "bakedVertexAnimationTexture"
      ];
      const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"];
      drawWrapper2.setEffect(mesh2.getScene().getEngine().createEffect("volumetricLightScatteringPass", {
        attributes: attribs,
        uniformsNames: uniforms2,
        uniformBuffersNames: [],
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: null,
        onError: null,
        indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }
      }, mesh2.getScene().getEngine()), join6);
    }
    return drawWrapper2.effect.isReady();
  }
  setCustomMeshPosition(position) {
    this.customMeshPosition = position;
  }
  getCustomMeshPosition() {
    return this.customMeshPosition;
  }
  dispose(camera2) {
    const rttIndex = camera2.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
    if (rttIndex !== -1) {
      camera2.getScene().customRenderTargets.splice(rttIndex, 1);
    }
    this._volumetricLightScatteringRTT.dispose();
    super.dispose(camera2);
  }
  getPass() {
    return this._volumetricLightScatteringRTT;
  }
  _meshExcluded(mesh2) {
    if (this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh2) === -1 || this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh2) !== -1) {
      return true;
    }
    return false;
  }
  _createPass(scene, ratio) {
    const engine2 = scene.getEngine();
    this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine2.getRenderWidth() * ratio, height: engine2.getRenderHeight() * ratio }, scene, false, true, 0);
    this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._volumetricLightScatteringRTT.renderList = null;
    this._volumetricLightScatteringRTT.renderParticles = false;
    this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
    const camera2 = this.getCamera();
    if (camera2) {
      camera2.customRenderTargets.push(this._volumetricLightScatteringRTT);
    } else {
      scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
    }
    const renderSubMesh = (subMesh2) => {
      const renderingMesh = subMesh2.getRenderingMesh();
      const effectiveMesh = subMesh2.getEffectiveMesh();
      if (this._meshExcluded(renderingMesh)) {
        return;
      }
      effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
      const material2 = subMesh2.getMaterial();
      if (!material2) {
        return;
      }
      const scene2 = renderingMesh.getScene();
      const engine3 = scene2.getEngine();
      engine3.setState(material2.backFaceCulling, undefined, undefined, undefined, material2.cullBackFaces);
      const batch = renderingMesh._getInstancesRenderList(subMesh2._id, !!subMesh2.getReplacementMesh());
      if (batch.mustReturn) {
        return;
      }
      const hardwareInstancedRendering = engine3.getCaps().instancedArrays && (batch.visibleInstances[subMesh2._id] !== null || renderingMesh.hasThinInstances);
      if (this._isReady(subMesh2, hardwareInstancedRendering)) {
        const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine3.currentRenderPassId];
        let drawWrapper2 = subMesh2._getDrawWrapper();
        if (renderingMesh === this.mesh && !drawWrapper2) {
          drawWrapper2 = material2._getDrawWrapper();
        }
        if (!drawWrapper2) {
          return;
        }
        const effect2 = drawWrapper2.effect;
        engine3.enableEffect(drawWrapper2);
        if (!hardwareInstancedRendering) {
          renderingMesh._bind(subMesh2, effect2, material2.fillMode);
        }
        if (renderingMesh === this.mesh) {
          material2.bind(effectiveMesh.getWorldMatrix(), renderingMesh);
        } else if (renderingMaterial) {
          renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh2);
        } else {
          effect2.setMatrix("viewProjection", scene2.getTransformMatrix());
          if (material2.needAlphaTestingForMesh(effectiveMesh)) {
            const alphaTexture = material2.getAlphaTestTexture();
            if (alphaTexture) {
              effect2.setTexture("diffuseSampler", alphaTexture);
              effect2.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
            }
          }
          BindBonesParameters(renderingMesh, effect2);
          BindMorphTargetParameters(renderingMesh, effect2);
          if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
            renderingMesh.morphTargetManager._bind(effect2);
          }
          const bvaManager = subMesh2.getMesh().bakedVertexAnimationManager;
          if (bvaManager && bvaManager.isEnabled) {
            bvaManager.bind(effect2, hardwareInstancedRendering);
          }
        }
        if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {
          effect2.setMatrix("world", effectiveMesh.getWorldMatrix());
        }
        renderingMesh._processRendering(effectiveMesh, subMesh2, effect2, Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => {
          if (!isInstance) {
            effect2.setMatrix("world", world);
          }
        });
      }
    };
    let savedSceneClearColor;
    const sceneClearColor = new Color4(0, 0, 0, 1);
    this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => {
      savedSceneClearColor = scene.clearColor;
      scene.clearColor = sceneClearColor;
    });
    this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => {
      scene.clearColor = savedSceneClearColor;
    });
    this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh2, refreshRate, preWarm) => {
      if ((preWarm || refreshRate === 0) && mesh2.subMeshes) {
        for (let i = 0;i < mesh2.subMeshes.length; ++i) {
          const subMesh2 = mesh2.subMeshes[i];
          const material2 = subMesh2.getMaterial();
          const renderingMesh = subMesh2.getRenderingMesh();
          if (!material2) {
            continue;
          }
          const batch = renderingMesh._getInstancesRenderList(subMesh2._id, !!subMesh2.getReplacementMesh());
          const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh2._id] !== null || renderingMesh.hasThinInstances);
          if (!this._isReady(subMesh2, hardwareInstancedRendering)) {
            return false;
          }
        }
      }
      return true;
    };
    this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {
      const engine3 = scene.getEngine();
      let index;
      if (depthOnlySubMeshes.length) {
        engine3.setColorWrite(false);
        for (index = 0;index < depthOnlySubMeshes.length; index++) {
          renderSubMesh(depthOnlySubMeshes.data[index]);
        }
        engine3.setColorWrite(true);
      }
      for (index = 0;index < opaqueSubMeshes.length; index++) {
        renderSubMesh(opaqueSubMeshes.data[index]);
      }
      for (index = 0;index < alphaTestSubMeshes.length; index++) {
        renderSubMesh(alphaTestSubMeshes.data[index]);
      }
      if (transparentSubMeshes.length) {
        for (index = 0;index < transparentSubMeshes.length; index++) {
          const submesh = transparentSubMeshes.data[index];
          const boundingInfo2 = submesh.getBoundingInfo();
          if (boundingInfo2 && scene.activeCamera) {
            submesh._alphaIndex = submesh.getMesh().alphaIndex;
            submesh._distanceToCamera = boundingInfo2.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
          }
        }
        const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
        sortedArray.sort((a, b) => {
          if (a._alphaIndex > b._alphaIndex) {
            return 1;
          }
          if (a._alphaIndex < b._alphaIndex) {
            return -1;
          }
          if (a._distanceToCamera < b._distanceToCamera) {
            return 1;
          }
          if (a._distanceToCamera > b._distanceToCamera) {
            return -1;
          }
          return 0;
        });
        engine3.setAlphaMode(2);
        for (index = 0;index < sortedArray.length; index++) {
          renderSubMesh(sortedArray[index]);
        }
        engine3.setAlphaMode(0);
      }
    };
  }
  _updateMeshScreenCoordinates(scene) {
    const transform = scene.getTransformMatrix();
    let meshPosition;
    if (this.useCustomMeshPosition) {
      meshPosition = this.customMeshPosition;
    } else if (this.attachedNode) {
      meshPosition = this.attachedNode.position;
    } else {
      meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
    }
    const pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);
    this._screenCoordinates.x = pos.x / this._viewPort.width;
    this._screenCoordinates.y = pos.y / this._viewPort.height;
    if (this.invert) {
      this._screenCoordinates.y = 1 - this._screenCoordinates.y;
    }
  }
  static CreateDefaultMesh(name439, scene) {
    const mesh2 = CreatePlane(name439, { size: 1 }, scene);
    mesh2.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
    const material2 = new StandardMaterial(name439 + "Material", scene);
    material2.emissiveColor = new Color3(1, 1, 1);
    mesh2.material = material2;
    return mesh2;
  }
}
__decorate([
  serializeAsVector3()
], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "invert", undefined);
__decorate([
  serializeAsMeshReference()
], VolumetricLightScatteringPostProcess.prototype, "mesh", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "includedMeshes", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "exposure", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "decay", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "weight", undefined);
__decorate([
  serialize()
], VolumetricLightScatteringPostProcess.prototype, "density", undefined);
RegisterClass("BABYLON.VolumetricLightScatteringPostProcess", VolumetricLightScatteringPostProcess);
// node_modules/@babylonjs/core/PostProcesses/screenSpaceCurvaturePostProcess.js
init_tslib_es6();
init_logger();
init_postProcess();

// node_modules/@babylonjs/core/Shaders/screenSpaceCurvature.fragment.js
init_shaderStore();
var name439 = "screenSpaceCurvaturePixelShader";
var shader438 = `precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley;
#ifndef CURVATURE_OFFSET
#define CURVATURE_OFFSET 1
#endif
float curvature_soft_clamp(float curvature,float control)
{if (curvature<0.5/control)
return curvature*(1.0-curvature*control);return 0.25/control;}
float calculate_curvature(ivec2 texel,float ridge,float valley)
{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0)
return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;
if (!ShaderStore.ShadersStore[name439]) {
  ShaderStore.ShadersStore[name439] = shader438;
}

// node_modules/@babylonjs/core/PostProcesses/screenSpaceCurvaturePostProcess.js
init_engineStore();
init_typeStore();
init_decorators();
init_decorators_serialization();

class ScreenSpaceCurvaturePostProcess extends PostProcess {
  getClassName() {
    return "ScreenSpaceCurvaturePostProcess";
  }
  constructor(name440, scene, options, camera2, samplingMode, engine2, reusable, textureType = 0, blockCompilation = false) {
    super(name440, "screenSpaceCurvature", ["curvature_ridge", "curvature_valley"], ["textureSampler", "normalSampler"], options, camera2, samplingMode, engine2, reusable, undefined, textureType, undefined, null, blockCompilation);
    this.ridge = 1;
    this.valley = 1;
    this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
    if (!this._geometryBufferRenderer) {
      Logger.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.");
    } else {
      if (this._geometryBufferRenderer.generateNormalsInWorldSpace) {
        Logger.Error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!");
      }
      this.onApply = (effect2) => {
        effect2.setFloat("curvature_ridge", 0.5 / Math.max(this.ridge * this.ridge, 0.0001));
        effect2.setFloat("curvature_valley", 0.7 / Math.max(this.valley * this.valley, 0.0001));
        const normalTexture = this._geometryBufferRenderer.getGBuffer().textures[1];
        effect2.setTexture("normalSampler", normalTexture);
      };
    }
  }
  static get IsSupported() {
    const engine2 = EngineStore.LastCreatedEngine;
    if (!engine2) {
      return false;
    }
    return engine2.getCaps().drawBuffersExtension;
  }
  static _Parse(parsedPostProcess, targetCamera2, scene, rootUrl) {
    return SerializationHelper.Parse(() => {
      return new ScreenSpaceCurvaturePostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera2, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);
    }, parsedPostProcess, scene, rootUrl);
  }
}
__decorate([
  serialize()
], ScreenSpaceCurvaturePostProcess.prototype, "ridge", undefined);
__decorate([
  serialize()
], ScreenSpaceCurvaturePostProcess.prototype, "valley", undefined);
RegisterClass("BABYLON.ScreenSpaceCurvaturePostProcess", ScreenSpaceCurvaturePostProcess);

// node_modules/@babylonjs/core/PostProcesses/index.js
init_thinPassPostProcess();
init_postprocess_vertex();
init_postprocess_vertex2();
init_kernelBlur_fragment2();
init_kernelBlur_vertex2();
init_kernelBlur_fragment();
init_kernelBlur_vertex();
init_pass_fragment();
init_passCube_fragment2();
init_pass_fragment2();
init_passCube_fragment();
init_vrDistortionCorrection_fragment2();
init_vrDistortionCorrection_fragment();
init_imageProcessing_fragment();
init_imageProcessing_fragment2();
init_sharpen_fragment();
init_sharpen_fragment2();
init_grain_fragment2();
init_grain_fragment();
init_chromaticAberration_fragment2();
init_chromaticAberration_fragment();
init_depthOfFieldMerge_fragment2();
init_depthOfFieldMerge_fragment();
init_circleOfConfusion_fragment2();
init_circleOfConfusion_fragment();
init_bloomMerge_fragment2();
init_bloomMerge_fragment();
init_extractHighlights_fragment2();
init_extractHighlights_fragment();
init_fxaa_fragment2();
init_fxaa_vertex2();
init_fxaa_fragment();
init_fxaa_vertex();
init_blackAndWhite_fragment2();
init_blackAndWhite_fragment();
init_anaglyph_fragment2();
init_anaglyph_fragment();
init_convolution_fragment2();
init_convolution_fragment();
init_colorCorrection_fragment2();
init_colorCorrection_fragment();
init_motionBlur_fragment2();
init_motionBlur_fragment();
init_filter_fragment2();
init_filter_fragment();
init_highlights_fragment();
init_highlights_fragment2();
init_displayPass_fragment2();
init_displayPass_fragment();
init_tonemap_fragment();
init_tonemap_fragment2();
// node_modules/@babylonjs/core/Rendering/boundingBoxRenderer.js
init_scene();
init_buffer();
init_math_vector();
init_smartArray();
init_sceneComponent();
init_math_color();
init_observable();
init_drawWrapper();
init_uniformBuffer();
Object.defineProperty(Scene.prototype, "forceShowBoundingBoxes", {
  get: function() {
    return this._forceShowBoundingBoxes || false;
  },
  set: function(value) {
    this._forceShowBoundingBoxes = value;
    if (value) {
      this.getBoundingBoxRenderer();
    }
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.getBoundingBoxRenderer = function() {
  if (!this._boundingBoxRenderer) {
    this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  }
  return this._boundingBoxRenderer;
};
Object.defineProperty(AbstractMesh.prototype, "showBoundingBox", {
  get: function() {
    return this._showBoundingBox || false;
  },
  set: function(value) {
    this._showBoundingBox = value;
    if (value) {
      this.getScene().getBoundingBoxRenderer();
    }
  },
  enumerable: true,
  configurable: true
});
var tempMatrix = Matrix.Identity();
var tempVec1 = new Vector3;
var tempVec2 = new Vector3;
var tempMatrixArray = tempMatrix.asArray();
var dummyBoundingBox = new BoundingBox(tempVec1, tempVec1);

class BoundingBoxRenderer {
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
    this.frontColor = new Color3(1, 1, 1);
    this.backColor = new Color3(0.1, 0.1, 0.1);
    this.showBackLines = true;
    this.onBeforeBoxRenderingObservable = new Observable;
    this.onAfterBoxRenderingObservable = new Observable;
    this.onResourcesReadyObservable = new Observable;
    this.enabled = true;
    this._shaderLanguage = 0;
    this.renderList = new SmartArray(32);
    this._vertexBuffers = {};
    this._fillIndexBuffer = null;
    this._fillIndexData = null;
    this._matrixBuffer = null;
    this._matrices = null;
    this._useInstances = false;
    this._drawWrapperFront = null;
    this._drawWrapperBack = null;
    this.scene = scene;
    const engine2 = this.scene.getEngine();
    if (engine2.isWebGPU) {
      this._shaderLanguage = 1;
    }
    scene._addComponent(this);
    this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererFront", true);
    this._buildUniformLayout(this._uniformBufferFront);
    this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererBack", true);
    this._buildUniformLayout(this._uniformBufferBack);
  }
  _buildUniformLayout(ubo) {
    ubo.addUniform("color", 4);
    ubo.addUniform("world", 16);
    ubo.addUniform("viewProjection", 16);
    ubo.addUniform("viewProjectionR", 16);
    ubo.create();
  }
  register() {
    this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
    this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh);
    this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
    this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  }
  _evaluateSubMesh(mesh2, subMesh2) {
    if (mesh2.showSubMeshesBoundingBox) {
      const boundingInfo2 = subMesh2.getBoundingInfo();
      if (boundingInfo2 !== null && boundingInfo2 !== undefined) {
        boundingInfo2.boundingBox._tag = mesh2.renderingGroupId;
        this.renderList.push(boundingInfo2.boundingBox);
      }
    }
  }
  _preActiveMesh(mesh2) {
    if (mesh2.showBoundingBox || this.scene.forceShowBoundingBoxes) {
      const boundingInfo2 = mesh2.getBoundingInfo();
      boundingInfo2.boundingBox._tag = mesh2.renderingGroupId;
      this.renderList.push(boundingInfo2.boundingBox);
    }
  }
  _prepareResources() {
    if (this._colorShader) {
      return;
    }
    this._colorShader = new ShaderMaterial("colorShader", this.scene, "boundingBoxRenderer", {
      attributes: [VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
      uniforms: ["world", "viewProjection", "viewProjectionR", "color"],
      uniformBuffers: ["BoundingBoxRenderer"],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_boundingBoxRenderer_vertex(), exports_boundingBoxRenderer_vertex)), Promise.resolve().then(() => (init_boundingBoxRenderer_fragment(), exports_boundingBoxRenderer_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_boundingBoxRenderer_vertex2(), exports_boundingBoxRenderer_vertex2)), Promise.resolve().then(() => (init_boundingBoxRenderer_fragment2(), exports_boundingBoxRenderer_fragment2))]);
        }
      }
    }, false);
    this._colorShader.setDefine("INSTANCES", this._useInstances);
    this._colorShader.doNotSerialize = true;
    this._colorShader.reservedDataStore = {
      hidden: true
    };
    this._colorShaderForOcclusionQuery = new ShaderMaterial("colorShaderOccQuery", this.scene, "boundingBoxRenderer", {
      attributes: [VertexBuffer.PositionKind],
      uniforms: ["world", "viewProjection", "viewProjectionR", "color"],
      uniformBuffers: ["BoundingBoxRenderer"],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_boundingBoxRenderer_vertex(), exports_boundingBoxRenderer_vertex)), Promise.resolve().then(() => (init_boundingBoxRenderer_fragment(), exports_boundingBoxRenderer_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_boundingBoxRenderer_vertex2(), exports_boundingBoxRenderer_vertex2)), Promise.resolve().then(() => (init_boundingBoxRenderer_fragment2(), exports_boundingBoxRenderer_fragment2))]);
        }
      }
    }, true);
    this._colorShaderForOcclusionQuery.doNotSerialize = true;
    this._colorShaderForOcclusionQuery.reservedDataStore = {
      hidden: true
    };
    const engine2 = this.scene.getEngine();
    const boxdata = CreateBoxVertexData({ size: 1 });
    this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine2, boxdata.positions, VertexBuffer.PositionKind, false);
    this._createIndexBuffer();
    this._fillIndexData = boxdata.indices;
    this.onResourcesReadyObservable.notifyObservers(this);
  }
  _createIndexBuffer() {
    const engine2 = this.scene.getEngine();
    this._indexBuffer = engine2.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  }
  rebuild() {
    const vb = this._vertexBuffers[VertexBuffer.PositionKind];
    if (vb) {
      vb._rebuild();
    }
    this._createIndexBuffer();
    if (this._matrixBuffer) {
      this._matrixBuffer._rebuild();
    }
  }
  reset() {
    this.renderList.reset();
  }
  render(renderingGroupId) {
    if (this.renderList.length === 0 || !this.enabled) {
      return;
    }
    if (this._useInstances) {
      this._renderInstanced(renderingGroupId);
      return;
    }
    this._prepareResources();
    if (!this._colorShader.isReady()) {
      return;
    }
    const engine2 = this.scene.getEngine();
    engine2.setDepthWrite(false);
    const transformMatrix = this.scene.getTransformMatrix();
    for (let boundingBoxIndex = 0;boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
      const boundingBox2 = this.renderList.data[boundingBoxIndex];
      if (boundingBox2._tag !== renderingGroupId) {
        continue;
      }
      this._createWrappersForBoundingBox(boundingBox2);
      this.onBeforeBoxRenderingObservable.notifyObservers(boundingBox2);
      const min = boundingBox2.minimum;
      const max = boundingBox2.maximum;
      const diff = max.subtract(min);
      const median = min.add(diff.scale(0.5));
      const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox2.getWorldMatrix());
      const useReverseDepthBuffer = engine2.useReverseDepthBuffer;
      if (this.showBackLines) {
        const drawWrapperBack = boundingBox2._drawWrapperBack ?? this._colorShader._getDrawWrapper();
        this._colorShader._preBind(drawWrapperBack);
        engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
        if (useReverseDepthBuffer) {
          engine2.setDepthFunctionToLessOrEqual();
        } else {
          engine2.setDepthFunctionToGreaterOrEqual();
        }
        this._uniformBufferBack.bindToEffect(drawWrapperBack.effect, "BoundingBoxRenderer");
        this._uniformBufferBack.updateColor4("color", this.backColor, 1);
        this._uniformBufferBack.updateMatrix("world", worldMatrix);
        this._uniformBufferBack.updateMatrix("viewProjection", transformMatrix);
        this._uniformBufferBack.update();
        engine2.drawElementsType(Material.LineListDrawMode, 0, 24);
      }
      const drawWrapperFront = boundingBox2._drawWrapperFront ?? this._colorShader._getDrawWrapper();
      this._colorShader._preBind(drawWrapperFront);
      engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
      if (useReverseDepthBuffer) {
        engine2.setDepthFunctionToGreater();
      } else {
        engine2.setDepthFunctionToLess();
      }
      this._uniformBufferFront.bindToEffect(drawWrapperFront.effect, "BoundingBoxRenderer");
      this._uniformBufferFront.updateColor4("color", this.frontColor, 1);
      this._uniformBufferFront.updateMatrix("world", worldMatrix);
      this._uniformBufferFront.updateMatrix("viewProjection", transformMatrix);
      this._uniformBufferFront.update();
      engine2.drawElementsType(Material.LineListDrawMode, 0, 24);
      this.onAfterBoxRenderingObservable.notifyObservers(boundingBox2);
    }
    this._colorShader.unbind();
    engine2.setDepthFunctionToLessOrEqual();
    engine2.setDepthWrite(true);
  }
  _createWrappersForBoundingBox(boundingBox2) {
    if (!boundingBox2._drawWrapperFront) {
      const engine2 = this.scene.getEngine();
      boundingBox2._drawWrapperFront = new DrawWrapper(engine2);
      boundingBox2._drawWrapperBack = new DrawWrapper(engine2);
      boundingBox2._drawWrapperFront.setEffect(this._colorShader.getEffect());
      boundingBox2._drawWrapperBack.setEffect(this._colorShader.getEffect());
    }
  }
  renderOcclusionBoundingBox(mesh2) {
    const engine2 = this.scene.getEngine();
    if (this._renderPassIdForOcclusionQuery === undefined) {
      this._renderPassIdForOcclusionQuery = engine2.createRenderPassId(`Render pass for occlusion query`);
    }
    const currentRenderPassId = engine2.currentRenderPassId;
    engine2.currentRenderPassId = this._renderPassIdForOcclusionQuery;
    this._prepareResources();
    const subMesh2 = mesh2.subMeshes[0];
    if (!this._colorShaderForOcclusionQuery.isReady(mesh2, undefined, subMesh2) || !mesh2.hasBoundingInfo) {
      engine2.currentRenderPassId = currentRenderPassId;
      return;
    }
    if (!this._fillIndexBuffer) {
      this._fillIndexBuffer = engine2.createIndexBuffer(this._fillIndexData);
    }
    const useReverseDepthBuffer = engine2.useReverseDepthBuffer;
    engine2.setDepthWrite(false);
    engine2.setColorWrite(false);
    const boundingBox2 = mesh2.getBoundingInfo().boundingBox;
    const min = boundingBox2.minimum;
    const max = boundingBox2.maximum;
    const diff = max.subtract(min);
    const median = min.add(diff.scale(0.5));
    const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox2.getWorldMatrix());
    const drawWrapper2 = subMesh2._drawWrapper;
    this._colorShaderForOcclusionQuery._preBind(drawWrapper2);
    engine2.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, drawWrapper2.effect);
    if (useReverseDepthBuffer) {
      engine2.setDepthFunctionToGreater();
    } else {
      engine2.setDepthFunctionToLess();
    }
    this.scene.resetCachedMaterial();
    this._uniformBufferFront.bindToEffect(drawWrapper2.effect, "BoundingBoxRenderer");
    this._uniformBufferFront.updateMatrix("world", worldMatrix);
    this._uniformBufferFront.updateMatrix("viewProjection", this.scene.getTransformMatrix());
    this._uniformBufferFront.update();
    engine2.drawElementsType(Material.TriangleFillMode, 0, 36);
    this._colorShaderForOcclusionQuery.unbind();
    engine2.setDepthFunctionToLessOrEqual();
    engine2.setDepthWrite(true);
    engine2.setColorWrite(true);
    engine2.currentRenderPassId = currentRenderPassId;
  }
  set useInstances(val) {
    this._useInstances = val;
    if (this._colorShader) {
      this._colorShader.setDefine("INSTANCES", val);
    }
    if (!val) {
      this._cleanupInstances();
    }
  }
  get useInstances() {
    return this._useInstances;
  }
  _renderInstanced(renderingGroupId) {
    if (this.renderList.length === 0 || !this.enabled) {
      return;
    }
    this._prepareResources();
    if (!this._colorShader.isReady()) {
      return;
    }
    const colorShader = this._colorShader;
    let matrices = this._matrices;
    const expectedLength = this.renderList.length * 16;
    if (!matrices || matrices.length < expectedLength || matrices.length > expectedLength * 2) {
      matrices = new Float32Array(expectedLength);
      this._matrices = matrices;
    }
    this.onBeforeBoxRenderingObservable.notifyObservers(dummyBoundingBox);
    let instancesCount = 0;
    for (let boundingBoxIndex = 0;boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
      const boundingBox2 = this.renderList.data[boundingBoxIndex];
      if (boundingBox2._tag !== renderingGroupId) {
        continue;
      }
      const min = boundingBox2.minimum;
      const max = boundingBox2.maximum;
      const diff = max.subtractToRef(min, tempVec2);
      const median = min.addToRef(diff.scaleToRef(0.5, tempVec1), tempVec1);
      const m = tempMatrixArray;
      m[0] = diff._x;
      m[3] = median._x;
      m[5] = diff._y;
      m[7] = median._y;
      m[10] = diff._z;
      m[11] = median._z;
      tempMatrix.multiplyToArray(boundingBox2.getWorldMatrix(), matrices, instancesCount * 16);
      instancesCount++;
    }
    const engine2 = this.scene.getEngine();
    const depthFunction = engine2.getDepthFunction() ?? 515;
    const depthWrite = engine2.getDepthWrite();
    engine2.setDepthWrite(false);
    const matrixBuffer = this._matrixBuffer;
    if (matrixBuffer?.isUpdatable() && matrixBuffer.getData() === matrices) {
      matrixBuffer.update(matrices);
    } else {
      this._createInstanceBuffer(matrices);
    }
    this._createWrappersForBoundingBox(this);
    const useReverseDepthBuffer = engine2.useReverseDepthBuffer;
    const transformMatrix = this.scene.getTransformMatrix();
    if (this.showBackLines) {
      const drawWrapperBack = this._drawWrapperBack ?? colorShader._getDrawWrapper();
      colorShader._preBind(drawWrapperBack);
      engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, colorShader.getEffect());
      if (useReverseDepthBuffer) {
        engine2.setDepthFunctionToLessOrEqual();
      } else {
        engine2.setDepthFunctionToGreaterOrEqual();
      }
      const _uniformBufferBack = this._uniformBufferBack;
      _uniformBufferBack.bindToEffect(drawWrapperBack.effect, "BoundingBoxRenderer");
      _uniformBufferBack.updateColor4("color", this.backColor, 1);
      _uniformBufferBack.updateMatrix("viewProjection", transformMatrix);
      _uniformBufferBack.update();
      engine2.drawElementsType(Material.LineListDrawMode, 0, 24, instancesCount);
    }
    const drawWrapperFront = colorShader._getDrawWrapper();
    colorShader._preBind(drawWrapperFront);
    engine2.bindBuffers(this._vertexBuffers, this._indexBuffer, colorShader.getEffect());
    if (useReverseDepthBuffer) {
      engine2.setDepthFunctionToGreater();
    } else {
      engine2.setDepthFunctionToLess();
    }
    const _uniformBufferFront = this._uniformBufferFront;
    _uniformBufferFront.bindToEffect(drawWrapperFront.effect, "BoundingBoxRenderer");
    _uniformBufferFront.updateColor4("color", this.frontColor, 1);
    _uniformBufferFront.updateMatrix("viewProjection", transformMatrix);
    _uniformBufferFront.update();
    engine2.drawElementsType(Material.LineListDrawMode, 0, 24, instancesCount);
    this.onAfterBoxRenderingObservable.notifyObservers(dummyBoundingBox);
    colorShader.unbind();
    engine2.setDepthFunction(depthFunction);
    engine2.setDepthWrite(depthWrite);
  }
  _createInstanceBuffer(buffer2) {
    const vertexBuffers = this._vertexBuffers;
    this._cleanupInstanceBuffer();
    const matrixBuffer = new Buffer2(this.scene.getEngine(), buffer2, true, 16, false, true);
    vertexBuffers.world0 = matrixBuffer.createVertexBuffer("world0", 0, 4);
    vertexBuffers.world1 = matrixBuffer.createVertexBuffer("world1", 4, 4);
    vertexBuffers.world2 = matrixBuffer.createVertexBuffer("world2", 8, 4);
    vertexBuffers.world3 = matrixBuffer.createVertexBuffer("world3", 12, 4);
    this._matrixBuffer = matrixBuffer;
  }
  _cleanupInstanceBuffer() {
    const vertexBuffers = this._vertexBuffers;
    if (vertexBuffers.world0) {
      vertexBuffers.world0.dispose();
      delete vertexBuffers.world0;
    }
    if (vertexBuffers.world1) {
      vertexBuffers.world1.dispose();
      delete vertexBuffers.world1;
    }
    if (vertexBuffers.world2) {
      vertexBuffers.world2.dispose();
      delete vertexBuffers.world2;
    }
    if (vertexBuffers.world3) {
      vertexBuffers.world3.dispose();
      delete vertexBuffers.world3;
    }
    this._matrices = null;
    if (this._matrixBuffer) {
      this._matrixBuffer.dispose();
      this._matrixBuffer = null;
    }
  }
  _cleanupInstances() {
    this._cleanupInstanceBuffer();
    if (this._drawWrapperFront) {
      this._drawWrapperFront.dispose();
      this._drawWrapperFront = null;
    }
    if (this._drawWrapperBack) {
      this._drawWrapperBack.dispose();
      this._drawWrapperBack = null;
    }
  }
  dispose() {
    if (this._renderPassIdForOcclusionQuery !== undefined) {
      this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery);
      this._renderPassIdForOcclusionQuery = undefined;
    }
    if (!this._colorShader) {
      return;
    }
    this.onBeforeBoxRenderingObservable.clear();
    this.onAfterBoxRenderingObservable.clear();
    this.onResourcesReadyObservable.clear();
    this.renderList.dispose();
    this._colorShader.dispose();
    this._colorShaderForOcclusionQuery.dispose();
    this._uniformBufferFront.dispose();
    this._uniformBufferBack.dispose();
    const buffer2 = this._vertexBuffers[VertexBuffer.PositionKind];
    if (buffer2) {
      buffer2.dispose();
      this._vertexBuffers[VertexBuffer.PositionKind] = null;
    }
    this.scene.getEngine()._releaseBuffer(this._indexBuffer);
    if (this._fillIndexBuffer) {
      this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer);
      this._fillIndexBuffer = null;
    }
    this._cleanupInstances();
  }
}
// node_modules/@babylonjs/core/Rendering/depthRendererSceneComponent.js
init_scene();
init_sceneComponent();
Scene.prototype.enableDepthRenderer = function(camera2, storeNonLinearDepth = false, force32bitsFloat = false, samplingMode = 3, storeCameraSpaceZ = false) {
  camera2 = camera2 || this.activeCamera;
  if (!camera2) {
    throw "No camera available to enable depth renderer";
  }
  if (!this._depthRenderer) {
    this._depthRenderer = {};
  }
  if (!this._depthRenderer[camera2.id]) {
    const supportFullfloat = !!this.getEngine().getCaps().textureFloatRender;
    let textureType = 0;
    if (this.getEngine().getCaps().textureHalfFloatRender && (!force32bitsFloat || !supportFullfloat)) {
      textureType = 2;
    } else if (supportFullfloat) {
      textureType = 1;
    } else {
      textureType = 0;
    }
    this._depthRenderer[camera2.id] = new DepthRenderer(this, textureType, camera2, storeNonLinearDepth, samplingMode, storeCameraSpaceZ);
  }
  return this._depthRenderer[camera2.id];
};
Scene.prototype.disableDepthRenderer = function(camera2) {
  camera2 = camera2 || this.activeCamera;
  if (!camera2 || !this._depthRenderer || !this._depthRenderer[camera2.id]) {
    return;
  }
  this._depthRenderer[camera2.id].dispose();
};

class DepthRendererSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_DEPTHRENDERER;
    this.scene = scene;
  }
  register() {
    this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
    this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  }
  rebuild() {}
  dispose() {
    for (const key in this.scene._depthRenderer) {
      this.scene._depthRenderer[key].dispose();
    }
  }
  _gatherRenderTargets(renderTargets) {
    if (this.scene._depthRenderer) {
      for (const key in this.scene._depthRenderer) {
        const depthRenderer = this.scene._depthRenderer[key];
        if (depthRenderer.enabled && !depthRenderer.useOnlyInActiveCamera) {
          renderTargets.push(depthRenderer.getDepthMap());
        }
      }
    }
  }
  _gatherActiveCameraRenderTargets(renderTargets) {
    if (this.scene._depthRenderer) {
      for (const key in this.scene._depthRenderer) {
        const depthRenderer = this.scene._depthRenderer[key];
        if (depthRenderer.enabled && depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
          renderTargets.push(depthRenderer.getDepthMap());
        }
      }
    }
  }
}
DepthRenderer._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_DEPTHRENDERER);
  if (!component) {
    component = new DepthRendererSceneComponent(scene);
    scene._addComponent(component);
  }
};
// node_modules/@babylonjs/core/Rendering/depthPeelingRenderer.js
init_math_color();
init_smartArray();
init_thinTexture();
init_effectRenderer();
init_renderTargetTexture();
init_logger();
class DepthPeelingEffectConfiguration {
  constructor() {
    this.enabled = true;
    this.name = "depthPeeling";
    this.texturesRequired = [4];
  }
}

class DepthPeelingRenderer {
  get passCount() {
    return this._passCount;
  }
  set passCount(count) {
    if (this._passCount === count) {
      return;
    }
    this._passCount = count;
    this._createRenderPassIds();
  }
  get useRenderPasses() {
    return this._useRenderPasses;
  }
  set useRenderPasses(usePasses) {
    if (this._useRenderPasses === usePasses) {
      return;
    }
    this._useRenderPasses = usePasses;
    this._createRenderPassIds();
  }
  addExcludedMesh(mesh2) {
    if (this._excludedMeshes.indexOf(mesh2.uniqueId) === -1) {
      this._excludedMeshes.push(mesh2.uniqueId);
    }
  }
  removeExcludedMesh(mesh2) {
    const index = this._excludedMeshes.indexOf(mesh2.uniqueId);
    if (index !== -1) {
      this._excludedMeshes.splice(index, 1);
    }
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene, passCount = 5) {
    this._thinTextures = [];
    this._currentPingPongState = 0;
    this._layoutCacheFormat = [[true], [true, true], [true, true, true]];
    this._layoutCache = [];
    this._candidateSubMeshes = new SmartArray(10);
    this._excludedSubMeshes = new SmartArray(10);
    this._excludedMeshes = [];
    this._colorCache = [
      new Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0),
      new Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0),
      new Color4(0, 0, 0, 0)
    ];
    this._shaderLanguage = 0;
    this._scene = scene;
    this._engine = scene.getEngine();
    this._passCount = passCount;
    if (!scene.enablePrePassRenderer()) {
      Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");
      return;
    }
    for (let i = 0;i < this._layoutCacheFormat.length; ++i) {
      this._layoutCache[i] = this._engine.buildTextureLayout(this._layoutCacheFormat[i]);
    }
    this._renderPassIds = [];
    this.useRenderPasses = false;
    if (this._engine.isWebGPU) {
      this._shaderLanguage = 1;
    }
    this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration;
    this._createTextures();
    this._createEffects();
  }
  _createRenderPassIds() {
    this._releaseRenderPassIds();
    if (this._useRenderPasses) {
      for (let i = 0;i < this._passCount + 1; ++i) {
        if (!this._renderPassIds[i]) {
          this._renderPassIds[i] = this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${i}`);
        }
      }
    }
  }
  _releaseRenderPassIds() {
    for (let i = 0;i < this._renderPassIds.length; ++i) {
      this._engine.releaseRenderPassId(this._renderPassIds[i]);
    }
    this._renderPassIds = [];
  }
  _createTextures() {
    const size = {
      width: this._engine.getRenderWidth(),
      height: this._engine.getRenderHeight()
    };
    this._depthMrts = [
      new MultiRenderTarget("depthPeelingDepth0MRT", size, 3, this._scene, undefined, [
        "depthPeelingDepth0MRT_depth",
        "depthPeelingDepth0MRT_frontColor",
        "depthPeelingDepth0MRT_backColor"
      ]),
      new MultiRenderTarget("depthPeelingDepth1MRT", size, 3, this._scene, undefined, [
        "depthPeelingDepth1MRT_depth",
        "depthPeelingDepth1MRT_frontColor",
        "depthPeelingDepth1MRT_backColor"
      ])
    ];
    this._colorMrts = [
      new MultiRenderTarget("depthPeelingColor0MRT", size, 2, this._scene, { generateDepthBuffer: false }, [
        "depthPeelingColor0MRT_frontColor",
        "depthPeelingColor0MRT_backColor"
      ]),
      new MultiRenderTarget("depthPeelingColor1MRT", size, 2, this._scene, { generateDepthBuffer: false }, [
        "depthPeelingColor1MRT_frontColor",
        "depthPeelingColor1MRT_backColor"
      ])
    ];
    this._blendBackMrt = new MultiRenderTarget("depthPeelingBackMRT", size, 1, this._scene, { generateDepthBuffer: false }, ["depthPeelingBackMRT_blendBack"]);
    this._outputRT = new RenderTargetTexture("depthPeelingOutputRTT", size, this._scene, false);
    const optionsArray = [
      {
        format: 7,
        samplingMode: 1,
        type: this._engine.getCaps().textureFloatLinearFiltering ? 1 : 2,
        label: "DepthPeelingRenderer-DepthTexture"
      },
      {
        format: 5,
        samplingMode: 1,
        type: 2,
        label: "DepthPeelingRenderer-ColorTexture"
      }
    ];
    for (let i = 0;i < 2; i++) {
      const depthTexture = this._engine._createInternalTexture(size, optionsArray[0], false);
      const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);
      const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);
      this._depthMrts[i].setInternalTexture(depthTexture, 0);
      this._depthMrts[i].setInternalTexture(frontColorTexture, 1);
      this._depthMrts[i].setInternalTexture(backColorTexture, 2);
      this._colorMrts[i].setInternalTexture(frontColorTexture, 0);
      this._colorMrts[i].setInternalTexture(backColorTexture, 1);
      this._thinTextures.push(new ThinTexture(depthTexture), new ThinTexture(frontColorTexture), new ThinTexture(backColorTexture));
    }
  }
  _disposeTextures() {
    for (let i = 0;i < this._thinTextures.length; i++) {
      if (i === 6) {
        continue;
      }
      this._thinTextures[i].dispose();
    }
    for (let i = 0;i < 2; i++) {
      this._depthMrts[i].dispose(true);
      this._colorMrts[i].dispose(true);
      this._blendBackMrt.dispose(true);
    }
    this._outputRT.dispose();
    this._thinTextures = [];
    this._colorMrts = [];
    this._depthMrts = [];
  }
  _updateTextures() {
    if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) {
      this._disposeTextures();
      this._createTextures();
    }
    return this._updateTextureReferences();
  }
  _updateTextureReferences() {
    const prePassRenderer = this._scene.prePassRenderer;
    if (!prePassRenderer) {
      return false;
    }
    const textureIndex = prePassRenderer.getIndex(4);
    const prePassTexture = prePassRenderer.defaultRT.textures?.length ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null;
    if (!prePassTexture) {
      return false;
    }
    if (this._blendBackTexture !== prePassTexture) {
      this._blendBackTexture = prePassTexture;
      this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0);
      if (this._thinTextures[6]) {
        this._thinTextures[6].dispose();
      }
      this._thinTextures[6] = new ThinTexture(this._blendBackTexture);
      prePassRenderer.defaultRT.renderTarget.shareDepth(this._depthMrts[0].renderTarget);
    }
    return true;
  }
  _createEffects() {
    this._blendBackEffectWrapper = new EffectWrapper({
      fragmentShader: "oitBackBlend",
      useShaderStore: true,
      engine: this._engine,
      samplerNames: ["uBackColor"],
      uniformNames: [],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_oitBackBlend_fragment(), exports_oitBackBlend_fragment));
        } else {
          await Promise.resolve().then(() => (init_oitBackBlend_fragment2(), exports_oitBackBlend_fragment2));
        }
      }
    });
    this._blendBackEffectWrapperPingPong = new EffectWrapper({
      fragmentShader: "oitBackBlend",
      useShaderStore: true,
      engine: this._engine,
      samplerNames: ["uBackColor"],
      uniformNames: [],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_oitBackBlend_fragment(), exports_oitBackBlend_fragment));
        } else {
          await Promise.resolve().then(() => (init_oitBackBlend_fragment2(), exports_oitBackBlend_fragment2));
        }
      }
    });
    this._finalEffectWrapper = new EffectWrapper({
      fragmentShader: "oitFinal",
      useShaderStore: true,
      engine: this._engine,
      samplerNames: ["uFrontColor", "uBackColor"],
      uniformNames: [],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_oitFinal_fragment(), exports_oitFinal_fragment));
        } else {
          await Promise.resolve().then(() => (init_oitFinal_fragment2(), exports_oitFinal_fragment2));
        }
      }
    });
    this._effectRenderer = new EffectRenderer(this._engine);
  }
  setPrePassRenderer(prePassRenderer) {
    prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);
  }
  bind(effect2) {
    effect2.setTexture("oitDepthSampler", this._thinTextures[this._currentPingPongState * 3]);
    effect2.setTexture("oitFrontColorSampler", this._thinTextures[this._currentPingPongState * 3 + 1]);
  }
  _renderSubMeshes(transparentSubMeshes) {
    let mapMaterialContext;
    if (this._useRenderPasses) {
      mapMaterialContext = {};
    }
    for (let j = 0;j < transparentSubMeshes.length; j++) {
      const material2 = transparentSubMeshes.data[j].getMaterial();
      let previousShaderHotSwapping = true;
      let previousBFC = false;
      const subMesh2 = transparentSubMeshes.data[j];
      let drawWrapper2;
      let firstDraw = false;
      if (this._useRenderPasses) {
        drawWrapper2 = subMesh2._getDrawWrapper();
        firstDraw = !drawWrapper2;
      }
      if (material2) {
        previousShaderHotSwapping = material2.allowShaderHotSwapping;
        previousBFC = material2.backFaceCulling;
        material2.allowShaderHotSwapping = false;
        material2.backFaceCulling = false;
      }
      subMesh2.render(false);
      if (firstDraw) {
        drawWrapper2 = subMesh2._getDrawWrapper();
        if (drawWrapper2.materialContext) {
          let newMaterialContext = mapMaterialContext[drawWrapper2.materialContext.uniqueId];
          if (!newMaterialContext) {
            newMaterialContext = mapMaterialContext[drawWrapper2.materialContext.uniqueId] = this._engine.createMaterialContext();
          }
          subMesh2._getDrawWrapper().materialContext = newMaterialContext;
        }
      }
      if (material2) {
        material2.allowShaderHotSwapping = previousShaderHotSwapping;
        material2.backFaceCulling = previousBFC;
      }
    }
  }
  _finalCompose(writeId) {
    const output = this._scene.prePassRenderer?.setCustomOutput(this._outputRT);
    if (output) {
      this._engine.bindFramebuffer(this._outputRT.renderTarget);
    } else {
      this._engine.restoreDefaultFramebuffer();
    }
    this._engine.setAlphaMode(0);
    this._engine.applyStates();
    this._engine.enableEffect(this._finalEffectWrapper.drawWrapper);
    this._finalEffectWrapper.effect.setTexture("uFrontColor", this._thinTextures[writeId * 3 + 1]);
    this._finalEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[6]);
    this._effectRenderer.render(this._finalEffectWrapper);
  }
  isReady() {
    return this._blendBackEffectWrapper.effect.isReady() && this._blendBackEffectWrapperPingPong.effect.isReady() && this._finalEffectWrapper.effect.isReady() && this._updateTextures();
  }
  render(transparentSubMeshes) {
    this._candidateSubMeshes.length = 0;
    this._excludedSubMeshes.length = 0;
    if (!this.isReady()) {
      return this._excludedSubMeshes;
    }
    if (this._scene.activeCamera) {
      this._engine.setViewport(this._scene.activeCamera.viewport);
    }
    for (let i = 0;i < transparentSubMeshes.length; i++) {
      const subMesh2 = transparentSubMeshes.data[i];
      const material2 = subMesh2.getMaterial();
      const fillMode = material2 && subMesh2.getRenderingMesh()._getRenderingFillMode(material2.fillMode);
      if (material2 && (fillMode === Material.TriangleFanDrawMode || fillMode === Material.TriangleFillMode || fillMode === Material.TriangleStripDrawMode) && this._excludedMeshes.indexOf(subMesh2.getMesh().uniqueId) === -1) {
        this._candidateSubMeshes.push(subMesh2);
      } else {
        this._excludedSubMeshes.push(subMesh2);
      }
    }
    if (!this._candidateSubMeshes.length) {
      this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);
      this._engine.bindAttachments(this._layoutCache[1]);
      this._engine.clear(this._colorCache[2], true, false, false);
      this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);
      this._finalCompose(1);
      return this._excludedSubMeshes;
    }
    const currentRenderPassId = this._engine.currentRenderPassId;
    this._scene.prePassRenderer._enabled = false;
    if (this._useRenderPasses) {
      this._engine.currentRenderPassId = this._renderPassIds[0];
    }
    this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);
    this._engine.bindAttachments(this._layoutCache[0]);
    this._engine.clear(this._colorCache[0], true, false, false);
    this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);
    this._engine.bindFramebuffer(this._depthMrts[1].renderTarget);
    this._engine.bindAttachments(this._layoutCache[0]);
    this._engine.clear(this._colorCache[1], true, false, false);
    this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget);
    this._engine.bindFramebuffer(this._colorMrts[0].renderTarget);
    this._engine.bindAttachments(this._layoutCache[1]);
    this._engine.clear(this._colorCache[2], true, false, false);
    this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget);
    this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);
    this._engine.bindAttachments(this._layoutCache[1]);
    this._engine.clear(this._colorCache[2], true, false, false);
    this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);
    this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);
    this._engine.bindAttachments(this._layoutCache[0]);
    this._engine.setAlphaMode(11);
    this._engine.setAlphaEquation(3);
    this._engine.depthCullingState.depthMask = false;
    this._engine.depthCullingState.depthTest = true;
    this._engine.applyStates();
    this._currentPingPongState = 1;
    this._renderSubMeshes(this._candidateSubMeshes);
    this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);
    this._scene.resetCachedMaterial();
    let readId = 0;
    let writeId = 0;
    for (let i = 0;i < this._passCount; i++) {
      readId = i % 2;
      writeId = 1 - readId;
      this._currentPingPongState = readId;
      if (this._useRenderPasses) {
        this._engine.currentRenderPassId = this._renderPassIds[i + 1];
      }
      if (this._scene.activeCamera) {
        this._engine.setViewport(this._scene.activeCamera.viewport);
      }
      this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);
      this._engine.bindAttachments(this._layoutCache[0]);
      this._engine.clear(this._colorCache[0], true, false, false);
      this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);
      this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget);
      this._engine.bindAttachments(this._layoutCache[1]);
      this._engine.clear(this._colorCache[2], true, false, false);
      this._engine.unBindFramebuffer(this._colorMrts[writeId].renderTarget);
      this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);
      this._engine.bindAttachments(this._layoutCache[2]);
      this._engine.setAlphaMode(11);
      this._engine.setAlphaEquation(3);
      this._engine.depthCullingState.depthTest = false;
      this._engine.applyStates();
      this._renderSubMeshes(this._candidateSubMeshes);
      this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);
      this._scene.resetCachedMaterial();
      this._engine.bindFramebuffer(this._blendBackMrt.renderTarget);
      this._engine.bindAttachments(this._layoutCache[0]);
      this._engine.setAlphaEquation(0);
      this._engine.setAlphaMode(17);
      this._engine.applyStates();
      const blendBackEffectWrapper = writeId === 0 || !this._useRenderPasses ? this._blendBackEffectWrapper : this._blendBackEffectWrapperPingPong;
      this._engine.enableEffect(blendBackEffectWrapper.drawWrapper);
      blendBackEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[writeId * 3 + 2]);
      this._effectRenderer.render(blendBackEffectWrapper);
      this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget);
    }
    this._engine.currentRenderPassId = currentRenderPassId;
    this._finalCompose(writeId);
    this._scene.prePassRenderer._enabled = true;
    this._engine.depthCullingState.depthMask = true;
    this._engine.depthCullingState.depthTest = true;
    return this._excludedSubMeshes;
  }
  dispose() {
    this._disposeTextures();
    this._blendBackEffectWrapper.dispose();
    this._finalEffectWrapper.dispose();
    this._effectRenderer.dispose();
    this._releaseRenderPassIds();
  }
}
DepthPeelingRenderer._DEPTH_CLEAR_VALUE = -99999;
DepthPeelingRenderer._MIN_DEPTH = 0;
DepthPeelingRenderer._MAX_DEPTH = 1;
// node_modules/@babylonjs/core/Rendering/depthPeelingSceneComponent.js
init_scene();
init_sceneComponent();
Object.defineProperty(Scene.prototype, "depthPeelingRenderer", {
  get: function() {
    if (!this._depthPeelingRenderer) {
      let component = this._getComponent(SceneComponentConstants.NAME_DEPTHPEELINGRENDERER);
      if (!component) {
        component = new DepthPeelingSceneComponent(this);
        this._addComponent(component);
      }
    }
    return this._depthPeelingRenderer;
  },
  set: function(value) {
    this._depthPeelingRenderer = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Scene.prototype, "useOrderIndependentTransparency", {
  get: function() {
    return this._useOrderIndependentTransparency;
  },
  set: function(value) {
    if (this._useOrderIndependentTransparency === value) {
      return;
    }
    this._useOrderIndependentTransparency = value;
    this.markAllMaterialsAsDirty(127);
    this.prePassRenderer?.markAsDirty();
  },
  enumerable: true,
  configurable: true
});

class DepthPeelingSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_DEPTHPEELINGRENDERER;
    this.scene = scene;
    scene.depthPeelingRenderer = new DepthPeelingRenderer(scene);
  }
  register() {}
  rebuild() {}
  dispose() {
    this.scene.depthPeelingRenderer?.dispose();
    this.scene.depthPeelingRenderer = null;
  }
}
// node_modules/@babylonjs/core/Rendering/edgesRenderer.js
init_buffer();
init_math_vector();
init_smartArray();
init_drawWrapper();
AbstractMesh.prototype.disableEdgesRendering = function() {
  if (this._edgesRenderer) {
    this._edgesRenderer.dispose();
    this._edgesRenderer = null;
  }
  return this;
};
AbstractMesh.prototype.enableEdgesRendering = function(epsilon = 0.95, checkVerticesInsteadOfIndices = false, options) {
  this.disableEdgesRendering();
  this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices, true, options);
  return this;
};
Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  get: function() {
    return this._edgesRenderer;
  },
  enumerable: true,
  configurable: true
});
LinesMesh.prototype.enableEdgesRendering = function(epsilon = 0.95, checkVerticesInsteadOfIndices = false) {
  this.disableEdgesRendering();
  this._edgesRenderer = new LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  return this;
};
InstancedLinesMesh.prototype.enableEdgesRendering = function(epsilon = 0.95, checkVerticesInsteadOfIndices = false) {
  LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  return this;
};

class FaceAdjacencies {
  constructor() {
    this.edges = [];
    this.edgesConnectedCount = 0;
  }
}

class EdgesRenderer {
  get linesPositions() {
    return this._linesPositions;
  }
  get linesNormals() {
    return this._linesNormals;
  }
  get linesIndices() {
    return this._linesIndices;
  }
  get lineShader() {
    return this._lineShader;
  }
  set lineShader(shader460) {
    this._lineShader = shader460;
  }
  static _GetShader(scene, shaderLanguage2) {
    if (!scene._edgeRenderLineShader) {
      const shader460 = new ShaderMaterial("lineShader", scene, "line", {
        attributes: ["position", "normal"],
        uniforms: ["world", "viewProjection", "color", "width", "aspectRatio"],
        uniformBuffers: ["Scene", "Mesh"],
        shaderLanguage: shaderLanguage2,
        extraInitializationsAsync: async () => {
          if (shaderLanguage2 === 1) {
            await Promise.all([Promise.resolve().then(() => (init_line_vertex(), exports_line_vertex)), Promise.resolve().then(() => (init_line_fragment(), exports_line_fragment))]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_line_vertex2(), exports_line_vertex2)), Promise.resolve().then(() => (init_line_fragment2(), exports_line_fragment2))]);
          }
        }
      }, false);
      shader460.disableDepthWrite = true;
      shader460.backFaceCulling = false;
      shader460.checkReadyOnEveryCall = scene.getEngine().isWebGPU;
      scene._edgeRenderLineShader = shader460;
      scene.onDisposeObservable.add(() => {
        scene._edgeRenderLineShader.dispose();
        scene._edgeRenderLineShader = null;
      });
    }
    return scene._edgeRenderLineShader;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false, generateEdgesLines = true, options) {
    this.edgesWidthScalerForOrthographic = 1000;
    this.edgesWidthScalerForPerspective = 50;
    this._linesPositions = new Array;
    this._linesNormals = new Array;
    this._linesIndices = new Array;
    this._buffers = {};
    this._buffersForInstances = {};
    this._checkVerticesInsteadOfIndices = false;
    this.isEnabled = true;
    this.customInstances = new SmartArray(32);
    this._shaderLanguage = 0;
    this._source = source;
    this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
    this._options = options ?? null;
    this._epsilon = epsilon;
    const engine2 = this._source.getScene().getEngine();
    if (engine2.isWebGPU) {
      this._drawWrapper = new DrawWrapper(engine2);
      this._shaderLanguage = 1;
    }
    this._prepareRessources();
    if (generateEdgesLines) {
      if (options?.useAlternateEdgeFinder ?? true) {
        this._generateEdgesLinesAlternate();
      } else {
        this._generateEdgesLines();
      }
    }
    this._meshRebuildObserver = this._source.onRebuildObservable.add(() => {
      this._rebuild();
    });
    this._meshDisposeObserver = this._source.onDisposeObservable.add(() => {
      this.dispose();
    });
  }
  _prepareRessources() {
    if (this._lineShader) {
      return;
    }
    this._lineShader = EdgesRenderer._GetShader(this._source.getScene(), this._shaderLanguage);
  }
  _rebuild() {
    let buffer2 = this._buffers[VertexBuffer.PositionKind];
    if (buffer2) {
      buffer2._rebuild();
    }
    buffer2 = this._buffers[VertexBuffer.NormalKind];
    if (buffer2) {
      buffer2._rebuild();
    }
    const scene = this._source.getScene();
    const engine2 = scene.getEngine();
    this._ib = engine2.createIndexBuffer(this._linesIndices);
  }
  dispose() {
    this._source.onRebuildObservable.remove(this._meshRebuildObserver);
    this._source.onDisposeObservable.remove(this._meshDisposeObserver);
    let buffer2 = this._buffers[VertexBuffer.PositionKind];
    if (buffer2) {
      buffer2.dispose();
      this._buffers[VertexBuffer.PositionKind] = null;
    }
    buffer2 = this._buffers[VertexBuffer.NormalKind];
    if (buffer2) {
      buffer2.dispose();
      this._buffers[VertexBuffer.NormalKind] = null;
    }
    if (this._ib) {
      this._source.getScene().getEngine()._releaseBuffer(this._ib);
    }
    this._drawWrapper?.dispose();
  }
  _processEdgeForAdjacencies(pa, pb, p0, p1, p2) {
    if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
      return 0;
    }
    if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
      return 1;
    }
    if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
      return 2;
    }
    return -1;
  }
  _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2) {
    const eps = 0.0000000001;
    if (pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p1, eps) || pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p0, eps)) {
      return 0;
    }
    if (pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p2, eps) || pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p1, eps)) {
      return 1;
    }
    if (pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p0, eps) || pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p2, eps)) {
      return 2;
    }
    return -1;
  }
  _checkEdge(faceIndex, edge, faceNormals, p0, p1) {
    let needToCreateLine;
    if (edge === undefined) {
      needToCreateLine = true;
    } else {
      const dotProduct = Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
      needToCreateLine = dotProduct < this._epsilon;
    }
    if (needToCreateLine) {
      this.createLine(p0, p1, this._linesPositions.length / 3);
    }
  }
  createLine(p0, p1, offset) {
    this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);
    this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);
    this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  }
  _tessellateTriangle(edgePoints, indexTriangle, indices, remapVertexIndices) {
    const makePointList = (edgePoints2, pointIndices, firstIndex) => {
      if (firstIndex >= 0) {
        pointIndices.push(firstIndex);
      }
      for (let i = 0;i < edgePoints2.length; ++i) {
        pointIndices.push(edgePoints2[i][0]);
      }
    };
    let startEdge = 0;
    if (edgePoints[1].length >= edgePoints[0].length && edgePoints[1].length >= edgePoints[2].length) {
      startEdge = 1;
    } else if (edgePoints[2].length >= edgePoints[0].length && edgePoints[2].length >= edgePoints[1].length) {
      startEdge = 2;
    }
    for (let e = 0;e < 3; ++e) {
      if (e === startEdge) {
        edgePoints[e].sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0);
      } else {
        edgePoints[e].sort((a, b) => a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0);
      }
    }
    const mainPointIndices = [], otherPointIndices = [];
    makePointList(edgePoints[startEdge], mainPointIndices, -1);
    const numMainPoints = mainPointIndices.length;
    for (let i = startEdge + 2;i >= startEdge + 1; --i) {
      makePointList(edgePoints[i % 3], otherPointIndices, i !== startEdge + 2 ? remapVertexIndices[indices[indexTriangle + (i + 1) % 3]] : -1);
    }
    const numOtherPoints = otherPointIndices.length;
    const idxMain = 0;
    const idxOther = 0;
    indices.push(remapVertexIndices[indices[indexTriangle + startEdge]], mainPointIndices[0], otherPointIndices[0]);
    indices.push(remapVertexIndices[indices[indexTriangle + (startEdge + 1) % 3]], otherPointIndices[numOtherPoints - 1], mainPointIndices[numMainPoints - 1]);
    const bucketIsMain = numMainPoints <= numOtherPoints;
    const bucketStep = bucketIsMain ? numMainPoints : numOtherPoints;
    const bucketLimit = bucketIsMain ? numOtherPoints : numMainPoints;
    const bucketIdxLimit = bucketIsMain ? numMainPoints - 1 : numOtherPoints - 1;
    const winding = bucketIsMain ? 0 : 1;
    let numTris = numMainPoints + numOtherPoints - 2;
    let bucketIdx = bucketIsMain ? idxMain : idxOther;
    let nbucketIdx = bucketIsMain ? idxOther : idxMain;
    const bucketPoints = bucketIsMain ? mainPointIndices : otherPointIndices;
    const nbucketPoints = bucketIsMain ? otherPointIndices : mainPointIndices;
    let bucket = 0;
    while (numTris-- > 0) {
      if (winding) {
        indices.push(bucketPoints[bucketIdx], nbucketPoints[nbucketIdx]);
      } else {
        indices.push(nbucketPoints[nbucketIdx], bucketPoints[bucketIdx]);
      }
      bucket += bucketStep;
      let lastIdx;
      if (bucket >= bucketLimit && bucketIdx < bucketIdxLimit) {
        lastIdx = bucketPoints[++bucketIdx];
        bucket -= bucketLimit;
      } else {
        lastIdx = nbucketPoints[++nbucketIdx];
      }
      indices.push(lastIdx);
    }
    indices[indexTriangle + 0] = indices[indices.length - 3];
    indices[indexTriangle + 1] = indices[indices.length - 2];
    indices[indexTriangle + 2] = indices[indices.length - 1];
    indices.length = indices.length - 3;
  }
  _generateEdgesLinesAlternate() {
    const positions = this._source.getVerticesData(VertexBuffer.PositionKind);
    let indices = this._source.getIndices();
    if (!indices || !positions) {
      return;
    }
    if (!Array.isArray(indices)) {
      indices = Array.from(indices);
    }
    const useFastVertexMerger = this._options?.useFastVertexMerger ?? true;
    const epsVertexMerge = useFastVertexMerger ? Math.round(-Math.log(this._options?.epsilonVertexMerge ?? 0.000001) / Math.log(10)) : this._options?.epsilonVertexMerge ?? 0.000001;
    const remapVertexIndices = [];
    const uniquePositions = [];
    if (useFastVertexMerger) {
      const mapVertices = {};
      for (let v12 = 0;v12 < positions.length; v12 += 3) {
        const x1 = positions[v12 + 0], y1 = positions[v12 + 1], z1 = positions[v12 + 2];
        const key = x1.toFixed(epsVertexMerge) + "|" + y1.toFixed(epsVertexMerge) + "|" + z1.toFixed(epsVertexMerge);
        if (mapVertices[key] !== undefined) {
          remapVertexIndices.push(mapVertices[key]);
        } else {
          const idx = v12 / 3;
          mapVertices[key] = idx;
          remapVertexIndices.push(idx);
          uniquePositions.push(idx);
        }
      }
    } else {
      for (let v12 = 0;v12 < positions.length; v12 += 3) {
        const x1 = positions[v12 + 0], y1 = positions[v12 + 1], z1 = positions[v12 + 2];
        let found = false;
        for (let v22 = 0;v22 < v12 && !found; v22 += 3) {
          const x2 = positions[v22 + 0], y2 = positions[v22 + 1], z2 = positions[v22 + 2];
          if (Math.abs(x1 - x2) < epsVertexMerge && Math.abs(y1 - y2) < epsVertexMerge && Math.abs(z1 - z2) < epsVertexMerge) {
            remapVertexIndices.push(v22 / 3);
            found = true;
            break;
          }
        }
        if (!found) {
          remapVertexIndices.push(v12 / 3);
          uniquePositions.push(v12 / 3);
        }
      }
    }
    if (this._options?.applyTessellation) {
      const epsVertexAligned = this._options?.epsilonVertexAligned ?? 0.000001;
      const mustTesselate = [];
      for (let index = 0;index < indices.length; index += 3) {
        let triangleToTessellate;
        for (let i = 0;i < 3; ++i) {
          const p0Index = remapVertexIndices[indices[index + i]];
          const p1Index = remapVertexIndices[indices[index + (i + 1) % 3]];
          const p2Index = remapVertexIndices[indices[index + (i + 2) % 3]];
          if (p0Index === p1Index) {
            continue;
          }
          const p0x = positions[p0Index * 3 + 0], p0y = positions[p0Index * 3 + 1], p0z = positions[p0Index * 3 + 2];
          const p1x = positions[p1Index * 3 + 0], p1y = positions[p1Index * 3 + 1], p1z = positions[p1Index * 3 + 2];
          const p0p1 = Math.sqrt((p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + (p1z - p0z) * (p1z - p0z));
          for (let v = 0;v < uniquePositions.length - 1; v++) {
            const vIndex = uniquePositions[v];
            if (vIndex === p0Index || vIndex === p1Index || vIndex === p2Index) {
              continue;
            }
            const x = positions[vIndex * 3 + 0], y = positions[vIndex * 3 + 1], z = positions[vIndex * 3 + 2];
            const p0p = Math.sqrt((x - p0x) * (x - p0x) + (y - p0y) * (y - p0y) + (z - p0z) * (z - p0z));
            const pp1 = Math.sqrt((x - p1x) * (x - p1x) + (y - p1y) * (y - p1y) + (z - p1z) * (z - p1z));
            if (Math.abs(p0p + pp1 - p0p1) < epsVertexAligned) {
              if (!triangleToTessellate) {
                triangleToTessellate = {
                  index,
                  edgesPoints: [[], [], []]
                };
                mustTesselate.push(triangleToTessellate);
              }
              triangleToTessellate.edgesPoints[i].push([vIndex, p0p]);
            }
          }
        }
      }
      for (let t = 0;t < mustTesselate.length; ++t) {
        const triangle = mustTesselate[t];
        this._tessellateTriangle(triangle.edgesPoints, triangle.index, indices, remapVertexIndices);
      }
      mustTesselate.length = 0;
    }
    const edges = {};
    for (let index = 0;index < indices.length; index += 3) {
      let faceNormal;
      for (let i = 0;i < 3; ++i) {
        let p0Index = remapVertexIndices[indices[index + i]];
        let p1Index = remapVertexIndices[indices[index + (i + 1) % 3]];
        const p2Index = remapVertexIndices[indices[index + (i + 2) % 3]];
        if (p0Index === p1Index || (p0Index === p2Index || p1Index === p2Index) && this._options?.removeDegeneratedTriangles) {
          continue;
        }
        TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
        TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
        TmpVectors.Vector3[2].copyFromFloats(positions[p2Index * 3 + 0], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
        if (!faceNormal) {
          TmpVectors.Vector3[1].subtractToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[3]);
          TmpVectors.Vector3[2].subtractToRef(TmpVectors.Vector3[1], TmpVectors.Vector3[4]);
          faceNormal = Vector3.Cross(TmpVectors.Vector3[3], TmpVectors.Vector3[4]);
          faceNormal.normalize();
        }
        if (p0Index > p1Index) {
          const tmp = p0Index;
          p0Index = p1Index;
          p1Index = tmp;
        }
        const key = p0Index + "_" + p1Index;
        const ei = edges[key];
        if (ei) {
          if (!ei.done) {
            const dotProduct = Vector3.Dot(faceNormal, ei.normal);
            if (dotProduct < this._epsilon) {
              this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);
            }
            ei.done = true;
          }
        } else {
          edges[key] = { normal: faceNormal, done: false, index, i };
        }
      }
    }
    for (const key in edges) {
      const ei = edges[key];
      if (!ei.done) {
        const p0Index = remapVertexIndices[indices[ei.index + ei.i]];
        const p1Index = remapVertexIndices[indices[ei.index + (ei.i + 1) % 3]];
        TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
        TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
        this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);
      }
    }
    const engine2 = this._source.getScene().getEngine();
    this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine2, this._linesPositions, VertexBuffer.PositionKind, false);
    this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine2, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);
    this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];
    this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];
    this._ib = engine2.createIndexBuffer(this._linesIndices);
    this._indicesCount = this._linesIndices.length;
  }
  _generateEdgesLines() {
    const positions = this._source.getVerticesData(VertexBuffer.PositionKind);
    const indices = this._source.getIndices();
    if (!indices || !positions) {
      return;
    }
    const adjacencies = [];
    const faceNormals = [];
    let index;
    let faceAdjacencies;
    for (index = 0;index < indices.length; index += 3) {
      faceAdjacencies = new FaceAdjacencies;
      const p0Index = indices[index];
      const p1Index = indices[index + 1];
      const p2Index = indices[index + 2];
      faceAdjacencies.p0 = new Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
      faceAdjacencies.p1 = new Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
      faceAdjacencies.p2 = new Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
      const faceNormal = Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
      faceNormal.normalize();
      faceNormals.push(faceNormal);
      adjacencies.push(faceAdjacencies);
    }
    for (index = 0;index < adjacencies.length; index++) {
      faceAdjacencies = adjacencies[index];
      for (let otherIndex = index + 1;otherIndex < adjacencies.length; otherIndex++) {
        const otherFaceAdjacencies = adjacencies[otherIndex];
        if (faceAdjacencies.edgesConnectedCount === 3) {
          break;
        }
        if (otherFaceAdjacencies.edgesConnectedCount === 3) {
          continue;
        }
        const otherP0 = indices[otherIndex * 3];
        const otherP1 = indices[otherIndex * 3 + 1];
        const otherP2 = indices[otherIndex * 3 + 2];
        for (let edgeIndex = 0;edgeIndex < 3; edgeIndex++) {
          let otherEdgeIndex = 0;
          if (faceAdjacencies.edges[edgeIndex] !== undefined) {
            continue;
          }
          switch (edgeIndex) {
            case 0:
              if (this._checkVerticesInsteadOfIndices) {
                otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
              } else {
                otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
              }
              break;
            case 1:
              if (this._checkVerticesInsteadOfIndices) {
                otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
              } else {
                otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
              }
              break;
            case 2:
              if (this._checkVerticesInsteadOfIndices) {
                otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
              } else {
                otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
              }
              break;
          }
          if (otherEdgeIndex === -1) {
            continue;
          }
          faceAdjacencies.edges[edgeIndex] = otherIndex;
          otherFaceAdjacencies.edges[otherEdgeIndex] = index;
          faceAdjacencies.edgesConnectedCount++;
          otherFaceAdjacencies.edgesConnectedCount++;
          if (faceAdjacencies.edgesConnectedCount === 3) {
            break;
          }
        }
      }
    }
    for (index = 0;index < adjacencies.length; index++) {
      const current = adjacencies[index];
      this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
      this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
      this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
    }
    const engine2 = this._source.getScene().getEngine();
    this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine2, this._linesPositions, VertexBuffer.PositionKind, false);
    this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine2, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);
    this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];
    this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];
    this._ib = engine2.createIndexBuffer(this._linesIndices);
    this._indicesCount = this._linesIndices.length;
  }
  isReady() {
    return this._lineShader.isReady(this._source, this._source.hasInstances && this.customInstances.length > 0 || this._source.hasThinInstances);
  }
  render() {
    const scene = this._source.getScene();
    const currentDrawWrapper = this._lineShader._getDrawWrapper();
    if (this._drawWrapper) {
      this._lineShader._setDrawWrapper(this._drawWrapper);
    }
    if (!this.isReady() || !scene.activeCamera) {
      this._lineShader._setDrawWrapper(currentDrawWrapper);
      return;
    }
    const hasInstances = this._source.hasInstances && this.customInstances.length > 0;
    const useBuffersWithInstances = hasInstances || this._source.hasThinInstances;
    let instanceCount = 0;
    if (useBuffersWithInstances) {
      this._buffersForInstances["world0"] = this._source.getVertexBuffer("world0");
      this._buffersForInstances["world1"] = this._source.getVertexBuffer("world1");
      this._buffersForInstances["world2"] = this._source.getVertexBuffer("world2");
      this._buffersForInstances["world3"] = this._source.getVertexBuffer("world3");
      if (hasInstances) {
        const instanceStorage = this._source._instanceDataStorage;
        instanceCount = this.customInstances.length;
        if (!instanceStorage.instancesData) {
          if (!this._source.getScene()._activeMeshesFrozen) {
            this.customInstances.reset();
          }
          return;
        }
        if (!instanceStorage.isFrozen) {
          let offset = 0;
          for (let i = 0;i < instanceCount; ++i) {
            this.customInstances.data[i].copyToArray(instanceStorage.instancesData, offset);
            offset += 16;
          }
          instanceStorage.instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instanceCount);
        }
      } else {
        instanceCount = this._source.thinInstanceCount;
      }
    }
    const engine2 = scene.getEngine();
    this._lineShader._preBind();
    if (this._source.edgesColor.a !== 1) {
      engine2.setAlphaMode(2);
    } else {
      engine2.setAlphaMode(0);
    }
    engine2.bindBuffers(useBuffersWithInstances ? this._buffersForInstances : this._buffers, this._ib, this._lineShader.getEffect());
    scene.resetCachedMaterial();
    this._lineShader.setColor4("color", this._source.edgesColor);
    if (scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA) {
      this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
    } else {
      this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
    }
    this._lineShader.setFloat("aspectRatio", engine2.getAspectRatio(scene.activeCamera));
    this._lineShader.bind(this._source.getWorldMatrix(), this._source);
    engine2.drawElementsType(Material.TriangleFillMode, 0, this._indicesCount, instanceCount);
    this._lineShader.unbind();
    if (useBuffersWithInstances) {
      engine2.unbindInstanceAttributes();
    }
    if (!this._source.getScene()._activeMeshesFrozen) {
      this.customInstances.reset();
    }
    this._lineShader._setDrawWrapper(currentDrawWrapper);
  }
}

class LineEdgesRenderer extends EdgesRenderer {
  constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false) {
    super(source, epsilon, checkVerticesInsteadOfIndices, false);
    this._generateEdgesLines();
  }
  _generateEdgesLines() {
    const positions = this._source.getVerticesData(VertexBuffer.PositionKind);
    const indices = this._source.getIndices();
    if (!indices || !positions) {
      return;
    }
    const p0 = TmpVectors.Vector3[0];
    const p1 = TmpVectors.Vector3[1];
    const len = indices.length - 1;
    for (let i = 0, offset = 0;i < len; i += 2, offset += 4) {
      Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
      Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
      this.createLine(p0, p1, offset);
    }
    const engine2 = this._source.getScene().getEngine();
    this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine2, this._linesPositions, VertexBuffer.PositionKind, false);
    this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine2, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);
    this._ib = engine2.createIndexBuffer(this._linesIndices);
    this._indicesCount = this._linesIndices.length;
  }
}
// node_modules/@babylonjs/core/Rendering/iblCdfGeneratorSceneComponent.js
init_scene();
init_sceneComponent();
Object.defineProperty(Scene.prototype, "iblCdfGenerator", {
  get: function() {
    return this._iblCdfGenerator;
  },
  set: function(value) {
    if (value) {
      this._iblCdfGenerator = value;
    }
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.enableIblCdfGenerator = function() {
  if (this._iblCdfGenerator) {
    return this._iblCdfGenerator;
  }
  this._iblCdfGenerator = new IblCdfGenerator(this);
  if (this.environmentTexture) {
    this._iblCdfGenerator.iblSource = this.environmentTexture;
  }
  return this._iblCdfGenerator;
};
Scene.prototype.disableIblCdfGenerator = function() {
  if (!this._iblCdfGenerator) {
    return;
  }
  this._iblCdfGenerator.dispose();
  this._iblCdfGenerator = null;
};

class IblCdfGeneratorSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_IBLCDFGENERATOR;
    this._newIblObserver = null;
    this.scene = scene;
  }
  register() {
    this._updateIblSource();
    this._newIblObserver = this.scene.onEnvironmentTextureChangedObservable.add(this._updateIblSource.bind(this));
  }
  rebuild() {}
  dispose() {
    this.scene.onEnvironmentTextureChangedObservable.remove(this._newIblObserver);
  }
  _updateIblSource() {
    if (this.scene.iblCdfGenerator && this.scene.environmentTexture) {
      this.scene.iblCdfGenerator.iblSource = this.scene.environmentTexture;
    }
  }
}
IblCdfGenerator._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_IBLCDFGENERATOR);
  if (!component) {
    component = new IblCdfGeneratorSceneComponent(scene);
    scene._addComponent(component);
  }
};
// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsRenderPipeline.js
init_engineStore();
init_math_vector();
init_texture();
init_logger();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsVoxelRenderer.js
init_engine();
init_renderTargetTexture();
init_math_color();
init_math_vector();
init_texture();
init_logger();
init_observable();
init_postProcess();
init_effectRenderer();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsVoxelTracingPass.js
init_math_vector();
init_postProcess();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsRenderPipeline.js
init_postProcess();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsSpatialBlurPass.js
init_math_vector();
init_postProcess();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsAccumulationPass.js
init_math_vector();
init_postProcess();
init_observable();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsRenderPipeline.js
init_engine();

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsPluginMaterial.js
init_tslib_es6();
init_decorators();
init_typeStore();

class MaterialIBLShadowsRenderDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.RENDER_WITH_IBL_SHADOWS = false;
    this.COLORED_IBL_SHADOWS = false;
  }
}

class IBLShadowsPluginMaterial extends MaterialPluginBase {
  get isColored() {
    return this._isColored;
  }
  set isColored(value) {
    if (this._isColored === value) {
      return;
    }
    this._isColored = value;
    this._markAllSubMeshesAsTexturesDirty();
  }
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material2) {
    super(material2, IBLShadowsPluginMaterial.Name, 310, new MaterialIBLShadowsRenderDefines);
    this.shadowOpacity = 1;
    this._isEnabled = false;
    this._isColored = false;
    this.isEnabled = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material2._dirtyCallbacks[1];
  }
  prepareDefines(defines) {
    defines.RENDER_WITH_IBL_SHADOWS = this._isEnabled;
    defines.COLORED_IBL_SHADOWS = this.isColored;
  }
  getClassName() {
    return "IBLShadowsPluginMaterial";
  }
  getUniforms() {
    return {
      ubo: [
        { name: "renderTargetSize", size: 2, type: "vec2" },
        { name: "shadowOpacity", size: 1, type: "float" }
      ],
      fragment: `#ifdef RENDER_WITH_IBL_SHADOWS
                    uniform vec2 renderTargetSize;
                    uniform float shadowOpacity;
                #endif`
    };
  }
  getSamplers(samplers) {
    samplers.push("iblShadowsTexture");
  }
  bindForSubMesh(uniformBuffer2) {
    if (this._isEnabled) {
      uniformBuffer2.bindTexture("iblShadowsTexture", this.iblShadowsTexture);
      uniformBuffer2.updateFloat2("renderTargetSize", this._material.getScene().getEngine().getRenderWidth(), this._material.getScene().getEngine().getRenderHeight());
      uniformBuffer2.updateFloat("shadowOpacity", this.shadowOpacity);
    }
  }
  getCustomCode(shaderType, shaderLanguage2) {
    let frag;
    if (shaderLanguage2 === 1) {
      frag = {
        CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    var iblShadowsTextureSampler: sampler;
                    var iblShadowsTexture: texture_2d<f32>;

                    #ifdef COLORED_IBL_SHADOWS
                        fn computeIndirectShadow() -> vec3f {
                            var uv = fragmentInputs.position.xy / uniforms.renderTargetSize;
                            var shadowValue: vec3f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rgb;
                            return mix(shadowValue, vec3f(1.0), 1.0 - uniforms.shadowOpacity);
                        }
                    #else
                        fn computeIndirectShadow() -> vec2f {
                            var uv = fragmentInputs.position.xy / uniforms.renderTargetSize;
                            var shadowValue: vec2f = textureSample(iblShadowsTexture, iblShadowsTextureSampler, uv).rg;
                            return mix(shadowValue, vec2f(1.0), 1.0 - uniforms.shadowOpacity);
                        }
                    #endif
                #endif
            `
      };
      if (this._material instanceof PBRBaseMaterial) {
        frag["CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION"] = `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    #ifndef UNLIT
                        #ifdef REFLECTION
                            #ifdef COLORED_IBL_SHADOWS
                                var shadowValue: vec3f = computeIndirectShadow();
                                finalIrradiance *= shadowValue;
                                finalRadianceScaled *= mix(vec3f(1.0), shadowValue, roughness);
                            #else
                                var shadowValue: vec2f = computeIndirectShadow();
                                finalIrradiance *= vec3f(shadowValue.x);
                                finalRadianceScaled *= vec3f(mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness));
                            #endif
                        #endif
                    #else
                        finalDiffuse *= computeIndirectShadow().x;
                    #endif
                #endif
            `;
      } else {
        frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    #ifdef COLORED_IBL_SHADOWS
                        var shadowValue: vec3f = computeIndirectShadow();
                        color *= toGammaSpace(vec4f(shadowValue, 1.0f));
                    #else
                        var shadowValue: vec2f = computeIndirectShadow();
                        color *= toGammaSpace(vec4f(shadowValue.x, shadowValue.x, shadowValue.x, 1.0f));
                    #endif
                #endif
            `;
      }
    } else {
      frag = {
        CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    uniform sampler2D iblShadowsTexture;
                #ifdef COLORED_IBL_SHADOWS
                    vec3 computeIndirectShadow() {
                        vec2 uv = gl_FragCoord.xy / renderTargetSize;
                        vec3 shadowValue = texture2D(iblShadowsTexture, uv).rgb;
                        return mix(shadowValue.rgb, vec3(1.0), 1.0 - shadowOpacity);
                    }
                #else
                    vec2 computeIndirectShadow() {
                        vec2 uv = gl_FragCoord.xy / renderTargetSize;
                        vec2 shadowValue = texture2D(iblShadowsTexture, uv).rg;
                        return mix(shadowValue.rg, vec2(1.0), 1.0 - shadowOpacity);
                    }
                #endif
                #endif
            `
      };
      if (this._material instanceof PBRBaseMaterial) {
        frag["CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION"] = `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    #ifndef UNLIT
                        #ifdef REFLECTION
                            #ifdef COLORED_IBL_SHADOWS
                                vec3 shadowValue = computeIndirectShadow();
                                finalIrradiance.rgb *= shadowValue.rgb;
                                finalRadianceScaled *= mix(vec3(1.0), shadowValue.rgb, roughness);
                            #else
                                vec2 shadowValue = computeIndirectShadow();
                                finalIrradiance *= shadowValue.x;
                                finalRadianceScaled *= mix(pow(shadowValue.y, 4.0), shadowValue.x, roughness);
                            #endif
                        #endif
                    #else
                        finalDiffuse *= computeIndirectShadow().x;
                    #endif
                #endif
            `;
      } else {
        frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = `
                #ifdef RENDER_WITH_IBL_SHADOWS
                    #ifdef COLORED_IBL_SHADOWS
                        vec3 shadowValue = computeIndirectShadow();
                        color.rgb *= toGammaSpace(shadowValue.rgb);
                    #else
                        vec2 shadowValue = computeIndirectShadow();
                        color.rgb *= toGammaSpace(shadowValue.x);
                    #endif
                #endif
            `;
      }
    }
    return shaderType === "vertex" ? null : frag;
  }
}
IBLShadowsPluginMaterial.Name = "IBLShadowsPluginMaterial";
__decorate([
  serialize()
], IBLShadowsPluginMaterial.prototype, "iblShadowsTexture", undefined);
__decorate([
  serialize()
], IBLShadowsPluginMaterial.prototype, "shadowOpacity", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], IBLShadowsPluginMaterial.prototype, "isEnabled", undefined);
RegisterClass(`BABYLON.IBLShadowsPluginMaterial`, IBLShadowsPluginMaterial);

// node_modules/@babylonjs/core/Rendering/IBLShadows/iblShadowsRenderPipeline.js
init_observable();
// node_modules/@babylonjs/core/Materials/Textures/prePassRenderTarget.js
class PrePassRenderTarget extends MultiRenderTarget {
  constructor(name461, renderTargetTexture2, size, count, scene, options) {
    super(name461, size, count, scene, options);
    this._beforeCompositionPostProcesses = [];
    this._internalTextureDirty = false;
    this.enabled = false;
    this.renderTargetTexture = null;
    this.renderTargetTexture = renderTargetTexture2;
  }
  _createCompositionEffect() {
    this.imageProcessingPostProcess = new ImageProcessingPostProcess("prePassComposition", 1, null, undefined, this._engine);
    this.imageProcessingPostProcess._updateParameters();
  }
  _checkSize() {
    const requiredWidth = this._engine.getRenderWidth(true);
    const requiredHeight = this._engine.getRenderHeight(true);
    const width = this.getRenderWidth();
    const height = this.getRenderHeight();
    if (width !== requiredWidth || height !== requiredHeight) {
      this.resize({ width: requiredWidth, height: requiredHeight });
      this._internalTextureDirty = true;
    }
  }
  updateCount(count, options, textureNames) {
    super.updateCount(count, options, textureNames);
    this._internalTextureDirty = true;
  }
  _resetPostProcessChain() {
    this._beforeCompositionPostProcesses.length = 0;
  }
  dispose() {
    const scene = this._scene;
    super.dispose();
    if (scene && scene.prePassRenderer) {
      const index = scene.prePassRenderer.renderTargets.indexOf(this);
      if (index !== -1) {
        scene.prePassRenderer.renderTargets.splice(index, 1);
      }
    }
    if (this.imageProcessingPostProcess) {
      this.imageProcessingPostProcess.dispose();
    }
    if (this.renderTargetTexture) {
      this.renderTargetTexture._prePassRenderTarget = null;
    }
    if (this._outputPostProcess) {
      this._outputPostProcess.autoClear = true;
      this._outputPostProcess.restoreDefaultInputTexture();
    }
  }
}

// node_modules/@babylonjs/core/Rendering/prePassRenderer.js
init_devTools();
init_math_color();
class PrePassRenderer {
  get generateNormalsInWorldSpace() {
    return this._generateNormalsInWorldSpace;
  }
  set generateNormalsInWorldSpace(value) {
    if (this._generateNormalsInWorldSpace === value) {
      return;
    }
    this._generateNormalsInWorldSpace = value;
    this._markAllMaterialsAsPrePassDirty();
  }
  getIndex(type) {
    return this._textureIndices[type];
  }
  get samples() {
    return this.defaultRT.samples;
  }
  set samples(n) {
    this.defaultRT.samples = n;
  }
  get useSpecificClearForDepthTexture() {
    return this._useSpecificClearForDepthTexture;
  }
  set useSpecificClearForDepthTexture(value) {
    if (this._useSpecificClearForDepthTexture === value) {
      return;
    }
    this._useSpecificClearForDepthTexture = value;
    this._isDirty = true;
  }
  getRenderTarget() {
    return this._currentTarget;
  }
  _setRenderTarget(prePassRenderTarget) {
    if (prePassRenderTarget) {
      this._currentTarget = prePassRenderTarget;
    } else {
      this._currentTarget = this.defaultRT;
      this._engine.currentRenderPassId = this._scene.activeCamera?.renderPassId ?? this._currentTarget.renderPassId;
    }
  }
  get currentRTisSceneRT() {
    return this._currentTarget === this.defaultRT;
  }
  _refreshGeometryBufferRendererLink() {
    if (!this.doNotUseGeometryRendererFallback) {
      this._geometryBuffer = this._scene.enableGeometryBufferRenderer();
      if (!this._geometryBuffer) {
        this.doNotUseGeometryRendererFallback = true;
        return;
      }
      this._geometryBuffer._linkPrePassRenderer(this);
    } else {
      if (this._geometryBuffer) {
        this._geometryBuffer._unlinkPrePassRenderer();
      }
      this._geometryBuffer = null;
      this._scene.disableGeometryBufferRenderer();
    }
  }
  get enabled() {
    return this._enabled;
  }
  constructor(scene) {
    this.excludedSkinnedMesh = [];
    this.excludedMaterials = [];
    this.mrtCount = 0;
    this._mrtTypes = [];
    this._mrtFormats = [];
    this._mrtLayout = [];
    this._mrtNames = [];
    this._textureIndices = [];
    this._generateNormalsInWorldSpace = false;
    this._useSpecificClearForDepthTexture = false;
    this._isDirty = true;
    this._effectConfigurations = [];
    this.doNotUseGeometryRendererFallback = true;
    this.renderTargets = [];
    this._clearColor = new Color4(0, 0, 0, 0);
    this._clearDepthColor = new Color4(1e8, 0, 0, 1);
    this._enabled = false;
    this._needsCompositionForThisPass = false;
    this.disableGammaTransform = false;
    this._scene = scene;
    this._engine = scene.getEngine();
    let type = 0;
    if (this._engine._caps.textureFloat && this._engine._caps.textureFloatLinearFiltering) {
      type = 1;
    } else if (this._engine._caps.textureHalfFloat && this._engine._caps.textureHalfFloatLinearFiltering) {
      type = 2;
    }
    for (let i = 0;i < PrePassRenderer.TextureFormats.length; ++i) {
      const format = PrePassRenderer.TextureFormats[i].format;
      if (PrePassRenderer.TextureFormats[i].type === 1) {
        PrePassRenderer.TextureFormats[i].type = type;
        if (type === 1 && (format === 6 || format === 7 || format === 5) && !this._engine._caps.supportFloatTexturesResolve) {
          PrePassRenderer.TextureFormats[i].type = 2;
        }
      }
    }
    PrePassRenderer._SceneComponentInitialization(this._scene);
    this.defaultRT = this._createRenderTarget("sceneprePassRT", null);
    this._currentTarget = this.defaultRT;
  }
  _createRenderTarget(name461, renderTargetTexture2) {
    const rt = new PrePassRenderTarget(name461, renderTargetTexture2, { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, 0, this._scene, {
      generateMipMaps: false,
      generateStencilBuffer: this._engine.isStencilEnable,
      defaultType: 0,
      types: [],
      drawOnlyOnFirstAttachmentByDefault: true
    });
    this.renderTargets.push(rt);
    if (this._enabled) {
      this._update();
    }
    return rt;
  }
  get isSupported() {
    return this._scene.getEngine().getCaps().drawBuffersExtension;
  }
  bindAttachmentsForEffect(effect2, subMesh2) {
    const material2 = subMesh2.getMaterial();
    const isPrePassCapable = material2 && material2.isPrePassCapable;
    const excluded = material2 && this.excludedMaterials.indexOf(material2) !== -1;
    if (this.enabled && this._currentTarget.enabled) {
      if (effect2._multiTarget && isPrePassCapable && !excluded) {
        this._engine.bindAttachments(this._multiRenderAttachments);
      } else {
        if (this._engine._currentRenderTarget) {
          this._engine.bindAttachments(this._defaultAttachments);
        } else {
          this._engine.restoreSingleAttachment();
        }
        if (this._geometryBuffer && this.currentRTisSceneRT && !excluded) {
          this._geometryBuffer.renderList.push(subMesh2.getRenderingMesh());
        }
      }
    }
  }
  _reinitializeAttachments() {
    const multiRenderLayout = [];
    const clearLayout = [false];
    const clearDepthLayout = [false];
    const defaultLayout = [true];
    for (let i = 0;i < this.mrtCount; i++) {
      multiRenderLayout.push(true);
      if (i > 0) {
        if (this._useSpecificClearForDepthTexture && this._mrtLayout[i] === 5) {
          clearLayout.push(false);
          clearDepthLayout.push(true);
        } else {
          clearLayout.push(true);
          clearDepthLayout.push(false);
        }
        defaultLayout.push(false);
      }
    }
    this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout);
    this._clearAttachments = this._engine.buildTextureLayout(clearLayout);
    this._clearDepthAttachments = this._engine.buildTextureLayout(clearDepthLayout);
    this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout);
  }
  _resetLayout() {
    for (let i = 0;i < PrePassRenderer.TextureFormats.length; i++) {
      this._textureIndices[PrePassRenderer.TextureFormats[i].purpose] = -1;
    }
    this._textureIndices[4] = 0;
    this._mrtLayout = [4];
    this._mrtTypes = [PrePassRenderer.TextureFormats[4].type];
    this._mrtFormats = [PrePassRenderer.TextureFormats[4].format];
    this._mrtNames = [PrePassRenderer.TextureFormats[4].name];
    this.mrtCount = 1;
  }
  _updateGeometryBufferLayout() {
    this._refreshGeometryBufferRendererLink();
    if (this._geometryBuffer) {
      this._geometryBuffer._resetLayout();
      const texturesActivated = [];
      for (let i = 0;i < this._mrtLayout.length; i++) {
        texturesActivated.push(false);
      }
      this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());
      const matches = [
        {
          prePassConstant: 5,
          geometryBufferConstant: GeometryBufferRenderer.DEPTH_TEXTURE_TYPE
        },
        {
          prePassConstant: 6,
          geometryBufferConstant: GeometryBufferRenderer.NORMAL_TEXTURE_TYPE
        },
        {
          prePassConstant: 1,
          geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE
        },
        {
          prePassConstant: 3,
          geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE
        },
        {
          prePassConstant: 2,
          geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE
        }
      ];
      for (let i = 0;i < matches.length; i++) {
        const index = this._mrtLayout.indexOf(matches[i].prePassConstant);
        if (index !== -1) {
          this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index);
          texturesActivated[index] = true;
        }
      }
      this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated));
    }
  }
  restoreAttachments() {
    if (this.enabled && this._currentTarget.enabled && this._defaultAttachments) {
      if (this._engine._currentRenderTarget) {
        this._engine.bindAttachments(this._defaultAttachments);
      } else {
        this._engine.restoreSingleAttachment();
      }
    }
  }
  _beforeDraw(camera2, faceIndex, layer2) {
    if (this._isDirty) {
      this._update();
    }
    if (!this._enabled || !this._currentTarget.enabled) {
      return;
    }
    if (this._geometryBuffer) {
      this._geometryBuffer.renderList = [];
    }
    this._setupOutputForThisPass(this._currentTarget, camera2);
  }
  _prepareFrame(prePassRenderTarget, faceIndex, layer2) {
    if (prePassRenderTarget.renderTargetTexture) {
      prePassRenderTarget.renderTargetTexture._prepareFrame(this._scene, faceIndex, layer2, prePassRenderTarget.renderTargetTexture.useCameraPostProcesses);
    } else if (this._postProcessesSourceForThisPass.length) {
      this._scene.postProcessManager._prepareFrame();
    } else {
      this._engine.restoreDefaultFramebuffer();
    }
  }
  setCustomOutput(rt) {
    const firstPP = this._postProcessesSourceForThisPass[0];
    if (!firstPP) {
      return false;
    }
    firstPP.inputTexture = rt.renderTarget;
    return true;
  }
  _renderPostProcesses(prePassRenderTarget, faceIndex) {
    const firstPP = this._postProcessesSourceForThisPass[0];
    const outputTexture = firstPP ? firstPP.inputTexture : prePassRenderTarget.renderTargetTexture ? prePassRenderTarget.renderTargetTexture.renderTarget : null;
    let postProcessChain = this._currentTarget._beforeCompositionPostProcesses;
    if (this._needsCompositionForThisPass) {
      postProcessChain = postProcessChain.concat([this._currentTarget.imageProcessingPostProcess]);
    }
    if (postProcessChain.length) {
      this._scene.postProcessManager._prepareFrame(this._currentTarget.renderTarget?.texture, postProcessChain);
      this._scene.postProcessManager.directRender(postProcessChain, outputTexture, false, faceIndex);
    }
  }
  _afterDraw(faceIndex, layer2) {
    if (this._enabled && this._currentTarget.enabled) {
      this._prepareFrame(this._currentTarget, faceIndex, layer2);
      this._renderPostProcesses(this._currentTarget, faceIndex);
    }
  }
  _clear() {
    if (this._isDirty) {
      this._update();
    }
    if (this._enabled && this._currentTarget.enabled) {
      this._bindFrameBuffer();
      this._engine.bindAttachments(this._clearAttachments);
      this._engine.clear(this._clearColor, true, false, false);
      if (this._useSpecificClearForDepthTexture) {
        this._engine.bindAttachments(this._clearDepthAttachments);
        this._engine.clear(this._clearDepthColor, true, false, false);
      }
      this._engine.bindAttachments(this._defaultAttachments);
    }
  }
  _bindFrameBuffer() {
    if (this._enabled && this._currentTarget.enabled) {
      this._currentTarget._checkSize();
      const internalTexture2 = this._currentTarget.renderTarget;
      if (internalTexture2) {
        this._engine.bindFramebuffer(internalTexture2);
      }
    }
  }
  _setEnabled(enabled) {
    this._enabled = enabled;
  }
  _setRenderTargetEnabled(prePassRenderTarget, enabled) {
    prePassRenderTarget.enabled = enabled;
    if (!enabled) {
      this._unlinkInternalTexture(prePassRenderTarget);
    }
  }
  addEffectConfiguration(cfg) {
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      if (this._effectConfigurations[i].name === cfg.name) {
        return this._effectConfigurations[i];
      }
    }
    this._effectConfigurations.push(cfg);
    return cfg;
  }
  getEffectConfiguration(name461) {
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      if (this._effectConfigurations[i].name === name461) {
        return this._effectConfigurations[i];
      }
    }
    return null;
  }
  _enable() {
    const previousMrtCount = this.mrtCount;
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      if (this._effectConfigurations[i].enabled) {
        this._enableTextures(this._effectConfigurations[i].texturesRequired);
      }
    }
    for (let i = 0;i < this.renderTargets.length; i++) {
      if (this.mrtCount !== previousMrtCount || this.renderTargets[i].count !== this.mrtCount) {
        this.renderTargets[i].updateCount(this.mrtCount, { types: this._mrtTypes, formats: this._mrtFormats }, this._mrtNames.concat("prePass_DepthBuffer"));
      }
      this.renderTargets[i]._resetPostProcessChain();
      for (let j = 0;j < this._effectConfigurations.length; j++) {
        if (this._effectConfigurations[j].enabled) {
          if (!this._effectConfigurations[j].postProcess && this._effectConfigurations[j].createPostProcess) {
            this._effectConfigurations[j].createPostProcess();
          }
          if (this._effectConfigurations[j].postProcess) {
            this.renderTargets[i]._beforeCompositionPostProcesses.push(this._effectConfigurations[j].postProcess);
          }
        }
      }
    }
    this._reinitializeAttachments();
    this._setEnabled(true);
    this._updateGeometryBufferLayout();
  }
  _disable() {
    this._setEnabled(false);
    for (let i = 0;i < this.renderTargets.length; i++) {
      this._setRenderTargetEnabled(this.renderTargets[i], false);
    }
    this._resetLayout();
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      this._effectConfigurations[i].enabled = false;
    }
  }
  _getPostProcessesSource(prePassRenderTarget, camera2) {
    if (camera2) {
      return camera2._postProcesses;
    } else if (prePassRenderTarget.renderTargetTexture) {
      if (prePassRenderTarget.renderTargetTexture.useCameraPostProcesses) {
        const camera3 = prePassRenderTarget.renderTargetTexture.activeCamera ? prePassRenderTarget.renderTargetTexture.activeCamera : this._scene.activeCamera;
        return camera3 ? camera3._postProcesses : [];
      } else if (prePassRenderTarget.renderTargetTexture.postProcesses) {
        return prePassRenderTarget.renderTargetTexture.postProcesses;
      } else {
        return [];
      }
    } else {
      return this._scene.activeCamera ? this._scene.activeCamera._postProcesses : [];
    }
  }
  _setupOutputForThisPass(prePassRenderTarget, camera2) {
    const secondaryCamera = camera2 && this._scene.activeCameras && !!this._scene.activeCameras.length && this._scene.activeCameras.indexOf(camera2) !== 0;
    this._postProcessesSourceForThisPass = this._getPostProcessesSource(prePassRenderTarget, camera2);
    this._postProcessesSourceForThisPass = this._postProcessesSourceForThisPass.filter((pp) => {
      return pp != null;
    });
    this._scene.autoClear = true;
    const cameraHasImageProcessing = this._hasImageProcessing(this._postProcessesSourceForThisPass);
    this._needsCompositionForThisPass = !cameraHasImageProcessing && !this.disableGammaTransform && this._needsImageProcessing() && !secondaryCamera;
    const firstCameraPP = this._getFirstPostProcess(this._postProcessesSourceForThisPass);
    const firstPrePassPP = prePassRenderTarget._beforeCompositionPostProcesses && prePassRenderTarget._beforeCompositionPostProcesses[0];
    let firstPP = null;
    this._scene.imageProcessingConfiguration.applyByPostProcess = this._needsCompositionForThisPass || cameraHasImageProcessing;
    if (this._needsCompositionForThisPass && !prePassRenderTarget.imageProcessingPostProcess) {
      prePassRenderTarget._createCompositionEffect();
    }
    if (firstPrePassPP) {
      firstPP = firstPrePassPP;
    } else if (this._needsCompositionForThisPass) {
      firstPP = prePassRenderTarget.imageProcessingPostProcess;
    } else if (firstCameraPP) {
      firstPP = firstCameraPP;
    }
    this._bindFrameBuffer();
    this._linkInternalTexture(prePassRenderTarget, firstPP);
  }
  _linkInternalTexture(prePassRenderTarget, postProcess2) {
    if (postProcess2) {
      postProcess2.autoClear = false;
      postProcess2.inputTexture = prePassRenderTarget.renderTarget;
    }
    if (prePassRenderTarget._outputPostProcess !== postProcess2) {
      if (prePassRenderTarget._outputPostProcess) {
        this._unlinkInternalTexture(prePassRenderTarget);
      }
      prePassRenderTarget._outputPostProcess = postProcess2;
    }
    if (prePassRenderTarget._internalTextureDirty) {
      this._updateGeometryBufferLayout();
      prePassRenderTarget._internalTextureDirty = false;
    }
  }
  _unlinkInternalTexture(prePassRenderTarget) {
    if (prePassRenderTarget._outputPostProcess) {
      prePassRenderTarget._outputPostProcess.autoClear = true;
      prePassRenderTarget._outputPostProcess.restoreDefaultInputTexture();
      prePassRenderTarget._outputPostProcess = null;
    }
  }
  _needsImageProcessing() {
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      if (this._effectConfigurations[i].enabled && this._effectConfigurations[i].needsImageProcessing) {
        return true;
      }
    }
    return false;
  }
  _hasImageProcessing(postProcesses) {
    let isIPPAlreadyPresent = false;
    if (postProcesses) {
      for (let i = 0;i < postProcesses.length; i++) {
        if (postProcesses[i]?.getClassName() === "ImageProcessingPostProcess") {
          isIPPAlreadyPresent = true;
          break;
        }
      }
    }
    return isIPPAlreadyPresent;
  }
  _getFirstPostProcess(postProcesses) {
    for (let ppIndex = 0;ppIndex < postProcesses.length; ppIndex++) {
      if (postProcesses[ppIndex] !== null) {
        return postProcesses[ppIndex];
      }
    }
    return null;
  }
  markAsDirty() {
    this._isDirty = true;
  }
  _enableTextures(types) {
    this._scene.needsPreviousWorldMatrices = false;
    for (let i = 0;i < types.length; i++) {
      const type = types[i];
      if (this._textureIndices[type] === -1) {
        this._textureIndices[type] = this._mrtLayout.length;
        this._mrtLayout.push(type);
        this._mrtTypes.push(PrePassRenderer.TextureFormats[type].type);
        this._mrtFormats.push(PrePassRenderer.TextureFormats[type].format);
        this._mrtNames.push(PrePassRenderer.TextureFormats[type].name);
        this.mrtCount++;
      }
      if (type === 2 || type === 11) {
        this._scene.needsPreviousWorldMatrices = true;
      }
    }
  }
  update() {
    if (this._isDirty) {
      this._update();
    }
  }
  _update() {
    this._disable();
    let enablePrePass = false;
    this._scene.imageProcessingConfiguration.applyByPostProcess = false;
    if (this._scene._depthPeelingRenderer && this._scene.useOrderIndependentTransparency) {
      this._scene._depthPeelingRenderer.setPrePassRenderer(this);
      enablePrePass = true;
    }
    for (let i = 0;i < this._scene.materials.length; i++) {
      if (this._scene.materials[i].setPrePassRenderer(this)) {
        enablePrePass = true;
      }
    }
    if (enablePrePass) {
      this._setRenderTargetEnabled(this.defaultRT, true);
    }
    let postProcesses;
    for (let i = 0;i < this.renderTargets.length; i++) {
      if (this.renderTargets[i].renderTargetTexture) {
        postProcesses = this._getPostProcessesSource(this.renderTargets[i]);
      } else {
        const camera2 = this._scene.activeCamera;
        if (!camera2) {
          continue;
        }
        postProcesses = camera2._postProcesses;
      }
      if (!postProcesses) {
        continue;
      }
      postProcesses = postProcesses.filter((pp) => {
        return pp != null;
      });
      if (postProcesses) {
        for (let j = 0;j < postProcesses.length; j++) {
          if (postProcesses[j].setPrePassRenderer(this)) {
            this._setRenderTargetEnabled(this.renderTargets[i], true);
            enablePrePass = true;
          }
        }
        if (this._hasImageProcessing(postProcesses)) {
          this._scene.imageProcessingConfiguration.applyByPostProcess = true;
        }
      }
    }
    this._markAllMaterialsAsPrePassDirty();
    this._isDirty = false;
    if (enablePrePass) {
      this._enable();
    }
  }
  _markAllMaterialsAsPrePassDirty() {
    const materials = this._scene.materials;
    for (let i = 0;i < materials.length; i++) {
      materials[i].markAsDirty(Material.PrePassDirtyFlag);
    }
  }
  dispose() {
    for (let i = this.renderTargets.length - 1;i >= 0; i--) {
      this.renderTargets[i].dispose();
    }
    for (let i = 0;i < this._effectConfigurations.length; i++) {
      if (this._effectConfigurations[i].dispose) {
        this._effectConfigurations[i].dispose();
      }
    }
  }
}
PrePassRenderer._SceneComponentInitialization = (_) => {
  throw _WarnImport("PrePassRendererSceneComponent");
};
PrePassRenderer.TextureFormats = [
  {
    purpose: 0,
    type: 2,
    format: 5,
    name: "prePass_Irradiance"
  },
  {
    purpose: 1,
    type: 2,
    format: 5,
    name: "prePass_Position"
  },
  {
    purpose: 2,
    type: 0,
    format: 5,
    name: "prePass_Velocity"
  },
  {
    purpose: 3,
    type: 0,
    format: 5,
    name: "prePass_Reflectivity"
  },
  {
    purpose: 4,
    type: 2,
    format: 5,
    name: "prePass_Color"
  },
  {
    purpose: 5,
    type: 1,
    format: 6,
    name: "prePass_Depth"
  },
  {
    purpose: 6,
    type: 2,
    format: 5,
    name: "prePass_Normal"
  },
  {
    purpose: 7,
    type: 0,
    format: 5,
    name: "prePass_Albedo"
  },
  {
    purpose: 8,
    type: 0,
    format: 5,
    name: "prePass_WorldNormal"
  },
  {
    purpose: 9,
    type: 2,
    format: 5,
    name: "prePass_LocalPosition"
  },
  {
    purpose: 10,
    type: 1,
    format: 6,
    name: "prePass_ScreenDepth"
  },
  {
    purpose: 11,
    type: 2,
    format: 5,
    name: "prePass_VelocityLinear"
  }
];
// node_modules/@babylonjs/core/Rendering/prePassRendererSceneComponent.js
init_scene();
init_sceneComponent();
init_logger();
Object.defineProperty(Scene.prototype, "prePassRenderer", {
  get: function() {
    return this._prePassRenderer;
  },
  set: function(value) {
    if (value && value.isSupported) {
      this._prePassRenderer = value;
    }
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.enablePrePassRenderer = function() {
  if (this._prePassRenderer) {
    return this._prePassRenderer;
  }
  this._prePassRenderer = new PrePassRenderer(this);
  if (!this._prePassRenderer.isSupported) {
    this._prePassRenderer = null;
    Logger.Error(`PrePassRenderer needs WebGL 2 support.
` + `Maybe you tried to use the following features that need the PrePassRenderer :
` + " + Subsurface Scattering");
  }
  return this._prePassRenderer;
};
Scene.prototype.disablePrePassRenderer = function() {
  if (!this._prePassRenderer) {
    return;
  }
  this._prePassRenderer.dispose();
  this._prePassRenderer = null;
};

class PrePassRendererSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_PREPASSRENDERER;
    this.scene = scene;
  }
  register() {
    this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS, this, this._beforeCameraDraw);
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterCameraDraw);
    this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS, this, this._beforeRenderTargetDraw);
    this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterRenderTargetDraw);
    this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PREPASS, this, this._beforeClearStage);
    this.scene._beforeRenderTargetClearStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS, this, this._beforeRenderTargetClearStage);
    this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS, this, this._beforeRenderingMeshStage);
    this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS, this, this._afterRenderingMeshStage);
  }
  _beforeRenderTargetDraw(renderTarget, faceIndex, layer2) {
    if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {
      this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);
      this.scene.prePassRenderer._beforeDraw(undefined, faceIndex, layer2);
    }
  }
  _afterRenderTargetDraw(renderTarget, faceIndex, layer2) {
    if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {
      this.scene.prePassRenderer._afterDraw(faceIndex, layer2);
    }
  }
  _beforeRenderTargetClearStage(renderTarget) {
    if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {
      if (!renderTarget._prePassRenderTarget) {
        renderTarget._prePassRenderTarget = this.scene.prePassRenderer._createRenderTarget(renderTarget.name + "_prePassRTT", renderTarget);
      }
      this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);
      this.scene.prePassRenderer._clear();
    }
  }
  _beforeCameraDraw(camera2) {
    if (this.scene.prePassRenderer) {
      this.scene.prePassRenderer._setRenderTarget(null);
      this.scene.prePassRenderer._beforeDraw(camera2);
    }
  }
  _afterCameraDraw() {
    if (this.scene.prePassRenderer) {
      this.scene.prePassRenderer._afterDraw();
    }
  }
  _beforeClearStage() {
    if (this.scene.prePassRenderer) {
      this.scene.prePassRenderer._setRenderTarget(null);
      this.scene.prePassRenderer._clear();
    }
  }
  _beforeRenderingMeshStage(mesh2, subMesh2, batch, effect2) {
    if (!effect2) {
      return;
    }
    const scene = mesh2.getScene();
    if (scene.prePassRenderer) {
      scene.prePassRenderer.bindAttachmentsForEffect(effect2, subMesh2);
    }
  }
  _afterRenderingMeshStage(mesh2) {
    const scene = mesh2.getScene();
    if (scene.prePassRenderer) {
      scene.prePassRenderer.restoreAttachments();
    }
  }
  rebuild() {}
  dispose() {
    this.scene.disablePrePassRenderer();
  }
}
PrePassRenderer._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_PREPASSRENDERER);
  if (!component) {
    component = new PrePassRendererSceneComponent(scene);
    scene._addComponent(component);
  }
};
// node_modules/@babylonjs/core/Rendering/subSurfaceSceneComponent.js
init_scene();
init_sceneComponent();

// node_modules/@babylonjs/core/Rendering/subSurfaceConfiguration.js
init_logger();
init_math_color();

// node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js
init_texture();
init_postProcess();
init_logger();
init_imageProcessing_fragment2();

// node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js
init_shaderStore();
init_helperFunctions2();

// node_modules/@babylonjs/core/Shaders/ShadersInclude/fibonacci.js
init_shaderStore();
var name461 = "fibonacci";
var shader460 = `#define rcp(x) 1./x
#define GOLDEN_RATIO 1.618033988749895
vec2 Golden2dSeq(int i,float n)
{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}
vec2 SampleDiskGolden(int i,int sampleCount)
{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;
if (!ShaderStore.IncludesShadersStore[name461]) {
  ShaderStore.IncludesShadersStore[name461] = shader460;
}

// node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js
init_subSurfaceScatteringFunctions2();

// node_modules/@babylonjs/core/Shaders/ShadersInclude/diffusionProfile.js
init_shaderStore();
var name462 = "diffusionProfile";
var shader461 = `uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];`;
if (!ShaderStore.IncludesShadersStore[name462]) {
  ShaderStore.IncludesShadersStore[name462] = shader461;
}

// node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js
var name463 = "subSurfaceScatteringPixelShader";
var shader462 = `#include<helperFunctions>
#include<fibonacci>
#include<subSurfaceScatteringFunctions>
#include<diffusionProfile>
varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;
#define rcp(x) 1./x
#define Sq(x) x*x
#define SSS_BILATERAL_FILTER true
vec3 EvalBurleyDiffusionProfile(float r,vec3 S)
{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); 
vec3 expSum=exp_13*(1.+exp_13*exp_13); 
return (S*rcp((8.*PI)))*expSum; }
vec2 SampleBurleyDiffusionProfile(float u,float rcpS)
{u=1.-u; 
float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); 
float p=(g*n)*n; 
float c=1.+p+n; 
float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); 
float x=(3./LOG2_E)*log2(c)-d; 
float rcpExp=((c*c)*c)*rcp(((4.*u)*((c*c)+(4.*u)*(4.*u))));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; 
return vec2(r,rcpPdf);}
vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)
{
#ifndef SSS_BILATERAL_FILTER
z=0.;
#endif
float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;
#if SSS_CLAMP_ARTIFACT
return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);
#else
return EvalBurleyDiffusionProfile(r,S)*area;
#endif
}
void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,
float phase,inout vec3 totalIrradiance,inout vec3 totalWeight)
{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; 
float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; 
vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; 
float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))
{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}
else
{}}
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) 
{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)
{centerDepth=texture2D(depthSampler,vUV).r;}
if (!passedStencilTest) { 
gl_FragColor=inputColor;return;}
float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; 
vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; 
float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)
{
#ifdef DEBUG_SSS_SAMPLES
vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;
#endif
gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}
#ifdef DEBUG_SSS_SAMPLES
vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;
#endif
float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); 
vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++)
{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm,
phase,totalIrradiance,totalWeight);}
totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;
if (!ShaderStore.ShadersStore[name463]) {
  ShaderStore.ShadersStore[name463] = shader462;
}

// node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js
init_postprocess_vertex();
init_imageProcessing_fragment();

// node_modules/@babylonjs/core/ShadersWGSL/subSurfaceScattering.fragment.js
init_shaderStore();
init_helperFunctions();

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fibonacci.js
init_shaderStore();
var name464 = "fibonacci";
var shader463 = `fn rcp(x: f32)->f32
{return 1./x;}
const GOLDEN_RATIO=1.618033988749895;fn Golden2dSeq(i: u32,n: f32)->vec2f
{return vec2f(f32(i)/n+(0.5/n),fract(f32(i)*rcp(GOLDEN_RATIO)));}
fn SampleDiskGolden(i: u32,sampleCount: u32)->vec2f
{let f=Golden2dSeq(i,f32(sampleCount));return vec2f(sqrt(f.x),TWO_PI*f.y);}
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name464]) {
  ShaderStore.IncludesShadersStoreWGSL[name464] = shader463;
}

// node_modules/@babylonjs/core/ShadersWGSL/subSurfaceScattering.fragment.js
init_subSurfaceScatteringFunctions();

// node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/diffusionProfile.js
init_shaderStore();
var name465 = "diffusionProfile";
var shader464 = `uniform diffusionS: array<vec3f,5>;uniform diffusionD: array<f32,5>;uniform filterRadii: array<f32,5>;
`;
if (!ShaderStore.IncludesShadersStoreWGSL[name465]) {
  ShaderStore.IncludesShadersStoreWGSL[name465] = shader464;
}

// node_modules/@babylonjs/core/ShadersWGSL/subSurfaceScattering.fragment.js
var name466 = "subSurfaceScatteringPixelShader";
var shader465 = `#include<helperFunctions>
#include<fibonacci>
#include<subSurfaceScatteringFunctions>
#include<diffusionProfile>
varying vUV: vec2f;uniform texelSize: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;var irradianceSamplerSampler: sampler;var irradianceSampler: texture_2d<f32>;var depthSamplerSampler: sampler;var depthSampler: texture_2d<f32>;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d<f32>;uniform viewportSize: vec2f;uniform metersPerUnit: f32;const LOG2_E=1.4426950408889634;const SSS_PIXELS_PER_SAMPLE=4.;const _SssSampleBudget=40u;
#define SSS_BILATERAL_FILTER true
fn EvalBurleyDiffusionProfile(r: f32,S: vec3f)->vec3f
{let exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); 
let expSum=exp_13*(1.+exp_13*exp_13); 
return (S*rcp(8.*PI))*expSum; }
fn SampleBurleyDiffusionProfile(u_: f32,rcpS: f32)->vec2f
{let u=1.-u_; 
let g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));let n=exp2(log2(g)*(-1.0/3.0)); 
let p=(g*n)*n; 
let c=1.+p+n; 
let d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); 
let x=(3./LOG2_E)*log2(c)-d; 
let rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));let r=x*rcpS;let rcpPdf=(8.*PI*rcpS)*rcpExp; 
return vec2f(r,rcpPdf);}
fn ComputeBilateralWeight(xy2: f32,z_: f32,mmPerUnit: f32,S: vec3f,rcpPdf: f32)->vec3f
{
#ifndef SSS_BILATERAL_FILTER
let z=0.;
#else
let z=z_;
#endif
let r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));let area=rcpPdf;
#ifdef SSS_CLAMP_ARTIFACT
return clamp(EvalBurleyDiffusionProfile(r,S)*area,vec3f(0.0),vec3f(1.0));
#else
return EvalBurleyDiffusionProfile(r,S)*area;
#endif
}
fn EvaluateSample(i: u32,n: u32,S: vec3f,d: f32,centerPosVS: vec3f,mmPerUnit: f32,pixelsPerMm: f32,
phase: f32,totalIrradiance: ptr<function,vec3f>,totalWeight: ptr<function,vec3f>)
{let scale =rcp(f32(n));let offset=rcp(f32(n))*0.5;let sinPhase=sin(phase);let cosPhase=cos(phase);let bdp=SampleBurleyDiffusionProfile(f32(i)*scale+offset,d);let r=bdp.x;let rcpPdf=bdp.y;let phi=SampleDiskGolden(i,n).y;let sinPhi=sin(phi);let cosPhi=cos(phi);let sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; 
let cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; 
let vec=r*vec2f(cosPsi,sinPsi);let position=fragmentInputs.vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*uniforms.texelSize;let xy2 =r*r;let textureRead=textureSampleLevel(irradianceSampler,irradianceSamplerSampler,position,0.);let viewZ=textureSampleLevel(depthSampler,depthSamplerSampler,position,0.).r;let irradiance =textureRead.rgb;if (testLightingForSSS(textureRead.a))
{let relZ=viewZ-centerPosVS.z;let weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);*totalIrradiance+=weight*irradiance;*totalWeight +=weight;}
else
{}}
#define CUSTOM_FRAGMENT_DEFINITIONS
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let irradianceAndDiffusionProfile =textureSampleLevel(irradianceSampler,irradianceSamplerSampler,fragmentInputs.vUV,0.);let centerIrradiance=irradianceAndDiffusionProfile.rgb;let diffusionProfileIndex=u32(round(irradianceAndDiffusionProfile.a*255.));var centerDepth =0.;let inputColor=textureSampleLevel(textureSampler,textureSamplerSampler,fragmentInputs.vUV,0.);let passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)
{centerDepth=textureSampleLevel(depthSampler,depthSamplerSampler,fragmentInputs.vUV,0.).r;}
if (!passedStencilTest) { 
fragmentOutputs.color=inputColor;return fragmentOutputs;}
let distScale =1.;let S =uniforms.diffusionS[diffusionProfileIndex];let d =uniforms.diffusionD[diffusionProfileIndex];let filterRadius=uniforms.filterRadii[diffusionProfileIndex];let centerPosNDC=fragmentInputs.vUV;let cornerPosNDC=fragmentInputs.vUV+0.5*uniforms.texelSize;let centerPosVS =vec3f(centerPosNDC*uniforms.viewportSize,1.0)*centerDepth; 
let cornerPosVS =vec3f(cornerPosNDC*uniforms.viewportSize,1.0)*centerDepth; 
let mmPerUnit =1000.*(uniforms.metersPerUnit*rcp(distScale));let unitsPerMm=rcp(mmPerUnit);let unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);let pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;let filterArea =PI*square(filterRadius*pixelsPerMm);let sampleCount =u32(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));let sampleBudget=_SssSampleBudget;let albedo =textureSampleLevel(albedoSampler,albedoSamplerSampler,fragmentInputs.vUV,0.).rgb;if (distScale==0. || sampleCount<1)
{
#ifdef DEBUG_SSS_SAMPLES
let green=vec3f(0.,1.,0.);fragmentOutputs.color=vec4f(green,1.0);return fragmentOutputs;
#endif
fragmentOutputs.color=vec4f(inputColor.rgb+albedo*centerIrradiance,1.0);return fragmentOutputs;}
#ifdef DEBUG_SSS_SAMPLES
let red =vec3f(1.,0.,0.);let blue=vec3f(0.,0.,1.);fragmentOutputs.color=vec4f(mix(blue,red,clamp(f32(sampleCount)/f32(sampleBudget),0.0,1.0)),1.0);return fragmentOutputs;
#endif
let phase=0.;let n=min(sampleCount,sampleBudget);var totalIrradiance=vec3f(0.);var totalWeight =vec3f(0.);for (var i=0u; i<n; i++)
{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm,
phase,&totalIrradiance,&totalWeight);}
totalWeight=max(totalWeight,vec3f(HALF_MIN));fragmentOutputs.color=vec4f(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3f(0.0)),1.);}
`;
if (!ShaderStore.ShadersStoreWGSL[name466]) {
  ShaderStore.ShadersStoreWGSL[name466] = shader465;
}

// node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js
init_postprocess_vertex2();

class SubSurfaceScatteringPostProcess extends PostProcess {
  getClassName() {
    return "SubSurfaceScatteringPostProcess";
  }
  constructor(name467, scene, options, camera2 = null, samplingMode, engine2, reusable, textureType = 0) {
    const localOptions = {
      uniforms: ["texelSize", "viewportSize", "metersPerUnit"],
      samplers: ["diffusionS", "diffusionD", "filterRadii", "irradianceSampler", "depthSampler", "albedoSampler"],
      size: typeof options === "number" ? options : undefined,
      camera: camera2,
      samplingMode,
      engine: engine2,
      reusable,
      textureType,
      ...options,
      blockCompilation: true
    };
    super(name467, "subSurfaceScattering", { ...localOptions, samplingMode: samplingMode || Texture.BILINEAR_SAMPLINGMODE });
    this._scene = scene;
    this.updateEffect();
    this.onApplyObservable.add((effect2) => {
      if (!scene.prePassRenderer || !scene.subSurfaceConfiguration) {
        Logger.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");
        return;
      }
      const texelSize = this.texelSize;
      effect2.setFloat("metersPerUnit", scene.subSurfaceConfiguration.metersPerUnit);
      effect2.setFloat2("texelSize", texelSize.x, texelSize.y);
      effect2.setTexture("irradianceSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(0)]);
      effect2.setTexture("depthSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(5)]);
      effect2.setTexture("albedoSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(7)]);
      effect2.setFloat2("viewportSize", Math.tan(scene.activeCamera.fov / 2) * scene.getEngine().getAspectRatio(scene.activeCamera, true), Math.tan(scene.activeCamera.fov / 2));
      effect2.setArray3("diffusionS", scene.subSurfaceConfiguration.ssDiffusionS);
      effect2.setArray("diffusionD", scene.subSurfaceConfiguration.ssDiffusionD);
      effect2.setArray("filterRadii", scene.subSurfaceConfiguration.ssFilterRadii);
    });
  }
}

// node_modules/@babylonjs/core/Rendering/subSurfaceConfiguration.js
init_sceneComponent();
init_devTools();

class SubSurfaceConfiguration {
  get ssDiffusionS() {
    return this._ssDiffusionS;
  }
  get ssDiffusionD() {
    return this._ssDiffusionD;
  }
  get ssFilterRadii() {
    return this._ssFilterRadii;
  }
  constructor(scene) {
    this._ssDiffusionS = [];
    this._ssFilterRadii = [];
    this._ssDiffusionD = [];
    this.enabled = false;
    this.needsImageProcessing = true;
    this.name = SceneComponentConstants.NAME_SUBSURFACE;
    this.ssDiffusionProfileColors = [];
    this.metersPerUnit = 1;
    this.texturesRequired = [
      5,
      7,
      4,
      0
    ];
    this.addDiffusionProfile(new Color3(1, 1, 1));
    this._scene = scene;
    SubSurfaceConfiguration._SceneComponentInitialization(this._scene);
  }
  addDiffusionProfile(color) {
    if (this.ssDiffusionD.length >= 5) {
      Logger.Error("You already reached the maximum number of diffusion profiles.");
      return 0;
    }
    for (let i = 0;i < this._ssDiffusionS.length / 3; i++) {
      if (this._ssDiffusionS[i * 3] === color.r && this._ssDiffusionS[i * 3 + 1] === color.g && this._ssDiffusionS[i * 3 + 2] === color.b) {
        return i;
      }
    }
    this._ssDiffusionS.push(color.r, color.b, color.g);
    this._ssDiffusionD.push(Math.max(Math.max(color.r, color.b), color.g));
    this._ssFilterRadii.push(this.getDiffusionProfileParameters(color));
    this.ssDiffusionProfileColors.push(color);
    return this._ssDiffusionD.length - 1;
  }
  createPostProcess() {
    this.postProcess = new SubSurfaceScatteringPostProcess("subSurfaceScattering", this._scene, {
      size: 1,
      engine: this._scene.getEngine(),
      shaderLanguage: this._scene.getEngine().isWebGPU ? 1 : 0
    });
    this.postProcess.autoClear = false;
    return this.postProcess;
  }
  clearAllDiffusionProfiles() {
    this._ssDiffusionD = [];
    this._ssDiffusionS = [];
    this._ssFilterRadii = [];
    this.ssDiffusionProfileColors = [];
  }
  dispose() {
    this.clearAllDiffusionProfiles();
    if (this.postProcess) {
      this.postProcess.dispose();
    }
  }
  getDiffusionProfileParameters(color) {
    const cdf = 0.997;
    const maxScatteringDistance = Math.max(color.r, color.g, color.b);
    return this._sampleBurleyDiffusionProfile(cdf, maxScatteringDistance);
  }
  _sampleBurleyDiffusionProfile(u, rcpS) {
    u = 1 - u;
    const g = 1 + 4 * u * (2 * u + Math.sqrt(1 + 4 * u * u));
    const n = Math.pow(g, -1 / 3);
    const p = g * n * n;
    const c = 1 + p + n;
    const x = 3 * Math.log(c / (4 * u));
    return x * rcpS;
  }
}
SubSurfaceConfiguration._SceneComponentInitialization = (_) => {
  throw _WarnImport("SubSurfaceSceneComponent");
};

// node_modules/@babylonjs/core/Rendering/subSurfaceSceneComponent.js
init_math_color();
AddParser(SceneComponentConstants.NAME_SUBSURFACE, (parsedData, scene) => {
  if (parsedData.ssDiffusionProfileColors !== undefined && parsedData.ssDiffusionProfileColors !== null) {
    scene.enableSubSurfaceForPrePass();
    if (scene.subSurfaceConfiguration) {
      for (let index = 0, cache = parsedData.ssDiffusionProfileColors.length;index < cache; index++) {
        const color = parsedData.ssDiffusionProfileColors[index];
        scene.subSurfaceConfiguration.addDiffusionProfile(new Color3(color.r, color.g, color.b));
      }
    }
  }
});
Object.defineProperty(Scene.prototype, "subSurfaceConfiguration", {
  get: function() {
    return this._subSurfaceConfiguration;
  },
  set: function(value) {
    if (value) {
      if (this.enablePrePassRenderer()) {
        this._subSurfaceConfiguration = value;
      }
    }
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.enableSubSurfaceForPrePass = function() {
  if (this._subSurfaceConfiguration) {
    return this._subSurfaceConfiguration;
  }
  const prePassRenderer = this.enablePrePassRenderer();
  if (prePassRenderer) {
    this._subSurfaceConfiguration = new SubSurfaceConfiguration(this);
    prePassRenderer.addEffectConfiguration(this._subSurfaceConfiguration);
    return this._subSurfaceConfiguration;
  }
  return null;
};
Scene.prototype.disableSubSurfaceForPrePass = function() {
  if (!this._subSurfaceConfiguration) {
    return;
  }
  this._subSurfaceConfiguration.dispose();
  this._subSurfaceConfiguration = null;
};

class SubSurfaceSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_PREPASSRENDERER;
    this.scene = scene;
  }
  register() {}
  serialize(serializationObject) {
    if (!this.scene.subSurfaceConfiguration) {
      return;
    }
    const ssDiffusionProfileColors = this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;
    serializationObject.ssDiffusionProfileColors = [];
    for (let i = 0;i < ssDiffusionProfileColors.length; i++) {
      serializationObject.ssDiffusionProfileColors.push({
        r: ssDiffusionProfileColors[i].r,
        g: ssDiffusionProfileColors[i].g,
        b: ssDiffusionProfileColors[i].b
      });
    }
  }
  addFromContainer() {}
  removeFromContainer() {
    if (!this.scene.prePassRenderer) {
      return;
    }
    if (this.scene.subSurfaceConfiguration) {
      this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles();
    }
  }
  rebuild() {}
  dispose() {}
}
SubSurfaceConfiguration._SceneComponentInitialization = (scene) => {
  let component = scene._getComponent(SceneComponentConstants.NAME_SUBSURFACE);
  if (!component) {
    component = new SubSurfaceSceneComponent(scene);
    scene._addComponent(component);
  }
};
// node_modules/@babylonjs/core/Rendering/outlineRenderer.js
init_buffer();
init_scene();
init_sceneComponent();
init_drawWrapper();
init_materialHelper_functions();
Scene.prototype.getOutlineRenderer = function() {
  if (!this._outlineRenderer) {
    this._outlineRenderer = new OutlineRenderer(this);
  }
  return this._outlineRenderer;
};
Object.defineProperty(Mesh.prototype, "renderOutline", {
  get: function() {
    return this._renderOutline;
  },
  set: function(value) {
    if (value) {
      this.getScene().getOutlineRenderer();
    }
    this._renderOutline = value;
  },
  enumerable: true,
  configurable: true
});
Object.defineProperty(Mesh.prototype, "renderOverlay", {
  get: function() {
    return this._renderOverlay;
  },
  set: function(value) {
    if (value) {
      this.getScene().getOutlineRenderer();
    }
    this._renderOverlay = value;
  },
  enumerable: true,
  configurable: true
});

class OutlineRenderer {
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_OUTLINERENDERER;
    this.zOffset = 1;
    this.zOffsetUnits = 4;
    this._shaderLanguage = 0;
    this.scene = scene;
    this._engine = scene.getEngine();
    this.scene._addComponent(this);
    this._passIdForDrawWrapper = [];
    for (let i = 0;i < 4; ++i) {
      this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`);
    }
    const engine2 = this._engine;
    if (engine2.isWebGPU) {
      this._shaderLanguage = 1;
    }
  }
  register() {
    this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
    this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  }
  rebuild() {}
  dispose() {
    for (let i = 0;i < this._passIdForDrawWrapper.length; ++i) {
      this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]);
    }
  }
  render(subMesh2, batch, useOverlay = false, renderPassId) {
    renderPassId = renderPassId ?? this._passIdForDrawWrapper[0];
    const scene = this.scene;
    const engine2 = scene.getEngine();
    const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh2._id] !== null && batch.visibleInstances[subMesh2._id] !== undefined || subMesh2.getRenderingMesh().hasThinInstances);
    if (!this.isReady(subMesh2, hardwareInstancedRendering, renderPassId)) {
      return;
    }
    const ownerMesh = subMesh2.getMesh();
    const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;
    const renderingMesh = subMesh2.getRenderingMesh();
    const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;
    const material2 = subMesh2.getMaterial();
    if (!material2 || !scene.activeCamera) {
      return;
    }
    const drawWrapper2 = subMesh2._getDrawWrapper(renderPassId);
    const effect2 = DrawWrapper.GetEffect(drawWrapper2);
    engine2.enableEffect(drawWrapper2);
    if (material2.useLogarithmicDepth) {
      effect2.setFloat("logarithmicDepthConstant", 2 / (Math.log(scene.activeCamera.maxZ + 1) / Math.LN2));
    }
    effect2.setFloat("offset", useOverlay ? 0 : renderingMesh.outlineWidth);
    effect2.setColor4("color", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material2.alpha);
    effect2.setMatrix("viewProjection", scene.getTransformMatrix());
    effect2.setMatrix("world", effectiveMesh.getWorldMatrix());
    BindBonesParameters(renderingMesh, effect2);
    BindMorphTargetParameters(renderingMesh, effect2);
    if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
      renderingMesh.morphTargetManager._bind(effect2);
    }
    if (!hardwareInstancedRendering) {
      renderingMesh._bind(subMesh2, effect2, material2.fillMode);
    }
    const bvaManager = subMesh2.getMesh().bakedVertexAnimationManager;
    if (bvaManager && bvaManager.isEnabled) {
      bvaManager.bind(effect2, hardwareInstancedRendering);
    }
    if (material2 && material2.needAlphaTestingForMesh(effectiveMesh)) {
      const alphaTexture = material2.getAlphaTestTexture();
      if (alphaTexture) {
        effect2.setTexture("diffuseSampler", alphaTexture);
        effect2.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
      }
    }
    bindClipPlane(effect2, material2, scene);
    engine2.setZOffset(-this.zOffset);
    engine2.setZOffsetUnits(-this.zOffsetUnits);
    renderingMesh._processRendering(effectiveMesh, subMesh2, effect2, material2.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => {
      effect2.setMatrix("world", world);
    });
    engine2.setZOffset(0);
    engine2.setZOffsetUnits(0);
  }
  isReady(subMesh2, useInstances, renderPassId) {
    renderPassId = renderPassId ?? this._passIdForDrawWrapper[0];
    const defines = [];
    const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];
    const mesh2 = subMesh2.getMesh();
    const material2 = subMesh2.getMaterial();
    if (!material2) {
      return false;
    }
    const scene = mesh2.getScene();
    let uv1 = false;
    let uv2 = false;
    const color = false;
    if (material2.needAlphaTestingForMesh(mesh2)) {
      defines.push("#define ALPHATEST");
      if (mesh2.isVerticesDataPresent(VertexBuffer.UVKind)) {
        attribs.push(VertexBuffer.UVKind);
        defines.push("#define UV1");
        uv1 = true;
      }
      if (mesh2.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
        attribs.push(VertexBuffer.UV2Kind);
        defines.push("#define UV2");
        uv2 = true;
      }
    }
    if (material2.useLogarithmicDepth) {
      defines.push("#define LOGARITHMICDEPTH");
    }
    prepareStringDefinesForClipPlanes(material2, scene, defines);
    const fallbacks = new EffectFallbacks;
    if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
      attribs.push(VertexBuffer.MatricesIndicesKind);
      attribs.push(VertexBuffer.MatricesWeightsKind);
      if (mesh2.numBoneInfluencers > 4) {
        attribs.push(VertexBuffer.MatricesIndicesExtraKind);
        attribs.push(VertexBuffer.MatricesWeightsExtraKind);
      }
      const skeleton2 = mesh2.skeleton;
      defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
      if (mesh2.numBoneInfluencers > 0) {
        fallbacks.addCPUSkinningFallback(0, mesh2);
      }
      if (skeleton2.isUsingTextureForMatrices) {
        defines.push("#define BONETEXTURE");
      } else {
        defines.push("#define BonesPerMesh " + (skeleton2.bones.length + 1));
      }
    } else {
      defines.push("#define NUM_BONE_INFLUENCERS 0");
    }
    const numMorphInfluencers = mesh2.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets(mesh2.morphTargetManager, defines, attribs, mesh2, true, true, false, uv1, uv2, color) : 0;
    if (useInstances) {
      defines.push("#define INSTANCES");
      PushAttributesForInstances(attribs);
      if (subMesh2.getRenderingMesh().hasThinInstances) {
        defines.push("#define THIN_INSTANCES");
      }
    }
    const bvaManager = mesh2.bakedVertexAnimationManager;
    if (bvaManager && bvaManager.isEnabled) {
      defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE");
      if (useInstances) {
        attribs.push("bakedVertexAnimationSettingsInstanced");
      }
    }
    const drawWrapper2 = subMesh2._getDrawWrapper(renderPassId, true);
    const cachedDefines = drawWrapper2.defines;
    const join6 = defines.join(`
`);
    if (cachedDefines !== join6) {
      const uniforms2 = [
        "world",
        "mBones",
        "viewProjection",
        "diffuseMatrix",
        "offset",
        "color",
        "logarithmicDepthConstant",
        "morphTargetInfluences",
        "boneTextureWidth",
        "morphTargetCount",
        "morphTargetTextureInfo",
        "morphTargetTextureIndices",
        "bakedVertexAnimationSettings",
        "bakedVertexAnimationTextureSizeInverted",
        "bakedVertexAnimationTime",
        "bakedVertexAnimationTexture"
      ];
      const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"];
      addClipPlaneUniforms(uniforms2);
      drawWrapper2.setEffect(this.scene.getEngine().createEffect("outline", {
        attributes: attribs,
        uniformsNames: uniforms2,
        uniformBuffersNames: [],
        samplers,
        defines: join6,
        fallbacks,
        onCompiled: null,
        onError: null,
        indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers },
        shaderLanguage: this._shaderLanguage,
        extraInitializationsAsync: async () => {
          if (this._shaderLanguage === 1) {
            await Promise.all([Promise.resolve().then(() => (init_outline_fragment(), exports_outline_fragment)), Promise.resolve().then(() => (init_outline_vertex(), exports_outline_vertex))]);
          } else {
            await Promise.all([Promise.resolve().then(() => (init_outline_fragment2(), exports_outline_fragment2)), Promise.resolve().then(() => (init_outline_vertex2(), exports_outline_vertex2))]);
          }
        }
      }, this.scene.getEngine()), join6);
    }
    return drawWrapper2.effect.isReady();
  }
  _beforeRenderingMesh(mesh2, subMesh2, batch) {
    this._savedDepthWrite = this._engine.getDepthWrite();
    if (mesh2.renderOutline) {
      const material2 = subMesh2.getMaterial();
      if (material2 && material2.needAlphaBlendingForMesh(mesh2)) {
        this._engine.cacheStencilState();
        this._engine.setDepthWrite(false);
        this._engine.setColorWrite(false);
        this._engine.setStencilBuffer(true);
        this._engine.setStencilOperationPass(7681);
        this._engine.setStencilFunction(519);
        this._engine.setStencilMask(OutlineRenderer._StencilReference);
        this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference);
        this._engine.stencilStateComposer.useStencilGlobalOnly = true;
        this.render(subMesh2, batch, true, this._passIdForDrawWrapper[1]);
        this._engine.setColorWrite(true);
        this._engine.setStencilFunction(517);
      }
      this._engine.setDepthWrite(false);
      this.render(subMesh2, batch, false, this._passIdForDrawWrapper[0]);
      this._engine.setDepthWrite(this._savedDepthWrite);
      if (material2 && material2.needAlphaBlendingForMesh(mesh2)) {
        this._engine.stencilStateComposer.useStencilGlobalOnly = false;
        this._engine.restoreStencilState();
      }
    }
  }
  _afterRenderingMesh(mesh2, subMesh2, batch) {
    if (mesh2.renderOverlay) {
      const currentMode = this._engine.getAlphaMode();
      const alphaBlendState = this._engine.alphaState.alphaBlend;
      this._engine.setAlphaMode(2);
      this.render(subMesh2, batch, true, this._passIdForDrawWrapper[3]);
      this._engine.setAlphaMode(currentMode);
      this._engine.setDepthWrite(this._savedDepthWrite);
      this._engine.alphaState.alphaBlend = alphaBlendState;
    }
    if (mesh2.renderOutline && this._savedDepthWrite) {
      this._engine.setDepthWrite(true);
      this._engine.setColorWrite(false);
      this.render(subMesh2, batch, false, this._passIdForDrawWrapper[2]);
      this._engine.setColorWrite(true);
    }
  }
}
OutlineRenderer._StencilReference = 4;

// node_modules/@babylonjs/core/Rendering/index.js
init_renderingGroup();
init_renderingManager();

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderer.js
init_scene();
init_sceneComponent();

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObject.js
init_effectRenderer();
init_observable();

class FluidRenderingObject {
  get particleSize() {
    return this._particleSize;
  }
  set particleSize(size) {
    if (size === this._particleSize) {
      return;
    }
    this._particleSize = size;
    this.onParticleSizeChanged.notifyObservers(this);
  }
  get useInstancing() {
    return !this.indexBuffer;
  }
  get useVelocity() {
    return this._useVelocity;
  }
  set useVelocity(use) {
    if (this._useVelocity === use || !this._hasVelocity()) {
      return;
    }
    this._useVelocity = use;
    this._effectsAreDirty = true;
  }
  _hasVelocity() {
    return !!this.vertexBuffers?.velocity;
  }
  get indexBuffer() {
    return null;
  }
  getClassName() {
    return "FluidRenderingObject";
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene, shaderLanguage2) {
    this.priority = 0;
    this._particleSize = 0.1;
    this.onParticleSizeChanged = new Observable;
    this.particleThicknessAlpha = 0.05;
    this._useVelocity = false;
    this._shaderLanguage = 0;
    this._scene = scene;
    this._engine = scene.getEngine();
    this._effectsAreDirty = true;
    this._depthEffectWrapper = null;
    this._thicknessEffectWrapper = null;
    this._shaderLanguage = shaderLanguage2 ?? (this._engine.isWebGPU ? 1 : 0);
  }
  _createEffects() {
    const uniformNames = ["view", "projection", "particleRadius", "size"];
    const attributeNames = ["position", "offset"];
    const defines = [];
    this._effectsAreDirty = false;
    if (this.useVelocity) {
      attributeNames.push("velocity");
      defines.push("#define FLUIDRENDERING_VELOCITY");
    }
    if (this._scene.useRightHandedSystem) {
      defines.push("#define FLUIDRENDERING_RHS");
    }
    this._depthEffectWrapper = new EffectWrapper({
      engine: this._engine,
      useShaderStore: true,
      vertexShader: "fluidRenderingParticleDepth",
      fragmentShader: "fluidRenderingParticleDepth",
      attributeNames,
      uniformNames,
      samplerNames: [],
      defines,
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_fluidRenderingParticleDepth_vertex(), exports_fluidRenderingParticleDepth_vertex)), Promise.resolve().then(() => (init_fluidRenderingParticleDepth_fragment(), exports_fluidRenderingParticleDepth_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_fluidRenderingParticleDepth_vertex2(), exports_fluidRenderingParticleDepth_vertex2)), Promise.resolve().then(() => (init_fluidRenderingParticleDepth_fragment2(), exports_fluidRenderingParticleDepth_fragment2))]);
        }
      }
    });
    uniformNames.push("particleAlpha");
    this._thicknessEffectWrapper = new EffectWrapper({
      engine: this._engine,
      useShaderStore: true,
      vertexShader: "fluidRenderingParticleThickness",
      fragmentShader: "fluidRenderingParticleThickness",
      attributeNames: ["position", "offset"],
      uniformNames,
      samplerNames: [],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.all([Promise.resolve().then(() => (init_fluidRenderingParticleThickness_vertex(), exports_fluidRenderingParticleThickness_vertex)), Promise.resolve().then(() => (init_fluidRenderingParticleThickness_fragment(), exports_fluidRenderingParticleThickness_fragment))]);
        } else {
          await Promise.all([Promise.resolve().then(() => (init_fluidRenderingParticleThickness_vertex2(), exports_fluidRenderingParticleThickness_vertex2)), Promise.resolve().then(() => (init_fluidRenderingParticleThickness_fragment2(), exports_fluidRenderingParticleThickness_fragment2))]);
        }
      }
    });
  }
  isReady() {
    if (this._effectsAreDirty) {
      this._createEffects();
    }
    if (!this._depthEffectWrapper || !this._thicknessEffectWrapper) {
      return false;
    }
    const depthEffect = this._depthEffectWrapper.drawWrapper.effect;
    const thicknessEffect = this._thicknessEffectWrapper.drawWrapper.effect;
    return depthEffect.isReady() && thicknessEffect.isReady();
  }
  renderDepthTexture() {
    const numParticles = this.numParticles;
    if (!this._depthEffectWrapper || numParticles === 0) {
      return;
    }
    const depthDrawWrapper = this._depthEffectWrapper.drawWrapper;
    const depthEffect = depthDrawWrapper.effect;
    this._engine.enableEffect(depthDrawWrapper);
    this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, depthEffect);
    depthEffect.setMatrix("view", this._scene.getViewMatrix());
    depthEffect.setMatrix("projection", this._scene.getProjectionMatrix());
    depthEffect.setFloat2("size", this._particleSize, this._particleSize);
    depthEffect.setFloat("particleRadius", this._particleSize / 2);
    if (this.useInstancing) {
      this._engine.drawArraysType(7, 0, 4, numParticles);
    } else {
      this._engine.drawElementsType(0, 0, numParticles);
    }
  }
  renderThicknessTexture() {
    const numParticles = this.numParticles;
    if (!this._thicknessEffectWrapper || numParticles === 0) {
      return;
    }
    const thicknessDrawWrapper = this._thicknessEffectWrapper.drawWrapper;
    const thicknessEffect = thicknessDrawWrapper.effect;
    this._engine.setAlphaMode(6);
    this._engine.setDepthWrite(false);
    this._engine.enableEffect(thicknessDrawWrapper);
    this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, thicknessEffect);
    thicknessEffect.setMatrix("view", this._scene.getViewMatrix());
    thicknessEffect.setMatrix("projection", this._scene.getProjectionMatrix());
    thicknessEffect.setFloat("particleAlpha", this.particleThicknessAlpha);
    thicknessEffect.setFloat2("size", this._particleSize, this._particleSize);
    if (this.useInstancing) {
      this._engine.drawArraysType(7, 0, 4, numParticles);
    } else {
      this._engine.drawElementsType(0, 0, numParticles);
    }
    this._engine.setDepthWrite(true);
    this._engine.setAlphaMode(0);
  }
  renderDiffuseTexture() {}
  dispose() {
    this._depthEffectWrapper?.dispose(false);
    this._thicknessEffectWrapper?.dispose(false);
    this.onParticleSizeChanged.clear();
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectParticleSystem.js
class FluidRenderingObjectParticleSystem extends FluidRenderingObject {
  get particleSystem() {
    return this._particleSystem;
  }
  getClassName() {
    return "FluidRenderingObjectParticleSystem";
  }
  get useTrueRenderingForDiffuseTexture() {
    return this._useTrueRenderingForDiffuseTexture;
  }
  set useTrueRenderingForDiffuseTexture(use) {
    if (this._useTrueRenderingForDiffuseTexture === use) {
      return;
    }
    this._useTrueRenderingForDiffuseTexture = use;
    if (use) {
      this._particleSystem.blendMode = this._blendMode;
      this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver);
      this._onBeforeDrawParticleObserver = null;
    } else {
      this._particleSystem.blendMode = -1;
      this._onBeforeDrawParticleObserver = this._particleSystem.onBeforeDrawParticlesObservable.add(() => {
        this._engine.setAlphaMode(2);
      });
    }
  }
  get vertexBuffers() {
    return this._particleSystem.vertexBuffers;
  }
  get indexBuffer() {
    return this._particleSystem.indexBuffer;
  }
  constructor(scene, ps, shaderLanguage2) {
    super(scene, shaderLanguage2);
    this._useTrueRenderingForDiffuseTexture = true;
    this._particleSystem = ps;
    this._originalRender = ps.render.bind(ps);
    this._blendMode = ps.blendMode;
    this._onBeforeDrawParticleObserver = null;
    this._updateInAnimate = this._particleSystem.updateInAnimate;
    this._particleSystem.updateInAnimate = true;
    this._particleSystem.render = () => 0;
    this.particleSize = (ps.minSize + ps.maxSize) / 2;
    this.useTrueRenderingForDiffuseTexture = false;
  }
  isReady() {
    return super.isReady() && this._particleSystem.isReady();
  }
  get numParticles() {
    return this._particleSystem.getActiveCount();
  }
  renderDiffuseTexture() {
    this._originalRender();
  }
  dispose() {
    super.dispose();
    this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver);
    this._onBeforeDrawParticleObserver = null;
    this._particleSystem.render = this._originalRender;
    this._particleSystem.blendMode = this._blendMode;
    this._particleSystem.updateInAnimate = this._updateInAnimate;
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTargetRenderer.js
init_math_color();
init_math_vector();
init_observable();
init_postProcess();

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTextures.js
init_texture();
init_math_vector();
init_postProcess();
init_observable();

class FluidRenderingTextures {
  get blurNumIterations() {
    return this._blurNumIterations;
  }
  set blurNumIterations(numIterations) {
    if (this._blurNumIterations === numIterations) {
      return;
    }
    this._blurNumIterations = numIterations;
    if (this._blurPostProcesses !== null) {
      const blurX = this._blurPostProcesses[0];
      const blurY = this._blurPostProcesses[1];
      this._blurPostProcesses = [];
      for (let i = 0;i < this._blurNumIterations * 2; ++i) {
        this._blurPostProcesses[i] = i & 1 ? blurY : blurX;
      }
    }
  }
  get renderTarget() {
    return this._rt;
  }
  get renderTargetBlur() {
    return this._rtBlur;
  }
  get texture() {
    return this._texture;
  }
  get textureBlur() {
    return this._textureBlurred;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(name483, scene, width, height, blurTextureSizeX, blurTextureSizeY, textureType = 1, textureFormat = 6, blurTextureType = 1, blurTextureFormat = 6, useStandardBlur = false, camera2 = null, generateDepthBuffer = true, samples = 1, shaderLanguage2) {
    this.enableBlur = true;
    this.blurSizeDivisor = 1;
    this.blurFilterSize = 7;
    this._blurNumIterations = 3;
    this.blurMaxFilterSize = 100;
    this.blurDepthScale = 10;
    this.particleSize = 0.02;
    this.onDisposeObservable = new Observable;
    this._shaderLanguage = 0;
    this._name = name483;
    this._scene = scene;
    this._camera = camera2;
    this._engine = scene.getEngine();
    this._width = width;
    this._height = height;
    this._blurTextureSizeX = blurTextureSizeX;
    this._blurTextureSizeY = blurTextureSizeY;
    this._textureType = textureType;
    this._textureFormat = textureFormat;
    this._blurTextureType = blurTextureType;
    this._blurTextureFormat = blurTextureFormat;
    this._useStandardBlur = useStandardBlur;
    this._generateDepthBuffer = generateDepthBuffer;
    this._samples = samples;
    this._postProcessRunningIndex = 0;
    this.enableBlur = blurTextureSizeX !== 0 && blurTextureSizeY !== 0;
    this._rt = null;
    this._texture = null;
    this._rtBlur = null;
    this._textureBlurred = null;
    this._blurPostProcesses = null;
    this._shaderLanguage = shaderLanguage2 ?? (this._engine.isWebGPU ? 1 : 0);
  }
  initialize() {
    this.dispose();
    this._createRenderTarget();
    if (this.enableBlur && this._texture) {
      const [rtBlur, textureBlurred, blurPostProcesses] = this._createBlurPostProcesses(this._texture, this._blurTextureType, this._blurTextureFormat, this.blurSizeDivisor, this._name, this._useStandardBlur);
      this._rtBlur = rtBlur;
      this._textureBlurred = textureBlurred;
      this._blurPostProcesses = blurPostProcesses;
    }
  }
  applyBlurPostProcesses() {
    if (this.enableBlur && this._blurPostProcesses) {
      this._postProcessRunningIndex = 0;
      this._scene.postProcessManager.directRender(this._blurPostProcesses, this._rtBlur, true);
      this._engine.unBindFramebuffer(this._rtBlur);
    }
  }
  _createRenderTarget() {
    this._rt = this._engine.createRenderTargetTexture({ width: this._width, height: this._height }, {
      generateMipMaps: false,
      type: this._textureType,
      format: this._textureFormat,
      samplingMode: 1,
      generateDepthBuffer: this._generateDepthBuffer,
      generateStencilBuffer: false,
      samples: this._samples,
      label: `FluidRenderingRTT-${this._name}`
    });
    const renderTexture = this._rt.texture;
    renderTexture.incrementReferences();
    this._texture = new Texture(null, this._scene);
    this._texture.name = "rtt" + this._name;
    this._texture._texture = renderTexture;
    this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;
    this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;
    this._texture.anisotropicFilteringLevel = 1;
  }
  _createBlurPostProcesses(textureBlurSource, textureType, textureFormat, blurSizeDivisor, debugName, useStandardBlur = false) {
    const engine2 = this._scene.getEngine();
    const targetSize = new Vector2(Math.floor(this._blurTextureSizeX / blurSizeDivisor), Math.floor(this._blurTextureSizeY / blurSizeDivisor));
    const useBilinearFiltering = textureType === 1 && engine2.getCaps().textureFloatLinearFiltering || textureType === 2 && engine2.getCaps().textureHalfFloatLinearFiltering;
    const rtBlur = this._engine.createRenderTargetTexture({ width: targetSize.x, height: targetSize.y }, {
      generateMipMaps: false,
      type: textureType,
      format: textureFormat,
      samplingMode: useBilinearFiltering ? 2 : 1,
      generateDepthBuffer: false,
      generateStencilBuffer: false,
      samples: this._samples,
      label: `FluidRenderingRTTBlur-${debugName}`
    });
    const renderTexture = rtBlur.texture;
    renderTexture.incrementReferences();
    const texture2 = new Texture(null, this._scene);
    texture2.name = "rttBlurred" + debugName;
    texture2._texture = renderTexture;
    texture2.wrapU = Texture.CLAMP_ADDRESSMODE;
    texture2.wrapV = Texture.CLAMP_ADDRESSMODE;
    texture2.anisotropicFilteringLevel = 1;
    if (useStandardBlur) {
      const kernelBlurXPostprocess = new PostProcess("BilateralBlurX", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine2, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => {
        if (this.shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_fluidRenderingStandardBlur_fragment(), exports_fluidRenderingStandardBlur_fragment));
        } else {
          await Promise.resolve().then(() => (init_fluidRenderingStandardBlur_fragment2(), exports_fluidRenderingStandardBlur_fragment2));
        }
      });
      kernelBlurXPostprocess.samples = this._samples;
      kernelBlurXPostprocess.externalTextureSamplerBinding = true;
      kernelBlurXPostprocess.onApplyObservable.add((effect2) => {
        if (this._postProcessRunningIndex === 0) {
          effect2.setTexture("textureSampler", textureBlurSource);
        } else {
          effect2._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture);
        }
        effect2.setInt("filterSize", this.blurFilterSize);
        effect2.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0);
        this._postProcessRunningIndex++;
      });
      kernelBlurXPostprocess.onSizeChangedObservable.add(() => {
        kernelBlurXPostprocess._textures.forEach((rt) => {
          rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
          rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
        });
      });
      this._fixReusablePostProcess(kernelBlurXPostprocess);
      const kernelBlurYPostprocess = new PostProcess("BilateralBlurY", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine2, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => {
        if (this.shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_fluidRenderingStandardBlur_fragment(), exports_fluidRenderingStandardBlur_fragment));
        } else {
          await Promise.resolve().then(() => (init_fluidRenderingStandardBlur_fragment2(), exports_fluidRenderingStandardBlur_fragment2));
        }
      });
      kernelBlurYPostprocess.samples = this._samples;
      kernelBlurYPostprocess.onApplyObservable.add((effect2) => {
        effect2.setInt("filterSize", this.blurFilterSize);
        effect2.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY);
        this._postProcessRunningIndex++;
      });
      kernelBlurYPostprocess.onSizeChangedObservable.add(() => {
        kernelBlurYPostprocess._textures.forEach((rt) => {
          rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
          rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
        });
      });
      this._fixReusablePostProcess(kernelBlurYPostprocess);
      kernelBlurXPostprocess.autoClear = false;
      kernelBlurYPostprocess.autoClear = false;
      const blurList = [];
      for (let i = 0;i < this._blurNumIterations * 2; ++i) {
        blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;
      }
      return [rtBlur, texture2, blurList];
    } else {
      const uniforms2 = ["maxFilterSize", "blurDir", "projectedParticleConstant", "depthThreshold"];
      const kernelBlurXPostprocess = new PostProcess("BilateralBlurX", "fluidRenderingBilateralBlur", uniforms2, null, 1, null, 1, engine2, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => {
        if (this.shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_fluidRenderingBilateralBlur_fragment(), exports_fluidRenderingBilateralBlur_fragment));
        } else {
          await Promise.resolve().then(() => (init_fluidRenderingBilateralBlur_fragment2(), exports_fluidRenderingBilateralBlur_fragment2));
        }
      });
      kernelBlurXPostprocess.samples = this._samples;
      kernelBlurXPostprocess.externalTextureSamplerBinding = true;
      kernelBlurXPostprocess.onApplyObservable.add((effect2) => {
        if (this._postProcessRunningIndex === 0) {
          effect2.setTexture("textureSampler", textureBlurSource);
        } else {
          effect2._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture);
        }
        effect2.setInt("maxFilterSize", this.blurMaxFilterSize);
        effect2.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0);
        effect2.setFloat("projectedParticleConstant", this._getProjectedParticleConstant());
        effect2.setFloat("depthThreshold", this._getDepthThreshold());
        this._postProcessRunningIndex++;
      });
      kernelBlurXPostprocess.onSizeChangedObservable.add(() => {
        kernelBlurXPostprocess._textures.forEach((rt) => {
          rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
          rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
        });
      });
      this._fixReusablePostProcess(kernelBlurXPostprocess);
      const kernelBlurYPostprocess = new PostProcess("BilateralBlurY", "fluidRenderingBilateralBlur", uniforms2, null, 1, null, 1, engine2, true, null, textureType, undefined, undefined, undefined, textureFormat, this._shaderLanguage, async () => {
        if (this.shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_fluidRenderingBilateralBlur_fragment(), exports_fluidRenderingBilateralBlur_fragment));
        } else {
          await Promise.resolve().then(() => (init_fluidRenderingBilateralBlur_fragment2(), exports_fluidRenderingBilateralBlur_fragment2));
        }
      });
      kernelBlurYPostprocess.samples = this._samples;
      kernelBlurYPostprocess.onApplyObservable.add((effect2) => {
        effect2.setInt("maxFilterSize", this.blurMaxFilterSize);
        effect2.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY);
        effect2.setFloat("projectedParticleConstant", this._getProjectedParticleConstant());
        effect2.setFloat("depthThreshold", this._getDepthThreshold());
        this._postProcessRunningIndex++;
      });
      kernelBlurYPostprocess.onSizeChangedObservable.add(() => {
        kernelBlurYPostprocess._textures.forEach((rt) => {
          rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
          rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
        });
      });
      this._fixReusablePostProcess(kernelBlurYPostprocess);
      kernelBlurXPostprocess.autoClear = false;
      kernelBlurYPostprocess.autoClear = false;
      const blurList = [];
      for (let i = 0;i < this._blurNumIterations * 2; ++i) {
        blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;
      }
      return [rtBlur, texture2, blurList];
    }
  }
  _fixReusablePostProcess(pp) {
    if (!pp.isReusable()) {
      return;
    }
    pp.onActivateObservable.add(() => {
      pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;
    });
    pp.onApplyObservable.add(() => {
      pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;
    });
  }
  _getProjectedParticleConstant() {
    return this.blurFilterSize * this.particleSize * 0.05 * (this._height / 2) / Math.tan((this._camera?.fov ?? 45 * Math.PI / 180) / 2);
  }
  _getDepthThreshold() {
    return this.particleSize / 2 * this.blurDepthScale;
  }
  dispose() {
    if (this.onDisposeObservable.hasObservers()) {
      this.onDisposeObservable.notifyObservers(this);
    }
    this.onDisposeObservable.clear();
    this._rt?.dispose();
    this._rt = null;
    this._texture?.dispose();
    this._texture = null;
    this._rtBlur?.dispose();
    this._rtBlur = null;
    this._textureBlurred?.dispose();
    this._textureBlurred = null;
    if (this._blurPostProcesses) {
      this._blurPostProcesses[0].dispose();
      this._blurPostProcesses[1].dispose();
    }
    this._blurPostProcesses = null;
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTargetRenderer.js
var FluidRenderingDebug;
(function(FluidRenderingDebug2) {
  FluidRenderingDebug2[FluidRenderingDebug2["DepthTexture"] = 0] = "DepthTexture";
  FluidRenderingDebug2[FluidRenderingDebug2["DepthBlurredTexture"] = 1] = "DepthBlurredTexture";
  FluidRenderingDebug2[FluidRenderingDebug2["ThicknessTexture"] = 2] = "ThicknessTexture";
  FluidRenderingDebug2[FluidRenderingDebug2["ThicknessBlurredTexture"] = 3] = "ThicknessBlurredTexture";
  FluidRenderingDebug2[FluidRenderingDebug2["DiffuseTexture"] = 4] = "DiffuseTexture";
  FluidRenderingDebug2[FluidRenderingDebug2["Normals"] = 5] = "Normals";
  FluidRenderingDebug2[FluidRenderingDebug2["DiffuseRendering"] = 6] = "DiffuseRendering";
})(FluidRenderingDebug || (FluidRenderingDebug = {}));

class FluidRenderingTargetRenderer {
  get needInitialization() {
    return this._needInitialization;
  }
  get generateDiffuseTexture() {
    return this._generateDiffuseTexture;
  }
  set generateDiffuseTexture(generate) {
    if (this._generateDiffuseTexture === generate) {
      return;
    }
    this._generateDiffuseTexture = generate;
    this._needInitialization = true;
  }
  get debugFeature() {
    return this._debugFeature;
  }
  set debugFeature(feature) {
    if (this._debugFeature === feature) {
      return;
    }
    this._needInitialization = true;
    this._debugFeature = feature;
  }
  get debug() {
    return this._debug;
  }
  set debug(debug) {
    if (this._debug === debug) {
      return;
    }
    this._debug = debug;
    this._needInitialization = true;
  }
  get environmentMap() {
    return this._environmentMap;
  }
  set environmentMap(map) {
    if (this._environmentMap === map) {
      return;
    }
    this._needInitialization = true;
    this._environmentMap = map;
  }
  get enableBlurDepth() {
    return this._enableBlurDepth;
  }
  set enableBlurDepth(enable) {
    if (this._enableBlurDepth === enable) {
      return;
    }
    this._enableBlurDepth = enable;
    this._needInitialization = true;
  }
  get blurDepthSizeDivisor() {
    return this._blurDepthSizeDivisor;
  }
  set blurDepthSizeDivisor(scale) {
    if (this._blurDepthSizeDivisor === scale) {
      return;
    }
    this._blurDepthSizeDivisor = scale;
    this._needInitialization = true;
  }
  get blurDepthFilterSize() {
    return this._blurDepthFilterSize;
  }
  set blurDepthFilterSize(filterSize) {
    if (this._blurDepthFilterSize === filterSize) {
      return;
    }
    this._blurDepthFilterSize = filterSize;
    this._setBlurParameters();
  }
  get blurDepthNumIterations() {
    return this._blurDepthNumIterations;
  }
  set blurDepthNumIterations(numIterations) {
    if (this._blurDepthNumIterations === numIterations) {
      return;
    }
    this._blurDepthNumIterations = numIterations;
    this._setBlurParameters();
  }
  get blurDepthMaxFilterSize() {
    return this._blurDepthMaxFilterSize;
  }
  set blurDepthMaxFilterSize(maxFilterSize) {
    if (this._blurDepthMaxFilterSize === maxFilterSize) {
      return;
    }
    this._blurDepthMaxFilterSize = maxFilterSize;
    this._setBlurParameters();
  }
  get blurDepthDepthScale() {
    return this._blurDepthDepthScale;
  }
  set blurDepthDepthScale(scale) {
    if (this._blurDepthDepthScale === scale) {
      return;
    }
    this._blurDepthDepthScale = scale;
    this._setBlurParameters();
  }
  get enableBlurThickness() {
    return this._enableBlurThickness;
  }
  set enableBlurThickness(enable) {
    if (this._enableBlurThickness === enable) {
      return;
    }
    this._enableBlurThickness = enable;
    this._needInitialization = true;
  }
  get blurThicknessSizeDivisor() {
    return this._blurThicknessSizeDivisor;
  }
  set blurThicknessSizeDivisor(scale) {
    if (this._blurThicknessSizeDivisor === scale) {
      return;
    }
    this._blurThicknessSizeDivisor = scale;
    this._needInitialization = true;
  }
  get blurThicknessFilterSize() {
    return this._blurThicknessFilterSize;
  }
  set blurThicknessFilterSize(filterSize) {
    if (this._blurThicknessFilterSize === filterSize) {
      return;
    }
    this._blurThicknessFilterSize = filterSize;
    this._setBlurParameters();
  }
  get blurThicknessNumIterations() {
    return this._blurThicknessNumIterations;
  }
  set blurThicknessNumIterations(numIterations) {
    if (this._blurThicknessNumIterations === numIterations) {
      return;
    }
    this._blurThicknessNumIterations = numIterations;
    this._setBlurParameters();
  }
  get useFixedThickness() {
    return this._useFixedThickness;
  }
  set useFixedThickness(use) {
    if (this._useFixedThickness === use) {
      return;
    }
    this._useFixedThickness = use;
    this._needInitialization = true;
  }
  get useVelocity() {
    return this._useVelocity;
  }
  set useVelocity(use) {
    if (this._useVelocity === use) {
      return;
    }
    this._useVelocity = use;
    this._needInitialization = true;
    this._onUseVelocityChanged.notifyObservers(this);
  }
  get depthMapSize() {
    return this._depthMapSize;
  }
  set depthMapSize(size) {
    if (this._depthMapSize === size) {
      return;
    }
    this._depthMapSize = size;
    this._needInitialization = true;
  }
  get thicknessMapSize() {
    return this._thicknessMapSize;
  }
  set thicknessMapSize(size) {
    if (this._thicknessMapSize === size) {
      return;
    }
    this._thicknessMapSize = size;
    this._needInitialization = true;
  }
  get diffuseMapSize() {
    return this._diffuseMapSize;
  }
  set diffuseMapSize(size) {
    if (this._diffuseMapSize === size) {
      return;
    }
    this._diffuseMapSize = size;
    this._needInitialization = true;
  }
  get samples() {
    return this._samples;
  }
  set samples(samples) {
    if (this._samples === samples) {
      return;
    }
    this._samples = samples;
    this._needInitialization = true;
  }
  get compositeMode() {
    return this._compositeMode;
  }
  set compositeMode(value) {
    if (this._compositeMode === value) {
      return;
    }
    this._compositeMode = value;
    this._needInitialization = true;
  }
  get camera() {
    return this._camera;
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene, camera2, shaderLanguage2) {
    this._generateDiffuseTexture = false;
    this.fluidColor = new Color3(0.085, 0.6375, 0.765);
    this.density = 2;
    this.refractionStrength = 0.1;
    this.fresnelClamp = 1;
    this.specularPower = 250;
    this.minimumThickness = 0;
    this.dirLight = new Vector3(-2, -1, 1).normalize();
    this._debugFeature = 1;
    this._debug = false;
    this._enableBlurDepth = true;
    this._blurDepthSizeDivisor = 1;
    this._blurDepthFilterSize = 7;
    this._blurDepthNumIterations = 3;
    this._blurDepthMaxFilterSize = 100;
    this._blurDepthDepthScale = 10;
    this._enableBlurThickness = true;
    this._blurThicknessSizeDivisor = 1;
    this._blurThicknessFilterSize = 5;
    this._blurThicknessNumIterations = 1;
    this._useFixedThickness = false;
    this._onUseVelocityChanged = new Observable;
    this._useVelocity = false;
    this._depthMapSize = null;
    this._thicknessMapSize = null;
    this._diffuseMapSize = null;
    this._samples = 1;
    this._compositeMode = false;
    this._shaderLanguage = 0;
    this._scene = scene;
    this._engine = scene.getEngine();
    this._camera = camera2 ?? scene.activeCamera;
    this._needInitialization = true;
    this._bgDepthTexture = null;
    this._invProjectionMatrix = new Matrix;
    this._depthClearColor = new Color4(1e6, 1e6, 1e6, 1);
    this._thicknessClearColor = new Color4(0, 0, 0, 1);
    this._depthRenderTarget = null;
    this._diffuseRenderTarget = null;
    this._thicknessRenderTarget = null;
    this._renderPostProcess = null;
    this._shaderLanguage = shaderLanguage2 ?? (this._engine.isWebGPU ? 1 : 0);
  }
  _initialize() {
    this.dispose();
    this._needInitialization = false;
    const depthWidth = this._depthMapSize ?? this._engine.getRenderWidth();
    const depthHeight = this._depthMapSize !== null ? Math.round(this._depthMapSize * this._engine.getRenderHeight() / this._engine.getRenderWidth()) : this._engine.getRenderHeight();
    this._depthRenderTarget = new FluidRenderingTextures("Depth", this._scene, depthWidth, depthHeight, depthWidth, depthHeight, 1, 7, 1, 7, false, this._camera, true, this._samples, this._shaderLanguage);
    this._initializeRenderTarget(this._depthRenderTarget);
    if (this.generateDiffuseTexture) {
      const diffuseWidth = this._diffuseMapSize ?? this._engine.getRenderWidth();
      const diffuseHeight = this._diffuseMapSize !== null ? Math.round(this._diffuseMapSize * this._engine.getRenderHeight() / this._engine.getRenderWidth()) : this._engine.getRenderHeight();
      this._diffuseRenderTarget = new FluidRenderingTextures("Diffuse", this._scene, diffuseWidth, diffuseHeight, 0, 0, 0, 5, 0, 5, true, this._camera, true, this._samples, this._shaderLanguage);
      this._initializeRenderTarget(this._diffuseRenderTarget);
    }
    const thicknessWidth = this._thicknessMapSize ?? this._engine.getRenderWidth();
    const thicknessHeight = this._thicknessMapSize !== null ? Math.round(this._thicknessMapSize * this._engine.getRenderHeight() / this._engine.getRenderWidth()) : this._engine.getRenderHeight();
    if (!this._useFixedThickness) {
      this._thicknessRenderTarget = new FluidRenderingTextures("Thickness", this._scene, thicknessWidth, thicknessHeight, thicknessWidth, thicknessHeight, 2, 6, 2, 6, true, this._camera, false, this._samples, this._shaderLanguage);
      this._initializeRenderTarget(this._thicknessRenderTarget);
    }
    this._createLiquidRenderingPostProcess();
  }
  _setBlurParameters(renderTarget = null) {
    if (renderTarget === null || renderTarget === this._depthRenderTarget) {
      this._setBlurDepthParameters();
    }
    if (renderTarget === null || renderTarget === this._thicknessRenderTarget) {
      this._setBlurThicknessParameters();
    }
  }
  _setBlurDepthParameters() {
    if (!this._depthRenderTarget) {
      return;
    }
    this._depthRenderTarget.blurFilterSize = this.blurDepthFilterSize;
    this._depthRenderTarget.blurMaxFilterSize = this.blurDepthMaxFilterSize;
    this._depthRenderTarget.blurNumIterations = this.blurDepthNumIterations;
    this._depthRenderTarget.blurDepthScale = this.blurDepthDepthScale;
  }
  _setBlurThicknessParameters() {
    if (!this._thicknessRenderTarget) {
      return;
    }
    this._thicknessRenderTarget.blurFilterSize = this.blurThicknessFilterSize;
    this._thicknessRenderTarget.blurNumIterations = this.blurThicknessNumIterations;
  }
  _initializeRenderTarget(renderTarget) {
    if (renderTarget !== this._diffuseRenderTarget) {
      renderTarget.enableBlur = renderTarget === this._depthRenderTarget ? this.enableBlurDepth : this.enableBlurThickness;
      renderTarget.blurSizeDivisor = renderTarget === this._depthRenderTarget ? this.blurDepthSizeDivisor : this.blurThicknessSizeDivisor;
    }
    this._setBlurParameters(renderTarget);
    renderTarget.initialize();
  }
  _createLiquidRenderingPostProcess() {
    const engine2 = this._scene.getEngine();
    const uniformNames = [
      "viewMatrix",
      "projectionMatrix",
      "invProjectionMatrix",
      "texelSize",
      "dirLight",
      "cameraFar",
      "density",
      "refractionStrength",
      "fresnelClamp",
      "specularPower"
    ];
    const samplerNames = ["depthSampler"];
    const defines = [];
    this.dispose(true);
    if (!this._camera) {
      return;
    }
    const texture2 = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;
    const texelSize = new Vector2(1 / texture2.getSize().width, 1 / texture2.getSize().height);
    if (this._scene.useRightHandedSystem) {
      defines.push("#define FLUIDRENDERING_RHS");
    }
    if (this._environmentMap !== null) {
      const envMap = this._environmentMap ?? this._scene.environmentTexture;
      if (envMap) {
        samplerNames.push("reflectionSampler");
        defines.push("#define FLUIDRENDERING_ENVIRONMENT");
      }
    }
    if (this._diffuseRenderTarget) {
      samplerNames.push("diffuseSampler");
      defines.push("#define FLUIDRENDERING_DIFFUSETEXTURE");
    } else {
      uniformNames.push("diffuseColor");
    }
    if (this._useVelocity) {
      samplerNames.push("velocitySampler");
      defines.push("#define FLUIDRENDERING_VELOCITY");
    }
    if (this._useFixedThickness) {
      uniformNames.push("thickness");
      samplerNames.push("bgDepthSampler");
      defines.push("#define FLUIDRENDERING_FIXED_THICKNESS");
    } else {
      uniformNames.push("minimumThickness");
      samplerNames.push("thicknessSampler");
    }
    if (this._compositeMode) {
      defines.push("#define FLUIDRENDERING_COMPOSITE_MODE");
    }
    if (this._debug) {
      defines.push("#define FLUIDRENDERING_DEBUG");
      if (this._debugFeature === 5) {
        defines.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL");
      } else if (this._debugFeature === 6) {
        defines.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING");
      } else {
        defines.push("#define FLUIDRENDERING_DEBUG_TEXTURE");
        samplerNames.push("debugSampler");
        if (this._debugFeature === 0 || this._debugFeature === 1) {
          defines.push("#define FLUIDRENDERING_DEBUG_DEPTH");
        }
      }
    }
    this._renderPostProcess = new PostProcess("FluidRendering", "fluidRenderingRender", uniformNames, samplerNames, 1, null, 2, engine2, false, null, 0, undefined, undefined, true, undefined, this._shaderLanguage, async () => {
      if (this._shaderLanguage === 1) {
        await Promise.resolve().then(() => (init_fluidRenderingRender_fragment(), exports_fluidRenderingRender_fragment));
      } else {
        await Promise.resolve().then(() => (init_fluidRenderingRender_fragment2(), exports_fluidRenderingRender_fragment2));
      }
    });
    this._renderPostProcess.updateEffect(defines.join(`
`));
    this._renderPostProcess.samples = this._samples;
    const engineWebGPU = engine2;
    const setTextureSampler = engineWebGPU.setTextureSampler;
    this._renderPostProcess.onApplyObservable.add((effect2) => {
      this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix());
      this._invProjectionMatrix.invert();
      if (setTextureSampler) {
        setTextureSampler.call(engineWebGPU, "textureSamplerSampler", this._renderPostProcess.inputTexture.texture);
      }
      if (!this._depthRenderTarget.enableBlur) {
        effect2.setTexture("depthSampler", this._depthRenderTarget.texture);
        if (setTextureSampler) {
          setTextureSampler.call(engineWebGPU, "depthSamplerSampler", this._depthRenderTarget.texture?.getInternalTexture() ?? null);
        }
      } else {
        effect2.setTexture("depthSampler", this._depthRenderTarget.textureBlur);
        if (setTextureSampler) {
          setTextureSampler.call(engineWebGPU, "depthSamplerSampler", this._depthRenderTarget.textureBlur?.getInternalTexture() ?? null);
        }
      }
      if (this._diffuseRenderTarget) {
        if (!this._diffuseRenderTarget.enableBlur) {
          effect2.setTexture("diffuseSampler", this._diffuseRenderTarget.texture);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "diffuseSamplerSampler", this._diffuseRenderTarget.texture?.getInternalTexture() ?? null);
          }
        } else {
          effect2.setTexture("diffuseSampler", this._diffuseRenderTarget.textureBlur);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "diffuseSamplerSampler", this._diffuseRenderTarget.textureBlur?.getInternalTexture() ?? null);
          }
        }
      } else {
        effect2.setColor3("diffuseColor", this.fluidColor);
      }
      if (this._useFixedThickness) {
        effect2.setFloat("thickness", this.minimumThickness);
        effect2._bindTexture("bgDepthSampler", this._bgDepthTexture);
        if (setTextureSampler) {
          setTextureSampler.call(engineWebGPU, "bgDepthSamplerSampler", this._bgDepthTexture ?? null);
        }
      } else {
        if (!this._thicknessRenderTarget.enableBlur) {
          effect2.setTexture("thicknessSampler", this._thicknessRenderTarget.texture);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "thicknessSamplerSampler", this._thicknessRenderTarget.texture?.getInternalTexture() ?? null);
          }
        } else {
          effect2.setTexture("thicknessSampler", this._thicknessRenderTarget.textureBlur);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "thicknessSamplerSampler", this._thicknessRenderTarget.textureBlur?.getInternalTexture() ?? null);
          }
        }
        effect2.setFloat("minimumThickness", this.minimumThickness);
      }
      if (this._environmentMap !== null) {
        const envMap = this._environmentMap ?? this._scene.environmentTexture;
        if (envMap) {
          effect2.setTexture("reflectionSampler", envMap);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "reflectionSamplerSampler", envMap?.getInternalTexture() ?? null);
          }
        }
      }
      effect2.setMatrix("viewMatrix", this._scene.getViewMatrix());
      effect2.setMatrix("invProjectionMatrix", this._invProjectionMatrix);
      effect2.setMatrix("projectionMatrix", this._scene.getProjectionMatrix());
      effect2.setVector2("texelSize", texelSize);
      effect2.setFloat("density", this.density);
      effect2.setFloat("refractionStrength", this.refractionStrength);
      effect2.setFloat("fresnelClamp", this.fresnelClamp);
      effect2.setFloat("specularPower", this.specularPower);
      effect2.setVector3("dirLight", this.dirLight);
      effect2.setFloat("cameraFar", this._camera.maxZ);
      if (this._debug) {
        let texture3 = null;
        switch (this._debugFeature) {
          case 0:
            texture3 = this._depthRenderTarget.texture;
            break;
          case 1:
            texture3 = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;
            break;
          case 2:
            texture3 = this._thicknessRenderTarget?.texture ?? null;
            break;
          case 3:
            texture3 = this._thicknessRenderTarget?.enableBlur ? this._thicknessRenderTarget?.textureBlur ?? null : this._thicknessRenderTarget?.texture ?? null;
            break;
          case 4:
            if (this._diffuseRenderTarget) {
              texture3 = this._diffuseRenderTarget.texture;
            }
            break;
        }
        if (this._debugFeature !== 5) {
          effect2.setTexture("debugSampler", texture3);
          if (setTextureSampler) {
            setTextureSampler.call(engineWebGPU, "debugSamplerSampler", texture3?.getInternalTexture() ?? null);
          }
        }
      }
    });
  }
  _clearTargets() {
    if (this._depthRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);
      this._engine.clear(this._depthClearColor, true, true, false);
      this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);
    }
    if (this._diffuseRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);
      this._engine.clear(this._thicknessClearColor, true, true, false);
      this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);
    }
    if (this._thicknessRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);
      this._engine.clear(this._thicknessClearColor, true, false, false);
      this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);
    }
  }
  _render(fluidObject) {
    if (this._needInitialization || !fluidObject.isReady()) {
      return;
    }
    const currentRenderTarget = this._engine._currentRenderTarget;
    this._engine.setState(false, undefined, undefined, undefined, true);
    this._engine.setDepthBuffer(true);
    this._engine.setDepthWrite(true);
    this._engine.setAlphaMode(0);
    if (this._depthRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);
      fluidObject.renderDepthTexture();
      this._engine.unbindInstanceAttributes();
      this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);
    }
    if (this._diffuseRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);
      fluidObject.renderDiffuseTexture();
      this._engine.unbindInstanceAttributes();
      this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);
    }
    if (this._thicknessRenderTarget?.renderTarget) {
      this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);
      fluidObject.renderThicknessTexture();
      this._engine.unbindInstanceAttributes();
      this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);
    }
    this._depthRenderTarget?.applyBlurPostProcesses();
    this._diffuseRenderTarget?.applyBlurPostProcesses();
    this._thicknessRenderTarget?.applyBlurPostProcesses();
    if (currentRenderTarget) {
      this._engine.bindFramebuffer(currentRenderTarget);
    }
  }
  dispose(onlyPostProcesses = false) {
    if (!onlyPostProcesses) {
      this._depthRenderTarget?.dispose();
      this._depthRenderTarget = null;
      this._diffuseRenderTarget?.dispose();
      this._diffuseRenderTarget = null;
      this._thicknessRenderTarget?.dispose();
      this._thicknessRenderTarget = null;
    }
    if (this._renderPostProcess && this._camera) {
      this._camera.detachPostProcess(this._renderPostProcess);
    }
    this._renderPostProcess?.dispose();
    this._renderPostProcess = null;
    this._onUseVelocityChanged.clear();
    this._needInitialization = false;
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectCustomParticles.js
init_buffer();
init_effectRenderer();
class FluidRenderingObjectCustomParticles extends FluidRenderingObject {
  getClassName() {
    return "FluidRenderingObjectCustomParticles";
  }
  get vertexBuffers() {
    return this._vertexBuffers;
  }
  constructor(scene, buffers, numParticles, shaderLanguage2) {
    super(scene, shaderLanguage2);
    this._numParticles = numParticles;
    this._diffuseEffectWrapper = null;
    this._vertexBuffers = {};
    this.addBuffers(buffers);
  }
  addBuffers(buffers) {
    for (const name487 in buffers) {
      let stride;
      let instanced = true;
      switch (name487) {
        case "velocity":
          stride = 3;
          break;
        case "offset":
          instanced = false;
          break;
      }
      this._vertexBuffers[name487] = new VertexBuffer(this._engine, buffers[name487], name487, true, false, stride, instanced);
    }
  }
  _createEffects() {
    super._createEffects();
    const uniformNames = ["view", "projection", "size"];
    const attributeNames = ["position", "offset", "color"];
    this._diffuseEffectWrapper = new EffectWrapper({
      engine: this._engine,
      useShaderStore: true,
      vertexShader: "fluidRenderingParticleDiffuse",
      fragmentShader: "fluidRenderingParticleDiffuse",
      attributeNames,
      uniformNames,
      samplerNames: [],
      shaderLanguage: this._shaderLanguage,
      extraInitializationsAsync: async () => {
        if (this._shaderLanguage === 1) {
          await Promise.resolve().then(() => (init_fluidRenderingParticleDiffuse_fragment(), exports_fluidRenderingParticleDiffuse_fragment));
        } else {
          await Promise.resolve().then(() => (init_fluidRenderingParticleDiffuse_fragment2(), exports_fluidRenderingParticleDiffuse_fragment2));
        }
      }
    });
  }
  isReady() {
    if (!this._vertexBuffers["offset"]) {
      this._vertexBuffers["offset"] = new VertexBuffer(this._engine, [0, 0, 1, 0, 0, 1, 1, 1], "offset", false, false, 2);
    }
    return super.isReady() && (this._diffuseEffectWrapper?.effect.isReady() ?? false);
  }
  get numParticles() {
    return this._numParticles;
  }
  setNumParticles(num) {
    this._numParticles = num;
  }
  renderDiffuseTexture() {
    const numParticles = this.numParticles;
    if (!this._diffuseEffectWrapper || numParticles === 0) {
      return;
    }
    const diffuseDrawWrapper = this._diffuseEffectWrapper.drawWrapper;
    const diffuseEffect = diffuseDrawWrapper.effect;
    this._engine.enableEffect(diffuseDrawWrapper);
    this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, diffuseEffect);
    diffuseEffect.setMatrix("view", this._scene.getViewMatrix());
    diffuseEffect.setMatrix("projection", this._scene.getProjectionMatrix());
    if (this._particleSize !== null) {
      diffuseEffect.setFloat2("size", this._particleSize, this._particleSize);
    }
    if (this.useInstancing) {
      this._engine.drawArraysType(7, 0, 4, numParticles);
    } else {
      this._engine.drawElementsType(0, 0, numParticles);
    }
  }
  dispose() {
    super.dispose();
    this._diffuseEffectWrapper?.dispose();
    for (const name487 in this._vertexBuffers) {
      this._vertexBuffers[name487].dispose();
    }
    this._vertexBuffers = {};
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingDepthTextureCopy.js
class FluidRenderingDepthTextureCopy {
  get depthRTWrapper() {
    return this._depthRTWrapper;
  }
  constructor(engine2, width, height, samples = 1) {
    this._engine = engine2;
    this._copyTextureToTexture = new CopyTextureToTexture(engine2, true);
    this._depthRTWrapper = this._engine.createRenderTargetTexture({ width, height }, {
      generateMipMaps: false,
      type: 0,
      format: 6,
      samplingMode: 1,
      generateDepthBuffer: true,
      generateStencilBuffer: false,
      samples,
      noColorAttachment: true,
      label: "FluidRenderingDepthTextureCopyRTT"
    });
    const depthTexture = this._depthRTWrapper.createDepthStencilTexture(0, false, false, 1, undefined, "FluidRenderingDepthTextureCopyRTTDepthStencil");
    depthTexture.label = `FluidDepthTextureCopy${width}x${height}x${samples}`;
  }
  copy(source) {
    return this._copyTextureToTexture.copy(source, this._depthRTWrapper);
  }
  dispose() {
    this._depthRTWrapper.dispose();
    this._copyTextureToTexture.dispose();
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderer.js
Object.defineProperty(Scene.prototype, "fluidRenderer", {
  get: function() {
    return this._fluidRenderer;
  },
  set: function(value) {
    this._fluidRenderer = value;
  },
  enumerable: true,
  configurable: true
});
Scene.prototype.enableFluidRenderer = function() {
  if (this._fluidRenderer) {
    return this._fluidRenderer;
  }
  this._fluidRenderer = new FluidRenderer(this);
  return this._fluidRenderer;
};
Scene.prototype.disableFluidRenderer = function() {
  this._fluidRenderer?.dispose();
  this._fluidRenderer = null;
};
function IsParticleSystemObject(obj) {
  return !!obj.particleSystem;
}
function IsCustomParticlesObject(obj) {
  return !!obj.addBuffers;
}

class FluidRendererSceneComponent {
  constructor(scene) {
    this.name = SceneComponentConstants.NAME_FLUIDRENDERER;
    this.scene = scene;
  }
  register() {
    this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER, this, this._gatherActiveCameraRenderTargets);
    this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER, this, this._afterCameraDraw);
  }
  _gatherActiveCameraRenderTargets(_renderTargets) {
    this.scene.fluidRenderer?._prepareRendering();
  }
  _afterCameraDraw(camera2) {
    this.scene.fluidRenderer?._render(camera2);
  }
  rebuild() {
    const fluidRenderer = this.scene.fluidRenderer;
    if (!fluidRenderer) {
      return;
    }
    const buffers = new Set;
    for (let i = 0;i < fluidRenderer.renderObjects.length; ++i) {
      const obj = fluidRenderer.renderObjects[i].object;
      if (IsCustomParticlesObject(obj)) {
        const vbuffers = obj.vertexBuffers;
        for (const name487 in vbuffers) {
          buffers.add(vbuffers[name487].getWrapperBuffer());
        }
      }
    }
    buffers.forEach((buffer2) => {
      buffer2._rebuild();
    });
  }
  dispose() {
    this.scene.disableFluidRenderer();
  }
}

class FluidRenderer {
  static _SceneComponentInitialization(scene) {
    let component = scene._getComponent(SceneComponentConstants.NAME_FLUIDRENDERER);
    if (!component) {
      component = new FluidRendererSceneComponent(scene);
      scene._addComponent(component);
    }
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  constructor(scene) {
    this._shaderLanguage = 0;
    this._scene = scene;
    this._engine = scene.getEngine();
    this._onEngineResizeObserver = null;
    this.renderObjects = [];
    this.targetRenderers = [];
    this._cameras = new Map;
    FluidRenderer._SceneComponentInitialization(this._scene);
    this._onEngineResizeObserver = this._engine.onResizeObservable.add(() => {
      this._initialize();
    });
    const engine2 = this._engine;
    if (engine2.isWebGPU) {
      this._shaderLanguage = 1;
    }
  }
  recreate() {
    this._sortRenderingObjects();
    this._initialize();
  }
  getRenderObjectFromParticleSystem(ps) {
    const index = this._getParticleSystemIndex(ps);
    return index !== -1 ? this.renderObjects[index] : null;
  }
  addParticleSystem(ps, generateDiffuseTexture, targetRenderer, camera2) {
    const object = new FluidRenderingObjectParticleSystem(this._scene, ps, this._shaderLanguage);
    object.onParticleSizeChanged.add(() => this._setParticleSizeForRenderTargets());
    if (!targetRenderer) {
      targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera2, this._shaderLanguage);
      this.targetRenderers.push(targetRenderer);
    }
    if (!targetRenderer._onUseVelocityChanged.hasObservers()) {
      targetRenderer._onUseVelocityChanged.add(() => this._setUseVelocityForRenderObject());
    }
    if (generateDiffuseTexture !== undefined) {
      targetRenderer.generateDiffuseTexture = generateDiffuseTexture;
    }
    const renderObject = { object, targetRenderer };
    this.renderObjects.push(renderObject);
    this._sortRenderingObjects();
    this._setParticleSizeForRenderTargets();
    return renderObject;
  }
  addCustomParticles(buffers, numParticles, generateDiffuseTexture, targetRenderer, camera2) {
    const object = new FluidRenderingObjectCustomParticles(this._scene, buffers, numParticles, this._shaderLanguage);
    object.onParticleSizeChanged.add(() => this._setParticleSizeForRenderTargets());
    if (!targetRenderer) {
      targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera2, this._shaderLanguage);
      this.targetRenderers.push(targetRenderer);
    }
    if (!targetRenderer._onUseVelocityChanged.hasObservers()) {
      targetRenderer._onUseVelocityChanged.add(() => this._setUseVelocityForRenderObject());
    }
    if (generateDiffuseTexture !== undefined) {
      targetRenderer.generateDiffuseTexture = generateDiffuseTexture;
    }
    const renderObject = { object, targetRenderer };
    this.renderObjects.push(renderObject);
    this._sortRenderingObjects();
    this._setParticleSizeForRenderTargets();
    return renderObject;
  }
  removeRenderObject(renderObject, removeUnusedTargetRenderer = true) {
    const index = this.renderObjects.indexOf(renderObject);
    if (index === -1) {
      return false;
    }
    renderObject.object.dispose();
    this.renderObjects.splice(index, 1);
    if (removeUnusedTargetRenderer && this._removeUnusedTargetRenderers()) {
      this._initialize();
    } else {
      this._setParticleSizeForRenderTargets();
    }
    return true;
  }
  _sortRenderingObjects() {
    this.renderObjects.sort((a, b) => {
      return a.object.priority < b.object.priority ? -1 : a.object.priority > b.object.priority ? 1 : 0;
    });
  }
  _removeUnusedTargetRenderers() {
    const indexes = {};
    for (let i = 0;i < this.renderObjects.length; ++i) {
      const targetRenderer = this.renderObjects[i].targetRenderer;
      indexes[this.targetRenderers.indexOf(targetRenderer)] = true;
    }
    let removed = false;
    const newList = [];
    for (let i = 0;i < this.targetRenderers.length; ++i) {
      if (!indexes[i]) {
        this.targetRenderers[i].dispose();
        removed = true;
      } else {
        newList.push(this.targetRenderers[i]);
      }
    }
    if (removed) {
      this.targetRenderers.length = 0;
      this.targetRenderers.push(...newList);
    }
    return removed;
  }
  _getParticleSystemIndex(ps) {
    for (let i = 0;i < this.renderObjects.length; ++i) {
      const obj = this.renderObjects[i].object;
      if (IsParticleSystemObject(obj) && obj.particleSystem === ps) {
        return i;
      }
    }
    return -1;
  }
  _initialize() {
    for (let i = 0;i < this.targetRenderers.length; ++i) {
      this.targetRenderers[i].dispose();
    }
    const cameras = new Map;
    for (let i = 0;i < this.targetRenderers.length; ++i) {
      const targetRenderer = this.targetRenderers[i];
      targetRenderer._initialize();
      if (targetRenderer.camera && targetRenderer._renderPostProcess) {
        let list = cameras.get(targetRenderer.camera);
        if (!list) {
          list = [[], {}];
          cameras.set(targetRenderer.camera, list);
        }
        list[0].push(targetRenderer);
        targetRenderer.camera.attachPostProcess(targetRenderer._renderPostProcess, i);
      }
    }
    let iterator = cameras.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      const camera2 = key.value;
      const list = cameras.get(camera2);
      const firstPostProcess = camera2._getFirstPostProcess();
      if (!firstPostProcess) {
        continue;
      }
      const [targetRenderers, copyDepthTextures] = list;
      firstPostProcess.onSizeChangedObservable.add(() => {
        if (!firstPostProcess.inputTexture.depthStencilTexture) {
          firstPostProcess.inputTexture.createDepthStencilTexture(0, true, this._engine.isStencilEnable, targetRenderers[0].samples, this._engine.isStencilEnable ? 13 : 14, `PostProcessRTTDepthStencil-${firstPostProcess.name}`);
        }
        for (const targetRenderer of targetRenderers) {
          const thicknessRT = targetRenderer._thicknessRenderTarget?.renderTarget;
          const thicknessTexture = thicknessRT?.texture;
          if (thicknessRT && thicknessTexture) {
            const key2 = thicknessTexture.width + "_" + thicknessTexture.height;
            let copyDepthTexture = copyDepthTextures[key2];
            if (!copyDepthTexture) {
              copyDepthTexture = copyDepthTextures[key2] = new FluidRenderingDepthTextureCopy(this._engine, thicknessTexture.width, thicknessTexture.height);
            }
            copyDepthTexture.depthRTWrapper.shareDepth(thicknessRT);
          }
        }
      });
    }
    iterator = this._cameras.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      const camera2 = key.value;
      const list = this._cameras.get(camera2);
      const copyDepthTextures = list[1];
      const list2 = cameras.get(camera2);
      if (!list2) {
        for (const key2 in copyDepthTextures) {
          copyDepthTextures[key2].dispose();
        }
      } else {
        for (const key2 in copyDepthTextures) {
          if (!list2[1][key2]) {
            copyDepthTextures[key2].dispose();
          }
        }
      }
    }
    this._cameras.clear();
    this._cameras = cameras;
    this._setParticleSizeForRenderTargets();
  }
  _setParticleSizeForRenderTargets() {
    const particleSizes = new Map;
    for (let i = 0;i < this.renderObjects.length; ++i) {
      const renderingObject = this.renderObjects[i];
      let curSize = particleSizes.get(renderingObject.targetRenderer);
      if (curSize === undefined) {
        curSize = 0;
      }
      particleSizes.set(renderingObject.targetRenderer, Math.max(curSize, renderingObject.object.particleSize));
    }
    particleSizes.forEach((particleSize, targetRenderer) => {
      if (targetRenderer._depthRenderTarget) {
        targetRenderer._depthRenderTarget.particleSize = particleSize;
      }
    });
  }
  _setUseVelocityForRenderObject() {
    for (const renderingObject of this.renderObjects) {
      renderingObject.object.useVelocity = renderingObject.targetRenderer.useVelocity;
    }
  }
  _prepareRendering() {
    for (const renderer of this.targetRenderers) {
      if (renderer.needInitialization) {
        this._initialize();
        return;
      }
    }
  }
  _render(forCamera) {
    for (let i = 0;i < this.targetRenderers.length; ++i) {
      if (!forCamera || this.targetRenderers[i].camera === forCamera) {
        this.targetRenderers[i]._clearTargets();
      }
    }
    const iterator = this._cameras.keys();
    for (let key = iterator.next();key.done !== true; key = iterator.next()) {
      const camera2 = key.value;
      const list = this._cameras.get(camera2);
      if (forCamera && camera2 !== forCamera) {
        continue;
      }
      const firstPostProcess = camera2._getFirstPostProcess();
      if (!firstPostProcess) {
        continue;
      }
      const sourceCopyDepth = firstPostProcess.inputTexture?.depthStencilTexture;
      if (sourceCopyDepth) {
        const [targetRenderers, copyDepthTextures] = list;
        for (const targetRenderer of targetRenderers) {
          targetRenderer._bgDepthTexture = sourceCopyDepth;
        }
        for (const key2 in copyDepthTextures) {
          copyDepthTextures[key2].copy(sourceCopyDepth);
        }
      }
    }
    for (let i = 0;i < this.renderObjects.length; ++i) {
      const renderingObject = this.renderObjects[i];
      if (!forCamera || renderingObject.targetRenderer.camera === forCamera) {
        renderingObject.targetRenderer._render(renderingObject.object);
      }
    }
  }
  dispose() {
    this._engine.onResizeObservable.remove(this._onEngineResizeObserver);
    this._onEngineResizeObserver = null;
    for (let i = 0;i < this.renderObjects.length; ++i) {
      this.renderObjects[i].object.dispose();
    }
    for (let i = 0;i < this.targetRenderers.length; ++i) {
      this.targetRenderers[i].dispose();
    }
    this._cameras.forEach((list) => {
      const copyDepthTextures = list[1];
      for (const key in copyDepthTextures) {
        copyDepthTextures[key].dispose();
      }
    });
    this.renderObjects = [];
    this.targetRenderers = [];
    this._cameras.clear();
  }
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js
init_fluidRenderingParticleDepth_vertex2();
init_fluidRenderingParticleDepth_fragment2();
init_fluidRenderingParticleThickness_vertex2();
init_fluidRenderingParticleThickness_fragment2();

// node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.vertex.js
init_shaderStore();
var name487 = "fluidRenderingParticleDiffuseVertexShader";
var shader486 = `attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}
`;
if (!ShaderStore.ShadersStore[name487]) {
  ShaderStore.ShadersStore[name487] = shader486;
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js
init_fluidRenderingParticleDiffuse_fragment2();
init_fluidRenderingBilateralBlur_fragment2();
init_fluidRenderingStandardBlur_fragment2();
init_fluidRenderingRender_fragment2();
init_fluidRenderingParticleDepth_vertex();
init_fluidRenderingParticleDepth_fragment();
init_fluidRenderingParticleThickness_vertex();
init_fluidRenderingParticleThickness_fragment();

// node_modules/@babylonjs/core/ShadersWGSL/fluidRenderingParticleDiffuse.vertex.js
init_shaderStore();
var name488 = "fluidRenderingParticleDiffuseVertexShader";
var shader487 = `attribute position: vec3f;attribute offset: vec2f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform size: vec2f;varying uv: vec2f;varying diffuseColor: vec3f;@vertex
fn main(input: VertexInputs)->FragmentInputs {var cornerPos: vec3f=vec3f(
vec2f(input.offset.x-0.5,input.offset.y-0.5)*uniforms.size,
0.0
);var viewPos: vec3f=(uniforms.view*vec4f(input.position,1.0)).xyz+cornerPos;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0);vertexOutputs.uv=input.offset;vertexOutputs.diffuseColor=input.color.rgb;}
`;
if (!ShaderStore.ShadersStoreWGSL[name488]) {
  ShaderStore.ShadersStoreWGSL[name488] = shader487;
}

// node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js
init_fluidRenderingParticleDiffuse_fragment();
init_fluidRenderingBilateralBlur_fragment();
init_fluidRenderingStandardBlur_fragment();
init_fluidRenderingRender_fragment();
// node_modules/@babylonjs/core/Rendering/reflectiveShadowMap.js
init_tslib_es6();
init_math_color();
init_math_vector();
init_decorators();
init_typeStore();
class MaterialRSMCreateDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.RSMCREATE = false;
    this.RSMCREATE_PROJTEXTURE = false;
    this.RSMCREATE_LIGHT_IS_SPOT = false;
  }
}

class RSMCreatePluginMaterial extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material2) {
    super(material2, RSMCreatePluginMaterial.Name, 300, new MaterialRSMCreateDefines);
    this._lightColor = new Color3;
    this._hasProjectionTexture = false;
    this._isEnabled = false;
    this.isEnabled = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material2._dirtyCallbacks[1];
    this._varAlbedoName = material2 instanceof PBRBaseMaterial ? "surfaceAlbedo" : "baseColor.rgb";
  }
  prepareDefines(defines) {
    defines.RSMCREATE = this._isEnabled;
    this._hasProjectionTexture = false;
    const isSpot = this.light.getTypeID() === Light.LIGHTTYPEID_SPOTLIGHT;
    if (isSpot) {
      const spot = this.light;
      this._hasProjectionTexture = spot.projectionTexture ? spot.projectionTexture.isReady() : false;
    }
    defines.RSMCREATE_PROJTEXTURE = this._hasProjectionTexture;
    defines.RSMCREATE_LIGHT_IS_SPOT = isSpot;
    defines.SCENE_MRT_COUNT = 3;
  }
  getClassName() {
    return "RSMCreatePluginMaterial";
  }
  getUniforms() {
    return {
      ubo: [
        { name: "rsmTextureProjectionMatrix", size: 16, type: "mat4" },
        { name: "rsmSpotInfo", size: 4, type: "vec4" },
        { name: "rsmLightColor", size: 3, type: "vec3" },
        { name: "rsmLightPosition", size: 3, type: "vec3" }
      ],
      fragment: `#ifdef RSMCREATE
                    uniform mat4 rsmTextureProjectionMatrix;
                    uniform vec4 rsmSpotInfo;
                    uniform vec3 rsmLightColor;
                    uniform vec3 rsmLightPosition;
                #endif`
    };
  }
  getSamplers(samplers) {
    samplers.push("rsmTextureProjectionSampler");
  }
  bindForSubMesh(uniformBuffer2) {
    if (!this._isEnabled) {
      return;
    }
    this.light.diffuse.scaleToRef(this.light.getScaledIntensity(), this._lightColor);
    uniformBuffer2.updateColor3("rsmLightColor", this._lightColor);
    if (this.light.getTypeID() === Light.LIGHTTYPEID_SPOTLIGHT) {
      const spot = this.light;
      if (this._hasProjectionTexture) {
        uniformBuffer2.updateMatrix("rsmTextureProjectionMatrix", spot.projectionTextureMatrix);
        uniformBuffer2.setTexture("rsmTextureProjectionSampler", spot.projectionTexture);
      }
      const normalizeDirection = TmpVectors.Vector3[0];
      if (spot.computeTransformedInformation()) {
        uniformBuffer2.updateFloat3("rsmLightPosition", this.light.transformedPosition.x, this.light.transformedPosition.y, this.light.transformedPosition.z);
        spot.transformedDirection.normalizeToRef(normalizeDirection);
      } else {
        uniformBuffer2.updateFloat3("rsmLightPosition", this.light.position.x, this.light.position.y, this.light.position.z);
        spot.direction.normalizeToRef(normalizeDirection);
      }
      uniformBuffer2.updateFloat4("rsmSpotInfo", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(spot.angle * 0.5));
    }
  }
  getCustomCode(shaderType, shaderLanguage2) {
    if (shaderType === "vertex") {
      return null;
    }
    if (shaderLanguage2 === 1) {
      return {
        CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RSMCREATE
                    #ifdef RSMCREATE_PROJTEXTURE
                        var rsmTextureProjectionSamplerSampler: sampler;
                        var rsmTextureProjectionSampler: texture_2d<f32>;
                    #endif
                #endif
            `,
        CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `
                #ifdef RSMCREATE
                    var rsmColor = ${this._varAlbedoName} * uniforms.rsmLightColor;
                    #ifdef RSMCREATE_PROJTEXTURE
                    {
                        var strq = uniforms.rsmTextureProjectionMatrix * vec4f(fragmentInputs.vPositionW, 1.0);
                        strq /= strq.w;
                        rsmColor *= textureSample(rsmTextureProjectionSampler, rsmTextureProjectionSamplerSampler, strq.xy).rgb;
                    }
                    #endif
                    #ifdef RSMCREATE_LIGHT_IS_SPOT
                    {
                        var cosAngle = max(0., dot(uniforms.rsmSpotInfo.xyz, normalize(fragmentInputs.vPositionW - uniforms.rsmLightPosition)));
                        rsmColor = sign(cosAngle - uniforms.rsmSpotInfo.w) * rsmColor;
                    }
                    #endif

                    #define MRT_AND_COLOR
                    fragmentOutputs.fragData0 = vec4f(fragmentInputs.vPositionW, 1.);
                    fragmentOutputs.fragData1 = vec4f(normalize(normalW) * 0.5 + 0.5, 1.);
                    fragmentOutputs.fragData2 = vec4f(rsmColor, 1.);
                #endif
            `
      };
    }
    return {
      CUSTOM_FRAGMENT_BEGIN: `
                #ifdef RSMCREATE
                    #extension GL_EXT_draw_buffers : require
                #endif
            `,
      CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RSMCREATE
                    #ifdef RSMCREATE_PROJTEXTURE
                        uniform highp sampler2D rsmTextureProjectionSampler;                    
                    #endif
                    layout(location = 0) out highp vec4 glFragData[3];
                    vec4 glFragColor;
                #endif
            `,
      CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `
                #ifdef RSMCREATE
                    vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;
                    #ifdef RSMCREATE_PROJTEXTURE
                    {
                        vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);
                        strq /= strq.w;
                        rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;
                    }
                    #endif
                    #ifdef RSMCREATE_LIGHT_IS_SPOT
                    {
                        float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));
                        rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;
                    }
                    #endif
                    glFragData[0] = vec4(vPositionW, 1.);
                    glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);
                    glFragData[2] = vec4(rsmColor, 1.);
                #endif
            `
    };
  }
}
RSMCreatePluginMaterial.Name = "RSMCreate";
__decorate([
  serialize()
], RSMCreatePluginMaterial.prototype, "light", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], RSMCreatePluginMaterial.prototype, "isEnabled", undefined);
RegisterClass(`BABYLON.RSMCreatePluginMaterial`, RSMCreatePluginMaterial);

// node_modules/@babylonjs/core/Rendering/index.js
init_objectRenderer();
// node_modules/@babylonjs/core/Rendering/GlobalIllumination/giRSMManager.js
init_tslib_es6();
init_renderTargetTexture();
init_postProcess();
init_observable();
init_math_vector();
init_baseTexture();
init_decorators();
init_typeStore();

class GIRSMManager {
  get enable() {
    return this._enable;
  }
  set enable(enable) {
    if (this._giRSM.length === 0) {
      enable = false;
    }
    if (enable === this._enable) {
      return;
    }
    this._enable = enable;
    this._debugLayer.isEnabled = this._showOnlyGI && enable;
    this._materialsWithRenderPlugin.forEach((mat) => {
      if (mat.pluginManager) {
        const plugin = mat.pluginManager.getPlugin(GIRSMRenderPluginMaterial.Name);
        plugin.isEnabled = enable;
      }
    });
    this.recreateResources(!enable);
  }
  get enableBlur() {
    return this._enableBlur;
  }
  set enableBlur(enable) {
    if (enable === this._enableBlur) {
      return;
    }
    this._enableBlur = enable;
    this.recreateResources();
  }
  get useQualityBlur() {
    return this._useQualityBlur;
  }
  set useQualityBlur(enable) {
    if (enable === this._useQualityBlur) {
      return;
    }
    this._useQualityBlur = enable;
    this.recreateResources();
  }
  get fullSizeBlur() {
    return this._forceFullSizeBlur;
  }
  set fullSizeBlur(mode) {
    if (this._forceFullSizeBlur === mode) {
      return;
    }
    this._forceFullSizeBlur = mode;
    this.recreateResources();
  }
  get useQualityUpsampling() {
    return this._useQualityUpsampling;
  }
  set useQualityUpsampling(enable) {
    if (enable === this._useQualityUpsampling) {
      return;
    }
    this._useQualityUpsampling = enable;
    this.recreateResources();
  }
  get showOnlyGI() {
    return this._showOnlyGI;
  }
  set showOnlyGI(show) {
    if (this._showOnlyGI === show) {
      return;
    }
    this._showOnlyGI = show;
    this._debugLayer.isEnabled = show;
  }
  get use32BitsDepthBuffer() {
    return this._use32BitsDepthBuffer;
  }
  set use32BitsDepthBuffer(enable) {
    if (this._use32BitsDepthBuffer === enable) {
      return;
    }
    this._use32BitsDepthBuffer = enable;
    this.recreateResources();
  }
  setOutputDimensions(dimensions) {
    this._outputDimensions = dimensions;
    this.recreateResources();
  }
  setGITextureDimensions(dimensions) {
    this._giTextureDimensions = dimensions;
    this.recreateResources();
  }
  get giTextureType() {
    return this._giTextureType;
  }
  set giTextureType(textureType) {
    if (this._giTextureType === textureType) {
      return;
    }
    this._giTextureType = textureType;
    this.recreateResources();
  }
  get shaderLanguage() {
    return this._shaderLanguage;
  }
  get giRSM() {
    return this._giRSM;
  }
  addGIRSM(rsm) {
    if (Array.isArray(rsm)) {
      this._giRSM.push(...rsm);
    } else {
      this._giRSM.push(rsm);
    }
    this.recreateResources();
  }
  removeGIRSM(rsm) {
    if (Array.isArray(rsm)) {
      for (let i = 0;i < rsm.length; ++i) {
        const idx = this._giRSM.indexOf(rsm[i]);
        if (idx !== -1) {
          this._giRSM.splice(idx, 1);
        }
      }
    } else {
      const idx = this._giRSM.indexOf(rsm);
      if (idx !== -1) {
        this._giRSM.splice(idx, 1);
      }
    }
    if (this._giRSM.length === 0) {
      this.enable = false;
    } else {
      this.recreateResources();
    }
  }
  addMaterial(material2) {
    if (material2) {
      this._addGISupportToMaterial(material2);
    } else {
      this._scene.meshes.forEach((mesh2) => {
        if (mesh2.getTotalVertices() > 0 && mesh2.isEnabled() && mesh2.material) {
          this._addGISupportToMaterial(mesh2.material);
        }
      });
    }
  }
  get countersGPU() {
    return this._counters;
  }
  recreateResources(disposeGeometryBufferRenderer = false) {
    if (!this._shadersLoaded) {
      this._onShaderLoadedObservable.addOnce(() => {
        this.recreateResources(disposeGeometryBufferRenderer);
      });
      return;
    }
    this._disposePostProcesses(disposeGeometryBufferRenderer);
    this._createPostProcesses();
    this._setPluginParameters();
  }
  generateSampleTexture(maxSamples) {
    this._sampleTexture?.dispose();
    this._maxSamples = maxSamples;
    const data = new Float32Array(this._maxSamples * 4);
    for (let i = 0;i < this._maxSamples; i++) {
      const xi1 = Math.random();
      const xi2 = Math.random();
      const x = xi1 * Math.sin(2 * Math.PI * xi2);
      const y = xi1 * Math.cos(2 * Math.PI * xi2);
      data[i * 4 + 0] = x;
      data[i * 4 + 1] = y;
      data[i * 4 + 2] = xi1 * xi1;
      data[i * 4 + 3] = 1;
    }
    this._sampleTexture = new RawTexture(data, this._maxSamples, 1, 5, this._scene, false, false, 1, 1);
    this._sampleTexture.name = "GIRSMSamples";
  }
  dispose() {
    this._disposePostProcesses(true);
    this._debugLayer.texture?.dispose();
    this._debugLayer.dispose();
    this._scene.onBeforeDrawPhaseObservable.remove(this._drawPhaseObserver);
    this._onShaderLoadedObservable.clear();
  }
  constructor(scene, outputDimensions, giTextureDimensions = { width: 256, height: 256 }, maxSamples = 2048, giTextureType = 11) {
    this._giRSM = [];
    this._blurRTT = null;
    this._blurPostProcesses = null;
    this._blurXPostprocess = null;
    this._blurYPostprocess = null;
    this._upsamplingXPostprocess = null;
    this._upsamplingYPostprocess = null;
    this._ppGlobalIllumination = [];
    this._firstActivation = true;
    this._geomBufferEnabled = false;
    this._geomBufferEnablePosition = false;
    this._tempMatrix = new Matrix;
    this._enable = false;
    this.pause = false;
    this._enableBlur = true;
    this._useQualityBlur = false;
    this.blurDepthThreshold = 0.05;
    this.blurNormalThreshold = 0.25;
    this.blurKernel = 12;
    this._forceFullSizeBlur = false;
    this._useQualityUpsampling = false;
    this.upsamplerKernel = 6;
    this._showOnlyGI = false;
    this._use32BitsDepthBuffer = false;
    this._shaderLanguage = 0;
    this._shadersLoaded = false;
    this._onShaderLoadedObservable = new Observable;
    this._scene = scene;
    this._engine = scene.getEngine();
    this._outputDimensions = outputDimensions;
    this._giTextureDimensions = giTextureDimensions;
    this._giTextureType = giTextureType;
    this._materialsWithRenderPlugin = [];
    this._maxSamples = maxSamples;
    this._debugLayer = new Layer("debug layer", null, this._scene, false);
    this._debugLayer.isEnabled = false;
    this._counters = [];
    this._countersRTW = [];
    this._initShaderSourceAsync();
    this.generateSampleTexture(maxSamples);
    this._drawPhaseObserver = this._scene.onBeforeDrawPhaseObservable.add(() => {
      const currentRenderTarget = this._engine._currentRenderTarget;
      let rebindCurrentRenderTarget = false;
      if (this._enable && this._shadersLoaded) {
        if (!this.pause && this._ppGlobalIllumination.length > 0) {
          this._scene.postProcessManager.directRender(this._ppGlobalIllumination, this._ppGlobalIllumination[0].inputTexture);
          this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture, true);
          this._engine.setAlphaMode(0);
          rebindCurrentRenderTarget = true;
          if (this.enableBlur && this._blurPostProcesses) {
            this._scene.postProcessManager.directRender(this._blurPostProcesses, this._blurRTT.renderTarget, true);
            this._engine.unBindFramebuffer(this._blurRTT.renderTarget, true);
          }
        }
        for (let i = 0;i < this._counters.length; ++i) {
          const rtws = this._countersRTW[i];
          for (let t = 0;t < rtws.length; ++t) {
            if (t === 0) {
              this._counters[i].value = this.pause ? 0 : rtws[t].gpuTimeInFrame?.counter.lastSecAverage ?? 0;
            } else if (!this.pause) {
              this._counters[i].value += rtws[t].gpuTimeInFrame?.counter.lastSecAverage ?? 0;
            }
          }
        }
        if (this._scene.activeCamera) {
          this._engine.setViewport(this._scene.activeCamera.viewport);
        }
      }
      if (rebindCurrentRenderTarget && currentRenderTarget) {
        this._engine.bindFramebuffer(currentRenderTarget);
      }
    });
  }
  async _initShaderSourceAsync() {
    const engine2 = this._engine;
    if (engine2.isWebGPU) {
      this._shaderLanguage = 1;
      await Promise.all([
        Promise.resolve().then(() => (init_bilateralBlur_fragment(), exports_bilateralBlur_fragment)),
        Promise.resolve().then(() => (init_bilateralBlurQuality_fragment(), exports_bilateralBlurQuality_fragment)),
        Promise.resolve().then(() => (init_rsmGlobalIllumination_fragment(), exports_rsmGlobalIllumination_fragment)),
        Promise.resolve().then(() => (init_rsmFullGlobalIllumination_fragment(), exports_rsmFullGlobalIllumination_fragment))
      ]);
    } else {
      await Promise.all([
        Promise.resolve().then(() => (init_bilateralBlur_fragment2(), exports_bilateralBlur_fragment2)),
        Promise.resolve().then(() => (init_bilateralBlurQuality_fragment2(), exports_bilateralBlurQuality_fragment2)),
        Promise.resolve().then(() => (init_rsmGlobalIllumination_fragment2(), exports_rsmGlobalIllumination_fragment2)),
        Promise.resolve().then(() => (init_rsmFullGlobalIllumination_fragment2(), exports_rsmFullGlobalIllumination_fragment2))
      ]);
    }
    this._shadersLoaded = true;
    this._onShaderLoadedObservable.notifyObservers();
  }
  _disposePostProcesses(disposeGeometryBufferRenderer = false) {
    this._blurRTT?.dispose();
    this._blurRTT = null;
    this._blurPostProcesses = [];
    this._blurXPostprocess?.dispose();
    this._blurXPostprocess = null;
    this._blurYPostprocess?.dispose();
    this._blurYPostprocess = null;
    this._upsamplingXPostprocess?.dispose();
    this._upsamplingXPostprocess = null;
    this._upsamplingYPostprocess?.dispose();
    this._upsamplingYPostprocess = null;
    for (const ppGlobalIllumination of this._ppGlobalIllumination) {
      ppGlobalIllumination.dispose();
    }
    this._ppGlobalIllumination = [];
    if (disposeGeometryBufferRenderer) {
      if (this._geomBufferEnabled) {
        this._scene.enableGeometryBufferRenderer();
        this._scene.geometryBufferRenderer.enablePosition = this._geomBufferEnablePosition;
      } else {
        this._scene.disableGeometryBufferRenderer();
      }
    }
    this._counters = [];
    this._countersRTW = [];
  }
  _setPluginParameters() {
    if (!this._enable) {
      return;
    }
    this._materialsWithRenderPlugin.forEach((mat) => {
      if (mat.pluginManager) {
        const plugin = mat.pluginManager.getPlugin(GIRSMRenderPluginMaterial.Name);
        plugin.textureGIContrib = this.enableBlur ? this._blurRTT.renderTarget.texture : this._ppGlobalIllumination[0].inputTexture.texture;
        plugin.outputTextureWidth = this._outputDimensions.width;
        plugin.outputTextureHeight = this._outputDimensions.height;
      }
    });
  }
  _createPostProcesses() {
    if (!this._enable) {
      return;
    }
    const textureFormat = this._giTextureType === 13 ? 4 : 5;
    if (this._firstActivation) {
      this._firstActivation = false;
      this._geomBufferEnabled = !!this._scene.geometryBufferRenderer;
      this._geomBufferEnablePosition = this._scene.geometryBufferRenderer?.enablePosition ?? false;
    }
    if (!this._geomBufferEnabled) {
      this._scene.disableGeometryBufferRenderer();
    }
    const geometryBufferRenderer = this._scene.enableGeometryBufferRenderer(this._enableBlur ? this._outputDimensions : this._giTextureDimensions, this._use32BitsDepthBuffer ? 14 : 15, GIRSMManager.GeometryBufferTextureTypesAndFormats);
    if (!geometryBufferRenderer) {
      throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");
    }
    geometryBufferRenderer.enablePosition = true;
    if (!this._geomBufferEnabled) {
      geometryBufferRenderer.generateNormalsInWorldSpace = true;
    }
    const decodeGeometryBufferNormals = geometryBufferRenderer.normalsAreUnsigned;
    const normalsAreInWorldSpace = geometryBufferRenderer.generateNormalsInWorldSpace;
    this._counters.push({ name: "Geometry buffer renderer", value: 0 });
    this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);
    let defines = "";
    if (decodeGeometryBufferNormals) {
      defines += `#define DECODE_NORMAL
`;
    }
    if (!normalsAreInWorldSpace) {
      defines += `#define TRANSFORM_NORMAL
`;
    }
    for (let i = 0;i < this._giRSM.length; ++i) {
      const giRSM = this._giRSM[i];
      const rsm = giRSM.rsm;
      const ppGlobalIllumination = new PostProcess("RSMGlobalIllumination" + i, giRSM.useFullTexture ? "rsmFullGlobalIllumination" : "rsmGlobalIllumination", {
        ...this._giTextureDimensions,
        uniforms: ["rsmLightMatrix", "rsmInfo", "rsmInfo2", "invView"],
        samplers: ["normalSampler", "rsmPositionW", "rsmNormalW", "rsmFlux", "rsmSamples"],
        defines,
        samplingMode: 2,
        engine: this._engine,
        textureType: this._giTextureType,
        textureFormat,
        shaderLanguage: this._shaderLanguage
      });
      this._ppGlobalIllumination.push(ppGlobalIllumination);
      if (i !== 0) {
        ppGlobalIllumination.shareOutputWith(this._ppGlobalIllumination[0]);
        ppGlobalIllumination.alphaMode = 1;
      }
      ppGlobalIllumination.autoClear = false;
      ppGlobalIllumination.externalTextureSamplerBinding = true;
      ppGlobalIllumination.onApplyObservable.add((effect2) => {
        effect2.setTexture("textureSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE)]);
        effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE)]);
        effect2.setTexture("rsmPositionW", rsm.positionWorldTexture);
        effect2.setTexture("rsmNormalW", rsm.normalWorldTexture);
        effect2.setTexture("rsmFlux", rsm.fluxTexture);
        effect2.setMatrix("rsmLightMatrix", rsm.lightTransformationMatrix);
        if (!giRSM.useFullTexture) {
          effect2.setTexture("rsmSamples", this._sampleTexture);
          effect2.setFloat4("rsmInfo", giRSM.numSamples, giRSM.radius, giRSM.intensity, giRSM.edgeArtifactCorrection);
          effect2.setFloat4("rsmInfo2", giRSM.noiseFactor, giRSM.rotateSample ? 1 : 0, rsm.fluxTexture.getInternalTexture().width, rsm.fluxTexture.getInternalTexture().height);
        } else {
          effect2.setFloat4("rsmInfo", rsm.fluxTexture.getInternalTexture().width, rsm.fluxTexture.getInternalTexture().height, giRSM.intensity, giRSM.edgeArtifactCorrection);
        }
        if (!normalsAreInWorldSpace) {
          this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix());
          this._tempMatrix.invert();
          effect2.setMatrix("invView", this._tempMatrix);
        }
      });
    }
    for (const ppGlobalIllumination of this._ppGlobalIllumination) {
      if (!ppGlobalIllumination.inputTexture) {
        ppGlobalIllumination.resize(this._giTextureDimensions.width, this._giTextureDimensions.height);
      }
    }
    this._counters.push({ name: "GI generation", value: 0 });
    this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]);
    if (this._enableBlur) {
      const blurTextureSize = this._forceFullSizeBlur ? this._outputDimensions : this._giTextureDimensions;
      this._blurRTT = new RenderTargetTexture("GIRSMContribution", this._outputDimensions, this._scene, {
        type: this._giTextureType,
        format: textureFormat,
        generateDepthBuffer: false
      });
      this._blurRTT.wrapU = 0;
      this._blurRTT.wrapV = 0;
      this._blurRTT.updateSamplingMode(1);
      this._blurRTT.skipInitialClear = true;
      const blurRTWs = [];
      this._counters.push({ name: "GI blur", value: 0 });
      this._countersRTW.push(blurRTWs);
      this._blurXPostprocess = new PostProcess(this._useQualityBlur ? "BilateralBlur" : "BilateralBlurX", this._useQualityBlur ? "bilateralBlurQuality" : "bilateralBlur", {
        uniforms: ["filterSize", "blurDir", "depthThreshold", "normalThreshold"],
        samplers: ["depthSampler", "normalSampler"],
        defines: decodeGeometryBufferNormals ? "#define DECODE_NORMAL" : undefined,
        size: blurTextureSize,
        samplingMode: 2,
        engine: this._engine,
        textureType: this._giTextureType,
        textureFormat,
        shaderLanguage: this._shaderLanguage
      });
      this._blurXPostprocess.onApplyObservable.add((effect2) => {
        effect2._bindTexture("textureSampler", this._ppGlobalIllumination[0].inputTexture.texture);
        effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE)]);
        effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE)]);
        effect2.setInt("filterSize", this.blurKernel);
        effect2.setFloat2("blurDir", 1 / this._giTextureDimensions.width, this._useQualityBlur ? 1 / this._giTextureDimensions.height : 0);
        effect2.setFloat("depthThreshold", this.blurDepthThreshold);
        effect2.setFloat("normalThreshold", this.blurNormalThreshold);
      });
      this._blurXPostprocess.externalTextureSamplerBinding = true;
      this._blurXPostprocess.autoClear = false;
      if (!this._useQualityBlur) {
        this._blurYPostprocess = new PostProcess("BilateralBlurY", "bilateralBlur", {
          uniforms: ["filterSize", "blurDir", "depthThreshold", "normalThreshold"],
          samplers: ["depthSampler", "normalSampler"],
          defines: decodeGeometryBufferNormals ? "#define DECODE_NORMAL" : undefined,
          size: blurTextureSize,
          samplingMode: 2,
          engine: this._engine,
          textureType: this._giTextureType,
          textureFormat,
          shaderLanguage: this._shaderLanguage
        });
        this._blurYPostprocess.autoClear = false;
        this._blurYPostprocess.onApplyObservable.add((effect2) => {
          effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE)]);
          effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE)]);
          effect2.setInt("filterSize", this.blurKernel);
          effect2.setFloat2("blurDir", 0, 1 / this._giTextureDimensions.height);
          effect2.setFloat("depthThreshold", this.blurDepthThreshold);
          effect2.setFloat("normalThreshold", this.blurNormalThreshold);
        });
        this._blurYPostprocess.resize(blurTextureSize.width, blurTextureSize.height);
        blurRTWs.push(this._blurYPostprocess.inputTexture);
      }
      this._blurPostProcesses = [this._blurXPostprocess];
      if (this._blurYPostprocess) {
        this._blurPostProcesses.push(this._blurYPostprocess);
      }
      const giFullDimensions = this._giTextureDimensions.width >= this._outputDimensions.width && this._giTextureDimensions.height >= this._outputDimensions.height;
      if (!giFullDimensions && !this._forceFullSizeBlur) {
        const upsamplingRTWs = [];
        this._counters.push({ name: "GI upsampling", value: 0 });
        this._countersRTW.push(upsamplingRTWs);
        this._upsamplingXPostprocess = new PostProcess(this._useQualityUpsampling ? "BilateralUpsampling" : "BilateralUpsamplingX", this._useQualityUpsampling ? "bilateralBlurQuality" : "bilateralBlur", {
          uniforms: ["filterSize", "blurDir", "depthThreshold", "normalThreshold"],
          samplers: ["depthSampler", "normalSampler"],
          defines: decodeGeometryBufferNormals ? "#define DECODE_NORMAL" : undefined,
          size: blurTextureSize,
          samplingMode: 2,
          engine: this._engine,
          textureType: this._giTextureType,
          textureFormat,
          shaderLanguage: this._shaderLanguage
        });
        this._upsamplingXPostprocess.autoClear = false;
        this._upsamplingXPostprocess.onApplyObservable.add((effect2) => {
          effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE)]);
          effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE)]);
          effect2.setInt("filterSize", this.upsamplerKernel);
          effect2.setFloat2("blurDir", 1 / this._outputDimensions.width, this._useQualityUpsampling ? 1 / this._outputDimensions.height : 0);
          effect2.setFloat("depthThreshold", this.blurDepthThreshold);
          effect2.setFloat("normalThreshold", this.blurNormalThreshold);
        });
        this._upsamplingXPostprocess.resize(blurTextureSize.width, blurTextureSize.height);
        blurRTWs.push(this._upsamplingXPostprocess.inputTexture);
        if (!this.useQualityUpsampling) {
          this._upsamplingYPostprocess = new PostProcess("BilateralUpsamplingY", "bilateralBlur", {
            uniforms: ["filterSize", "blurDir", "depthThreshold", "normalThreshold"],
            samplers: ["depthSampler", "normalSampler"],
            defines: decodeGeometryBufferNormals ? "#define DECODE_NORMAL" : undefined,
            size: this._outputDimensions,
            samplingMode: 2,
            engine: this._engine,
            textureType: this._giTextureType,
            textureFormat,
            shaderLanguage: this._shaderLanguage
          });
          this._upsamplingYPostprocess.autoClear = false;
          this._upsamplingYPostprocess.onApplyObservable.add((effect2) => {
            effect2.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE)]);
            effect2.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE)]);
            effect2.setInt("filterSize", this.upsamplerKernel);
            effect2.setFloat2("blurDir", 0, 1 / this._outputDimensions.height);
            effect2.setFloat("depthThreshold", this.blurDepthThreshold);
            effect2.setFloat("normalThreshold", this.blurNormalThreshold);
          });
          this._upsamplingYPostprocess.resize(this._outputDimensions.width, this._outputDimensions.height);
          upsamplingRTWs.push(this._upsamplingYPostprocess.inputTexture);
        }
        upsamplingRTWs.push(this._blurRTT.renderTarget);
        this._blurPostProcesses.push(this._upsamplingXPostprocess);
        if (this._upsamplingYPostprocess) {
          this._blurPostProcesses.push(this._upsamplingYPostprocess);
        }
      } else {
        blurRTWs.push(this._blurRTT.renderTarget);
      }
    }
    this._debugLayer.texture?.dispose();
    this._debugLayer.texture = new BaseTexture(this._scene, this._enableBlur ? this._blurRTT.renderTarget.texture : this._ppGlobalIllumination[0].inputTexture.texture);
  }
  _addGISupportToMaterial(material2) {
    if (material2.pluginManager?.getPlugin(GIRSMRenderPluginMaterial.Name)) {
      return;
    }
    const plugin = new GIRSMRenderPluginMaterial(material2);
    if (this._enable && this._ppGlobalIllumination.length > 0) {
      plugin.textureGIContrib = this._ppGlobalIllumination[0].inputTexture.texture;
      plugin.outputTextureWidth = this._outputDimensions.width;
      plugin.outputTextureHeight = this._outputDimensions.height;
    }
    plugin.isEnabled = this._enable;
    this._materialsWithRenderPlugin.push(material2);
  }
}
GIRSMManager.GeometryBufferTextureTypesAndFormats = {
  0: { textureType: 2, textureFormat: 6 },
  1: { textureType: 11, textureFormat: 5 },
  2: { textureType: 2, textureFormat: 5 }
};

class MaterialGIRSMRenderDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.RENDER_WITH_GIRSM = false;
    this.RSMCREATE_PROJTEXTURE = false;
  }
}

class GIRSMRenderPluginMaterial extends MaterialPluginBase {
  _markAllSubMeshesAsTexturesDirty() {
    this._enable(this._isEnabled);
    this._internalMarkAllSubMeshesAsTexturesDirty();
  }
  isCompatible() {
    return true;
  }
  constructor(material2) {
    super(material2, GIRSMRenderPluginMaterial.Name, 310, new MaterialGIRSMRenderDefines);
    this._isEnabled = false;
    this.isEnabled = false;
    this._internalMarkAllSubMeshesAsTexturesDirty = material2._dirtyCallbacks[1];
    this._isPBR = material2 instanceof PBRBaseMaterial;
  }
  prepareDefines(defines) {
    defines.RENDER_WITH_GIRSM = this._isEnabled;
  }
  getClassName() {
    return "GIRSMRenderPluginMaterial";
  }
  getUniforms() {
    return {
      ubo: [{ name: "girsmTextureOutputSize", size: 2, type: "vec2" }],
      fragment: `#ifdef RENDER_WITH_GIRSM
                    uniform vec2 girsmTextureOutputSize;
                #endif`
    };
  }
  getSamplers(samplers) {
    samplers.push("girsmTextureGIContrib");
  }
  bindForSubMesh(uniformBuffer2) {
    if (this._isEnabled) {
      uniformBuffer2.bindTexture("girsmTextureGIContrib", this.textureGIContrib);
      uniformBuffer2.updateFloat2("girsmTextureOutputSize", this.outputTextureWidth, this.outputTextureHeight);
    }
  }
  getCustomCode(shaderType, shaderLanguage2) {
    let frag;
    if (shaderLanguage2 === 1) {
      frag = {
        CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RENDER_WITH_GIRSM
                    var girsmTextureGIContribSampler: sampler;
                    var girsmTextureGIContrib: texture_2d<f32>;

                    fn computeIndirect() -> vec3f {
                        var uv = fragmentInputs.position.xy / uniforms.girsmTextureOutputSize;
                        return textureSample(girsmTextureGIContrib, girsmTextureGIContribSampler, uv).rgb;
                    }
                #endif
            `,
        CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: `
                #ifdef RENDER_WITH_GIRSM
                    finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;
                #endif
            `
      };
      if (!this._isPBR) {
        frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = `
                #ifdef RENDER_WITH_GIRSM
                    color = vec4f(color.rgb + computeIndirect() * baseColor.rgb, color.a);
                #endif
            `;
      }
    } else {
      frag = {
        CUSTOM_FRAGMENT_DEFINITIONS: `
                #ifdef RENDER_WITH_GIRSM
                    uniform sampler2D girsmTextureGIContrib;

                    vec3 computeIndirect() {
                        vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;
                        return texture2D(girsmTextureGIContrib, uv).rgb;
                    }
                #endif
            `,
        CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION: `
                #ifdef RENDER_WITH_GIRSM
                    finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;
                #endif
            `
      };
      if (!this._isPBR) {
        frag["CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR"] = `
                #ifdef RENDER_WITH_GIRSM
                    color.rgb += computeIndirect() * baseColor.rgb;
                #endif
            `;
      }
    }
    return shaderType === "vertex" ? null : frag;
  }
}
GIRSMRenderPluginMaterial.Name = "GIRSMRender";
__decorate([
  serialize()
], GIRSMRenderPluginMaterial.prototype, "textureGIContrib", undefined);
__decorate([
  serialize()
], GIRSMRenderPluginMaterial.prototype, "outputTextureWidth", undefined);
__decorate([
  serialize()
], GIRSMRenderPluginMaterial.prototype, "outputTextureHeight", undefined);
__decorate([
  serialize(),
  expandToProperty("_markAllSubMeshesAsTexturesDirty")
], GIRSMRenderPluginMaterial.prototype, "isEnabled", undefined);
RegisterClass(`BABYLON.GIRSMRenderPluginMaterial`, GIRSMRenderPluginMaterial);

// node_modules/@babylonjs/core/Rendering/GlobalIllumination/index.js
init_bilateralBlur_fragment2();
init_bilateralBlurQuality_fragment2();
init_rsmGlobalIllumination_fragment2();
init_rsmFullGlobalIllumination_fragment2();
init_bilateralBlur_fragment();
init_bilateralBlurQuality_fragment();
init_rsmGlobalIllumination_fragment();
init_rsmFullGlobalIllumination_fragment();

// node_modules/@babylonjs/core/Rendering/index.js
init_depth_fragment();
init_depth_vertex();
init_depth_fragment2();
init_depth_vertex2();
init_geometry_fragment();
init_geometry_vertex();
init_geometry_fragment2();
init_geometry_vertex2();
init_boundingBoxRenderer_fragment2();
init_boundingBoxRenderer_vertex2();
init_boundingBoxRenderer_fragment();
init_boundingBoxRenderer_vertex();
init_line_fragment2();
init_line_vertex2();
init_line_fragment();
init_line_vertex();
init_outline_fragment2();
init_outline_vertex2();
init_outline_fragment();
init_outline_vertex();
init_copyTexture3DLayerToTexture_fragment();
init_copyTexture3DLayerToTexture_fragment2();
init_iblShadowVoxelTracing_fragment();
init_iblShadowVoxelTracing_fragment2();
init_iblShadowDebug_fragment();
init_iblShadowDebug_fragment2();
init_iblShadowSpatialBlur_fragment();
init_iblShadowSpatialBlur_fragment2();
init_iblShadowAccumulation_fragment();
init_iblShadowAccumulation_fragment2();

// node_modules/@babylonjs/core/Shaders/iblShadowsCombine.fragment.js
init_shaderStore();
var name507 = "iblShadowsCombinePixelShader";
var shader506 = `precision highp float;varying vec2 vUV;uniform sampler2D shadowSampler;uniform sampler2D textureSampler;uniform float shadowOpacity;void main(void)
{vec3 shadow=texture(shadowSampler,vUV).rgb;vec3 sceneColor=texture(textureSampler,vUV).rgb;float shadowValue=mix(1.0,shadow.x,shadowOpacity);gl_FragColor=vec4(sceneColor*shadowValue,1.0);}`;
if (!ShaderStore.ShadersStore[name507]) {
  ShaderStore.ShadersStore[name507] = shader506;
}
// node_modules/@babylonjs/core/ShadersWGSL/iblShadowsCombine.fragment.js
init_shaderStore();
var name508 = "iblShadowsCombinePixelShader";
var shader507 = `varying vUV: vec2f;var shadowSamplerSampler : sampler;var shadowSampler : texture_2d<f32>;var textureSamplerSampler: sampler;var textureSampler: texture_2d<f32>;uniform shadowOpacity: f32;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {var shadow
: vec3f =
textureSample(shadowSampler,shadowSamplerSampler,input.vUV).rgb;var color
: vec3f =
textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var shadowValue: f32=mix(1.0,shadow.x,uniforms.shadowOpacity);fragmentOutputs.color=vec4f(color*shadowValue,1.0);}`;
if (!ShaderStore.ShadersStoreWGSL[name508]) {
  ShaderStore.ShadersStoreWGSL[name508] = shader507;
}

// node_modules/@babylonjs/core/Rendering/index.js
init_iblCombineVoxelGrids_fragment();
init_iblCombineVoxelGrids_fragment2();
init_iblGenerateVoxelMip_fragment();
init_iblGenerateVoxelMip_fragment2();
init_iblShadowGBufferDebug_fragment();
init_iblShadowGBufferDebug_fragment2();
init_iblCdfx_fragment();
init_iblCdfx_fragment2();
init_iblCdfy_fragment();
init_iblCdfy_fragment2();
init_iblIcdf_fragment();
init_iblIcdf_fragment2();
init_iblCdfDebug_fragment();
init_iblCdfDebug_fragment2();
init_iblScaledLuminance_fragment();
init_iblScaledLuminance_fragment2();
init_iblVoxelGrid2dArrayDebug_fragment();
init_iblVoxelGrid2dArrayDebug_fragment2();
init_iblVoxelGrid_fragment();
init_iblVoxelGrid_vertex();
init_iblVoxelGrid_fragment2();
init_iblVoxelGrid_vertex2();
init_iblVoxelGrid3dDebug_fragment();
init_iblVoxelGrid3dDebug_fragment2();
init_iblVoxelSlabDebug_vertex();
init_iblVoxelSlabDebug_fragment();
init_iblVoxelSlabDebug_vertex2();
init_iblVoxelSlabDebug_fragment2();
init_oitBackBlend_fragment2();
init_oitFinal_fragment2();
init_oitBackBlend_fragment();
init_oitFinal_fragment();

// node_modules/@babylonjs/core/index.js
init_scene();
init_sceneComponent();
// node_modules/@babylonjs/core/Sprites/spriteMap.js
init_math_vector();
init_texture();
init_effect();

// node_modules/@babylonjs/core/Shaders/spriteMap.fragment.js
init_shaderStore();
init_fogFragmentDeclaration2();
init_logDepthDeclaration2();
init_logDepthFragment2();
init_fogFragment2();
var name527 = "spriteMapPixelShader";
var shader526 = `#ifdef LOGARITHMICDEPTH
#extension GL_EXT_frag_depth : enable
#endif
#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)
#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)
#else
#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)
#endif
precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;
#include<fogFragmentDeclaration>
#include<logDepthDeclaration>
float mt;const float fdStep=1.0*0.25;const float aFrameSteps=MAX_ANIMATION_FRAMES==0.0 ? 0.0 : 1.0/MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID) {float fX=frameID/spriteCount;return mat4(
TEXTUREFUNC(frameMap,vec2(fX,0.0),0.0),
TEXTUREFUNC(frameMap,vec2(fX,fdStep*1.0),0.0),
TEXTUREFUNC(frameMap,vec2(fX,fdStep*2.0),0.0),
vec4(0.0)
);}
void main() {vec4 color=vec4(0.0);vec2 tileUV=fract(tUV);vec2 tileID=floor(tUV);vec2 sheetUnits=1.0/spriteMapSize;float spriteUnits=1.0/spriteCount;vec2 stageUnits=1.0/stageSize;for(int i=0; i<LAYERS; i++) {float frameID;
#define LAYER_ID_SWITCH
vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.0),0.0);if(animationData.y>0.0) {mt=mod(time*animationData.z,1.0);for(float f=0.0; f<MAX_ANIMATION_FRAMES; f++) {if(animationData.y>mt) {frameID=animationData.x;break;}
animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.0);}}
mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;
#ifdef FR_CW
if (frameData[2].z==1.0) {tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;}
#ifdef FLIPU
tileUV.y=1.0-tileUV.y;
#endif
#else
if (frameData[2].z==1.0) {
#ifdef FLIPU
tileUV.y=1.0-tileUV.y;
#endif
tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;
#ifdef FLIPU
tileUV.y=1.0-tileUV.y;
#endif
}
#endif
vec4 nc=TEXTUREFUNC(spriteSheet,tileUV*frameSize+offset,0.0);if (i==0) {color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}
color.xyz*=colorMul;
#include<logDepthFragment>
#include<fogFragment>
gl_FragColor=color;}`;
if (!ShaderStore.ShadersStore[name527]) {
  ShaderStore.ShadersStore[name527] = shader526;
}

// node_modules/@babylonjs/core/Shaders/spriteMap.vertex.js
init_shaderStore();
init_fogVertexDeclaration2();
init_logDepthDeclaration2();
init_logDepthVertex2();
var name528 = "spriteMapVertexShader";
var shader527 = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform mat4 world;uniform mat4 view;uniform mat4 projection;uniform vec2 stageSize;uniform float stageScale;
#include<fogVertexDeclaration>
#include<logDepthDeclaration>
void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; 
vec3 viewPos=(view*world*p).xyz; 
gl_Position=projection*vec4(viewPos,1.0); 
#ifdef FOG
vFogDistance=viewPos;
#endif
#include<logDepthVertex>
}`;
if (!ShaderStore.ShadersStore[name528]) {
  ShaderStore.ShadersStore[name528] = shader527;
}

// node_modules/@babylonjs/core/Sprites/spriteMap.js
var SpriteMapFrameRotationDirection;
(function(SpriteMapFrameRotationDirection2) {
  SpriteMapFrameRotationDirection2[SpriteMapFrameRotationDirection2["CCW"] = 0] = "CCW";
  SpriteMapFrameRotationDirection2[SpriteMapFrameRotationDirection2["CW"] = 1] = "CW";
})(SpriteMapFrameRotationDirection || (SpriteMapFrameRotationDirection = {}));
// node_modules/@babylonjs/core/Sprites/spritePackedManager.js
init_texture();

// node_modules/@babylonjs/core/Sprites/index.js
init_sprites_fragment2();
init_sprites_vertex2();
init_sprites_fragment();
init_sprites_vertex();
// node_modules/@babylonjs/core/States/index.js
init_stencilState();
// node_modules/@babylonjs/core/XR/webXRTypes.js
var WebXRState;
(function(WebXRState2) {
  WebXRState2[WebXRState2["ENTERING_XR"] = 0] = "ENTERING_XR";
  WebXRState2[WebXRState2["EXITING_XR"] = 1] = "EXITING_XR";
  WebXRState2[WebXRState2["IN_XR"] = 2] = "IN_XR";
  WebXRState2[WebXRState2["NOT_IN_XR"] = 3] = "NOT_IN_XR";
})(WebXRState || (WebXRState = {}));
var WebXRTrackingState;
(function(WebXRTrackingState2) {
  WebXRTrackingState2[WebXRTrackingState2["NOT_TRACKING"] = 0] = "NOT_TRACKING";
  WebXRTrackingState2[WebXRTrackingState2["TRACKING_LOST"] = 1] = "TRACKING_LOST";
  WebXRTrackingState2[WebXRTrackingState2["TRACKING"] = 2] = "TRACKING";
})(WebXRTrackingState || (WebXRTrackingState = {}));
// node_modules/@babylonjs/core/XR/features/WebXRHitTestLegacy.js
init_observable();
init_math_vector();
init_tools();

class WebXRHitTestLegacy extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options = {}) {
    super(_xrSessionManager);
    this.options = options;
    this._direction = new Vector3(0, 0, -1);
    this._mat = new Matrix;
    this._onSelectEnabled = false;
    this._origin = new Vector3(0, 0, 0);
    this.lastNativeXRHitResults = [];
    this.onHitTestResultObservable = new Observable;
    this._onHitTestResults = (xrResults) => {
      const mats = xrResults.map((result) => {
        const mat = Matrix.FromArray(result.hitMatrix);
        if (!this._xrSessionManager.scene.useRightHandedSystem) {
          mat.toggleModelMatrixHandInPlace();
        }
        if (this.options.worldParentNode) {
          mat.multiplyToRef(this.options.worldParentNode.getWorldMatrix(), mat);
        }
        return {
          xrHitResult: result,
          transformationMatrix: mat
        };
      });
      this.lastNativeXRHitResults = xrResults;
      this.onHitTestResultObservable.notifyObservers(mats);
    };
    this._onSelect = (event) => {
      if (!this._onSelectEnabled) {
        return;
      }
      WebXRHitTestLegacy.XRHitTestWithSelectEvent(event, this._xrSessionManager.referenceSpace);
    };
    this.xrNativeFeatureName = "hit-test";
    Tools.Warn("A newer version of this plugin is available");
  }
  static XRHitTestWithRay(xrSession, xrRay, referenceSpace, filter) {
    return xrSession.requestHitTest(xrRay, referenceSpace).then((results) => {
      const filterFunction = filter || ((result) => !!result.hitMatrix);
      return results.filter(filterFunction);
    });
  }
  static XRHitTestWithSelectEvent(event, referenceSpace) {
    const targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, referenceSpace);
    if (!targetRayPose) {
      return Promise.resolve([]);
    }
    const targetRay = new XRRay(targetRayPose.transform);
    return this.XRHitTestWithRay(event.frame.session, targetRay, referenceSpace);
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    if (this.options.testOnPointerDownOnly) {
      this._xrSessionManager.session.addEventListener("select", this._onSelect, false);
    }
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    this._onSelectEnabled = false;
    this._xrSessionManager.session.removeEventListener("select", this._onSelect);
    return true;
  }
  dispose() {
    super.dispose();
    this.onHitTestResultObservable.clear();
  }
  _onXRFrame(frame2) {
    if (!this.attached || this.options.testOnPointerDownOnly) {
      return;
    }
    const pose = frame2.getViewerPose(this._xrSessionManager.referenceSpace);
    if (!pose) {
      return;
    }
    Matrix.FromArrayToRef(pose.transform.matrix, 0, this._mat);
    Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, this._mat, this._origin);
    Vector3.TransformCoordinatesFromFloatsToRef(0, 0, -1, this._mat, this._direction);
    this._direction.subtractInPlace(this._origin);
    this._direction.normalize();
    const ray2 = new XRRay({ x: this._origin.x, y: this._origin.y, z: this._origin.z, w: 0 }, { x: this._direction.x, y: this._direction.y, z: this._direction.z, w: 0 });
    WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session, ray2, this._xrSessionManager.referenceSpace).then(this._onHitTestResults);
  }
}
WebXRHitTestLegacy.Name = WebXRFeatureName.HIT_TEST;
WebXRHitTestLegacy.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name, (xrSessionManager, options) => {
  return () => new WebXRHitTestLegacy(xrSessionManager, options);
}, WebXRHitTestLegacy.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRAnchorSystem.js
init_observable();
init_math_vector();
init_tools();
var anchorIdProvider = 0;

class WebXRAnchorSystem extends WebXRAbstractFeature {
  set referenceSpaceForFrameAnchors(referenceSpace) {
    this._referenceSpaceForFrameAnchors = referenceSpace;
  }
  constructor(_xrSessionManager, _options = {}) {
    super(_xrSessionManager);
    this._options = _options;
    this._lastFrameDetected = new Set;
    this._trackedAnchors = [];
    this._futureAnchors = [];
    this.onAnchorAddedObservable = new Observable;
    this.onAnchorRemovedObservable = new Observable;
    this.onAnchorUpdatedObservable = new Observable;
    this._tmpVector = new Vector3;
    this._tmpQuaternion = new Quaternion;
    this.xrNativeFeatureName = "anchors";
    if (this._options.clearAnchorsOnSessionInit) {
      this._xrSessionManager.onXRSessionInit.add(() => {
        this._trackedAnchors.length = 0;
        this._futureAnchors.length = 0;
        this._lastFrameDetected.clear();
      });
    }
  }
  _populateTmpTransformation(position, rotationQuaternion) {
    this._tmpVector.copyFrom(position);
    this._tmpQuaternion.copyFrom(rotationQuaternion);
    if (!this._xrSessionManager.scene.useRightHandedSystem) {
      this._tmpVector.z *= -1;
      this._tmpQuaternion.z *= -1;
      this._tmpQuaternion.w *= -1;
    }
    return {
      position: this._tmpVector,
      rotationQuaternion: this._tmpQuaternion
    };
  }
  async addAnchorPointUsingHitTestResultAsync(hitTestResult, position = new Vector3, rotationQuaternion = new Quaternion) {
    this._populateTmpTransformation(position, rotationQuaternion);
    const m = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });
    if (!hitTestResult.xrHitResult.createAnchor) {
      this.detach();
      throw new Error("Anchors not enabled in this environment/browser");
    } else {
      try {
        const nativeAnchor = await hitTestResult.xrHitResult.createAnchor(m);
        return new Promise((resolve3, reject) => {
          this._futureAnchors.push({
            nativeAnchor,
            resolved: false,
            submitted: true,
            xrTransformation: m,
            resolve: resolve3,
            reject
          });
        });
      } catch (error2) {
        throw new Error(error2);
      }
    }
  }
  async addAnchorAtPositionAndRotationAsync(position, rotationQuaternion = new Quaternion, forceCreateInCurrentFrame = false) {
    this._populateTmpTransformation(position, rotationQuaternion);
    const xrTransformation = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });
    const xrAnchor = forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame ? await this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame) : undefined;
    return new Promise((resolve3, reject) => {
      this._futureAnchors.push({
        nativeAnchor: xrAnchor,
        resolved: false,
        submitted: false,
        xrTransformation,
        resolve: resolve3,
        reject
      });
    });
  }
  get anchors() {
    return this._trackedAnchors;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    if (!this._options.doNotRemoveAnchorsOnSessionEnded) {
      while (this._trackedAnchors.length) {
        const toRemove = this._trackedAnchors.pop();
        if (toRemove && !toRemove._removed) {
          this.onAnchorRemovedObservable.notifyObservers(toRemove);
          toRemove._removed = true;
        }
      }
    }
    return true;
  }
  dispose() {
    this._futureAnchors.length = 0;
    super.dispose();
    this.onAnchorAddedObservable.clear();
    this.onAnchorRemovedObservable.clear();
    this.onAnchorUpdatedObservable.clear();
  }
  _onXRFrame(frame2) {
    if (!this.attached || !frame2) {
      return;
    }
    const trackedAnchors = frame2.trackedAnchors;
    if (trackedAnchors) {
      const toRemove = this._trackedAnchors.filter((anchor) => anchor._removed).map((anchor) => {
        return this._trackedAnchors.indexOf(anchor);
      });
      let idxTracker = 0;
      toRemove.forEach((index) => {
        const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0];
        anchor.xrAnchor.delete();
        this.onAnchorRemovedObservable.notifyObservers(anchor);
        idxTracker++;
      });
      trackedAnchors.forEach((xrAnchor) => {
        if (!this._lastFrameDetected.has(xrAnchor)) {
          const newAnchor = {
            id: anchorIdProvider++,
            xrAnchor,
            remove: () => {
              newAnchor._removed = true;
            }
          };
          const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame2);
          this._trackedAnchors.push(anchor);
          this.onAnchorAddedObservable.notifyObservers(anchor);
          const results = this._futureAnchors.filter((futureAnchor) => futureAnchor.nativeAnchor === xrAnchor);
          const result = results[0];
          if (result) {
            result.resolve(anchor);
            result.resolved = true;
          }
        } else {
          const index = this._findIndexInAnchorArray(xrAnchor);
          const anchor = this._trackedAnchors[index];
          try {
            this._updateAnchorWithXRFrame(xrAnchor, anchor, frame2);
            if (anchor.attachedNode) {
              anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new Quaternion;
              anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position);
            }
            this.onAnchorUpdatedObservable.notifyObservers(anchor);
          } catch (e) {
            Tools.Warn(`Anchor could not be updated`);
          }
        }
      });
      this._lastFrameDetected = trackedAnchors;
    }
    this._futureAnchors.forEach((futureAnchor) => {
      if (!futureAnchor.resolved && !futureAnchor.submitted) {
        this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame2).then((nativeAnchor) => {
          futureAnchor.nativeAnchor = nativeAnchor;
        }, (error2) => {
          futureAnchor.resolved = true;
          futureAnchor.reject(error2);
        });
        futureAnchor.submitted = true;
      }
    });
  }
  _findIndexInAnchorArray(xrAnchor) {
    for (let i = 0;i < this._trackedAnchors.length; ++i) {
      if (this._trackedAnchors[i].xrAnchor === xrAnchor) {
        return i;
      }
    }
    return -1;
  }
  _updateAnchorWithXRFrame(xrAnchor, anchor, xrFrame) {
    const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace);
    if (pose) {
      const mat = anchor.transformationMatrix || new Matrix;
      Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
      if (!this._xrSessionManager.scene.useRightHandedSystem) {
        mat.toggleModelMatrixHandInPlace();
      }
      anchor.transformationMatrix = mat;
      if (!this._options.worldParentNode) {} else {
        mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
      }
    }
    return anchor;
  }
  async _createAnchorAtTransformation(xrTransformation, xrFrame) {
    if (xrFrame.createAnchor) {
      try {
        return xrFrame.createAnchor(xrTransformation, this._referenceSpaceForFrameAnchors ?? this._xrSessionManager.referenceSpace);
      } catch (error2) {
        throw new Error(error2);
      }
    } else {
      this.detach();
      throw new Error("Anchors are not enabled in your browser");
    }
  }
}
WebXRAnchorSystem.Name = WebXRFeatureName.ANCHOR_SYSTEM;
WebXRAnchorSystem.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => {
  return () => new WebXRAnchorSystem(xrSessionManager, options);
}, WebXRAnchorSystem.Version);
// node_modules/@babylonjs/core/XR/features/WebXRPlaneDetector.js
init_observable();
init_math_vector();
var planeIdProvider = 0;

class WebXRPlaneDetector extends WebXRAbstractFeature {
  constructor(_xrSessionManager, _options = {}) {
    super(_xrSessionManager);
    this._options = _options;
    this._detectedPlanes = [];
    this._enabled = false;
    this._lastFrameDetected = new Set;
    this.onPlaneAddedObservable = new Observable;
    this.onPlaneRemovedObservable = new Observable;
    this.onPlaneUpdatedObservable = new Observable;
    this.xrNativeFeatureName = "plane-detection";
    if (this._xrSessionManager.session) {
      this._init();
    } else {
      this._xrSessionManager.onXRSessionInit.addOnce(() => {
        this._init();
      });
    }
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    if (!this._options.doNotRemovePlanesOnSessionEnded) {
      while (this._detectedPlanes.length) {
        const toRemove = this._detectedPlanes.pop();
        if (toRemove) {
          this.onPlaneRemovedObservable.notifyObservers(toRemove);
        }
      }
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.onPlaneAddedObservable.clear();
    this.onPlaneRemovedObservable.clear();
    this.onPlaneUpdatedObservable.clear();
  }
  isCompatible() {
    return typeof XRPlane !== "undefined";
  }
  async initiateRoomCapture() {
    if (this._xrSessionManager.session.initiateRoomCapture) {
      return this._xrSessionManager.session.initiateRoomCapture();
    }
    return Promise.reject("initiateRoomCapture is not supported on this session");
  }
  _onXRFrame(frame2) {
    if (!this.attached || !this._enabled || !frame2) {
      return;
    }
    const detectedPlanes = frame2.detectedPlanes || frame2.worldInformation?.detectedPlanes;
    if (detectedPlanes) {
      for (let planeIdx = 0;planeIdx < this._detectedPlanes.length; planeIdx++) {
        const plane = this._detectedPlanes[planeIdx];
        if (!detectedPlanes.has(plane.xrPlane)) {
          this._detectedPlanes.splice(planeIdx--, 1);
          this.onPlaneRemovedObservable.notifyObservers(plane);
        }
      }
      detectedPlanes.forEach((xrPlane) => {
        if (!this._lastFrameDetected.has(xrPlane)) {
          const newPlane = {
            id: planeIdProvider++,
            xrPlane,
            polygonDefinition: []
          };
          const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame2);
          this._detectedPlanes.push(plane);
          this.onPlaneAddedObservable.notifyObservers(plane);
        } else {
          if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) {
            const index = this._findIndexInPlaneArray(xrPlane);
            const plane = this._detectedPlanes[index];
            this._updatePlaneWithXRPlane(xrPlane, plane, frame2);
            this.onPlaneUpdatedObservable.notifyObservers(plane);
          }
        }
      });
      this._lastFrameDetected = detectedPlanes;
    }
  }
  _init() {
    const internalInit = () => {
      this._enabled = true;
      if (this._detectedPlanes.length) {
        this._detectedPlanes.length = 0;
      }
    };
    if (!!this._xrSessionManager.isNative && !!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions) {
      this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions);
    }
    if (!this._xrSessionManager.session.updateWorldTrackingState) {
      internalInit();
      return;
    }
    this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });
    internalInit();
  }
  _updatePlaneWithXRPlane(xrPlane, plane, xrFrame) {
    plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => {
      const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;
      return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem);
    });
    const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace);
    if (pose) {
      const mat = plane.transformationMatrix || new Matrix;
      Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
      if (!this._xrSessionManager.scene.useRightHandedSystem) {
        mat.toggleModelMatrixHandInPlace();
      }
      plane.transformationMatrix = mat;
      if (this._options.worldParentNode) {
        mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
      }
    }
    return plane;
  }
  _findIndexInPlaneArray(xrPlane) {
    for (let i = 0;i < this._detectedPlanes.length; ++i) {
      if (this._detectedPlanes[i].xrPlane === xrPlane) {
        return i;
      }
    }
    return -1;
  }
}
WebXRPlaneDetector.Name = WebXRFeatureName.PLANE_DETECTION;
WebXRPlaneDetector.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => {
  return () => new WebXRPlaneDetector(xrSessionManager, options);
}, WebXRPlaneDetector.Version);
// node_modules/@babylonjs/core/XR/features/WebXRBackgroundRemover.js
init_observable();
class WebXRBackgroundRemover extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options = {}) {
    super(_xrSessionManager);
    this.options = options;
    this.onBackgroundStateChangedObservable = new Observable;
  }
  attach() {
    this._setBackgroundState(false);
    return super.attach();
  }
  detach() {
    this._setBackgroundState(true);
    return super.detach();
  }
  dispose() {
    super.dispose();
    this.onBackgroundStateChangedObservable.clear();
  }
  _onXRFrame(_xrFrame) {}
  _setBackgroundState(newState) {
    const scene = this._xrSessionManager.scene;
    if (!this.options.ignoreEnvironmentHelper) {
      if (this.options.environmentHelperRemovalFlags) {
        if (this.options.environmentHelperRemovalFlags.skyBox) {
          const backgroundSkybox = scene.getMeshByName("BackgroundSkybox");
          if (backgroundSkybox) {
            backgroundSkybox.setEnabled(newState);
          }
        }
        if (this.options.environmentHelperRemovalFlags.ground) {
          const backgroundPlane = scene.getMeshByName("BackgroundPlane");
          if (backgroundPlane) {
            backgroundPlane.setEnabled(newState);
          }
        }
      } else {
        const backgroundHelper = scene.getMeshByName("BackgroundHelper");
        if (backgroundHelper) {
          backgroundHelper.setEnabled(newState);
        }
      }
    }
    if (this.options.backgroundMeshes) {
      this.options.backgroundMeshes.forEach((mesh2) => mesh2.setEnabled(newState));
    }
    this.onBackgroundStateChangedObservable.notifyObservers(newState);
  }
}
WebXRBackgroundRemover.Name = WebXRFeatureName.BACKGROUND_REMOVER;
WebXRBackgroundRemover.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name, (xrSessionManager, options) => {
  return () => new WebXRBackgroundRemover(xrSessionManager, options);
}, WebXRBackgroundRemover.Version, true);
// node_modules/@babylonjs/core/XR/features/WebXRControllerPhysics.js
init_math_vector();
init_logger();
class WebXRControllerPhysics extends WebXRAbstractFeature {
  _createPhysicsImpostor(xrController) {
    const impostorType = this._options.physicsProperties.impostorType || PhysicsImpostor.SphereImpostor;
    const impostorSize = this._options.physicsProperties.impostorSize || 0.1;
    const impostorMesh = CreateSphere("impostor-mesh-" + xrController.uniqueId, {
      diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width,
      diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height,
      diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth
    });
    impostorMesh.isVisible = this._debugMode;
    impostorMesh.isPickable = false;
    impostorMesh.rotationQuaternion = new Quaternion;
    const controllerMesh = xrController.grip || xrController.pointer;
    impostorMesh.position.copyFrom(controllerMesh.position);
    impostorMesh.rotationQuaternion.copyFrom(controllerMesh.rotationQuaternion);
    const impostor = new PhysicsImpostor(impostorMesh, impostorType, {
      mass: 0,
      ...this._options.physicsProperties
    });
    this._controllers[xrController.uniqueId] = {
      xrController,
      impostor,
      impostorMesh
    };
  }
  constructor(_xrSessionManager, _options) {
    super(_xrSessionManager);
    this._options = _options;
    this._attachController = (xrController) => {
      if (this._controllers[xrController.uniqueId]) {
        return;
      }
      if (!this._xrSessionManager.scene.isPhysicsEnabled()) {
        Logger.Warn("physics engine not enabled, skipped. Please add this controller manually.");
      }
      if (this._options.physicsProperties.useControllerMesh && xrController.inputSource.gamepad) {
        xrController.onMotionControllerInitObservable.addOnce((motionController) => {
          if (!motionController._doNotLoadControllerMesh) {
            motionController.onModelLoadedObservable.addOnce(() => {
              const impostor = new PhysicsImpostor(motionController.rootMesh, PhysicsImpostor.MeshImpostor, {
                mass: 0,
                ...this._options.physicsProperties
              });
              const controllerMesh = xrController.grip || xrController.pointer;
              this._controllers[xrController.uniqueId] = {
                xrController,
                impostor,
                oldPos: controllerMesh.position.clone(),
                oldRotation: controllerMesh.rotationQuaternion.clone()
              };
            });
          } else {
            this._createPhysicsImpostor(xrController);
          }
        });
      } else {
        this._createPhysicsImpostor(xrController);
      }
    };
    this._controllers = {};
    this._debugMode = false;
    this._delta = 0;
    this._lastTimestamp = 0;
    this._tmpQuaternion = new Quaternion;
    this._tmpVector = new Vector3;
    if (!this._options.physicsProperties) {
      this._options.physicsProperties = {};
    }
  }
  _enablePhysicsDebug() {
    this._debugMode = true;
    Object.keys(this._controllers).forEach((controllerId) => {
      const controllerData = this._controllers[controllerId];
      if (controllerData.impostorMesh) {
        controllerData.impostorMesh.isVisible = true;
      }
    });
  }
  addController(xrController) {
    this._attachController(xrController);
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    if (!this._options.xrInput) {
      return true;
    }
    this._options.xrInput.controllers.forEach(this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
    this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
      this._detachController(controller.uniqueId);
    });
    if (this._options.enableHeadsetImpostor) {
      const params = this._options.headsetImpostorParams || {
        impostorType: PhysicsImpostor.SphereImpostor,
        restitution: 0.8,
        impostorSize: 0.3
      };
      const impostorSize = params.impostorSize || 0.3;
      this._headsetMesh = CreateSphere("headset-mesh", {
        diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width,
        diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height,
        diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth
      });
      this._headsetMesh.rotationQuaternion = new Quaternion;
      this._headsetMesh.isVisible = false;
      this._headsetImpostor = new PhysicsImpostor(this._headsetMesh, params.impostorType, { mass: 0, ...params });
    }
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      this._detachController(controllerId);
    });
    if (this._headsetMesh) {
      this._headsetMesh.dispose();
    }
    return true;
  }
  getHeadsetImpostor() {
    return this._headsetImpostor;
  }
  getImpostorForController(controller) {
    const id = typeof controller === "string" ? controller : controller.uniqueId;
    if (this._controllers[id]) {
      return this._controllers[id].impostor;
    } else {
      return null;
    }
  }
  setPhysicsProperties(newProperties) {
    this._options.physicsProperties = {
      ...this._options.physicsProperties,
      ...newProperties
    };
  }
  _onXRFrame(_xrFrame) {
    this._delta = this._xrSessionManager.currentTimestamp - this._lastTimestamp;
    this._lastTimestamp = this._xrSessionManager.currentTimestamp;
    if (this._headsetMesh && this._headsetImpostor) {
      this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition);
      this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation);
      if (this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity) {
        const lv = this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;
        this._tmpVector.set(lv.x, lv.y, lv.z);
        this._headsetImpostor.setLinearVelocity(this._tmpVector);
      }
      if (this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity) {
        const av = this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;
        this._tmpVector.set(av.x, av.y, av.z);
        this._headsetImpostor.setAngularVelocity(this._tmpVector);
      }
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      const controllerData = this._controllers[controllerId];
      const controllerMesh = controllerData.xrController.grip || controllerData.xrController.pointer;
      const comparedPosition = controllerData.oldPos || controllerData.impostorMesh.position;
      if (controllerData.xrController._lastXRPose?.linearVelocity) {
        const lv = controllerData.xrController._lastXRPose.linearVelocity;
        this._tmpVector.set(lv.x, lv.y, lv.z);
        controllerData.impostor.setLinearVelocity(this._tmpVector);
      } else {
        controllerMesh.position.subtractToRef(comparedPosition, this._tmpVector);
        this._tmpVector.scaleInPlace(1000 / this._delta);
        controllerData.impostor.setLinearVelocity(this._tmpVector);
      }
      comparedPosition.copyFrom(controllerMesh.position);
      if (this._debugMode) {
        Logger.Log([this._tmpVector, "linear"]);
      }
      const comparedQuaternion = controllerData.oldRotation || controllerData.impostorMesh.rotationQuaternion;
      if (controllerData.xrController._lastXRPose?.angularVelocity) {
        const av = controllerData.xrController._lastXRPose.angularVelocity;
        this._tmpVector.set(av.x, av.y, av.z);
        controllerData.impostor.setAngularVelocity(this._tmpVector);
      } else {
        if (!comparedQuaternion.equalsWithEpsilon(controllerMesh.rotationQuaternion)) {
          comparedQuaternion.conjugateInPlace().multiplyToRef(controllerMesh.rotationQuaternion, this._tmpQuaternion);
          const len = Math.sqrt(this._tmpQuaternion.x * this._tmpQuaternion.x + this._tmpQuaternion.y * this._tmpQuaternion.y + this._tmpQuaternion.z * this._tmpQuaternion.z);
          this._tmpVector.set(this._tmpQuaternion.x, this._tmpQuaternion.y, this._tmpQuaternion.z);
          if (len < 0.001) {
            this._tmpVector.scaleInPlace(2);
          } else {
            const angle = 2 * Math.atan2(len, this._tmpQuaternion.w);
            this._tmpVector.scaleInPlace(angle / (len * (this._delta / 1000)));
          }
          controllerData.impostor.setAngularVelocity(this._tmpVector);
        }
      }
      comparedQuaternion.copyFrom(controllerMesh.rotationQuaternion);
      if (this._debugMode) {
        Logger.Log([this._tmpVector, this._tmpQuaternion, "angular"]);
      }
    });
  }
  _detachController(xrControllerUniqueId) {
    const controllerData = this._controllers[xrControllerUniqueId];
    if (!controllerData) {
      return;
    }
    if (controllerData.impostorMesh) {
      controllerData.impostorMesh.dispose();
    }
    delete this._controllers[xrControllerUniqueId];
  }
}
WebXRControllerPhysics.Name = WebXRFeatureName.PHYSICS_CONTROLLERS;
WebXRControllerPhysics.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name, (xrSessionManager, options) => {
  return () => new WebXRControllerPhysics(xrSessionManager, options);
}, WebXRControllerPhysics.Version, true);
// node_modules/@babylonjs/core/XR/features/WebXRHitTest.js
init_observable();
init_math_vector();
init_tools();

class WebXRHitTest extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options = {}) {
    super(_xrSessionManager);
    this.options = options;
    this._tmpMat = new Matrix;
    this._tmpPos = new Vector3;
    this._tmpQuat = new Quaternion;
    this._initHitTestSource = (referenceSpace) => {
      if (!referenceSpace) {
        return;
      }
      const offsetRay = new XRRay(this.options.offsetRay || {});
      const hitTestOptions = {
        space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace,
        offsetRay
      };
      if (this.options.entityTypes) {
        hitTestOptions.entityTypes = this.options.entityTypes;
      }
      if (!hitTestOptions.space) {
        Tools.Warn("waiting for viewer reference space to initialize");
        return;
      }
      this._xrSessionManager.session.requestHitTestSource(hitTestOptions).then((hitTestSource) => {
        if (this._xrHitTestSource) {
          this._xrHitTestSource.cancel();
        }
        this._xrHitTestSource = hitTestSource;
      });
    };
    this.autoCloneTransformation = false;
    this.onHitTestResultObservable = new Observable;
    this.paused = false;
    this.xrNativeFeatureName = "hit-test";
    Tools.Warn("Hit test is an experimental and unstable feature.");
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    if (!this._xrSessionManager.session.requestHitTestSource) {
      return false;
    }
    if (!this.options.disablePermanentHitTest) {
      if (this._xrSessionManager.referenceSpace) {
        this._initHitTestSource(this._xrSessionManager.referenceSpace);
      }
      this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource);
    }
    if (this.options.enableTransientHitTest) {
      const offsetRay = new XRRay(this.options.transientOffsetRay || {});
      this._xrSessionManager.session.requestHitTestSourceForTransientInput({
        profile: this.options.transientHitTestProfile || "generic-touchscreen",
        offsetRay,
        entityTypes: this.options.entityTypes
      }).then((hitSource) => {
        this._transientXrHitTestSource = hitSource;
      });
    }
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    if (this._xrHitTestSource) {
      this._xrHitTestSource.cancel();
      this._xrHitTestSource = null;
    }
    this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource);
    if (this._transientXrHitTestSource) {
      this._transientXrHitTestSource.cancel();
      this._transientXrHitTestSource = null;
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.onHitTestResultObservable.clear();
  }
  _onXRFrame(frame2) {
    if (!this.attached || this.paused) {
      return;
    }
    if (this._xrHitTestSource) {
      const results = frame2.getHitTestResults(this._xrHitTestSource);
      this._processWebXRHitTestResult(results);
    }
    if (this._transientXrHitTestSource) {
      const hitTestResultsPerInputSource = frame2.getHitTestResultsForTransientInput(this._transientXrHitTestSource);
      hitTestResultsPerInputSource.forEach((resultsPerInputSource) => {
        this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource);
      });
    }
  }
  _processWebXRHitTestResult(hitTestResults, inputSource) {
    const results = [];
    hitTestResults.forEach((hitTestResult) => {
      const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace);
      if (!pose) {
        return;
      }
      const pos = pose.transform.position;
      const quat = pose.transform.orientation;
      this._tmpPos.set(pos.x, pos.y, pos.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);
      this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w);
      Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat);
      if (!this._xrSessionManager.scene.useRightHandedSystem) {
        this._tmpPos.z *= -1;
        this._tmpQuat.z *= -1;
        this._tmpQuat.w *= -1;
        this._tmpMat.toggleModelMatrixHandInPlace();
      }
      const result = {
        position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos,
        rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat,
        transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat,
        inputSource,
        isTransient: !!inputSource,
        xrHitResult: hitTestResult
      };
      results.push(result);
    });
    this.onHitTestResultObservable.notifyObservers(results);
  }
}
WebXRHitTest.Name = WebXRFeatureName.HIT_TEST;
WebXRHitTest.Version = 2;
WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name, (xrSessionManager, options) => {
  return () => new WebXRHitTest(xrSessionManager, options);
}, WebXRHitTest.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRFeaturePointSystem.js
init_observable();
init_math_vector();
class WebXRFeaturePointSystem extends WebXRAbstractFeature {
  get featurePointCloud() {
    return this._featurePointCloud;
  }
  constructor(_xrSessionManager) {
    super(_xrSessionManager);
    this._enabled = false;
    this._featurePointCloud = [];
    this.onFeaturePointsAddedObservable = new Observable;
    this.onFeaturePointsUpdatedObservable = new Observable;
    this.xrNativeFeatureName = "bjsfeature-points";
    if (this._xrSessionManager.session) {
      this._init();
    } else {
      this._xrSessionManager.onXRSessionInit.addOnce(() => {
        this._init();
      });
    }
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    this.featurePointCloud.length = 0;
    return true;
  }
  dispose() {
    super.dispose();
    this._featurePointCloud.length = 0;
    this.onFeaturePointsUpdatedObservable.clear();
    this.onFeaturePointsAddedObservable.clear();
  }
  _onXRFrame(frame2) {
    if (!this.attached || !this._enabled || !frame2) {
      return;
    }
    const featurePointRawData = frame2.featurePointCloud;
    if (!featurePointRawData || featurePointRawData.length === 0) {
      return;
    } else {
      if (featurePointRawData.length % 5 !== 0) {
        throw new Error("Received malformed feature point cloud of length: " + featurePointRawData.length);
      }
      const numberOfFeaturePoints = featurePointRawData.length / 5;
      const updatedFeaturePoints = [];
      const addedFeaturePoints = [];
      for (let i = 0;i < numberOfFeaturePoints; i++) {
        const rawIndex = i * 5;
        const id = featurePointRawData[rawIndex + 4];
        if (!this._featurePointCloud[id]) {
          this._featurePointCloud[id] = { position: new Vector3, confidenceValue: 0 };
          addedFeaturePoints.push(id);
        } else {
          updatedFeaturePoints.push(id);
        }
        this._featurePointCloud[id].position.x = featurePointRawData[rawIndex];
        this._featurePointCloud[id].position.y = featurePointRawData[rawIndex + 1];
        this._featurePointCloud[id].position.z = featurePointRawData[rawIndex + 2];
        this._featurePointCloud[id].confidenceValue = featurePointRawData[rawIndex + 3];
      }
      if (addedFeaturePoints.length > 0) {
        this.onFeaturePointsAddedObservable.notifyObservers(addedFeaturePoints);
      }
      if (updatedFeaturePoints.length > 0) {
        this.onFeaturePointsUpdatedObservable.notifyObservers(updatedFeaturePoints);
      }
    }
  }
  _init() {
    if (!this._xrSessionManager.session.trySetFeaturePointCloudEnabled || !this._xrSessionManager.session.trySetFeaturePointCloudEnabled(true)) {
      return;
    }
    this._enabled = true;
  }
}
WebXRFeaturePointSystem.Name = WebXRFeatureName.FEATURE_POINTS;
WebXRFeaturePointSystem.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name, (xrSessionManager) => {
  return () => new WebXRFeaturePointSystem(xrSessionManager);
}, WebXRFeaturePointSystem.Version);
// node_modules/@babylonjs/core/XR/features/WebXRMeshDetector.js
init_math();
init_observable();
init_buffer();
init_logger();
var meshIdProvider = 0;

class WebXRMeshDetector extends WebXRAbstractFeature {
  constructor(_xrSessionManager, _options = {}) {
    super(_xrSessionManager);
    this._options = _options;
    this._detectedMeshes = new Map;
    this.onMeshAddedObservable = new Observable;
    this.onMeshRemovedObservable = new Observable;
    this.onMeshUpdatedObservable = new Observable;
    this.xrNativeFeatureName = "mesh-detection";
    if (this._options.generateMeshes) {
      this._options.convertCoordinateSystems = true;
    }
    if (this._xrSessionManager.session) {
      this._init();
    } else {
      this._xrSessionManager.onXRSessionInit.addOnce(() => {
        this._init();
      });
    }
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    if (!!this._xrSessionManager.isNative && !!this._xrSessionManager.session.trySetMeshDetectorEnabled) {
      this._xrSessionManager.session.trySetMeshDetectorEnabled(false);
    }
    if (!this._options.doNotRemoveMeshesOnSessionEnded) {
      this._detectedMeshes.forEach((mesh2) => {
        this.onMeshRemovedObservable.notifyObservers(mesh2);
      });
      this._detectedMeshes.clear();
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.onMeshAddedObservable.clear();
    this.onMeshRemovedObservable.clear();
    this.onMeshUpdatedObservable.clear();
  }
  _onXRFrame(frame2) {
    try {
      if (!this.attached || !frame2) {
        return;
      }
      const detectedMeshes = frame2.detectedMeshes || frame2.worldInformation?.detectedMeshes;
      if (detectedMeshes) {
        const toRemove = new Set;
        this._detectedMeshes.forEach((vertexData, xrMesh) => {
          if (!detectedMeshes.has(xrMesh)) {
            toRemove.add(xrMesh);
          }
        });
        toRemove.forEach((xrMesh) => {
          const vertexData = this._detectedMeshes.get(xrMesh);
          if (vertexData) {
            this.onMeshRemovedObservable.notifyObservers(vertexData);
            this._detectedMeshes.delete(xrMesh);
          }
        });
        detectedMeshes.forEach((xrMesh) => {
          if (!this._detectedMeshes.has(xrMesh)) {
            const partialVertexData = {
              id: meshIdProvider++,
              xrMesh
            };
            const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame2);
            this._detectedMeshes.set(xrMesh, vertexData);
            this.onMeshAddedObservable.notifyObservers(vertexData);
          } else {
            if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) {
              const vertexData = this._detectedMeshes.get(xrMesh);
              if (vertexData) {
                this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame2);
                this.onMeshUpdatedObservable.notifyObservers(vertexData);
              }
            }
          }
        });
      }
    } catch (error2) {
      Logger.Log(error2.stack);
    }
  }
  _init() {
    if (this._xrSessionManager.isNative) {
      if (this._xrSessionManager.session.trySetMeshDetectorEnabled) {
        this._xrSessionManager.session.trySetMeshDetectorEnabled(true);
      }
      if (!!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) {
        this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions);
      }
    }
  }
  _updateVertexDataWithXRMesh(xrMesh, mesh2, xrFrame) {
    mesh2.xrMesh = xrMesh;
    mesh2.worldParentNode = this._options.worldParentNode;
    const positions = xrMesh.vertices || xrMesh.positions;
    if (this._options.convertCoordinateSystems) {
      if (!this._xrSessionManager.scene.useRightHandedSystem) {
        mesh2.positions = new Float32Array(positions.length);
        for (let i = 0;i < positions.length; i += 3) {
          mesh2.positions[i] = positions[i];
          mesh2.positions[i + 1] = positions[i + 1];
          mesh2.positions[i + 2] = -1 * positions[i + 2];
        }
        if (xrMesh.normals) {
          mesh2.normals = new Float32Array(xrMesh.normals.length);
          for (let i = 0;i < xrMesh.normals.length; i += 3) {
            mesh2.normals[i] = xrMesh.normals[i];
            mesh2.normals[i + 1] = xrMesh.normals[i + 1];
            mesh2.normals[i + 2] = -1 * xrMesh.normals[i + 2];
          }
        }
      } else {
        mesh2.positions = positions;
        mesh2.normals = xrMesh.normals;
      }
      mesh2.indices = xrMesh.indices;
      const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace);
      if (pose) {
        const mat = mesh2.transformationMatrix || new Matrix;
        Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
        if (!this._xrSessionManager.scene.useRightHandedSystem) {
          mat.toggleModelMatrixHandInPlace();
        }
        mesh2.transformationMatrix = mat;
        if (this._options.worldParentNode) {
          mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
        }
      }
      if (this._options.generateMeshes) {
        if (!mesh2.mesh) {
          const generatedMesh = new Mesh("xr mesh " + mesh2.id, this._xrSessionManager.scene);
          generatedMesh.rotationQuaternion = new Quaternion;
          generatedMesh.setVerticesData(VertexBuffer.PositionKind, mesh2.positions);
          if (mesh2.normals) {
            generatedMesh.setVerticesData(VertexBuffer.NormalKind, mesh2.normals);
          } else {
            generatedMesh.createNormals(true);
          }
          generatedMesh.setIndices(mesh2.indices, undefined, true);
          mesh2.mesh = generatedMesh;
        } else {
          const generatedMesh = mesh2.mesh;
          generatedMesh.updateVerticesData(VertexBuffer.PositionKind, mesh2.positions);
          if (mesh2.normals) {
            generatedMesh.updateVerticesData(VertexBuffer.NormalKind, mesh2.normals);
          } else {
            generatedMesh.createNormals(true);
          }
          generatedMesh.updateIndices(mesh2.indices);
        }
        mesh2.transformationMatrix?.decompose(mesh2.mesh.scaling, mesh2.mesh.rotationQuaternion, mesh2.mesh.position);
      }
    }
    return mesh2;
  }
}
WebXRMeshDetector.Name = WebXRFeatureName.MESH_DETECTION;
WebXRMeshDetector.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name, (xrSessionManager, options) => {
  return () => new WebXRMeshDetector(xrSessionManager, options);
}, WebXRMeshDetector.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRImageTracking.js
init_observable();
init_math_vector();
init_tools();
var ImageTrackingScoreStatus;
(function(ImageTrackingScoreStatus2) {
  ImageTrackingScoreStatus2[ImageTrackingScoreStatus2["NotReceived"] = 0] = "NotReceived";
  ImageTrackingScoreStatus2[ImageTrackingScoreStatus2["Waiting"] = 1] = "Waiting";
  ImageTrackingScoreStatus2[ImageTrackingScoreStatus2["Received"] = 2] = "Received";
})(ImageTrackingScoreStatus || (ImageTrackingScoreStatus = {}));

class WebXRImageTracking extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this.options = options;
    this.onUntrackableImageFoundObservable = new Observable;
    this.onTrackableImageFoundObservable = new Observable;
    this.onTrackedImageUpdatedObservable = new Observable;
    this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;
    this._trackedImages = [];
    this.xrNativeFeatureName = "image-tracking";
  }
  attach() {
    return super.attach();
  }
  detach() {
    return super.detach();
  }
  getTrackedImageById(id) {
    return this._trackedImages[id] || null;
  }
  dispose() {
    super.dispose();
    this._trackedImages.forEach((trackedImage) => {
      trackedImage.originalBitmap.close();
    });
    this._trackedImages.length = 0;
    this.onTrackableImageFoundObservable.clear();
    this.onUntrackableImageFoundObservable.clear();
    this.onTrackedImageUpdatedObservable.clear();
  }
  async getXRSessionInitExtension() {
    if (!this.options.images || !this.options.images.length) {
      return {};
    }
    const promises = this.options.images.map((image) => {
      if (typeof image.src === "string") {
        return this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(image.src);
      } else {
        return Promise.resolve(image.src);
      }
    });
    try {
      const images = await Promise.all(promises);
      this._originalTrackingRequest = images.map((image, idx) => {
        return {
          image,
          widthInMeters: this.options.images[idx].estimatedRealWorldWidth
        };
      });
      return {
        trackedImages: this._originalTrackingRequest
      };
    } catch (ex) {
      Tools.Error("Error loading images for tracking, WebXRImageTracking disabled for this session.");
      return {};
    }
  }
  _onXRFrame(_xrFrame) {
    if (!_xrFrame.getImageTrackingResults || this._trackableScoreStatus === ImageTrackingScoreStatus.Waiting) {
      return;
    }
    if (this._trackableScoreStatus === ImageTrackingScoreStatus.NotReceived) {
      this._checkScoresAsync();
      return;
    }
    const imageTrackedResults = _xrFrame.getImageTrackingResults();
    for (const result of imageTrackedResults) {
      let changed = false;
      const imageIndex = result.index;
      const imageObject = this._trackedImages[imageIndex];
      if (!imageObject) {
        continue;
      }
      imageObject.xrTrackingResult = result;
      if (imageObject.realWorldWidth !== result.measuredWidthInMeters) {
        imageObject.realWorldWidth = result.measuredWidthInMeters;
        changed = true;
      }
      const pose = _xrFrame.getPose(result.imageSpace, this._xrSessionManager.referenceSpace);
      if (pose) {
        const mat = imageObject.transformationMatrix;
        Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
        if (!this._xrSessionManager.scene.useRightHandedSystem) {
          mat.toggleModelMatrixHandInPlace();
        }
        changed = true;
      }
      const state = result.trackingState;
      const emulated = state === "emulated";
      if (imageObject.emulated !== emulated) {
        imageObject.emulated = emulated;
        changed = true;
      }
      if (changed) {
        this.onTrackedImageUpdatedObservable.notifyObservers(imageObject);
      }
    }
  }
  async _checkScoresAsync() {
    if (!this._xrSessionManager.session.getTrackedImageScores || this._trackableScoreStatus !== ImageTrackingScoreStatus.NotReceived) {
      return;
    }
    this._trackableScoreStatus = ImageTrackingScoreStatus.Waiting;
    const imageScores = await this._xrSessionManager.session.getTrackedImageScores();
    if (!imageScores || imageScores.length === 0) {
      this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;
      return;
    }
    for (let idx = 0;idx < imageScores.length; ++idx) {
      if (imageScores[idx] == "untrackable") {
        this.onUntrackableImageFoundObservable.notifyObservers(idx);
      } else {
        const originalBitmap = this._originalTrackingRequest[idx].image;
        const imageObject = {
          id: idx,
          originalBitmap,
          transformationMatrix: new Matrix,
          ratio: originalBitmap.width / originalBitmap.height
        };
        this._trackedImages[idx] = imageObject;
        this.onTrackableImageFoundObservable.notifyObservers(imageObject);
      }
    }
    this._trackableScoreStatus = imageScores.length > 0 ? ImageTrackingScoreStatus.Received : ImageTrackingScoreStatus.NotReceived;
  }
}
WebXRImageTracking.Name = WebXRFeatureName.IMAGE_TRACKING;
WebXRImageTracking.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name, (xrSessionManager, options) => {
  return () => new WebXRImageTracking(xrSessionManager, options);
}, WebXRImageTracking.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRDOMOverlay.js
init_tools();
class WebXRDomOverlay extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this.options = options;
    this._domOverlayType = null;
    this._beforeXRSelectListener = null;
    this._element = null;
    this.xrNativeFeatureName = "dom-overlay";
    Tools.Warn("dom-overlay is an experimental and unstable feature.");
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    if (!this._xrSessionManager.session.domOverlayState || this._xrSessionManager.session.domOverlayState.type === null) {
      return false;
    }
    this._domOverlayType = this._xrSessionManager.session.domOverlayState.type;
    if (this._element !== null && this.options.supressXRSelectEvents === true) {
      this._beforeXRSelectListener = (ev) => {
        ev.preventDefault();
      };
      this._element.addEventListener("beforexrselect", this._beforeXRSelectListener);
    }
    return true;
  }
  get domOverlayType() {
    return this._domOverlayType;
  }
  dispose() {
    super.dispose();
    if (this._element !== null && this._beforeXRSelectListener) {
      this._element.removeEventListener("beforexrselect", this._beforeXRSelectListener);
    }
  }
  _onXRFrame(_xrFrame) {}
  async getXRSessionInitExtension() {
    if (this.options.element === undefined) {
      Tools.Warn('"element" option must be provided to attach xr-dom-overlay feature.');
      return {};
    } else if (typeof this.options.element === "string") {
      const selectedElement = document.querySelector(this.options.element);
      if (selectedElement === null) {
        Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`);
        return {};
      }
      this._element = selectedElement;
    } else {
      this._element = this.options.element;
    }
    return {
      domOverlay: {
        root: this._element
      }
    };
  }
}
WebXRDomOverlay.Name = WebXRFeatureName.DOM_OVERLAY;
WebXRDomOverlay.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name, (xrSessionManager, options) => {
  return () => new WebXRDomOverlay(xrSessionManager, options);
}, WebXRDomOverlay.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRControllerMovement.js
init_math_vector();
init_tools();

class WebXRControllerMovement extends WebXRAbstractFeature {
  get movementDirection() {
    return this._movementDirection;
  }
  get movementEnabled() {
    return this._featureContext.movementEnabled;
  }
  set movementEnabled(enabled) {
    this._featureContext.movementEnabled = enabled;
  }
  get movementOrientationFollowsViewerPose() {
    return this._featureContext.movementOrientationFollowsViewerPose;
  }
  set movementOrientationFollowsViewerPose(followsPose) {
    this._featureContext.movementOrientationFollowsViewerPose = followsPose;
  }
  get movementSpeed() {
    return this._featureContext.movementSpeed;
  }
  set movementSpeed(movementSpeed) {
    this._featureContext.movementSpeed = movementSpeed;
  }
  get movementThreshold() {
    return this._featureContext.movementThreshold;
  }
  set movementThreshold(movementThreshold) {
    this._featureContext.movementThreshold = movementThreshold;
  }
  get rotationEnabled() {
    return this._featureContext.rotationEnabled;
  }
  set rotationEnabled(enabled) {
    this._featureContext.rotationEnabled = enabled;
  }
  get rotationSpeed() {
    return this._featureContext.rotationSpeed;
  }
  set rotationSpeed(rotationSpeed) {
    this._featureContext.rotationSpeed = rotationSpeed;
  }
  get rotationThreshold() {
    return this._featureContext.rotationThreshold;
  }
  set rotationThreshold(threshold) {
    this._featureContext.rotationThreshold = threshold;
  }
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this._controllers = {};
    this._currentRegistrationConfigurations = [];
    this._movementDirection = new Quaternion;
    this._tmpRotationMatrix = Matrix.Identity();
    this._tmpTranslationDirection = new Vector3;
    this._tmpMovementTranslation = new Vector3;
    this._tempCacheQuaternion = new Quaternion;
    this._attachController = (xrController) => {
      if (this._controllers[xrController.uniqueId]) {
        return;
      }
      this._controllers[xrController.uniqueId] = {
        xrController,
        registeredComponents: []
      };
      const controllerData = this._controllers[xrController.uniqueId];
      if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) {
        const initController = () => {
          if (xrController.motionController) {
            for (const registration of this._currentRegistrationConfigurations) {
              let component = null;
              if (registration.allowedComponentTypes) {
                for (const componentType of registration.allowedComponentTypes) {
                  const componentOfType = xrController.motionController.getComponentOfType(componentType);
                  if (componentOfType !== null) {
                    component = componentOfType;
                    break;
                  }
                }
              }
              if (registration.mainComponentOnly) {
                const mainComponent = xrController.motionController.getMainComponent();
                if (mainComponent === null) {
                  continue;
                }
                component = mainComponent;
              }
              if (typeof registration.componentSelectionPredicate === "function") {
                component = registration.componentSelectionPredicate(xrController);
              }
              if (component && registration.forceHandedness) {
                if (xrController.inputSource.handedness !== registration.forceHandedness) {
                  continue;
                }
              }
              if (component === null) {
                continue;
              }
              const registeredComponent = {
                registrationConfiguration: registration,
                component
              };
              controllerData.registeredComponents.push(registeredComponent);
              if ("axisChangedHandler" in registration) {
                registeredComponent.onAxisChangedObserver = component.onAxisValueChangedObservable.add((axesData) => {
                  registration.axisChangedHandler(axesData, this._movementState, this._featureContext, this._xrInput);
                });
              }
              if ("buttonChangedHandler" in registration) {
                registeredComponent.onButtonChangedObserver = component.onButtonStateChangedObservable.add((component2) => {
                  if (component2.changes.pressed) {
                    registration.buttonChangedHandler(component2.changes.pressed, this._movementState, this._featureContext, this._xrInput);
                  }
                });
              }
            }
          }
        };
        if (xrController.motionController) {
          initController();
        } else {
          xrController.onMotionControllerInitObservable.addOnce(() => {
            initController();
          });
        }
      }
    };
    if (!options || options.xrInput === undefined) {
      Tools.Error('WebXRControllerMovement feature requires "xrInput" option.');
      return;
    }
    if (Array.isArray(options.customRegistrationConfigurations)) {
      this._currentRegistrationConfigurations = options.customRegistrationConfigurations;
    } else {
      this._currentRegistrationConfigurations = WebXRControllerMovement.REGISTRATIONS.default;
    }
    this._featureContext = {
      movementEnabled: options.movementEnabled || true,
      movementOrientationFollowsViewerPose: options.movementOrientationFollowsViewerPose ?? true,
      movementOrientationFollowsController: options.movementOrientationFollowsController ?? false,
      orientationPreferredHandedness: options.orientationPreferredHandedness,
      movementSpeed: options.movementSpeed ?? 1,
      movementThreshold: options.movementThreshold ?? 0.25,
      rotationEnabled: options.rotationEnabled ?? true,
      rotationSpeed: options.rotationSpeed ?? 1,
      rotationThreshold: options.rotationThreshold ?? 0.25
    };
    this._movementState = {
      moveX: 0,
      moveY: 0,
      rotateX: 0,
      rotateY: 0
    };
    this._xrInput = options.xrInput;
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    this._xrInput.controllers.forEach(this._attachController);
    this._addNewAttachObserver(this._xrInput.onControllerAddedObservable, this._attachController);
    this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable, (controller) => {
      this._detachController(controller.uniqueId);
    });
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    Object.keys(this._controllers).forEach((controllerId) => {
      this._detachController(controllerId);
    });
    this._controllers = {};
    return true;
  }
  _onXRFrame(_xrFrame) {
    if (!this.attached) {
      return;
    }
    if (this._movementState.rotateX !== 0 && this._featureContext.rotationEnabled) {
      const deltaMillis = this._xrSessionManager.scene.getEngine().getDeltaTime();
      const rotationY = deltaMillis * 0.001 * this._featureContext.rotationSpeed * this._movementState.rotateX * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);
      if (this._featureContext.movementOrientationFollowsViewerPose) {
        this._xrInput.xrCamera.cameraRotation.y += rotationY;
        Quaternion.RotationYawPitchRollToRef(rotationY, 0, 0, this._tempCacheQuaternion);
        this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion, this._movementDirection);
      } else if (this._featureContext.movementOrientationFollowsController) {
        this._xrInput.xrCamera.cameraRotation.y += rotationY;
        const handedness = this._featureContext.orientationPreferredHandedness || "right";
        const key = Object.keys(this._controllers).find((key2) => this._controllers[key2]?.xrController?.inputSource.handedness === handedness) || Object.keys(this._controllers)[0];
        const controller = this._controllers[key];
        Quaternion.RotationYawPitchRollToRef(rotationY, 0, 0, this._tempCacheQuaternion);
        (controller?.xrController.pointer.rotationQuaternion || Quaternion.Identity()).multiplyToRef(this._tempCacheQuaternion, this._movementDirection);
      } else {
        Quaternion.RotationYawPitchRollToRef(rotationY * 3, 0, 0, this._tempCacheQuaternion);
        this._movementDirection.multiplyInPlace(this._tempCacheQuaternion);
      }
    } else if (this._featureContext.movementOrientationFollowsViewerPose) {
      this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);
    } else if (this._featureContext.movementOrientationFollowsController) {
      const handedness = this._featureContext.orientationPreferredHandedness || "right";
      const key = Object.keys(this._controllers).find((key2) => this._controllers[key2]?.xrController.inputSource.handedness === handedness) || Object.keys(this._controllers)[0];
      const controller = this._controllers[key];
      this._movementDirection.copyFrom(controller?.xrController.pointer.rotationQuaternion || Quaternion.Identity());
    }
    if ((this._movementState.moveX || this._movementState.moveY) && this._featureContext.movementEnabled) {
      Matrix.FromQuaternionToRef(this._movementDirection, this._tmpRotationMatrix);
      this._tmpTranslationDirection.set(this._movementState.moveX, 0, this._movementState.moveY * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1));
      Vector3.TransformCoordinatesToRef(this._tmpTranslationDirection, this._tmpRotationMatrix, this._tmpMovementTranslation);
      this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed() * this._featureContext.movementSpeed);
      this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation);
    }
  }
  _detachController(xrControllerUniqueId) {
    const controllerData = this._controllers[xrControllerUniqueId];
    if (!controllerData) {
      return;
    }
    for (const registeredComponent of controllerData.registeredComponents) {
      if (registeredComponent.onAxisChangedObserver) {
        registeredComponent.component.onAxisValueChangedObservable.remove(registeredComponent.onAxisChangedObserver);
      }
      if (registeredComponent.onButtonChangedObserver) {
        registeredComponent.component.onButtonStateChangedObservable.remove(registeredComponent.onButtonChangedObserver);
      }
    }
    delete this._controllers[xrControllerUniqueId];
  }
}
WebXRControllerMovement.Name = WebXRFeatureName.MOVEMENT;
WebXRControllerMovement.REGISTRATIONS = {
  default: [
    {
      allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],
      forceHandedness: "left",
      axisChangedHandler: (axes, movementState, featureContext) => {
        movementState.rotateX = Math.abs(axes.x) > featureContext.rotationThreshold ? axes.x : 0;
        movementState.rotateY = Math.abs(axes.y) > featureContext.rotationThreshold ? axes.y : 0;
      }
    },
    {
      allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],
      forceHandedness: "right",
      axisChangedHandler: (axes, movementState, featureContext) => {
        movementState.moveX = Math.abs(axes.x) > featureContext.movementThreshold ? axes.x : 0;
        movementState.moveY = Math.abs(axes.y) > featureContext.movementThreshold ? axes.y : 0;
      }
    }
  ]
};
WebXRControllerMovement.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name, (xrSessionManager, options) => {
  return () => new WebXRControllerMovement(xrSessionManager, options);
}, WebXRControllerMovement.Version, true);
// node_modules/@babylonjs/core/XR/features/WebXRLightEstimation.js
init_internalTexture();
init_observable();
init_tools();
init_math_color();
init_math_vector();
init_baseTexture();
init_sphericalPolynomial();
init_lightConstants();
class WebXRLightEstimation extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this.options = options;
    this._canvasContext = null;
    this._reflectionCubeMap = null;
    this._xrLightEstimate = null;
    this._xrLightProbe = null;
    this._xrWebGLBinding = null;
    this._lightDirection = Vector3.Up().negateInPlace();
    this._lightColor = Color3.White();
    this._intensity = 1;
    this._sphericalHarmonics = new SphericalHarmonics;
    this._cubeMapPollTime = Date.now();
    this._lightEstimationPollTime = Date.now();
    this._reflectionCubeMapTextureSize = 16;
    this.directionalLight = null;
    this.onReflectionCubeMapUpdatedObservable = new Observable;
    this._updateReflectionCubeMap = () => {
      if (!this._xrLightProbe) {
        return;
      }
      if (this.options.cubeMapPollInterval) {
        const now = Date.now();
        if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) {
          return;
        }
        this._cubeMapPollTime = now;
      }
      const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);
      if (lp && this._reflectionCubeMap) {
        if (!this._reflectionCubeMap._texture) {
          const internalTexture2 = new InternalTexture(this._xrSessionManager.scene.getEngine(), 0);
          internalTexture2.isCube = true;
          internalTexture2.invertY = false;
          internalTexture2._useSRGBBuffer = this.options.reflectionFormat === "srgba8";
          internalTexture2.format = 5;
          internalTexture2.generateMipMaps = true;
          internalTexture2.type = this.options.reflectionFormat !== "srgba8" ? 2 : 0;
          internalTexture2.samplingMode = 3;
          internalTexture2.width = this._reflectionCubeMapTextureSize;
          internalTexture2.height = this._reflectionCubeMapTextureSize;
          internalTexture2._cachedWrapU = 1;
          internalTexture2._cachedWrapV = 1;
          internalTexture2._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext());
          this._reflectionCubeMap._texture = internalTexture2;
        } else {
          this._reflectionCubeMap._texture._hardwareTexture?.set(lp);
          this._reflectionCubeMap._texture.getEngine().resetTextureCache();
        }
        this._reflectionCubeMap._texture.isReady = true;
        if (!this.options.disablePreFiltering) {
          this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap);
          this._hdrFilter.prefilter(this._reflectionCubeMap).then(() => {
            this._xrSessionManager.scene.markAllMaterialsAsDirty(1);
            this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap);
            this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap);
          });
        } else {
          this._xrSessionManager.scene.markAllMaterialsAsDirty(1);
          this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap);
        }
      }
    };
    this.xrNativeFeatureName = "light-estimation";
    if (this.options.createDirectionalLightSource) {
      this.directionalLight = new DirectionalLight("light estimation directional", this._lightDirection, this._xrSessionManager.scene);
      this.directionalLight.position = new Vector3(0, 8, 0);
      this.directionalLight.intensity = 0;
      this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF;
    }
    this._hdrFilter = new HDRFiltering(this._xrSessionManager.scene.getEngine());
    Tools.Warn("light-estimation is an experimental and unstable feature.");
  }
  get reflectionCubeMapTexture() {
    return this._reflectionCubeMap;
  }
  get xrLightingEstimate() {
    if (this._xrLightEstimate) {
      return {
        lightColor: this._lightColor,
        lightDirection: this._lightDirection,
        lightIntensity: this._intensity,
        sphericalHarmonics: this._sphericalHarmonics
      };
    }
    return this._xrLightEstimate;
  }
  _getCanvasContext() {
    if (this._canvasContext === null) {
      this._canvasContext = this._xrSessionManager.scene.getEngine()._gl;
    }
    return this._canvasContext;
  }
  _getXRGLBinding() {
    if (this._xrWebGLBinding === null) {
      const context = this._getCanvasContext();
      this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context);
    }
    return this._xrWebGLBinding;
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    const reflectionFormat = this.options.reflectionFormat ?? (this._xrSessionManager.session.preferredReflectionFormat || "srgba8");
    this.options.reflectionFormat = reflectionFormat;
    this._xrSessionManager.session.requestLightProbe({
      reflectionFormat
    }).then((xrLightProbe) => {
      this._xrLightProbe = xrLightProbe;
      if (!this.options.disableCubeMapReflection) {
        if (!this._reflectionCubeMap) {
          this._reflectionCubeMap = new BaseTexture(this._xrSessionManager.scene);
          this._reflectionCubeMap._isCube = true;
          this._reflectionCubeMap.coordinatesMode = 3;
          if (this.options.setSceneEnvironmentTexture) {
            this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap;
          }
        }
        this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap);
      }
    });
    return true;
  }
  detach() {
    const detached = super.detach();
    if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) {
      this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap);
      this._xrLightProbe = null;
    }
    this._canvasContext = null;
    this._xrLightEstimate = null;
    this._xrWebGLBinding = null;
    return detached;
  }
  dispose() {
    super.dispose();
    this.onReflectionCubeMapUpdatedObservable.clear();
    if (this.directionalLight) {
      this.directionalLight.dispose();
      this.directionalLight = null;
    }
    if (this._reflectionCubeMap !== null) {
      if (this._reflectionCubeMap._texture) {
        this._reflectionCubeMap._texture.dispose();
      }
      this._reflectionCubeMap.dispose();
      this._reflectionCubeMap = null;
    }
  }
  _onXRFrame(_xrFrame) {
    if (this._xrLightProbe !== null) {
      if (this.options.lightEstimationPollInterval) {
        const now = Date.now();
        if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) {
          return;
        }
        this._lightEstimationPollTime = now;
      }
      this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe);
      if (this._xrLightEstimate) {
        this._intensity = Math.max(1, this._xrLightEstimate.primaryLightIntensity.x, this._xrLightEstimate.primaryLightIntensity.y, this._xrLightEstimate.primaryLightIntensity.z);
        const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;
        if (this.options.disableVectorReuse) {
          this._lightDirection = new Vector3;
          this._lightColor = new Color3;
          if (this.directionalLight) {
            this.directionalLight.direction = this._lightDirection;
            this.directionalLight.diffuse = this._lightColor;
          }
        }
        this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x, this._xrLightEstimate.primaryLightDirection.y, this._xrLightEstimate.primaryLightDirection.z * rhsFactor);
        this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x / this._intensity, this._xrLightEstimate.primaryLightIntensity.y / this._intensity, this._xrLightEstimate.primaryLightIntensity.z / this._intensity);
        this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients);
        if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) {
          this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial;
          this._reflectionCubeMap.sphericalPolynomial?.updateFromHarmonics(this._sphericalHarmonics);
        }
        this._lightDirection.negateInPlace();
        if (this.directionalLight) {
          this.directionalLight.direction.copyFrom(this._lightDirection);
          this.directionalLight.intensity = Math.min(this._intensity, 1);
          this.directionalLight.diffuse.copyFrom(this._lightColor);
        }
      }
    }
  }
}
WebXRLightEstimation.Name = WebXRFeatureName.LIGHT_ESTIMATION;
WebXRLightEstimation.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name, (xrSessionManager, options) => {
  return () => new WebXRLightEstimation(xrSessionManager, options);
}, WebXRLightEstimation.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXREyeTracking.js
init_observable();
init_math_vector();
class WebXREyeTracking extends WebXRAbstractFeature {
  constructor(_xrSessionManager) {
    super(_xrSessionManager);
    this.onEyeTrackingStartedObservable = new Observable;
    this.onEyeTrackingEndedObservable = new Observable;
    this.onEyeTrackingFrameUpdateObservable = new Observable;
    this._eyeTrackingStartListener = (event) => {
      this._latestEyeSpace = event.gazeSpace;
      this._gazeRay = new Ray(Vector3.Zero(), Vector3.Forward());
      this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay);
    };
    this._eyeTrackingEndListener = () => {
      this._latestEyeSpace = null;
      this._gazeRay = null;
      this.onEyeTrackingEndedObservable.notifyObservers();
    };
    this.xrNativeFeatureName = "eye-tracking";
    if (this._xrSessionManager.session) {
      this._init();
    } else {
      this._xrSessionManager.onXRSessionInit.addOnce(() => {
        this._init();
      });
    }
  }
  dispose() {
    super.dispose();
    this._xrSessionManager.session.removeEventListener("eyetrackingstart", this._eyeTrackingStartListener);
    this._xrSessionManager.session.removeEventListener("eyetrackingend", this._eyeTrackingEndListener);
    this.onEyeTrackingStartedObservable.clear();
    this.onEyeTrackingEndedObservable.clear();
    this.onEyeTrackingFrameUpdateObservable.clear();
  }
  get isEyeGazeValid() {
    return !!this._gazeRay;
  }
  getEyeGaze() {
    return this._gazeRay;
  }
  _onXRFrame(frame2) {
    if (!this.attached || !frame2) {
      return;
    }
    if (this._latestEyeSpace && this._gazeRay) {
      const pose = frame2.getPose(this._latestEyeSpace, this._xrSessionManager.referenceSpace);
      if (pose) {
        this._gazeRay.origin.set(pose.transform.position.x, pose.transform.position.y, pose.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);
        const quat = pose.transform.orientation;
        TmpVectors.Quaternion[0].set(quat.x, quat.y, quat.z, quat.w);
        if (!this._xrSessionManager.scene.useRightHandedSystem) {
          this._gazeRay.origin.z *= -1;
          TmpVectors.Quaternion[0].z *= -1;
          TmpVectors.Quaternion[0].w *= -1;
          Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(TmpVectors.Quaternion[0], this._gazeRay.direction);
        } else {
          Vector3.RightHandedForwardReadOnly.rotateByQuaternionToRef(TmpVectors.Quaternion[0], this._gazeRay.direction);
        }
        this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay);
      }
    }
  }
  _init() {
    if (this._xrSessionManager.isNative) {
      this._xrSessionManager.session.addEventListener("eyetrackingstart", this._eyeTrackingStartListener);
      this._xrSessionManager.session.addEventListener("eyetrackingend", this._eyeTrackingEndListener);
    }
  }
}
WebXREyeTracking.Name = WebXRFeatureName.EYE_TRACKING;
WebXREyeTracking.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name, (xrSessionManager) => {
  return () => new WebXREyeTracking(xrSessionManager);
}, WebXREyeTracking.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRWalkingLocomotion.js
init_math_vector();
init_logger();
init_observable();
class CircleBuffer {
  constructor(numSamples, initializer) {
    this._samples = [];
    this._idx = 0;
    for (let idx = 0;idx < numSamples; ++idx) {
      this._samples.push(initializer ? initializer() : Vector2.Zero());
    }
  }
  get length() {
    return this._samples.length;
  }
  push(x, y) {
    this._idx = (this._idx + this._samples.length - 1) % this._samples.length;
    this.at(0).copyFromFloats(x, y);
  }
  at(idx) {
    if (idx >= this._samples.length) {
      throw new Error("Index out of bounds");
    }
    return this._samples[(this._idx + idx) % this._samples.length];
  }
}

class FirstStepDetector {
  constructor() {
    this._samples = new CircleBuffer(20);
    this._entropy = 0;
    this.onFirstStepDetected = new Observable;
  }
  update(posX, posY, forwardX, forwardY) {
    this._samples.push(posX, posY);
    const origin = this._samples.at(0);
    this._entropy *= this._entropyDecayFactor;
    this._entropy += Vector2.Distance(origin, this._samples.at(1));
    if (this._entropy > this._entropyThreshold) {
      return;
    }
    let samePointIdx;
    for (samePointIdx = this._samePointCheckStartIdx;samePointIdx < this._samples.length; ++samePointIdx) {
      if (Vector2.DistanceSquared(origin, this._samples.at(samePointIdx)) < this._samePointSquaredDistanceThreshold) {
        break;
      }
    }
    if (samePointIdx === this._samples.length) {
      return;
    }
    let apexDistSquared = -1;
    let apexIdx = 0;
    for (let distSquared, idx = 1;idx < samePointIdx; ++idx) {
      distSquared = Vector2.DistanceSquared(origin, this._samples.at(idx));
      if (distSquared > apexDistSquared) {
        apexIdx = idx;
        apexDistSquared = distSquared;
      }
    }
    if (apexDistSquared < this._apexSquaredDistanceThreshold) {
      return;
    }
    const apex = this._samples.at(apexIdx);
    const axis = apex.subtract(origin);
    axis.normalize();
    const vec = TmpVectors.Vector2[0];
    let dot;
    let sample;
    let sumSquaredProjectionDistances = 0;
    for (let idx = 1;idx < samePointIdx; ++idx) {
      sample = this._samples.at(idx);
      sample.subtractToRef(origin, vec);
      dot = Vector2.Dot(axis, vec);
      sumSquaredProjectionDistances += vec.lengthSquared() - dot * dot;
    }
    if (sumSquaredProjectionDistances > samePointIdx * this._squaredProjectionDistanceThreshold) {
      return;
    }
    const forwardVec = TmpVectors.Vector3[0];
    forwardVec.set(forwardX, forwardY, 0);
    const axisVec = TmpVectors.Vector3[1];
    axisVec.set(axis.x, axis.y, 0);
    const isApexLeft = Vector3.Cross(forwardVec, axisVec).z > 0;
    const leftApex = origin.clone();
    const rightApex = origin.clone();
    apex.subtractToRef(origin, axis);
    if (isApexLeft) {
      axis.scaleAndAddToRef(this._axisToApexShrinkFactor, leftApex);
      axis.scaleAndAddToRef(this._axisToApexExtendFactor, rightApex);
    } else {
      axis.scaleAndAddToRef(this._axisToApexExtendFactor, leftApex);
      axis.scaleAndAddToRef(this._axisToApexShrinkFactor, rightApex);
    }
    this.onFirstStepDetected.notifyObservers({
      leftApex,
      rightApex,
      currentPosition: origin,
      currentStepDirection: isApexLeft ? "right" : "left"
    });
  }
  reset() {
    for (let idx = 0;idx < this._samples.length; ++idx) {
      this._samples.at(idx).copyFromFloats(0, 0);
    }
  }
  get _samePointCheckStartIdx() {
    return Math.floor(this._samples.length / 3);
  }
  get _samePointSquaredDistanceThreshold() {
    return 0.03 * 0.03;
  }
  get _apexSquaredDistanceThreshold() {
    return 0.09 * 0.09;
  }
  get _squaredProjectionDistanceThreshold() {
    return 0.03 * 0.03;
  }
  get _axisToApexShrinkFactor() {
    return 0.8;
  }
  get _axisToApexExtendFactor() {
    return -1.6;
  }
  get _entropyDecayFactor() {
    return 0.93;
  }
  get _entropyThreshold() {
    return 0.4;
  }
}

class WalkingTracker {
  constructor(leftApex, rightApex, currentPosition, currentStepDirection) {
    this._leftApex = new Vector2;
    this._rightApex = new Vector2;
    this._currentPosition = new Vector2;
    this._axis = new Vector2;
    this._axisLength = -1;
    this._forward = new Vector2;
    this._steppingLeft = false;
    this._t = -1;
    this._maxT = -1;
    this._maxTPosition = new Vector2;
    this._vitality = 0;
    this.onMovement = new Observable;
    this.onFootfall = new Observable;
    this._reset(leftApex, rightApex, currentPosition, currentStepDirection === "left");
  }
  _reset(leftApex, rightApex, currentPosition, steppingLeft) {
    this._leftApex.copyFrom(leftApex);
    this._rightApex.copyFrom(rightApex);
    this._steppingLeft = steppingLeft;
    if (this._steppingLeft) {
      this._leftApex.subtractToRef(this._rightApex, this._axis);
      this._forward.copyFromFloats(-this._axis.y, this._axis.x);
    } else {
      this._rightApex.subtractToRef(this._leftApex, this._axis);
      this._forward.copyFromFloats(this._axis.y, -this._axis.x);
    }
    this._axisLength = this._axis.length();
    this._forward.scaleInPlace(1 / this._axisLength);
    this._updateTAndVitality(currentPosition.x, currentPosition.y);
    this._maxT = this._t;
    this._maxTPosition.copyFrom(currentPosition);
    this._vitality = 1;
  }
  _updateTAndVitality(x, y) {
    this._currentPosition.copyFromFloats(x, y);
    if (this._steppingLeft) {
      this._currentPosition.subtractInPlace(this._rightApex);
    } else {
      this._currentPosition.subtractInPlace(this._leftApex);
    }
    const priorT = this._t;
    const dot = Vector2.Dot(this._currentPosition, this._axis);
    this._t = dot / (this._axisLength * this._axisLength);
    const projDistSquared = this._currentPosition.lengthSquared() - dot / this._axisLength * (dot / this._axisLength);
    this._vitality *= 0.92 - 100 * Math.max(projDistSquared - 0.0016, 0) + Math.max(this._t - priorT, 0);
  }
  update(x, y) {
    if (this._vitality < this._vitalityThreshold) {
      return false;
    }
    const priorT = this._t;
    this._updateTAndVitality(x, y);
    if (this._t > this._maxT) {
      this._maxT = this._t;
      this._maxTPosition.copyFromFloats(x, y);
    }
    if (this._vitality < this._vitalityThreshold) {
      return false;
    }
    if (this._t > priorT) {
      this.onMovement.notifyObservers({ deltaT: this._t - priorT });
      if (priorT < 0.5 && this._t >= 0.5) {
        this.onFootfall.notifyObservers({ foot: this._steppingLeft ? "left" : "right" });
      }
    }
    if (this._t < 0.95 * this._maxT) {
      this._currentPosition.copyFromFloats(x, y);
      if (this._steppingLeft) {
        this._leftApex.copyFrom(this._maxTPosition);
      } else {
        this._rightApex.copyFrom(this._maxTPosition);
      }
      this._reset(this._leftApex, this._rightApex, this._currentPosition, !this._steppingLeft);
    }
    if (this._axisLength < 0.03) {
      return false;
    }
    return true;
  }
  get _vitalityThreshold() {
    return 0.1;
  }
  get forward() {
    return this._forward;
  }
}

class Walker {
  static get _MillisecondsPerUpdate() {
    return 1000 / 15;
  }
  constructor(engine2) {
    this._detector = new FirstStepDetector;
    this._walker = null;
    this._movement = new Vector2;
    this._millisecondsSinceLastUpdate = Walker._MillisecondsPerUpdate;
    this.movementThisFrame = Vector3.Zero();
    this._engine = engine2;
    this._detector.onFirstStepDetected.add((event) => {
      if (!this._walker) {
        this._walker = new WalkingTracker(event.leftApex, event.rightApex, event.currentPosition, event.currentStepDirection);
        this._walker.onFootfall.add(() => {
          Logger.Log("Footfall!");
        });
        this._walker.onMovement.add((event2) => {
          this._walker.forward.scaleAndAddToRef(0.024 * event2.deltaT, this._movement);
        });
      }
    });
  }
  update(position, forward) {
    forward.y = 0;
    forward.normalize();
    this._millisecondsSinceLastUpdate += this._engine.getDeltaTime();
    if (this._millisecondsSinceLastUpdate >= Walker._MillisecondsPerUpdate) {
      this._millisecondsSinceLastUpdate -= Walker._MillisecondsPerUpdate;
      this._detector.update(position.x, position.z, forward.x, forward.z);
      if (this._walker) {
        const updated = this._walker.update(position.x, position.z);
        if (!updated) {
          this._walker = null;
        }
      }
      this._movement.scaleInPlace(0.85);
    }
    this.movementThisFrame.set(this._movement.x, 0, this._movement.y);
  }
}

class WebXRWalkingLocomotion extends WebXRAbstractFeature {
  static get Name() {
    return WebXRFeatureName.WALKING_LOCOMOTION;
  }
  static get Version() {
    return 1;
  }
  get locomotionTarget() {
    return this._locomotionTarget;
  }
  set locomotionTarget(locomotionTarget) {
    this._locomotionTarget = locomotionTarget;
    this._isLocomotionTargetWebXRCamera = this._locomotionTarget.getClassName() === "WebXRCamera";
  }
  constructor(sessionManager, options) {
    super(sessionManager);
    this._up = new Vector3;
    this._forward = new Vector3;
    this._position = new Vector3;
    this._movement = new Vector3;
    this._sessionManager = sessionManager;
    this.locomotionTarget = options.locomotionTarget;
    if (this._isLocomotionTargetWebXRCamera) {
      Logger.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended");
    }
  }
  isCompatible() {
    return this._sessionManager.sessionMode === undefined || this._sessionManager.sessionMode === "immersive-vr";
  }
  attach() {
    if (!this.isCompatible || !super.attach()) {
      return false;
    }
    this._walker = new Walker(this._sessionManager.scene.getEngine());
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    this._walker = null;
    return true;
  }
  _onXRFrame(frame2) {
    const pose = frame2.getViewerPose(this._sessionManager.baseReferenceSpace);
    if (!pose) {
      return;
    }
    const handednessScalar = this.locomotionTarget.getScene().useRightHandedSystem ? 1 : -1;
    const m = pose.transform.matrix;
    this._up.copyFromFloats(m[4], m[5], handednessScalar * m[6]);
    this._forward.copyFromFloats(m[8], m[9], handednessScalar * m[10]);
    this._position.copyFromFloats(m[12], m[13], handednessScalar * m[14]);
    this._forward.scaleAndAddToRef(0.05, this._position);
    this._up.scaleAndAddToRef(-0.05, this._position);
    this._walker.update(this._position, this._forward);
    this._movement.copyFrom(this._walker.movementThisFrame);
    if (!this._isLocomotionTargetWebXRCamera) {
      Vector3.TransformNormalToRef(this._movement, this.locomotionTarget.getWorldMatrix(), this._movement);
    }
    this.locomotionTarget.position.addInPlace(this._movement);
  }
}
WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name, (xrSessionManager, options) => {
  return () => new WebXRWalkingLocomotion(xrSessionManager, options);
}, WebXRWalkingLocomotion.Version, false);
// node_modules/@babylonjs/core/XR/features/Layers/WebXRCompositionLayer.js
init_observable();
class WebXRCompositionLayerWrapper extends WebXRLayerWrapper {
  constructor(getWidth, getHeight, layer2, layerType, isMultiview, createRTTProvider, _originalInternalTexture = null) {
    super(getWidth, getHeight, layer2, layerType, createRTTProvider);
    this.getWidth = getWidth;
    this.getHeight = getHeight;
    this.layer = layer2;
    this.layerType = layerType;
    this.isMultiview = isMultiview;
    this.createRTTProvider = createRTTProvider;
    this._originalInternalTexture = _originalInternalTexture;
  }
}

class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {
  constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) {
    super(_xrSessionManager.scene, layerWrapper);
    this._xrSessionManager = _xrSessionManager;
    this._xrWebGLBinding = _xrWebGLBinding;
    this.layerWrapper = layerWrapper;
    this._lastSubImages = new Map;
    this.onRenderTargetTextureCreatedObservable = new Observable;
    this._compositionLayer = layerWrapper.layer;
  }
  _getRenderTargetForSubImage(subImage, eye = "none") {
    const lastSubImage = this._lastSubImages.get(eye);
    const eyeIndex = eye == "right" ? 1 : 0;
    const colorTextureWidth = subImage.colorTextureWidth ?? subImage.textureWidth;
    const colorTextureHeight = subImage.colorTextureHeight ?? subImage.textureHeight;
    if (!this._renderTargetTextures[eyeIndex] || lastSubImage?.textureWidth !== colorTextureWidth || lastSubImage?.textureHeight !== colorTextureHeight) {
      let depthStencilTexture;
      const depthStencilTextureWidth = subImage.depthStencilTextureWidth ?? colorTextureWidth;
      const depthStencilTextureHeight = subImage.depthStencilTextureHeight ?? colorTextureHeight;
      if (colorTextureWidth === depthStencilTextureWidth || colorTextureHeight === depthStencilTextureHeight) {
        depthStencilTexture = subImage.depthStencilTexture;
      }
      this._renderTargetTextures[eyeIndex] = this._createRenderTargetTexture(colorTextureWidth, colorTextureHeight, null, subImage.colorTexture, depthStencilTexture, this.layerWrapper.isMultiview);
      this._framebufferDimensions = {
        framebufferWidth: colorTextureWidth,
        framebufferHeight: colorTextureHeight
      };
      this.onRenderTargetTextureCreatedObservable.notifyObservers({ texture: this._renderTargetTextures[eyeIndex], eye });
    }
    this._lastSubImages.set(eye, subImage);
    return this._renderTargetTextures[eyeIndex];
  }
  _getSubImageForEye(eye) {
    const currentFrame = this._xrSessionManager.currentFrame;
    if (currentFrame) {
      return this._xrWebGLBinding.getSubImage(this._compositionLayer, currentFrame, eye);
    }
    return null;
  }
  getRenderTargetTextureForEye(eye) {
    const subImage = this._getSubImageForEye(eye);
    if (subImage) {
      return this._getRenderTargetForSubImage(subImage, eye);
    }
    return null;
  }
  getRenderTargetTextureForView(view) {
    return this.getRenderTargetTextureForEye(view?.eye);
  }
  _setViewportForSubImage(viewport, subImage) {
    const textureWidth = subImage.colorTextureWidth ?? subImage.textureWidth;
    const textureHeight = subImage.colorTextureHeight ?? subImage.textureHeight;
    const xrViewport = subImage.viewport;
    viewport.x = xrViewport.x / textureWidth;
    viewport.y = xrViewport.y / textureHeight;
    viewport.width = xrViewport.width / textureWidth;
    viewport.height = xrViewport.height / textureHeight;
  }
  trySetViewportForView(viewport, view) {
    const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForEye(view.eye);
    if (subImage) {
      this._setViewportForSubImage(viewport, subImage);
      return true;
    }
    return false;
  }
}

// node_modules/@babylonjs/core/XR/features/Layers/WebXRProjectionLayer.js
class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper {
  constructor(layer2, isMultiview, xrGLBinding) {
    super(() => layer2.textureWidth, () => layer2.textureHeight, layer2, "XRProjectionLayer", isMultiview, (sessionManager) => new WebXRProjectionLayerRenderTargetTextureProvider(sessionManager, xrGLBinding, this));
    this.layer = layer2;
  }
}

class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider {
  constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) {
    super(_xrSessionManager, _xrWebGLBinding, layerWrapper);
    this.layerWrapper = layerWrapper;
    this._projectionLayer = layerWrapper.layer;
  }
  _getSubImageForView(view) {
    return this._xrWebGLBinding.getViewSubImage(this._projectionLayer, view);
  }
  getRenderTargetTextureForView(view) {
    return this._getRenderTargetForSubImage(this._getSubImageForView(view), view.eye);
  }
  getRenderTargetTextureForEye(eye) {
    const lastSubImage = this._lastSubImages.get(eye);
    if (lastSubImage) {
      return this._getRenderTargetForSubImage(lastSubImage, eye);
    }
    return null;
  }
  trySetViewportForView(viewport, view) {
    const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForView(view);
    if (subImage) {
      this._setViewportForSubImage(viewport, subImage);
      return true;
    }
    return false;
  }
}
var defaultXRProjectionLayerInit = {
  textureType: "texture",
  colorFormat: 6408,
  depthFormat: 35056,
  scaleFactor: 1,
  clearOnAccess: false
};

// node_modules/@babylonjs/core/XR/features/WebXRLayers.js
init_math_color();
var defaultXRWebGLLayerInit = {};

class WebXRLayers extends WebXRAbstractFeature {
  constructor(_xrSessionManager, _options = {}) {
    super(_xrSessionManager);
    this._options = _options;
    this._existingLayers = [];
    this._isMultiviewEnabled = false;
    this._projectionLayerInitialized = false;
    this._compositionLayerTextureMapping = new WeakMap;
    this._layerToRTTProviderMapping = new WeakMap;
    this.xrNativeFeatureName = "layers";
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    const engine2 = this._xrSessionManager.scene.getEngine();
    this._glContext = engine2._gl;
    this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext);
    this._existingLayers.length = 0;
    const projectionLayerInit = { ...defaultXRProjectionLayerInit, ...this._options.projectionLayerInit };
    this._isMultiviewEnabled = this._options.preferMultiviewOnInit && engine2.getCaps().multiview;
    this.createProjectionLayer(projectionLayerInit);
    this._projectionLayerInitialized = true;
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    this._existingLayers.forEach((layer2) => {
      layer2.dispose();
    });
    this._existingLayers.length = 0;
    this._projectionLayerInitialized = false;
    return true;
  }
  createXRWebGLLayer(params = defaultXRWebGLLayerInit) {
    const layer2 = new XRWebGLLayer(this._xrSessionManager.session, this._glContext, params);
    return new WebXRWebGLLayerWrapper(layer2);
  }
  _validateLayerInit(params, multiview = this._isMultiviewEnabled) {
    if (!this._xrSessionManager.inXRSession) {
      throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");
    }
    if (multiview && params.textureType !== "texture-array") {
      throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");
    }
    if (!multiview && params.textureType === "texture-array") {
      throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");
    }
  }
  _extendXRLayerInit(params, multiview = this._isMultiviewEnabled) {
    if (multiview) {
      params.textureType = "texture-array";
    }
    return params;
  }
  createProjectionLayer(params = defaultXRProjectionLayerInit, multiview = this._isMultiviewEnabled) {
    this._extendXRLayerInit(params, multiview);
    this._validateLayerInit(params, multiview);
    const projLayer = this._xrWebGLBinding.createProjectionLayer(params);
    const layer2 = new WebXRProjectionLayerWrapper(projLayer, multiview, this._xrWebGLBinding);
    this.addXRSessionLayer(layer2);
    return layer2;
  }
  _createQuadLayer(options = { params: {} }, babylonTexture) {
    this._extendXRLayerInit(options.params, false);
    const width = this._existingLayers[0].layer.textureWidth;
    const height = this._existingLayers[0].layer.textureHeight;
    const populatedParams = {
      space: this._xrSessionManager.referenceSpace,
      viewPixelWidth: width,
      viewPixelHeight: height,
      clearOnAccess: true,
      ...options.params
    };
    this._validateLayerInit(populatedParams, false);
    const quadLayer = this._xrWebGLBinding.createQuadLayer(populatedParams);
    quadLayer.width = this._isMultiviewEnabled ? 1 : 2;
    quadLayer.height = 1;
    const wrapper = new WebXRCompositionLayerWrapper(() => quadLayer.width, () => quadLayer.height, quadLayer, "XRQuadLayer", false, (sessionManager) => new WebXRCompositionLayerRenderTargetTextureProvider(sessionManager, this._xrWebGLBinding, wrapper));
    if (babylonTexture) {
      this._compositionLayerTextureMapping.set(quadLayer, babylonTexture);
    }
    const rtt = wrapper.createRenderTargetTextureProvider(this._xrSessionManager);
    this._layerToRTTProviderMapping.set(quadLayer, rtt);
    this.addXRSessionLayer(wrapper);
    return wrapper;
  }
  addFullscreenAdvancedDynamicTexture(texture2, options = { distanceFromHeadset: 1.5 }) {
    const wrapper = this._createQuadLayer({
      params: {
        space: this._xrSessionManager.viewerReferenceSpace,
        textureType: "texture",
        layout: "mono"
      }
    }, texture2);
    const layer2 = wrapper.layer;
    const distance = Math.max(0.1, options.distanceFromHeadset);
    const pos = { x: 0, y: 0, z: -distance };
    const orient = { x: 0, y: 0, z: 0, w: 1 };
    layer2.transform = new XRRigidTransform(pos, orient);
    const rttProvider = this._layerToRTTProviderMapping.get(layer2);
    if (!rttProvider) {
      throw new Error("Could not find the RTT provider for the layer");
    }
    const babylonLayer = this._xrSessionManager.scene.layers.find((babylonLayer2) => {
      return babylonLayer2.texture === texture2;
    });
    if (!babylonLayer) {
      throw new Error("Could not find the babylon layer for the texture");
    }
    rttProvider.onRenderTargetTextureCreatedObservable.add((data) => {
      if (data.eye && data.eye === "right") {
        return;
      }
      data.texture.clearColor = new Color4(0, 0, 0, 0);
      babylonLayer.renderTargetTextures.push(data.texture);
      babylonLayer.renderOnlyInRenderTargetTextures = true;
      this._xrSessionManager.scene.onBeforeRenderObservable.add(() => {
        data.texture.render();
      });
      babylonLayer.renderTargetTextures.push(data.texture);
      babylonLayer.renderOnlyInRenderTargetTextures = true;
      this._xrSessionManager.onXRSessionEnded.addOnce(() => {
        babylonLayer.renderTargetTextures.splice(babylonLayer.renderTargetTextures.indexOf(data.texture), 1);
        babylonLayer.renderOnlyInRenderTargetTextures = false;
      });
    });
    return wrapper;
  }
  _addLensFlareSystem(flareSystem) {
    const wrapper = this._createQuadLayer({
      params: {
        space: this._xrSessionManager.viewerReferenceSpace,
        textureType: "texture",
        layout: "mono"
      }
    });
    const layer2 = wrapper.layer;
    layer2.width = 2;
    layer2.height = 1;
    const distance = 10;
    const pos = { x: 0, y: 0, z: -distance };
    const orient = { x: 0, y: 0, z: 0, w: 1 };
    layer2.transform = new XRRigidTransform(pos, orient);
    const rttProvider = this._layerToRTTProviderMapping.get(layer2);
    if (!rttProvider) {
      throw new Error("Could not find the RTT provider for the layer");
    }
    rttProvider.onRenderTargetTextureCreatedObservable.add((data) => {
      data.texture.clearColor = new Color4(0, 0, 0, 0);
      data.texture.customRenderFunction = () => {
        flareSystem.render();
      };
    });
    this._xrSessionManager.onXRSessionInit.add(() => {
      this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(flareSystem), 1);
    });
    this._xrSessionManager.onXRSessionEnded.add(() => {
      this._xrSessionManager.scene.lensFlareSystems.push(flareSystem);
    });
    return wrapper;
  }
  addXRSessionLayer(wrappedLayer) {
    this._existingLayers.push(wrappedLayer);
    this.setXRSessionLayers(this._existingLayers);
  }
  setXRSessionLayers(wrappedLayers = this._existingLayers) {
    const renderStateInit = { ...this._xrSessionManager.session.renderState };
    renderStateInit.baseLayer = undefined;
    renderStateInit.layers = wrappedLayers.map((wrappedLayer) => wrappedLayer.layer);
    this._xrSessionManager.updateRenderState(renderStateInit);
    if (!this._projectionLayerInitialized) {
      this._xrSessionManager._setBaseLayerWrapper(wrappedLayers.length > 0 ? wrappedLayers.at(0) : null);
    }
  }
  isCompatible() {
    return !this._xrSessionManager.isNative && typeof XRWebGLBinding !== "undefined" && !!XRWebGLBinding.prototype.createProjectionLayer;
  }
  dispose() {
    super.dispose();
  }
  _onXRFrame(_xrFrame) {
    const layers = this._existingLayers;
    for (let i = 0;i < layers.length; ++i) {
      const layer2 = layers[i];
      if (layer2.layerType !== "XRProjectionLayer") {
        const rttProvider = this._layerToRTTProviderMapping.get(layer2.layer);
        if (!rttProvider) {
          continue;
        }
        if (rttProvider.layerWrapper.isMultiview) {
          const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace);
          if (pose) {
            const views = pose.views;
            for (let j = 0;j < views.length; ++j) {
              const view = views[j];
              rttProvider.getRenderTargetTextureForView(view);
            }
          }
        } else {
          rttProvider.getRenderTargetTextureForView();
        }
      }
    }
  }
}
WebXRLayers.Name = WebXRFeatureName.LAYERS;
WebXRLayers.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name, (xrSessionManager, options) => {
  return () => new WebXRLayers(xrSessionManager, options);
}, WebXRLayers.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRDepthSensing.js
init_tools();
init_texture();
init_observable();
init_math_vector();

class DepthSensingMaterialDefines extends MaterialDefines {
  constructor() {
    super(...arguments);
    this.DEPTH_SENSING = false;
    this.DEPTH_SENSING_TEXTURE_ARRAY = false;
    this.DEPTH_SENSING_TEXTURE_AL = false;
    this.DEPTH_SENSING_DISCARD = true;
  }
}
var isPluginEnabled = false;
var depthTexture = null;
var alphaLuminanceTexture = false;
var screenSize = { width: 512, height: 512 };
var shaderViewport = { x: 0, y: 0, width: 1, height: 1 };
var globalRawValueToMeters = 1;
var viewIndex = 0;
var enableDiscard = true;
var uvTransform = Matrix.Identity();
var managedMaterialPlugins = [];

class WebXRDepthSensingMaterialPlugin extends MaterialPluginBase {
  _markAllDefinesAsDirty() {
    this._enable(this._isEnabled);
    this.markAllDefinesAsDirty();
  }
  get isEnabled() {
    return this._isEnabled;
  }
  set isEnabled(value) {
    if (this._isEnabled === value) {
      return;
    }
    this._isEnabled = value;
    this._markAllDefinesAsDirty();
  }
  isCompatible(shaderLanguage2) {
    switch (shaderLanguage2) {
      case 0:
        return true;
      default:
        return true;
    }
  }
  constructor(material2) {
    super(material2, "DepthSensing", 222, new DepthSensingMaterialDefines);
    this._isEnabled = false;
    this._varColorName = material2 instanceof PBRBaseMaterial ? "finalColor" : "color";
    managedMaterialPlugins.push(this);
  }
  prepareDefines(defines) {
    defines.DEPTH_SENSING = !!depthTexture && isPluginEnabled;
    defines.DEPTH_SENSING_TEXTURE_ARRAY = depthTexture?.is2DArray ?? false;
    defines.DEPTH_SENSING_TEXTURE_AL = alphaLuminanceTexture;
    defines.DEPTH_SENSING_DISCARD = enableDiscard;
  }
  getUniforms() {
    return {
      ubo: [
        { name: "ds_invScreenSize", size: 2, type: "vec2" },
        { name: "ds_rawValueToMeters", size: 1, type: "float" },
        { name: "ds_viewIndex", size: 1, type: "float" },
        { name: "ds_shaderViewport", size: 4, type: "vec4" },
        { name: "ds_uvTransform", size: 16, type: "mat4" }
      ],
      fragment: `#ifdef DEPTH_SENSING
                uniform vec2 ds_invScreenSize;
                uniform float ds_rawValueToMeters;
                uniform float ds_viewIndex;
                uniform vec4 ds_shaderViewport;
                uniform mat4 ds_uvTransform;
                #endif
                `
    };
  }
  getSamplers(samplers) {
    samplers.push("ds_depthSampler");
  }
  bindForSubMesh(uniformBuffer2) {
    if (isPluginEnabled && depthTexture) {
      uniformBuffer2.updateFloat2("ds_invScreenSize", 1 / screenSize.width, 1 / screenSize.height);
      uniformBuffer2.updateFloat("ds_rawValueToMeters", globalRawValueToMeters);
      uniformBuffer2.updateFloat("ds_viewIndex", viewIndex);
      uniformBuffer2.updateFloat4("ds_shaderViewport", shaderViewport.x, shaderViewport.y, shaderViewport.width, shaderViewport.height);
      uniformBuffer2.setTexture("ds_depthSampler", depthTexture);
      uniformBuffer2.updateMatrix("ds_uvTransform", uvTransform);
    }
  }
  getClassName() {
    return "DepthSensingMaterialPlugin";
  }
  getCustomCode(shaderType) {
    return shaderType === "vertex" ? {
      CUSTOM_VERTEX_MAIN_BEGIN: `
                #ifdef DEPTH_SENSING
                #ifdef MULTIVIEW
                    ds_viewIndexMultiview = float(gl_ViewID_OVR);
                #endif
                #endif
                `,
      CUSTOM_VERTEX_DEFINITIONS: `
                #ifdef DEPTH_SENSING
                #ifdef MULTIVIEW
                    varying float ds_viewIndexMultiview;
                #endif
                #endif
                `
    } : {
      CUSTOM_FRAGMENT_DEFINITIONS: `
                    #ifdef DEPTH_SENSING
                        #ifdef DEPTH_SENSING_TEXTURE_ARRAY
                            uniform highp sampler2DArray ds_depthSampler;
                        #else
                            uniform sampler2D ds_depthSampler;
                        #endif
                        #ifdef MULTIVIEW
                            varying float ds_viewIndexMultiview;
                        #endif
                    #endif
                  `,
      CUSTOM_FRAGMENT_MAIN_BEGIN: `
#ifdef DEPTH_SENSING
    #ifdef MULTIVIEW
        float ds_viewIndexSet = ds_viewIndexMultiview;
        vec2 ds_compensation = vec2(0.0, 0.0);
    #else
        float ds_viewIndexSet = ds_viewIndex;
        vec2 ds_compensation = vec2(ds_viewIndexSet, 0.0);
    #endif
    vec2 ds_baseUv = gl_FragCoord.xy * ds_invScreenSize;
    #ifdef DEPTH_SENSING_TEXTURE_ARRAY
        vec2 ds_uv = ds_baseUv - ds_compensation;
        vec3 ds_depthUv = vec3((ds_uvTransform * vec4(ds_uv, 0.0, 1.0)).xy, ds_viewIndexSet);
    #else
        vec2 ds_depthUv = (ds_uvTransform * vec4(ds_baseUv.x, 1.0 - ds_baseUv.y, 0.0, 1.0)).xy;
    #endif
    #ifdef DEPTH_SENSING_TEXTURE_AL
        // from alpha-luminance - taken from the explainer
        vec2 ds_alphaLuminance = texture(ds_depthSampler, ds_depthUv).ra;
        float ds_cameraDepth = dot(ds_alphaLuminance, vec2(255.0, 256.0 * 255.0));
    #else
        float ds_cameraDepth = texture(ds_depthSampler, ds_depthUv).r;
    #endif

    ds_cameraDepth = ds_cameraDepth * ds_rawValueToMeters;

    float ds_assetDepth = gl_FragCoord.z;
    #ifdef DEPTH_SENSING_DISCARD
    if(ds_cameraDepth < ds_assetDepth) {
        discard;
    }
    #endif
#endif  
                  `,
      CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR: `
#ifdef DEPTH_SENSING
    #ifndef DEPTH_SENSING_DISCARD
        const float ds_depthTolerancePerM = 0.005;
        float ds_occlusion = clamp(1.0 - 0.5 * (ds_cameraDepth - ds_assetDepth) / (ds_depthTolerancePerM * ds_assetDepth) +
            0.5, 0.0, 1.0);
        ${this._varColorName} *= (1.0 - ds_occlusion);
    #endif
#endif                  
                  `
    };
  }
  dispose(_forceDisposeTextures) {
    const index = managedMaterialPlugins.indexOf(this);
    if (index !== -1) {
      managedMaterialPlugins.splice(index, 1);
    }
    super.dispose(_forceDisposeTextures);
  }
}

class WebXRDepthSensing extends WebXRAbstractFeature {
  get width() {
    return this._width;
  }
  get height() {
    return this._height;
  }
  get rawValueToMeters() {
    return this._rawValueToMeters;
  }
  get normDepthBufferFromNormView() {
    return this._normDepthBufferFromNormView;
  }
  get depthUsage() {
    switch (this._xrSessionManager.session.depthUsage) {
      case "cpu-optimized":
        return "cpu";
      case "gpu-optimized":
        return "gpu";
    }
  }
  get depthDataFormat() {
    switch (this._xrSessionManager.session.depthDataFormat) {
      case "luminance-alpha":
        return "ushort";
      case "float32":
        return "float";
      case "unsigned-short":
        return "ushort";
    }
  }
  get latestInternalTexture() {
    if (!this._cachedWebGLTexture) {
      return null;
    }
    return this._getInternalTextureFromDepthInfo();
  }
  get latestDepthBuffer() {
    if (!this._cachedDepthBuffer) {
      return null;
    }
    return this.depthDataFormat === "float" ? new Float32Array(this._cachedDepthBuffer) : new Uint16Array(this._cachedDepthBuffer);
  }
  get latestDepthImageTexture() {
    return this._cachedDepthImageTexture;
  }
  constructor(_xrSessionManager, options) {
    super(_xrSessionManager);
    this.options = options;
    this._width = null;
    this._height = null;
    this._rawValueToMeters = null;
    this._textureType = null;
    this._normDepthBufferFromNormView = null;
    this._cachedDepthBuffer = null;
    this._cachedWebGLTexture = null;
    this._cachedDepthImageTexture = null;
    this._onCameraObserver = null;
    this.onGetDepthInMetersAvailable = new Observable;
    this.xrNativeFeatureName = "depth-sensing";
    Tools.Warn("depth-sensing is an experimental and unstable feature.");
    enableDiscard = !options.useToleranceFactorForDepthSensing;
  }
  attach(force) {
    if (!super.attach(force)) {
      return false;
    }
    const isBothDepthUsageAndFormatNull = this._xrSessionManager.session.depthDataFormat == null || this._xrSessionManager.session.depthUsage == null;
    if (isBothDepthUsageAndFormatNull) {
      return false;
    }
    this._glBinding = new XRWebGLBinding(this._xrSessionManager.session, this._xrSessionManager.scene.getEngine()._gl);
    isPluginEnabled = !this.options.disableDepthSensingOnMaterials;
    if (isPluginEnabled) {
      managedMaterialPlugins.forEach((plugin) => {
        plugin.isEnabled = true;
      });
      this._onCameraObserver = this._xrSessionManager.scene.onBeforeCameraRenderObservable.add((camera2) => {
        if (!isPluginEnabled) {
          return;
        }
        if (camera2.outputRenderTarget) {
          const viewport = camera2.rigCameras.length > 0 ? camera2.rigCameras[0].viewport : camera2.viewport;
          screenSize.width = camera2.outputRenderTarget.getRenderWidth() / (camera2.rigParent ? camera2.rigParent.rigCameras.length || 1 : 1);
          screenSize.height = camera2.outputRenderTarget.getRenderHeight();
          shaderViewport.x = viewport.x;
          shaderViewport.y = viewport.y;
          shaderViewport.width = viewport.width;
          shaderViewport.height = viewport.height;
          if (camera2.rigParent) {
            viewIndex = camera2.isLeftCamera ? 0 : 1;
          }
        }
      });
    }
    return true;
  }
  detach() {
    isPluginEnabled = false;
    depthTexture = null;
    this._cachedWebGLTexture = null;
    this._cachedDepthBuffer = null;
    managedMaterialPlugins.forEach((plugin) => {
      plugin.isEnabled = false;
    });
    if (this._onCameraObserver) {
      this._xrSessionManager.scene.onBeforeCameraRenderObservable.remove(this._onCameraObserver);
    }
    return super.detach();
  }
  dispose() {
    this._cachedDepthImageTexture?.dispose();
    this.onGetDepthInMetersAvailable.clear();
    if (this._onCameraObserver) {
      this._xrSessionManager.scene.onBeforeCameraRenderObservable.remove(this._onCameraObserver);
    }
  }
  _onXRFrame(_xrFrame) {
    const referenceSPace = this._xrSessionManager.referenceSpace;
    const pose = _xrFrame.getViewerPose(referenceSPace);
    if (pose == null) {
      return;
    }
    for (const view of pose.views) {
      switch (this.depthUsage) {
        case "cpu":
          this._updateDepthInformationAndTextureCPUDepthUsage(_xrFrame, view, this.depthDataFormat);
          break;
        case "gpu":
          if (!this._glBinding) {
            break;
          }
          this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding, view, this.depthDataFormat);
          break;
        default:
          Tools.Error("Unknown depth usage");
          this.detach();
          break;
      }
    }
  }
  _updateDepthInformationAndTextureCPUDepthUsage(frame2, view, dataFormat) {
    const depthInfo = frame2.getDepthInformation(view);
    if (depthInfo === null) {
      return;
    }
    const { data, width, height, rawValueToMeters, getDepthInMeters, normDepthBufferFromNormView } = depthInfo;
    this._width = width;
    this._height = height;
    this._rawValueToMeters = rawValueToMeters;
    this._cachedDepthBuffer = data;
    globalRawValueToMeters = rawValueToMeters;
    alphaLuminanceTexture = dataFormat === "luminance-alpha";
    uvTransform.fromArray(normDepthBufferFromNormView.matrix);
    this.onGetDepthInMetersAvailable.notifyObservers(getDepthInMeters.bind(depthInfo));
    if (!this._cachedDepthImageTexture) {
      this._cachedDepthImageTexture = RawTexture.CreateRTexture(null, width, height, this._xrSessionManager.scene, false, false, Texture.NEAREST_SAMPLINGMODE, 1);
      depthTexture = this._cachedDepthImageTexture;
    }
    let float32Array = null;
    switch (dataFormat) {
      case "ushort":
      case "luminance-alpha":
        float32Array = Float32Array.from(new Uint16Array(data));
        break;
      case "float":
        float32Array = new Float32Array(data);
        break;
      default:
        break;
    }
    if (float32Array) {
      if (this.options.prepareTextureForVisualization) {
        float32Array = float32Array.map((val) => val * rawValueToMeters);
      }
      this._cachedDepthImageTexture.update(float32Array);
    }
  }
  _updateDepthInformationAndTextureWebGLDepthUsage(webglBinding, view, dataFormat) {
    const depthInfo = webglBinding.getDepthInformation(view);
    if (depthInfo === null) {
      return;
    }
    const { texture: texture2, width, height, textureType, rawValueToMeters, normDepthBufferFromNormView } = depthInfo;
    globalRawValueToMeters = rawValueToMeters;
    alphaLuminanceTexture = dataFormat === "luminance-alpha";
    uvTransform.fromArray(normDepthBufferFromNormView.matrix);
    if (this._cachedWebGLTexture) {
      return;
    }
    this._width = width;
    this._height = height;
    this._cachedWebGLTexture = texture2;
    this._textureType = textureType;
    const scene = this._xrSessionManager.scene;
    const internalTexture2 = this._getInternalTextureFromDepthInfo();
    if (!this._cachedDepthImageTexture) {
      this._cachedDepthImageTexture = RawTexture.CreateRTexture(null, width, height, scene, false, true, Texture.NEAREST_SAMPLINGMODE, dataFormat === "float" ? 1 : 0);
    }
    this._cachedDepthImageTexture._texture = internalTexture2;
    depthTexture = this._cachedDepthImageTexture;
    this._xrSessionManager.scene.markAllMaterialsAsDirty(1);
  }
  getXRSessionInitExtension() {
    const isDepthUsageDeclared = this.options.usagePreference != null && this.options.usagePreference.length !== 0;
    const isDataFormatDeclared = this.options.dataFormatPreference != null && this.options.dataFormatPreference.length !== 0;
    return new Promise((resolve3) => {
      if (isDepthUsageDeclared && isDataFormatDeclared) {
        const usages = this.options.usagePreference.map((usage) => {
          switch (usage) {
            case "cpu":
              return "cpu-optimized";
            case "gpu":
              return "gpu-optimized";
          }
        });
        const dataFormats = this.options.dataFormatPreference.map((format) => {
          switch (format) {
            case "luminance-alpha":
              return "luminance-alpha";
            case "float":
              return "float32";
            case "ushort":
              return "unsigned-short";
          }
        });
        resolve3({
          depthSensing: {
            usagePreference: usages,
            dataFormatPreference: dataFormats
          }
        });
      } else {
        resolve3({});
      }
    });
  }
  _getInternalTextureFromDepthInfo() {
    const engine2 = this._xrSessionManager.scene.getEngine();
    const dataFormat = this.depthDataFormat;
    const textureType = this._textureType;
    if (!this._width || !this._height || !this._cachedWebGLTexture) {
      throw new Error("Depth information is not available");
    }
    const internalTexture2 = engine2.wrapWebGLTexture(this._cachedWebGLTexture, false, 1, this._width || 256, this._height || 256);
    internalTexture2.isCube = false;
    internalTexture2.invertY = false;
    internalTexture2._useSRGBBuffer = false;
    internalTexture2.format = dataFormat === "luminance-alpha" ? 2 : 5;
    internalTexture2.generateMipMaps = false;
    internalTexture2.type = dataFormat === "float" ? 1 : dataFormat === "ushort" ? 5 : 0;
    internalTexture2._cachedWrapU = 1;
    internalTexture2._cachedWrapV = 1;
    internalTexture2._hardwareTexture = new WebGLHardwareTexture(this._cachedWebGLTexture, engine2._gl);
    internalTexture2.is2DArray = textureType === "texture-array";
    return internalTexture2;
  }
}
WebXRDepthSensing.Name = WebXRFeatureName.DEPTH_SENSING;
WebXRDepthSensing.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name, (xrSessionManager, options) => {
  return () => new WebXRDepthSensing(xrSessionManager, options);
}, WebXRDepthSensing.Version, false);
RegisterMaterialPlugin("WebXRDepthSensingMaterialPlugin", (material2) => new WebXRDepthSensingMaterialPlugin(material2));
// node_modules/@babylonjs/core/XR/features/WebXRSpaceWarp.js
init_math_vector();
init_renderTargetTexture();

// node_modules/@babylonjs/core/Shaders/velocity.fragment.js
init_shaderStore();
var name529 = "velocityPixelShader";
var shader528 = `precision highp float;
#define CUSTOM_FRAGMENT_BEGIN
varying vec4 clipPos;varying vec4 previousClipPos;
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void) {
#define CUSTOM_FRAGMENT_MAIN_BEGIN
highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;
#define CUSTOM_FRAGMENT_MAIN_END
}`;
if (!ShaderStore.ShadersStore[name529]) {
  ShaderStore.ShadersStore[name529] = shader528;
}

// node_modules/@babylonjs/core/Shaders/velocity.vertex.js
init_shaderStore();
init_instancesDeclaration2();
init_instancesVertex2();
var name530 = "velocityVertexShader";
var shader529 = `#define CUSTOM_VERTEX_BEGIN
#define VELOCITY
attribute vec3 position;
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform mat4 previousViewProjection;
#ifdef MULTIVIEW
uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;
#endif
varying vec4 clipPos;varying vec4 previousClipPos;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void) {
#define CUSTOM_VERTEX_MAIN_BEGIN
vec3 positionUpdated=position;
#include<instancesVertex>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);
#ifdef MULTIVIEW
if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}
#elif
clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;
#endif
#define CUSTOM_VERTEX_MAIN_END
}`;
if (!ShaderStore.ShadersStore[name530]) {
  ShaderStore.ShadersStore[name530] = shader529;
}

// node_modules/@babylonjs/core/XR/features/WebXRSpaceWarp.js
class XRSpaceWarpRenderTarget extends RenderTargetTexture {
  constructor(motionVectorTexture, depthStencilTexture, scene, size = 512) {
    super("spacewarp rtt", size, scene, false, true, 2, false, undefined, false, false, true, undefined, true);
    this._originalPairing = [];
    this._previousWorldMatrices = [];
    this._previousTransforms = [Matrix.Identity(), Matrix.Identity()];
    this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight(), motionVectorTexture, depthStencilTexture);
    this._renderTarget._disposeOnlyFramebuffers = true;
    this._texture = this._renderTarget.texture;
    this._texture.isMultiview = true;
    this._texture.format = 5;
    if (scene) {
      this._velocityMaterial = new ShaderMaterial("velocity shader material", scene, {
        vertex: "velocity",
        fragment: "velocity"
      }, {
        uniforms: ["world", "previousWorld", "viewProjection", "viewProjectionR", "previousViewProjection", "previousViewProjectionR"]
      });
      this._velocityMaterial._materialHelperNeedsPreviousMatrices = true;
      this._velocityMaterial.onBindObservable.add((mesh2) => {
        this._previousWorldMatrices[mesh2.uniqueId] = this._previousWorldMatrices[mesh2.uniqueId] || mesh2.getWorldMatrix();
        this._velocityMaterial.getEffect().setMatrix("previousWorld", this._previousWorldMatrices[mesh2.uniqueId]);
        this._previousWorldMatrices[mesh2.uniqueId] = mesh2.getWorldMatrix();
        this._velocityMaterial.getEffect().setMatrix("previousViewProjection", this._previousTransforms[0]);
        this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR", this._previousTransforms[1]);
        this._previousTransforms[0].copyFrom(scene.getTransformMatrix());
        this._previousTransforms[1].copyFrom(scene._transformMatrixR);
      });
      this._velocityMaterial.freeze();
    }
  }
  render(useCameraPostProcess = false, dumpForDebug = false) {
    this._originalPairing.length = 0;
    const scene = this.getScene();
    if (scene && this._velocityMaterial) {
      scene.getActiveMeshes().forEach((mesh2) => {
        this._originalPairing.push([mesh2, mesh2.material]);
        mesh2.material = this._velocityMaterial;
      });
    }
    super.render(useCameraPostProcess, dumpForDebug);
    this._originalPairing.forEach((tuple) => {
      tuple[0].material = tuple[1];
    });
  }
  _bindFrameBuffer() {
    if (!this._renderTarget) {
      return;
    }
    this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget);
  }
  getViewCount() {
    return 2;
  }
  dispose() {
    super.dispose();
    this._velocityMaterial.dispose();
    this._previousTransforms.length = 0;
    this._previousWorldMatrices.length = 0;
    this._originalPairing.length = 0;
  }
}

class WebXRSpaceWarpRenderTargetTextureProvider {
  constructor(_scene, _xrSessionManager, _xrWebGLBinding) {
    this._scene = _scene;
    this._xrSessionManager = _xrSessionManager;
    this._xrWebGLBinding = _xrWebGLBinding;
    this._lastSubImages = new Map;
    this._renderTargetTextures = new Map;
    this._engine = _scene.getEngine();
  }
  _getSubImageForView(view) {
    const layerWrapper = this._xrSessionManager._getBaseLayerWrapper();
    if (!layerWrapper) {
      throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");
    }
    if (layerWrapper.layerType !== "XRProjectionLayer") {
      throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');
    }
    const layer2 = layerWrapper.layer;
    return this._xrWebGLBinding.getViewSubImage(layer2, view);
  }
  _setViewportForSubImage(viewport, subImage) {
    viewport.x = 0;
    viewport.y = 0;
    viewport.width = subImage.motionVectorTextureWidth;
    viewport.height = subImage.motionVectorTextureHeight;
  }
  _createRenderTargetTexture(width, height, framebuffer, motionVectorTexture, depthStencilTexture) {
    if (!this._engine) {
      throw new Error("Engine is disposed");
    }
    const textureSize = { width, height };
    const renderTargetTexture2 = new XRSpaceWarpRenderTarget(motionVectorTexture, depthStencilTexture, this._scene, textureSize);
    const renderTargetWrapper2 = renderTargetTexture2.renderTarget;
    if (framebuffer) {
      renderTargetWrapper2._framebuffer = framebuffer;
    }
    renderTargetWrapper2._colorTextureArray = motionVectorTexture;
    renderTargetWrapper2._depthStencilTextureArray = depthStencilTexture;
    renderTargetTexture2.disableRescaling();
    renderTargetTexture2.renderListPredicate = () => true;
    return renderTargetTexture2;
  }
  _getRenderTargetForSubImage(subImage, view) {
    const lastSubImage = this._lastSubImages.get(view);
    let renderTargetTexture2 = this._renderTargetTextures.get(view.eye);
    const width = subImage.motionVectorTextureWidth;
    const height = subImage.motionVectorTextureHeight;
    if (!renderTargetTexture2 || lastSubImage?.textureWidth !== width || lastSubImage?.textureHeight != height) {
      renderTargetTexture2 = this._createRenderTargetTexture(width, height, null, subImage.motionVectorTexture, subImage.depthStencilTexture);
      this._renderTargetTextures.set(view.eye, renderTargetTexture2);
      this._framebufferDimensions = {
        framebufferWidth: width,
        framebufferHeight: height
      };
    }
    this._lastSubImages.set(view, subImage);
    return renderTargetTexture2;
  }
  trySetViewportForView(viewport, view) {
    const subImage = this._lastSubImages.get(view) || this._getSubImageForView(view);
    if (subImage) {
      this._setViewportForSubImage(viewport, subImage);
      return true;
    }
    return false;
  }
  accessMotionVector(view) {
    const subImage = this._getSubImageForView(view);
    if (subImage) {
      subImage.motionVectorTexture;
      subImage.depthStencilTexture;
    }
  }
  getRenderTargetTextureForEye(_eye) {
    return null;
  }
  getRenderTargetTextureForView(view) {
    const subImage = this._getSubImageForView(view);
    if (subImage) {
      return this._getRenderTargetForSubImage(subImage, view);
    }
    return null;
  }
  dispose() {
    this._renderTargetTextures.forEach((rtt) => rtt.dispose());
    this._renderTargetTextures.clear();
  }
}

class WebXRSpaceWarp extends WebXRAbstractFeature {
  constructor(_xrSessionManager) {
    super(_xrSessionManager);
    this._onAfterRenderObserver = null;
    this.dependsOn = [WebXRFeatureName.LAYERS];
    this.xrNativeFeatureName = "space-warp";
    this._xrSessionManager.scene.needsPreviousWorldMatrices = true;
  }
  attach() {
    if (!super.attach()) {
      return false;
    }
    const engine2 = this._xrSessionManager.scene.getEngine();
    this._glContext = engine2._gl;
    this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext);
    this.spaceWarpRTTProvider = new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene, this._xrSessionManager, this._xrWebGLBinding);
    this._onAfterRenderObserver = this._xrSessionManager.scene.onAfterRenderObservable.add(() => this._onAfterRender());
    return true;
  }
  detach() {
    this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
    return super.detach();
  }
  _onAfterRender() {
    if (this.attached && this._renderTargetTexture) {
      this._renderTargetTexture.render(false, false);
    }
  }
  isCompatible() {
    return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat || false;
  }
  dispose() {
    super.dispose();
  }
  _onXRFrame(_xrFrame) {
    const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace);
    if (!pose) {
      return;
    }
    const view = pose.views[0];
    this._renderTargetTexture = this._renderTargetTexture || this.spaceWarpRTTProvider.getRenderTargetTextureForView(view);
    this.spaceWarpRTTProvider.accessMotionVector(view);
  }
}
WebXRSpaceWarp.Name = WebXRFeatureName.SPACE_WARP;
WebXRSpaceWarp.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name, (xrSessionManager) => {
  return () => new WebXRSpaceWarp(xrSessionManager);
}, WebXRSpaceWarp.Version, false);
// node_modules/@babylonjs/core/XR/features/WebXRRawCameraAccess.js
init_observable();
init_internalTexture();
init_baseTexture();

class WebXRRawCameraAccess extends WebXRAbstractFeature {
  constructor(_xrSessionManager, options = {}) {
    super(_xrSessionManager);
    this.options = options;
    this._cachedInternalTextures = [];
    this.texturesData = [];
    this.viewIndex = [];
    this.cameraIntrinsics = [];
    this.onTexturesUpdatedObservable = new Observable;
    this.xrNativeFeatureName = "camera-access";
  }
  attach(force) {
    if (!super.attach(force)) {
      return false;
    }
    this._glContext = this._xrSessionManager.scene.getEngine()._gl;
    this._glBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext);
    return true;
  }
  detach() {
    if (!super.detach()) {
      return false;
    }
    this._glBinding = undefined;
    if (!this.options.doNotDisposeOnDetach) {
      this._cachedInternalTextures.forEach((t) => t.dispose());
      this.texturesData.forEach((t) => t.dispose());
      this._cachedInternalTextures.length = 0;
      this.texturesData.length = 0;
      this.cameraIntrinsics.length = 0;
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.onTexturesUpdatedObservable.clear();
  }
  _updateCameraIntrinsics(view, index) {
    const cameraViewport = {
      width: view.camera.width,
      height: view.camera.height,
      x: 0,
      y: 0
    };
    const p = view.projectionMatrix;
    const u0 = (1 - p[8]) * cameraViewport.width / 2 + cameraViewport.x;
    const v0 = (1 - p[9]) * cameraViewport.height / 2 + cameraViewport.y;
    const ax = cameraViewport.width / 2 * p[0];
    const ay = cameraViewport.height / 2 * p[5];
    const gamma = cameraViewport.width / 2 * p[4];
    this.cameraIntrinsics[index] = {
      u0,
      v0,
      ax,
      ay,
      gamma,
      width: cameraViewport.width,
      height: cameraViewport.height,
      viewportX: cameraViewport.x,
      viewportY: cameraViewport.y
    };
  }
  _updateInternalTextures(view, index = 0) {
    if (!view.camera) {
      return false;
    }
    this.viewIndex[index] = view.eye;
    const lp = this._glBinding?.getCameraImage(view.camera);
    if (!this._cachedInternalTextures[index]) {
      const internalTexture2 = new InternalTexture(this._xrSessionManager.scene.getEngine(), 0, true);
      internalTexture2.invertY = false;
      internalTexture2.format = 5;
      internalTexture2.generateMipMaps = true;
      internalTexture2.type = 0;
      internalTexture2.samplingMode = 3;
      internalTexture2.width = view.camera.width;
      internalTexture2.height = view.camera.height;
      internalTexture2._cachedWrapU = 1;
      internalTexture2._cachedWrapV = 1;
      internalTexture2._hardwareTexture = new WebGLHardwareTexture(lp, this._glContext);
      this._cachedInternalTextures[index] = internalTexture2;
      const texture2 = new BaseTexture(this._xrSessionManager.scene);
      texture2.name = `WebXR Raw Camera Access (${index})`;
      texture2._texture = this._cachedInternalTextures[index];
      this.texturesData[index] = texture2;
      this._updateCameraIntrinsics(view, index);
    } else {
      this._cachedInternalTextures[index]._hardwareTexture?.set(lp);
    }
    this._cachedInternalTextures[index].isReady = true;
    return true;
  }
  _onXRFrame(_xrFrame) {
    const referenceSPace = this._xrSessionManager.referenceSpace;
    const pose = _xrFrame.getViewerPose(referenceSPace);
    if (!pose || !pose.views) {
      return;
    }
    let updated = true;
    pose.views.forEach((view, index) => {
      updated = updated && this._updateInternalTextures(view, index);
    });
    if (updated) {
      this.onTexturesUpdatedObservable.notifyObservers(this.texturesData);
    }
  }
}
WebXRRawCameraAccess.Name = WebXRFeatureName.RAW_CAMERA_ACCESS;
WebXRRawCameraAccess.Version = 1;
WebXRFeaturesManager.AddWebXRFeature(WebXRRawCameraAccess.Name, (xrSessionManager, options) => {
  return () => new WebXRRawCameraAccess(xrSessionManager, options);
}, WebXRRawCameraAccess.Version, false);
// node_modules/@babylonjs/core/XR/motionController/webXRGenericHandController.js
class WebXRGenericHandController extends WebXRAbstractMotionController {
  constructor(scene, gamepadObject, handedness) {
    super(scene, GenericHandSelectGraspProfile[handedness], gamepadObject, handedness, true);
    this.profileId = "generic-hand-select-grasp";
  }
  _getFilenameAndPath() {
    return {
      filename: "generic.babylon",
      path: "https://controllers.babylonjs.com/generic/"
    };
  }
  _getModelLoadingConstraints() {
    return true;
  }
  _processLoadedModel(_meshes) {}
  _setRootMesh(meshes) {}
  _updateModel() {}
}
WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp", (xrInput, scene) => {
  return new WebXRGenericHandController(scene, xrInput.gamepad, xrInput.handedness);
});
var GenericHandSelectGraspProfile = {
  left: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr-standard-trigger",
        visualResponses: {}
      },
      grasp: {
        type: "trigger",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "grasp",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-hand-select-grasp-left",
    assetPath: "left.glb"
  },
  right: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr-standard-trigger",
        visualResponses: {}
      },
      grasp: {
        type: "trigger",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "grasp",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-hand-select-grasp-right",
    assetPath: "right.glb"
  },
  none: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr-standard-trigger",
        visualResponses: {}
      },
      grasp: {
        type: "trigger",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "grasp",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "generic-hand-select-grasp-none",
    assetPath: "none.glb"
  }
};
// node_modules/@babylonjs/core/XR/motionController/webXRMicrosoftMixedRealityController.js
init_math_vector();
init_logger();

class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController {
  constructor(scene, gamepadObject, handedness) {
    super(scene, MixedRealityProfile["left-right"], gamepadObject, handedness);
    this._mapping = {
      defaultButton: {
        valueNodeName: "VALUE",
        unpressedNodeName: "UNPRESSED",
        pressedNodeName: "PRESSED"
      },
      defaultAxis: {
        valueNodeName: "VALUE",
        minNodeName: "MIN",
        maxNodeName: "MAX"
      },
      buttons: {
        "xr-standard-trigger": {
          rootNodeName: "SELECT",
          componentProperty: "button",
          states: ["default", "touched", "pressed"]
        },
        "xr-standard-squeeze": {
          rootNodeName: "GRASP",
          componentProperty: "state",
          states: ["pressed"]
        },
        "xr-standard-touchpad": {
          rootNodeName: "TOUCHPAD_PRESS",
          labelAnchorNodeName: "squeeze-label",
          touchPointNodeName: "TOUCH"
        },
        "xr-standard-thumbstick": {
          rootNodeName: "THUMBSTICK_PRESS",
          componentProperty: "state",
          states: ["pressed"]
        }
      },
      axes: {
        "xr-standard-touchpad": {
          "x-axis": {
            rootNodeName: "TOUCHPAD_TOUCH_X"
          },
          "y-axis": {
            rootNodeName: "TOUCHPAD_TOUCH_Y"
          }
        },
        "xr-standard-thumbstick": {
          "x-axis": {
            rootNodeName: "THUMBSTICK_X"
          },
          "y-axis": {
            rootNodeName: "THUMBSTICK_Y"
          }
        }
      }
    };
    this.profileId = "microsoft-mixed-reality";
  }
  _getFilenameAndPath() {
    let filename = "";
    if (this.handedness === "left") {
      filename = WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME;
    } else {
      filename = WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;
    }
    const device = "default";
    const path = WebXRMicrosoftMixedRealityController.MODEL_BASE_URL + device + "/";
    return {
      filename,
      path
    };
  }
  _getModelLoadingConstraints() {
    const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(".glb");
    if (!glbLoaded) {
      Logger.Warn("glTF / glb loaded was not registered, using generic controller instead");
    }
    return glbLoaded;
  }
  _processLoadedModel(_meshes) {
    if (!this.rootMesh) {
      return;
    }
    this.getComponentIds().forEach((id, i) => {
      if (this.disableAnimation) {
        return;
      }
      if (id && this.rootMesh) {
        const buttonMap = this._mapping.buttons[id];
        const buttonMeshName = buttonMap.rootNodeName;
        if (!buttonMeshName) {
          Logger.Log("Skipping unknown button at index: " + i + " with mapped name: " + id);
          return;
        }
        const buttonMesh = this._getChildByName(this.rootMesh, buttonMeshName);
        if (!buttonMesh) {
          Logger.Warn("Missing button mesh with name: " + buttonMeshName);
          return;
        }
        buttonMap.valueMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.valueNodeName);
        buttonMap.pressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.pressedNodeName);
        buttonMap.unpressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.unpressedNodeName);
        if (buttonMap.valueMesh && buttonMap.pressedMesh && buttonMap.unpressedMesh) {
          const comp = this.getComponent(id);
          if (comp) {
            comp.onButtonStateChangedObservable.add((component) => {
              this._lerpTransform(buttonMap, component.value);
            }, undefined, true);
          }
        } else {
          Logger.Warn("Missing button submesh under mesh with name: " + buttonMeshName);
        }
      }
    });
    this.getComponentIds().forEach((id) => {
      const comp = this.getComponent(id);
      if (!comp.isAxes()) {
        return;
      }
      ["x-axis", "y-axis"].forEach((axis) => {
        if (!this.rootMesh) {
          return;
        }
        const axisMap = this._mapping.axes[id][axis];
        const axisMesh = this._getChildByName(this.rootMesh, axisMap.rootNodeName);
        if (!axisMesh) {
          Logger.Warn("Missing axis mesh with name: " + axisMap.rootNodeName);
          return;
        }
        axisMap.valueMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.valueNodeName);
        axisMap.minMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.minNodeName);
        axisMap.maxMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.maxNodeName);
        if (axisMap.valueMesh && axisMap.minMesh && axisMap.maxMesh) {
          if (comp) {
            comp.onAxisValueChangedObservable.add((axisValues) => {
              const value = axis === "x-axis" ? axisValues.x : axisValues.y;
              this._lerpTransform(axisMap, value, true);
            }, undefined, true);
          }
        } else {
          Logger.Warn("Missing axis submesh under mesh with name: " + axisMap.rootNodeName);
        }
      });
    });
  }
  _setRootMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene);
    this.rootMesh.isPickable = false;
    let rootMesh;
    for (let i = 0;i < meshes.length; i++) {
      const mesh2 = meshes[i];
      mesh2.isPickable = false;
      if (!mesh2.parent) {
        rootMesh = mesh2;
      }
    }
    if (rootMesh) {
      rootMesh.setParent(this.rootMesh);
    }
    if (!this.scene.useRightHandedSystem) {
      this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
    }
  }
  _updateModel() {}
}
WebXRMicrosoftMixedRealityController.MODEL_BASE_URL = "https://controllers.babylonjs.com/microsoft/";
WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME = "left.glb";
WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME = "right.glb";
WebXRMotionControllerManager.RegisterController("windows-mixed-reality", (xrInput, scene) => {
  return new WebXRMicrosoftMixedRealityController(scene, xrInput.gamepad, xrInput.handedness);
});
var MixedRealityProfile = {
  left: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {
          xr_standard_trigger_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_trigger_pressed_value",
            minNodeName: "xr_standard_trigger_pressed_min",
            maxNodeName: "xr_standard_trigger_pressed_max"
          }
        }
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {
          xr_standard_squeeze_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_squeeze_pressed_value",
            minNodeName: "xr_standard_squeeze_pressed_min",
            maxNodeName: "xr_standard_squeeze_pressed_max"
          }
        }
      },
      "xr-standard-touchpad": {
        type: "touchpad",
        gamepadIndices: {
          button: 2,
          xAxis: 0,
          yAxis: 1
        },
        rootNodeName: "xr_standard_touchpad",
        visualResponses: {
          xr_standard_touchpad_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_pressed_value",
            minNodeName: "xr_standard_touchpad_pressed_min",
            maxNodeName: "xr_standard_touchpad_pressed_max"
          },
          xr_standard_touchpad_xaxis_pressed: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_xaxis_pressed_value",
            minNodeName: "xr_standard_touchpad_xaxis_pressed_min",
            maxNodeName: "xr_standard_touchpad_xaxis_pressed_max"
          },
          xr_standard_touchpad_yaxis_pressed: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_yaxis_pressed_value",
            minNodeName: "xr_standard_touchpad_yaxis_pressed_min",
            maxNodeName: "xr_standard_touchpad_yaxis_pressed_max"
          },
          xr_standard_touchpad_xaxis_touched: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_xaxis_touched_value",
            minNodeName: "xr_standard_touchpad_xaxis_touched_min",
            maxNodeName: "xr_standard_touchpad_xaxis_touched_max"
          },
          xr_standard_touchpad_yaxis_touched: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_yaxis_touched_value",
            minNodeName: "xr_standard_touchpad_yaxis_touched_min",
            maxNodeName: "xr_standard_touchpad_yaxis_touched_max"
          },
          xr_standard_touchpad_axes_touched: {
            componentProperty: "state",
            states: ["touched", "pressed"],
            valueNodeProperty: "visibility",
            valueNodeName: "xr_standard_touchpad_axes_touched_value"
          }
        },
        touchPointNodeName: "xr_standard_touchpad_axes_touched_value"
      },
      "xr-standard-thumbstick": {
        type: "thumbstick",
        gamepadIndices: {
          button: 3,
          xAxis: 2,
          yAxis: 3
        },
        rootNodeName: "xr_standard_thumbstick",
        visualResponses: {
          xr_standard_thumbstick_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_pressed_value",
            minNodeName: "xr_standard_thumbstick_pressed_min",
            maxNodeName: "xr_standard_thumbstick_pressed_max"
          },
          xr_standard_thumbstick_xaxis_pressed: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_xaxis_pressed_value",
            minNodeName: "xr_standard_thumbstick_xaxis_pressed_min",
            maxNodeName: "xr_standard_thumbstick_xaxis_pressed_max"
          },
          xr_standard_thumbstick_yaxis_pressed: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_yaxis_pressed_value",
            minNodeName: "xr_standard_thumbstick_yaxis_pressed_min",
            maxNodeName: "xr_standard_thumbstick_yaxis_pressed_max"
          }
        }
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "microsoft-mixed-reality-left",
    assetPath: "left.glb"
  },
  right: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {
          xr_standard_trigger_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_trigger_pressed_value",
            minNodeName: "xr_standard_trigger_pressed_min",
            maxNodeName: "xr_standard_trigger_pressed_max"
          }
        }
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {
          xr_standard_squeeze_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_squeeze_pressed_value",
            minNodeName: "xr_standard_squeeze_pressed_min",
            maxNodeName: "xr_standard_squeeze_pressed_max"
          }
        }
      },
      "xr-standard-touchpad": {
        type: "touchpad",
        gamepadIndices: {
          button: 2,
          xAxis: 0,
          yAxis: 1
        },
        rootNodeName: "xr_standard_touchpad",
        visualResponses: {
          xr_standard_touchpad_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_pressed_value",
            minNodeName: "xr_standard_touchpad_pressed_min",
            maxNodeName: "xr_standard_touchpad_pressed_max"
          },
          xr_standard_touchpad_xaxis_pressed: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_xaxis_pressed_value",
            minNodeName: "xr_standard_touchpad_xaxis_pressed_min",
            maxNodeName: "xr_standard_touchpad_xaxis_pressed_max"
          },
          xr_standard_touchpad_yaxis_pressed: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_yaxis_pressed_value",
            minNodeName: "xr_standard_touchpad_yaxis_pressed_min",
            maxNodeName: "xr_standard_touchpad_yaxis_pressed_max"
          },
          xr_standard_touchpad_xaxis_touched: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_xaxis_touched_value",
            minNodeName: "xr_standard_touchpad_xaxis_touched_min",
            maxNodeName: "xr_standard_touchpad_xaxis_touched_max"
          },
          xr_standard_touchpad_yaxis_touched: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_touchpad_yaxis_touched_value",
            minNodeName: "xr_standard_touchpad_yaxis_touched_min",
            maxNodeName: "xr_standard_touchpad_yaxis_touched_max"
          },
          xr_standard_touchpad_axes_touched: {
            componentProperty: "state",
            states: ["touched", "pressed"],
            valueNodeProperty: "visibility",
            valueNodeName: "xr_standard_touchpad_axes_touched_value"
          }
        },
        touchPointNodeName: "xr_standard_touchpad_axes_touched_value"
      },
      "xr-standard-thumbstick": {
        type: "thumbstick",
        gamepadIndices: {
          button: 3,
          xAxis: 2,
          yAxis: 3
        },
        rootNodeName: "xr_standard_thumbstick",
        visualResponses: {
          xr_standard_thumbstick_pressed: {
            componentProperty: "button",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_pressed_value",
            minNodeName: "xr_standard_thumbstick_pressed_min",
            maxNodeName: "xr_standard_thumbstick_pressed_max"
          },
          xr_standard_thumbstick_xaxis_pressed: {
            componentProperty: "xAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_xaxis_pressed_value",
            minNodeName: "xr_standard_thumbstick_xaxis_pressed_min",
            maxNodeName: "xr_standard_thumbstick_xaxis_pressed_max"
          },
          xr_standard_thumbstick_yaxis_pressed: {
            componentProperty: "yAxis",
            states: ["default", "touched", "pressed"],
            valueNodeProperty: "transform",
            valueNodeName: "xr_standard_thumbstick_yaxis_pressed_value",
            minNodeName: "xr_standard_thumbstick_yaxis_pressed_min",
            maxNodeName: "xr_standard_thumbstick_yaxis_pressed_max"
          }
        }
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "microsoft-mixed-reality-right",
    assetPath: "right.glb"
  }
};
// node_modules/@babylonjs/core/XR/motionController/webXROculusTouchMotionController.js
init_math_vector();

class WebXROculusTouchMotionController extends WebXRAbstractMotionController {
  constructor(scene, gamepadObject, handedness, _legacyMapping = false, _forceLegacyControllers = false) {
    super(scene, OculusTouchLayouts[handedness], gamepadObject, handedness);
    this._forceLegacyControllers = _forceLegacyControllers;
    this.profileId = "oculus-touch";
  }
  _getFilenameAndPath() {
    let filename = "";
    if (this.handedness === "left") {
      filename = WebXROculusTouchMotionController.MODEL_LEFT_FILENAME;
    } else {
      filename = WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;
    }
    const path = this._isQuest() ? WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL : WebXROculusTouchMotionController.MODEL_BASE_URL;
    return {
      filename,
      path
    };
  }
  _getModelLoadingConstraints() {
    return true;
  }
  _processLoadedModel(_meshes) {
    const isQuest = this._isQuest();
    const triggerDirection = this.handedness === "right" ? -1 : 1;
    this.getComponentIds().forEach((id) => {
      const comp = id && this.getComponent(id);
      if (comp) {
        comp.onButtonStateChangedObservable.add((component) => {
          if (!this.rootMesh || this.disableAnimation) {
            return;
          }
          switch (id) {
            case "xr-standard-trigger":
              if (!isQuest) {
                this._modelRootNode.getChildren()[3].rotation.x = -component.value * 0.2;
                this._modelRootNode.getChildren()[3].position.y = -component.value * 0.005;
                this._modelRootNode.getChildren()[3].position.z = -component.value * 0.005;
              }
              return;
            case "xr-standard-squeeze":
              if (!isQuest) {
                this._modelRootNode.getChildren()[4].position.x = triggerDirection * component.value * 0.0035;
              }
              return;
            case "xr-standard-thumbstick":
              return;
            case "a-button":
            case "x-button":
              if (!isQuest) {
                if (component.pressed) {
                  this._modelRootNode.getChildren()[1].position.y = -0.001;
                } else {
                  this._modelRootNode.getChildren()[1].position.y = 0;
                }
              }
              return;
            case "b-button":
            case "y-button":
              if (!isQuest) {
                if (component.pressed) {
                  this._modelRootNode.getChildren()[2].position.y = -0.001;
                } else {
                  this._modelRootNode.getChildren()[2].position.y = 0;
                }
              }
              return;
          }
        }, undefined, true);
      }
    });
  }
  _setRootMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene);
    if (!this.scene.useRightHandedSystem) {
      this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
    }
    meshes.forEach((mesh2) => {
      mesh2.isPickable = false;
    });
    if (this._isQuest()) {
      this._modelRootNode = meshes[0];
    } else {
      this._modelRootNode = meshes[1];
      this.rootMesh.position.y = 0.034;
      this.rootMesh.position.z = 0.052;
    }
    this._modelRootNode.parent = this.rootMesh;
  }
  _updateModel() {}
  _isQuest() {
    return !!navigator.userAgent.match(/Quest/gi) && !this._forceLegacyControllers;
  }
}
WebXROculusTouchMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/oculus/";
WebXROculusTouchMotionController.MODEL_LEFT_FILENAME = "left.babylon";
WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME = "right.babylon";
WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL = "https://controllers.babylonjs.com/oculusQuest/";
WebXRMotionControllerManager.RegisterController("oculus-touch", (xrInput, scene) => {
  return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness);
});
WebXRMotionControllerManager.RegisterController("oculus-touch-legacy", (xrInput, scene) => {
  return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness, true);
});
var OculusTouchLayouts = {
  left: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {}
      },
      "xr-standard-thumbstick": {
        type: "thumbstick",
        gamepadIndices: {
          button: 3,
          xAxis: 2,
          yAxis: 3
        },
        rootNodeName: "xr_standard_thumbstick",
        visualResponses: {}
      },
      "x-button": {
        type: "button",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "x_button",
        visualResponses: {}
      },
      "y-button": {
        type: "button",
        gamepadIndices: {
          button: 5
        },
        rootNodeName: "y_button",
        visualResponses: {}
      },
      thumbrest: {
        type: "button",
        gamepadIndices: {
          button: 6
        },
        rootNodeName: "thumbrest",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "oculus-touch-v2-left",
    assetPath: "left.glb"
  },
  right: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {}
      },
      "xr-standard-thumbstick": {
        type: "thumbstick",
        gamepadIndices: {
          button: 3,
          xAxis: 2,
          yAxis: 3
        },
        rootNodeName: "xr_standard_thumbstick",
        visualResponses: {}
      },
      "a-button": {
        type: "button",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "a_button",
        visualResponses: {}
      },
      "b-button": {
        type: "button",
        gamepadIndices: {
          button: 5
        },
        rootNodeName: "b_button",
        visualResponses: {}
      },
      thumbrest: {
        type: "button",
        gamepadIndices: {
          button: 6
        },
        rootNodeName: "thumbrest",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "oculus-touch-v2-right",
    assetPath: "right.glb"
  }
};
// node_modules/@babylonjs/core/XR/motionController/webXRHTCViveMotionController.js
init_math_vector();
class WebXRHTCViveMotionController extends WebXRAbstractMotionController {
  constructor(scene, gamepadObject, handedness) {
    super(scene, HTCViveLayout[handedness], gamepadObject, handedness);
    this.profileId = "htc-vive";
  }
  _getFilenameAndPath() {
    const filename = WebXRHTCViveMotionController.MODEL_FILENAME;
    const path = WebXRHTCViveMotionController.MODEL_BASE_URL;
    return {
      filename,
      path
    };
  }
  _getModelLoadingConstraints() {
    return true;
  }
  _processLoadedModel(_meshes) {
    this.getComponentIds().forEach((id) => {
      const comp = id && this.getComponent(id);
      if (comp) {
        comp.onButtonStateChangedObservable.add((component) => {
          if (!this.rootMesh || this.disableAnimation) {
            return;
          }
          switch (id) {
            case "xr-standard-trigger":
              this._modelRootNode.getChildren()[6].rotation.x = -component.value * 0.15;
              return;
            case "xr-standard-touchpad":
              return;
            case "xr-standard-squeeze":
              return;
          }
        }, undefined, true);
      }
    });
  }
  _setRootMesh(meshes) {
    this.rootMesh = new Mesh(this.profileId + " " + this.handedness, this.scene);
    meshes.forEach((mesh2) => {
      mesh2.isPickable = false;
    });
    this._modelRootNode = meshes[1];
    this._modelRootNode.parent = this.rootMesh;
    if (!this.scene.useRightHandedSystem) {
      this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);
    }
  }
  _updateModel() {}
}
WebXRHTCViveMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/vive/";
WebXRHTCViveMotionController.MODEL_FILENAME = "wand.babylon";
WebXRMotionControllerManager.RegisterController("htc-vive", (xrInput, scene) => {
  return new WebXRHTCViveMotionController(scene, xrInput.gamepad, xrInput.handedness);
});
var HTCViveLayout = {
  left: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {}
      },
      "xr-standard-touchpad": {
        type: "touchpad",
        gamepadIndices: {
          button: 2,
          xAxis: 0,
          yAxis: 1
        },
        rootNodeName: "xr_standard_touchpad",
        visualResponses: {}
      },
      menu: {
        type: "button",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "menu",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "htc_vive_none",
    assetPath: "none.glb"
  },
  right: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {}
      },
      "xr-standard-touchpad": {
        type: "touchpad",
        gamepadIndices: {
          button: 2,
          xAxis: 0,
          yAxis: 1
        },
        rootNodeName: "xr_standard_touchpad",
        visualResponses: {}
      },
      menu: {
        type: "button",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "menu",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "htc_vive_none",
    assetPath: "none.glb"
  },
  none: {
    selectComponentId: "xr-standard-trigger",
    components: {
      "xr-standard-trigger": {
        type: "trigger",
        gamepadIndices: {
          button: 0
        },
        rootNodeName: "xr_standard_trigger",
        visualResponses: {}
      },
      "xr-standard-squeeze": {
        type: "squeeze",
        gamepadIndices: {
          button: 1
        },
        rootNodeName: "xr_standard_squeeze",
        visualResponses: {}
      },
      "xr-standard-touchpad": {
        type: "touchpad",
        gamepadIndices: {
          button: 2,
          xAxis: 0,
          yAxis: 1
        },
        rootNodeName: "xr_standard_touchpad",
        visualResponses: {}
      },
      menu: {
        type: "button",
        gamepadIndices: {
          button: 4
        },
        rootNodeName: "menu",
        visualResponses: {}
      }
    },
    gamepadMapping: "xr-standard",
    rootNodeName: "htc-vive-none",
    assetPath: "none.glb"
  }
};
// node_modules/@babylonjs/core/XR/native/nativeXRFrame.js
class NativeXRFrame {
  get session() {
    return this._nativeImpl.session;
  }
  constructor(_nativeImpl) {
    this._nativeImpl = _nativeImpl;
    this._xrTransform = new XRRigidTransform;
    this._xrPose = {
      transform: this._xrTransform,
      emulatedPosition: false
    };
    this._xrPoseVectorData = new Float32Array(4 + 4);
    this.fillPoses = this._nativeImpl.fillPoses.bind(this._nativeImpl);
    this.getViewerPose = this._nativeImpl.getViewerPose.bind(this._nativeImpl);
    this.getHitTestResults = this._nativeImpl.getHitTestResults.bind(this._nativeImpl);
    this.getHitTestResultsForTransientInput = () => {
      throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.");
    };
    this.createAnchor = this._nativeImpl.createAnchor.bind(this._nativeImpl);
    this.getJointPose = this._nativeImpl.getJointPose.bind(this._nativeImpl);
    this.fillJointRadii = this._nativeImpl.fillJointRadii.bind(this._nativeImpl);
    this.getLightEstimate = () => {
      throw new Error("XRFrame.getLightEstimate not supported on native.");
    };
    this.getImageTrackingResults = () => {
      return this._nativeImpl._imageTrackingResults ?? [];
    };
  }
  getPose(space, baseSpace) {
    if (!this._nativeImpl.getPoseData(space, baseSpace, this._xrPoseVectorData.buffer, this._xrTransform.matrix.buffer)) {
      return;
    }
    const position = this._xrTransform.position;
    position.x = this._xrPoseVectorData[0];
    position.y = this._xrPoseVectorData[1];
    position.z = this._xrPoseVectorData[2];
    position.w = this._xrPoseVectorData[3];
    const orientation = this._xrTransform.orientation;
    orientation.x = this._xrPoseVectorData[4];
    orientation.y = this._xrPoseVectorData[5];
    orientation.z = this._xrPoseVectorData[6];
    orientation.w = this._xrPoseVectorData[7];
    return this._xrPose;
  }
  get trackedAnchors() {
    return this._nativeImpl.trackedAnchors;
  }
  get worldInformation() {
    return this._nativeImpl.worldInformation;
  }
  get detectedPlanes() {
    return this._nativeImpl.detectedPlanes;
  }
  get featurePointCloud() {
    return this._nativeImpl.featurePointCloud;
  }
  getDepthInformation(view) {
    throw new Error("This function is not available in Babylon Native");
  }
}
RegisterNativeTypeAsync("NativeXRFrame", NativeXRFrame);
// node_modules/electrobun/dist/api/bun/index.ts
init_BuildConfig();
await init_native();

// src/bun/index.ts
import { CString as CString3, ptr as ptr3, toArrayBuffer as toArrayBuffer3 } from "bun:ffi";
var WGPUNative2 = webGPU_default.native;
var WGPU_STRLEN2 = 0xffffffffffffffffn;
var WGPU_DEPTH_SLICE_UNDEFINED2 = 4294967295;
var WGPUTextureUsage_RenderAttachment2 = 0x0000000000000010n;
var WGPUBufferUsage_Vertex = 0x0000000000000020n;
var WGPUBufferUsage_CopyDst = 0x0000000000000008n;
var WGPUVertexFormat_Float322 = 28;
var WGPUVertexFormat_Float32x22 = 29;
var WGPUVertexFormat_Float32x42 = 31;
var WGPUVertexStepMode_Vertex2 = 1;
var WGPUPrimitiveTopology_TriangleList2 = 4;
var WGPUFrontFace_CCW2 = 1;
var WGPUCullMode_None2 = 1;
var WGPUPresentMode_Fifo2 = 1;
var KEEPALIVE = [];
function writePtr2(view, offset, value) {
  view.setBigUint64(offset, BigInt(value ?? 0), true);
}
function writeU322(view, offset, value) {
  view.setUint32(offset, value >>> 0, true);
}
function writeU642(view, offset, value) {
  view.setBigUint64(offset, value, true);
}
function makeSurfaceConfiguration2(devicePtr, width, height, format) {
  const buffer2 = new ArrayBuffer(64);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, devicePtr);
  writeU322(view, 16, format);
  writeU322(view, 20, 0);
  writeU642(view, 24, WGPUTextureUsage_RenderAttachment2);
  writeU322(view, 32, width);
  writeU322(view, 36, height);
  writeU642(view, 40, 0n);
  writePtr2(view, 48, 0);
  writeU322(view, 56, 1);
  writeU322(view, 60, WGPUPresentMode_Fifo2);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeShaderSourceWGSL2(codePtr) {
  const buffer2 = new ArrayBuffer(32);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, 2);
  writeU322(view, 12, 0);
  writePtr2(view, 16, codePtr);
  writeU642(view, 24, WGPU_STRLEN2);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeShaderModuleDescriptor2(nextInChainPtr) {
  const buffer2 = new ArrayBuffer(24);
  const view = new DataView(buffer2);
  writePtr2(view, 0, nextInChainPtr);
  writePtr2(view, 8, 0);
  writeU642(view, 16, 0n);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeVertexAttribute2(offset, shaderLocation, format) {
  const buffer2 = new ArrayBuffer(32);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, format);
  writeU322(view, 12, 0);
  writeU642(view, 16, BigInt(offset));
  writeU322(view, 24, shaderLocation);
  writeU322(view, 28, 0);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeVertexBufferLayout2(attributePtr, attributeCount, stride) {
  const buffer2 = new ArrayBuffer(40);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, WGPUVertexStepMode_Vertex2);
  writeU322(view, 12, 0);
  writeU642(view, 16, BigInt(stride));
  writeU642(view, 24, BigInt(attributeCount));
  writePtr2(view, 32, attributePtr);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeColorTargetState2(format) {
  const buffer2 = new ArrayBuffer(32);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, format);
  writeU322(view, 12, 0);
  writePtr2(view, 16, 0);
  writeU642(view, 24, 0x0fn);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeVertexState2(modulePtr, entryPointPtr, bufferLayoutPtr) {
  const buffer2 = new ArrayBuffer(64);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, modulePtr);
  writePtr2(view, 16, entryPointPtr);
  writeU642(view, 24, WGPU_STRLEN2);
  writeU642(view, 32, 0n);
  writePtr2(view, 40, 0);
  writeU642(view, 48, 1n);
  writePtr2(view, 56, bufferLayoutPtr);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeFragmentState2(modulePtr, entryPointPtr, targetPtr) {
  const buffer2 = new ArrayBuffer(64);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, modulePtr);
  writePtr2(view, 16, entryPointPtr);
  writeU642(view, 24, WGPU_STRLEN2);
  writeU642(view, 32, 0n);
  writePtr2(view, 40, 0);
  writeU642(view, 48, 1n);
  writePtr2(view, 56, targetPtr);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makePrimitiveState2() {
  const buffer2 = new ArrayBuffer(32);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, WGPUPrimitiveTopology_TriangleList2);
  writeU322(view, 12, 0);
  writeU322(view, 16, WGPUFrontFace_CCW2);
  writeU322(view, 20, WGPUCullMode_None2);
  writeU322(view, 24, 0);
  writeU322(view, 28, 0);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeMultisampleState2() {
  const buffer2 = new ArrayBuffer(24);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writeU322(view, 8, 1);
  writeU322(view, 12, 4294967295);
  writeU322(view, 16, 0);
  writeU322(view, 20, 0);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeRenderPipelineDescriptor2(vertexStatePtr, primitiveStatePtr, multisampleStatePtr, fragmentStatePtr) {
  const buffer2 = new ArrayBuffer(168);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, 0);
  writeU642(view, 16, 0n);
  writePtr2(view, 24, 0);
  new Uint8Array(buffer2, 32, 64).set(new Uint8Array(vertexStatePtr.buffer));
  new Uint8Array(buffer2, 96, 32).set(new Uint8Array(primitiveStatePtr.buffer));
  writePtr2(view, 128, 0);
  new Uint8Array(buffer2, 136, 24).set(new Uint8Array(multisampleStatePtr.buffer));
  writePtr2(view, 160, fragmentStatePtr.ptr);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeBufferDescriptor2(size) {
  const buffer2 = new ArrayBuffer(48);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, 0);
  writeU642(view, 16, 0n);
  writeU642(view, 24, WGPUBufferUsage_Vertex | WGPUBufferUsage_CopyDst);
  writeU642(view, 32, BigInt(size));
  writeU322(view, 40, 0);
  writeU322(view, 44, 0);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeCommandEncoderDescriptor2() {
  const buffer2 = new ArrayBuffer(24);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, 0);
  writeU642(view, 16, 0n);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeSurfaceTexture2() {
  const buffer2 = new ArrayBuffer(24);
  return { buffer: buffer2, view: new DataView(buffer2), ptr: ptr3(buffer2) };
}
function makeRenderPassColorAttachment2(viewPtr, clear) {
  const buffer2 = new ArrayBuffer(72);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, viewPtr);
  writeU322(view, 16, WGPU_DEPTH_SLICE_UNDEFINED2);
  writeU322(view, 20, 0);
  writePtr2(view, 24, 0);
  writeU322(view, 32, 2);
  writeU322(view, 36, 1);
  view.setFloat64(40, clear.r, true);
  view.setFloat64(48, clear.g, true);
  view.setFloat64(56, clear.b, true);
  view.setFloat64(64, clear.a, true);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeRenderPassDescriptor2(colorAttachmentPtr) {
  const buffer2 = new ArrayBuffer(64);
  const view = new DataView(buffer2);
  writePtr2(view, 0, 0);
  writePtr2(view, 8, 0);
  writeU642(view, 16, 0n);
  writeU642(view, 24, 1n);
  writePtr2(view, 32, colorAttachmentPtr);
  writePtr2(view, 40, 0);
  writePtr2(view, 48, 0);
  writePtr2(view, 56, 0);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
function makeCommandBufferArray(cmdPtr) {
  const buffer2 = new BigUint64Array([BigInt(cmdPtr)]);
  return { buffer: buffer2, ptr: ptr3(buffer2) };
}
var size = 640;
var display = Screen.getPrimaryDisplay();
var workArea = display.workArea;
var x = workArea.x + Math.floor((workArea.width - size) / 2);
var y = workArea.y + Math.floor((workArea.height - size) / 2);
var win = new GpuWindow({
  title: "WGPU Shader",
  frame: { width: size, height: size, x, y },
  titleBarStyle: "default",
  transparent: false
});
if (!WGPUNative2.available) {
  throw new Error("WGPU not available for wgpu");
}
var instance = WGPUNative2.symbols.wgpuCreateInstance(0);
var surface = WGPUBridge.createSurfaceForView(instance, win.wgpuView.ptr);
var adapterDevice = new BigUint64Array(2);
WGPUBridge.createAdapterDeviceMainThread(instance, surface, ptr3(adapterDevice));
var adapter = Number(adapterDevice[0]);
var device = Number(adapterDevice[1]);
if (!adapter || !device) {
  throw new Error("Failed to get WGPU adapter/device");
}
var queue = WGPUNative2.symbols.wgpuDeviceGetQueue(device);
var capsBuffer = new ArrayBuffer(64);
var capsView = new DataView(capsBuffer);
WGPUNative2.symbols.wgpuSurfaceGetCapabilities(surface, adapter, ptr3(capsBuffer));
var formatCount = Number(capsView.getBigUint64(16, true));
var formatPtr = Number(capsView.getBigUint64(24, true));
var surfaceFormat = 23;
if (formatCount && formatPtr) {
  const formats = new Uint32Array(toArrayBuffer3(formatPtr, 0, formatCount * 4));
  if (formats.length)
    surfaceFormat = formats[0];
}
var surfaceConfig = makeSurfaceConfiguration2(device, size, size, surfaceFormat);
WGPUBridge.surfaceConfigure(surface, surfaceConfig.ptr);
var shaderText = `
struct VSOut {
  @builtin(position) position : vec4<f32>,
  @location(0) uv : vec2<f32>,
  @location(1) time : f32,
  @location(2) resolution : vec2<f32>,
  @location(3) mouse : vec4<f32>,
};

@vertex
fn vs_main(
  @location(0) position: vec2<f32>,
  @location(1) time: f32,
  @location(2) resolution: vec2<f32>,
  @location(3) mouse: vec4<f32>
) -> VSOut {
  var out: VSOut;
  out.position = vec4<f32>(position, 0.0, 1.0);
  out.uv = position;
  out.time = time;
  out.resolution = resolution;
  out.mouse = mouse;
  return out;
}

@fragment
fn fs_main(
  @location(0) uv: vec2<f32>,
  @location(1) time: f32,
  @location(2) resolution: vec2<f32>,
  @location(3) mouse: vec4<f32>
) -> @location(0) vec4<f32> {
  let fragCoord = (uv * 0.5 + vec2<f32>(0.5)) * resolution;
  let m = (mouse.xy / max(resolution, vec2<f32>(1.0))) * 2.0 - vec2<f32>(1.0);
  let loopMax: i32 = select(32, 64, mouse.z > 0.5);
  var o = vec4<f32>(0.0);
  var i: f32 = 0.0;
  var d: f32 = 0.0;
  var c: f32 = 0.0;
  var s: f32 = 0.0;
  var q = vec3<f32>(0.0);
  var p = vec3<f32>(0.0);
  let r = vec3<f32>(resolution, 0.0);
  var dir = normalize(vec3<f32>((fragCoord + fragCoord - r.xy) / r.y, 1.0));
  dir.x = dir.x + m.x * 0.35;
  dir.y = dir.y + -m.y * 0.35;

  for (var iter: i32 = 0; iter < loopMax; iter = iter + 1) {
    i = f32(iter + 1);
    p = dir * d;
    p.z = p.z + time * 4.0;
    q = p;
    s = 0.0;
    c = 20.0;
    loop {
      if (c <= 0.2) { break; }
      let m = mat2x2<f32>(
        vec2<f32>(cos(c / 30.0 + 0.0), cos(c / 30.0 + 33.0)),
        vec2<f32>(cos(c / 30.0 + 11.0), cos(c / 30.0 + 0.0))
      );
      let xz = m * vec2<f32>(p.x, p.z);
      p.x = xz.x;
      p.z = xz.y;
      p = abs(fract(p / c) * c - vec3<f32>(c * 0.5)) - vec3<f32>(c * 0.2);
      s = max(
        9.0 + 3.0 * sin(q.z * 0.05) - abs(q.x),
        max(s, min(p.x, min(p.y, p.z)))
      );
      p = q;
      c = c * 0.5;
    }
    let sinp = sin(p * 12.0);
    let dotv = dot(sinp, vec3<f32>(0.1, 0.1, 0.1));
    s = min(s, p.y + 8.0 + dotv);
    d = d + s;
    let add = i / max(s, 0.001);
    o = o + vec4<f32>(add, add, add, add);
  }

  let denom = max(d, 0.000001);
  o = tanh(o / denom / 30000.0);
  return vec4<f32>(o.xyz, 1.0);
}
`;
var shaderBytes = new TextEncoder().encode(shaderText + "\x00");
var shaderBuf = new Uint8Array(shaderBytes);
KEEPALIVE.push(shaderBuf);
var shaderPtr = ptr3(shaderBuf);
var shaderSource = makeShaderSourceWGSL2(shaderPtr);
var shaderDesc = makeShaderModuleDescriptor2(shaderSource.ptr);
var shaderModule = WGPUNative2.symbols.wgpuDeviceCreateShaderModule(device, shaderDesc.ptr);
var entryPoint = new CString3("vs_main");
var fragEntryPoint = new CString3("fs_main");
KEEPALIVE.push(entryPoint, fragEntryPoint);
var posAttr = makeVertexAttribute2(0, 0, WGPUVertexFormat_Float32x22);
var timeAttr = makeVertexAttribute2(8, 1, WGPUVertexFormat_Float322);
var resAttr = makeVertexAttribute2(12, 2, WGPUVertexFormat_Float32x22);
var mouseAttr = makeVertexAttribute2(20, 3, WGPUVertexFormat_Float32x42);
var attrBuf = new ArrayBuffer(32 * 4);
new Uint8Array(attrBuf, 0, 32).set(new Uint8Array(posAttr.buffer));
new Uint8Array(attrBuf, 32, 32).set(new Uint8Array(timeAttr.buffer));
new Uint8Array(attrBuf, 64, 32).set(new Uint8Array(resAttr.buffer));
new Uint8Array(attrBuf, 96, 32).set(new Uint8Array(mouseAttr.buffer));
var attrPtr = ptr3(attrBuf);
KEEPALIVE.push(attrBuf);
var vertexLayout = makeVertexBufferLayout2(attrPtr, 4, 36);
var vertexState = makeVertexState2(shaderModule, entryPoint.ptr, vertexLayout.ptr);
var colorTarget = makeColorTargetState2(surfaceFormat);
var fragmentState = makeFragmentState2(shaderModule, fragEntryPoint.ptr, colorTarget.ptr);
var primitiveState = makePrimitiveState2();
var multisampleState = makeMultisampleState2();
var pipelineDesc = makeRenderPipelineDescriptor2(vertexState, primitiveState, multisampleState, fragmentState);
var pipeline = WGPUNative2.symbols.wgpuDeviceCreateRenderPipeline(device, pipelineDesc.ptr);
var vertexCount = 3;
var bufferDesc = makeBufferDescriptor2(vertexCount * 9 * 4);
var vertexBuffer = WGPUNative2.symbols.wgpuDeviceCreateBuffer(device, bufferDesc.ptr);
var encoderDesc = makeCommandEncoderDescriptor2();
var lastLeftDown = false;
var qualityBoost = false;
var clickX = 0;
var clickY = 0;
function renderFrame() {
  const sizeNow = win.getSize();
  const t = performance.now() * 0.001;
  const positions = [-1, -1, 3, -1, -1, 3];
  const frame2 = win.getFrame();
  const cursor = Screen.getCursorScreenPoint();
  const rawX = cursor.x - frame2.x;
  const rawY = cursor.y - frame2.y;
  const mx = Math.max(0, Math.min(frame2.width, rawX));
  const my = Math.max(0, Math.min(frame2.height, rawY));
  const buttons = Screen.getMouseButtons();
  const leftDown = (buttons & 1n) === 1n;
  if (leftDown && !lastLeftDown) {
    qualityBoost = !qualityBoost;
    clickX = mx;
    clickY = my;
  }
  lastLeftDown = leftDown;
  const packed = new Float32Array(vertexCount * 9);
  for (let i = 0;i < vertexCount; i += 1) {
    const idx = i * 9;
    packed[idx] = positions[i * 2];
    packed[idx + 1] = positions[i * 2 + 1];
    packed[idx + 2] = t;
    packed[idx + 3] = sizeNow.width;
    packed[idx + 4] = sizeNow.height;
    packed[idx + 5] = mx;
    packed[idx + 6] = my;
    packed[idx + 7] = qualityBoost ? clickX : 0;
    packed[idx + 8] = qualityBoost ? clickY : 0;
  }
  WGPUNative2.symbols.wgpuQueueWriteBuffer(queue, vertexBuffer, 0, ptr3(packed), packed.byteLength);
  WGPUNative2.symbols.wgpuInstanceProcessEvents(instance);
  const surfaceTexture = makeSurfaceTexture2();
  WGPUBridge.surfaceGetCurrentTexture(surface, surfaceTexture.ptr);
  const status = surfaceTexture.view.getUint32(16, true);
  if (status !== 1 && status !== 2)
    return;
  const texPtr = Number(surfaceTexture.view.getBigUint64(8, true));
  if (!texPtr)
    return;
  const textureView = WGPUNative2.symbols.wgpuTextureCreateView(texPtr, 0);
  if (!textureView)
    return;
  const colorAttachment = makeRenderPassColorAttachment2(textureView, {
    r: 0.05,
    g: 0.05,
    b: 0.1,
    a: 1
  });
  const renderPassDesc = makeRenderPassDescriptor2(colorAttachment.ptr);
  const encoder = WGPUNative2.symbols.wgpuDeviceCreateCommandEncoder(device, encoderDesc.ptr);
  const pass2 = WGPUNative2.symbols.wgpuCommandEncoderBeginRenderPass(encoder, renderPassDesc.ptr);
  WGPUNative2.symbols.wgpuRenderPassEncoderSetPipeline(pass2, pipeline);
  WGPUNative2.symbols.wgpuRenderPassEncoderSetVertexBuffer(pass2, 0, vertexBuffer, 0, packed.byteLength);
  WGPUNative2.symbols.wgpuRenderPassEncoderDraw(pass2, vertexCount, 1, 0, 0);
  WGPUNative2.symbols.wgpuRenderPassEncoderEnd(pass2);
  const commandBuffer = WGPUNative2.symbols.wgpuCommandEncoderFinish(encoder, 0);
  const commandArray = makeCommandBufferArray(commandBuffer);
  WGPUNative2.symbols.wgpuQueueSubmit(queue, 1, commandArray.ptr);
  WGPUBridge.surfacePresent(surface);
  WGPUNative2.symbols.wgpuTextureViewRelease(textureView);
  WGPUNative2.symbols.wgpuTextureRelease(texPtr);
  WGPUNative2.symbols.wgpuCommandBufferRelease(commandBuffer);
  WGPUNative2.symbols.wgpuCommandEncoderRelease(encoder);
}
setInterval(renderFrame, 16);
