@zephyr3d/scene 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"scriptregistry.js","sources":["../../src/app/scriptregistry.ts"],"sourcesContent":["import type * as TS from 'typescript';\r\nimport type { Nullable, VFS } from '@zephyr3d/base';\r\nimport { textToBase64 } from '@zephyr3d/base';\r\nimport { init, parse } from 'es-module-lexer';\r\nimport { getApp } from './api';\r\n\r\n/**\r\n * Converts JavaScript source to a data URL tied to a logical module id.\r\n *\r\n * @param js - The JavaScript source code to embed.\r\n * @param id - Logical module identifier (used only for sourceURL tagging).\r\n * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.\r\n * @internal\r\n */\r\nfunction toDataUrl(js: string, id: string) {\r\n const b64 = textToBase64(js);\r\n return `data:text/javascript;base64,${b64}#${encodeURIComponent(String(id))}`;\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is an absolute HTTP(S) URL.\r\n * @internal\r\n */\r\nfunction isAbsoluteUrl(spec: string) {\r\n return /^https?:\\/\\//i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a special URL (data: or blob:).\r\n * @internal\r\n */\r\nfunction isSpecialUrl(spec: string) {\r\n return /^(data|blob):/i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).\r\n * @internal\r\n */\r\nfunction isBareModule(spec: string) {\r\n return !spec.startsWith('./') && !spec.startsWith('../') && !spec.startsWith('/') && !spec.startsWith('#/');\r\n}\r\n\r\nfunction splitSpecifierQuery(spec: string) {\r\n const hashIndex = spec.indexOf('#');\r\n const queryIndex = spec.indexOf('?');\r\n const cutIndex =\r\n queryIndex >= 0 && hashIndex >= 0\r\n ? Math.min(queryIndex, hashIndex)\r\n : queryIndex >= 0\r\n ? queryIndex\r\n : hashIndex;\r\n if (cutIndex < 0) {\r\n return {\r\n path: spec,\r\n suffix: ''\r\n };\r\n }\r\n return {\r\n path: spec.slice(0, cutIndex),\r\n suffix: spec.slice(cutIndex)\r\n };\r\n}\r\n\r\nfunction hasRawQuery(spec: string) {\r\n const { suffix } = splitSpecifierQuery(spec);\r\n if (!suffix || suffix[0] !== '?') {\r\n return false;\r\n }\r\n const queryEnd = suffix.indexOf('#');\r\n const query = (queryEnd >= 0 ? suffix.slice(1, queryEnd) : suffix.slice(1)).trim();\r\n if (!query) {\r\n return false;\r\n }\r\n return query.split('&').some((part) => part.trim() === 'raw');\r\n}\r\n\r\ntype ScriptModuleType = 'js' | 'ts';\r\n\r\ntype ScriptModuleInfo = {\r\n id: string;\r\n path: string;\r\n type: ScriptModuleType;\r\n deps: string[];\r\n systemCode: string;\r\n};\r\n\r\n/**\r\n * Resolves, builds, and serves runtime modules using a VFS.\r\n *\r\n * Responsibilities:\r\n * - Resolve logical module IDs to physical paths or URLs.\r\n * - In editor mode, bundle local script modules into a single data URL after transpile.\r\n * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).\r\n * - Gather static and dynamic import dependencies for tooling.\r\n *\r\n * Modes:\r\n * - Editor mode (`editorMode === true`): local script graphs are bundled to data URLs.\r\n * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\\> .js mapping).\r\n *\r\n * Caching:\r\n * - Built bundles are memoized in `_built` map keyed by canonical source path.\r\n *\r\n * @public\r\n */\r\nexport class ScriptRegistry {\r\n private _vfs: VFS;\r\n private _scriptsRoot: string;\r\n private _built: Map<string, string>; // logicalId -> dataURL\r\n private _building: Map<string, Promise<string>>;\r\n private _builtDeps: Map<string, Set<string>>;\r\n\r\n /**\r\n * @param vfs - The virtual file system for existence checks, reads, and path ops.\r\n * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).\r\n */\r\n constructor(vfs: VFS, scriptsRoot: string) {\r\n this._vfs = vfs;\r\n this._scriptsRoot = scriptsRoot;\r\n this._built = new Map();\r\n this._building = new Map();\r\n this._builtDeps = new Map();\r\n }\r\n\r\n /**\r\n * The active virtual file system.\r\n *\r\n * Assigning a new VFS clears the build cache.\r\n */\r\n get VFS() {\r\n return this._vfs;\r\n }\r\n set VFS(vfs: VFS) {\r\n if (vfs !== this._vfs) {\r\n this._vfs = vfs;\r\n this._built.clear();\r\n this._building.clear();\r\n this._builtDeps.clear();\r\n }\r\n }\r\n\r\n /**\r\n * The root path used by `#/` specifiers.\r\n */\r\n get scriptsRoot() {\r\n return this._scriptsRoot;\r\n }\r\n set scriptsRoot(path: string) {\r\n this._scriptsRoot = path;\r\n }\r\n\r\n /**\r\n * Invalidates cached built module output for one logical module id, or clears the full cache.\r\n *\r\n * Pass the same logical id shape that callers use with {@link ScriptRegistry.resolveRuntimeUrl},\r\n * for example `/assets/scripts/foo.ts`, `/assets/scripts/foo.js`, or `/assets/scripts/foo`.\r\n *\r\n * @param moduleId - Optional logical module id to invalidate. Omit to clear the entire build cache.\r\n */\r\n invalidate(moduleId?: string) {\r\n if (!moduleId) {\r\n this._built.clear();\r\n this._building.clear();\r\n this._builtDeps.clear();\r\n return;\r\n }\r\n const normalized = String(moduleId);\r\n const variants = new Set([normalized]);\r\n if (normalized.endsWith('.ts') || normalized.endsWith('.js')) {\r\n variants.add(normalized.slice(0, -3));\r\n } else if (normalized.endsWith('.mjs')) {\r\n variants.add(normalized.slice(0, -4));\r\n } else {\r\n variants.add(`${normalized}.ts`);\r\n variants.add(`${normalized}.js`);\r\n variants.add(`${normalized}.mjs`);\r\n }\r\n for (const key of variants) {\r\n this._built.delete(key);\r\n this._building.delete(key);\r\n this._builtDeps.delete(key);\r\n }\r\n for (const [entryId, deps] of [...this._builtDeps]) {\r\n for (const variant of variants) {\r\n if (deps.has(variant)) {\r\n this._built.delete(entryId);\r\n this._building.delete(entryId);\r\n this._builtDeps.delete(entryId);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Fetches raw source for a logical module id by probing known extensions.\r\n *\r\n * Search order:\r\n * - If `id` already ends with `.ts` or `.js` and is a file -\\> return it.\r\n * - Else try `.id.ts`, then `.id.js`.\r\n *\r\n * @param id - Logical module identifier (absolute or logical path-like).\r\n * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.\r\n */\r\n protected async fetchSource(id: string) {\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (id.endsWith('.ts')) {\r\n pathWithExt = id;\r\n type = 'ts';\r\n } else if (id.endsWith('.js')) {\r\n pathWithExt = id;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js'] as const;\r\n if (!type) {\r\n for (const t of types) {\r\n pathWithExt = `${id}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (type) {\r\n const code = (await this._vfs.readFile(pathWithExt, { encoding: 'utf8' })) as string;\r\n return { code, type, path: pathWithExt };\r\n }\r\n }\r\n\r\n /**\r\n * Resolves a module entry to a URL suitable for dynamic import.\r\n *\r\n * Behavior:\r\n * - In editor mode, builds the module to a data URL.\r\n * - Otherwise, returns `.js` URL directly:\r\n * - If `id` ends with `.js`: return as-is.\r\n * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).\r\n * - Else: append `.js`.\r\n *\r\n * @param entryId - Entry module identifier (logical or path-like).\r\n * @returns A URL string that can be used in `import(...)`.\r\n */\r\n async resolveRuntimeUrl(entryId: string) {\r\n const id = await this.resolveLogicalId(entryId);\r\n if (id.startsWith('/assets/@builtins/')) {\r\n return await this.build(String(id));\r\n }\r\n return getApp().editorMode !== 'none'\r\n ? await this.build(String(id))\r\n : id.endsWith('.js')\r\n ? id\r\n : id.endsWith('.ts')\r\n ? `${id.slice(0, -3)}.js`\r\n : `${id}.js`;\r\n }\r\n\r\n /**\r\n * Recursively gathers direct static and dynamic import dependencies for a module.\r\n *\r\n * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare\r\n * module specifiers are ignored here.\r\n *\r\n * @param entryId - The starting (possibly relative) specifier from `fromId`.\r\n * @param fromId - The logical id of the module containing `entryId`.\r\n * @param dependencies - Output map of `resolvedSourcePath -\\> file contents`.\r\n */\r\n async getDependencies(entryId: string, fromId: string, dependencies: Record<string, string>) {\r\n const reStatic = /\\b(?:import|export)\\s+[^\"']*?from\\s+(['\"])([^'\"]+)\\1/g;\r\n const reDynamic = /\\bimport\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/g;\r\n\r\n const normalizedId = await this.resolveLogicalId(entryId, fromId);\r\n const srcPath = await this.resolveSourcePath(normalizedId);\r\n if (!srcPath || dependencies[srcPath.path] !== undefined) {\r\n return;\r\n }\r\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\r\n dependencies[srcPath.path] = code;\r\n\r\n const gather = async (input: string, re: RegExp) => {\r\n for (;;) {\r\n const m = re.exec(input);\r\n if (!m) {\r\n break;\r\n }\r\n\r\n const spec = m[2];\r\n\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n await this.getDependencies(spec, normalizedId, dependencies);\r\n }\r\n }\r\n };\r\n\r\n await gather(code, reStatic);\r\n await gather(code, reDynamic);\r\n }\r\n\r\n /**\r\n * Builds a logical module id into a bundled data URL (editor mode pipeline).\r\n *\r\n * Steps:\r\n * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.\r\n * - Collect reachable local imports without recursively building data URLs.\r\n * - Transpile local modules to `System.register`.\r\n * - Emit a single `data:` URL with a small module loader and memoize it in `_built`.\r\n *\r\n * @param id - Logical module id to build.\r\n * @returns Data URL string for dynamic import, or empty string if not found.\r\n */\r\n private async build(id: string) {\r\n const entry = await this.resolveModuleInfo(String(id));\r\n if (!entry) {\r\n return '';\r\n }\r\n\r\n const key = entry.id;\r\n const cached = this._built.get(key);\r\n if (cached) {\r\n return cached;\r\n }\r\n const pending = this._building.get(key);\r\n if (pending) {\r\n return await pending;\r\n }\r\n\r\n const task = this.buildBundle(key);\r\n this._building.set(key, task);\r\n try {\r\n const url = await task;\r\n if (url) {\r\n this._built.set(key, url);\r\n }\r\n return url;\r\n } finally {\r\n this._building.delete(key);\r\n }\r\n }\r\n\r\n private async buildBundle(entryId: string) {\r\n const modules = new Map<string, ScriptModuleInfo>();\r\n const entry = await this.collectModule(entryId, modules);\r\n if (!entry) {\r\n return '';\r\n }\r\n\r\n const chunks = [this.getSystemBundleRuntime()];\r\n for (const module of modules.values()) {\r\n chunks.push(`__z3dRegister(${JSON.stringify(module.id)}, () => {\\n${module.systemCode}\\n});`);\r\n }\r\n chunks.push(\r\n `const __z3dEntry = await __z3dLoad(${JSON.stringify(entry.id)});\\n` +\r\n `const plugin = __z3dEntry.plugin;\\n` +\r\n `const __z3dDefault = __z3dEntry.default ?? __z3dEntry.plugin ?? __z3dEntry;\\n` +\r\n `export { plugin };\\n` +\r\n `export default __z3dDefault;\\n` +\r\n `//# sourceURL=${entry.id}`\r\n );\r\n\r\n const url = toDataUrl(chunks.join('\\n'), entry.id);\r\n this._builtDeps.set(entry.id, new Set(modules.keys()));\r\n return url;\r\n }\r\n\r\n private async collectModule(id: string, modules: Map<string, ScriptModuleInfo>) {\r\n const module = await this.resolveModuleInfo(id);\r\n if (!module) {\r\n return null;\r\n }\r\n if (modules.has(module.id)) {\r\n return modules.get(module.id)!;\r\n }\r\n\r\n modules.set(module.id, module);\r\n\r\n const source = (await this._vfs.readFile(module.path, { encoding: 'utf8' })) as string;\r\n const esmCode = hasRawQuery(module.id)\r\n ? `export default ${JSON.stringify(source)};\\n`\r\n : await this.transpileToESModule(source, module.id, module.type);\r\n const rewritten = await this.rewriteImportsToLogicalIds(esmCode, module.id);\r\n module.deps = rewritten.deps;\r\n module.systemCode = await this.transpileToSystemModule(rewritten.code, module.id);\r\n\r\n for (const dep of module.deps) {\r\n await this.collectModule(dep, modules);\r\n }\r\n return module;\r\n }\r\n\r\n private async resolveModuleInfo(id: string): Promise<Nullable<ScriptModuleInfo>> {\r\n const srcPath = await this.resolveSourcePath(id);\r\n if (!srcPath) {\r\n return null;\r\n }\r\n const { suffix } = splitSpecifierQuery(String(id));\r\n const path = this._vfs.normalizePath(srcPath.path);\r\n return {\r\n id: `${path}${suffix}`,\r\n path,\r\n type: srcPath.type,\r\n deps: [],\r\n systemCode: ''\r\n };\r\n }\r\n\r\n private getTypeScriptRuntime() {\r\n const ts = (window as any).ts as typeof TS;\r\n if (!ts) {\r\n throw new Error('TypeScript runtime (window.ts) not found. Load typescript.js first.');\r\n }\r\n return ts;\r\n }\r\n\r\n private async transpileToESModule(code: string, _id: string, type: ScriptModuleType) {\r\n const logicalId = String(_id);\r\n\r\n if (type === 'js') {\r\n return code;\r\n }\r\n\r\n const ts = this.getTypeScriptRuntime();\r\n\r\n const res = ts.transpileModule(code, {\r\n compilerOptions: {\r\n target: ts.ScriptTarget.ES2015,\r\n module: ts.ModuleKind.ESNext,\r\n experimentalDecorators: true,\r\n useDefineForClassFields: false\r\n },\r\n fileName: logicalId\r\n });\r\n\r\n return res.outputText || '';\r\n }\r\n\r\n private async transpileToSystemModule(code: string, _id: string) {\r\n const logicalId = String(_id);\r\n const ts = this.getTypeScriptRuntime();\r\n const res = ts.transpileModule(code, {\r\n compilerOptions: {\r\n allowJs: true,\r\n target: ts.ScriptTarget.ES2015,\r\n module: ts.ModuleKind.System,\r\n esModuleInterop: true,\r\n experimentalDecorators: true,\r\n useDefineForClassFields: false\r\n },\r\n fileName: logicalId\r\n });\r\n return res.outputText || '';\r\n }\r\n\r\n /**\r\n * Rewrites local ESM specifiers to canonical source paths and records local deps.\r\n * External URLs and package imports are left for the native dynamic import path.\r\n */\r\n private async rewriteImportsToLogicalIds(code: string, fromId: string) {\r\n await init;\r\n const [imports] = parse(code);\r\n const list = [...imports].sort((a, b) => (a.s || 0) - (b.s || 0));\r\n const deps = new Set<string>();\r\n let out = '';\r\n let last = 0;\r\n\r\n for (const im of list) {\r\n // Skip import.meta entries reported by es-module-lexer.\r\n // Their \"specifier\" span points to the whole \"import.meta\" expression,\r\n // which must remain untouched.\r\n if (im.d === -2) {\r\n continue;\r\n }\r\n // must have quotes\r\n const hasQuote = im.ss != null && im.se != null;\r\n if (!hasQuote || im.se <= im.ss) {\r\n continue;\r\n }\r\n // must have contents\r\n if (im.e <= im.s) {\r\n continue;\r\n }\r\n // append [last, s)\r\n out += code.slice(last, im.s);\r\n\r\n const spec = code.slice(im.s, im.e); // original spec\r\n const resolved = await this.resolveImportTarget(spec, String(fromId));\r\n const replacement = resolved.id ?? spec;\r\n if (resolved.id) {\r\n deps.add(resolved.id);\r\n }\r\n out += replacement; // Do not wrap in quotes\r\n last = im.e;\r\n }\r\n out += code.slice(last);\r\n return { code: out, deps: [...deps] };\r\n }\r\n\r\n private async resolveImportTarget(spec: string, fromId: string) {\r\n if (isAbsoluteUrl(spec) || isSpecialUrl(spec) || spec.startsWith('@zephyr3d/')) {\r\n return { id: null };\r\n }\r\n\r\n const depId = await this.resolveLogicalId(spec, isBareModule(spec) ? undefined : fromId);\r\n const module = await this.resolveModuleInfo(depId);\r\n return { id: module?.id ?? null };\r\n }\r\n\r\n private getSystemBundleRuntime() {\r\n return `\r\nconst __z3dRegistry = new Map();\r\nlet __z3dCurrentId = '';\r\nconst System = {\r\n register(deps, declare) {\r\n if (!__z3dCurrentId) {\r\n throw new Error('System.register called without module id');\r\n }\r\n __z3dRegistry.set(__z3dCurrentId, {\r\n id: __z3dCurrentId,\r\n deps,\r\n declare,\r\n exports: Object.create(null),\r\n setters: [],\r\n execute: null,\r\n importers: [],\r\n state: 0\r\n });\r\n }\r\n};\r\nfunction __z3dRegister(id, factory) {\r\n const prev = __z3dCurrentId;\r\n __z3dCurrentId = id;\r\n try {\r\n factory();\r\n } finally {\r\n __z3dCurrentId = prev;\r\n }\r\n}\r\nfunction __z3dResolve(spec, parentId) {\r\n if (__z3dRegistry.has(spec)) {\r\n return spec;\r\n }\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n const base = parentId.slice(0, parentId.lastIndexOf('/') + 1);\r\n return new URL(spec, 'file://' + base).pathname;\r\n }\r\n return spec;\r\n}\r\nfunction __z3dExport(record, name, value) {\r\n if (name && typeof name === 'object') {\r\n for (const key of Object.keys(name)) {\r\n __z3dExport(record, key, name[key]);\r\n }\r\n return name;\r\n }\r\n record.exports[name] = value;\r\n for (const notify of record.importers) {\r\n notify(record.exports);\r\n }\r\n return value;\r\n}\r\nasync function __z3dLoad(spec, parentId = '') {\r\n const id = parentId ? __z3dResolve(spec, parentId) : spec;\r\n const record = __z3dRegistry.get(id);\r\n if (!record) {\r\n return await import(id);\r\n }\r\n if (record.state === 2 || record.state === 1) {\r\n return record.exports;\r\n }\r\n record.state = 1;\r\n const declaration = record.declare((name, value) => __z3dExport(record, name, value), {\r\n id,\r\n import: (dep) => __z3dLoad(dep, id),\r\n meta: { url: id }\r\n }) || {};\r\n record.setters = declaration.setters || [];\r\n record.execute = declaration.execute || (() => {});\r\n for (let i = 0; i < record.deps.length; i++) {\r\n const depId = __z3dResolve(record.deps[i], id);\r\n const depRecord = __z3dRegistry.get(depId);\r\n const depExports = depRecord ? await __z3dLoad(depId) : await import(depId);\r\n const setter = record.setters[i];\r\n if (typeof setter === 'function') {\r\n setter(depExports);\r\n if (depRecord) {\r\n depRecord.importers.push((exports) => setter(exports));\r\n }\r\n }\r\n }\r\n const result = record.execute();\r\n if (result && typeof result.then === 'function') {\r\n await result;\r\n }\r\n record.state = 2;\r\n return record.exports;\r\n}\r\n`;\r\n }\r\n\r\n /**\r\n * Resolves a specifier to a logical id suitable for further processing.\r\n *\r\n * Resolution rules:\r\n * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.\r\n * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).\r\n * - `/absolute`: treated as absolute from root (normalized).\r\n * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,\r\n * map to the dependency's `entry` path; otherwise return as-is.\r\n * - Else (non-editor bare module): return `spec` unchanged (external).\r\n *\r\n * @param spec - Import specifier string.\r\n * @param fromId - Optional base logical id used for relative resolution.\r\n * @returns A normalized logical id or an external specifier string.\r\n * @throws If a relative import is provided without `fromId`.\r\n */\r\n async resolveLogicalId(spec: string, fromId?: string) {\r\n const { path: baseSpec, suffix } = splitSpecifierQuery(spec);\r\n if (baseSpec.startsWith('#/')) {\r\n return `${this._vfs.normalizePath(this._vfs.join(this._scriptsRoot, baseSpec.slice(2)))}${suffix}`;\r\n } else if (baseSpec.startsWith('./') || baseSpec.startsWith('../')) {\r\n if (!fromId) {\r\n throw new Error(`Relative import \"${spec}\" requires fromId`);\r\n }\r\n const fromPath = splitSpecifierQuery(this._vfs.normalizePath(fromId)).path;\r\n return `${this._vfs.normalizePath(this._vfs.join(this._vfs.dirname(fromPath), baseSpec))}${suffix}`;\r\n } else if (baseSpec.startsWith('/')) {\r\n return `${baseSpec.replace(/^\\/+/, '/')}${suffix}`;\r\n } else if (getApp().editorMode !== 'none') {\r\n const libRoot = '/'; //this._vfs.normalizePath(this._scriptsRoot || '/');\r\n // naked module, checking if it is a installed module in editor mode\r\n let depsLockPath = this._vfs.normalizePath(this._vfs.join(libRoot, 'libs/deps.lock.json'));\r\n let depsExists = await this._vfs.exists(depsLockPath);\r\n if (depsExists) {\r\n const content = (await this._vfs.readFile(depsLockPath, { encoding: 'utf8' })) as string;\r\n const depsInfo = JSON.parse(content) as { dependencies: Record<string, { entry: string }> };\r\n if (depsInfo?.dependencies[baseSpec]) {\r\n return `${this._vfs.normalizePath(this._vfs.join(libRoot, depsInfo.dependencies[baseSpec].entry))}${suffix}`;\r\n }\r\n }\r\n }\r\n return spec;\r\n }\r\n\r\n /**\r\n * Resolves a logical id to a concrete source path and type by probing extensions.\r\n *\r\n * Rules:\r\n * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.\r\n * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.\r\n * - Maps `.mjs` to type `'js'`.\r\n *\r\n * @param logicalId - The normalized logical module id (path-like).\r\n * @returns `{ type, path }` or `null` if not found.\r\n */\r\n async resolveSourcePath(logicalId: string) {\r\n const { path: normalizedLogicalId } = splitSpecifierQuery(logicalId);\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (normalizedLogicalId.endsWith('.ts')) {\r\n pathWithExt = normalizedLogicalId;\r\n type = 'ts';\r\n } else if (normalizedLogicalId.endsWith('.js') || normalizedLogicalId.endsWith('.mjs')) {\r\n pathWithExt = normalizedLogicalId;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js', 'mjs'] as const;\r\n if (!type) {\r\n for (const t of types) {\r\n pathWithExt = `${normalizedLogicalId}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t === 'ts' ? 'ts' : 'js';\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return type ? { type, path: pathWithExt } : null;\r\n }\r\n}\r\n"],"names":["toDataUrl","js","id","b64","textToBase64","encodeURIComponent","String","isAbsoluteUrl","spec","test","isSpecialUrl","isBareModule","startsWith","splitSpecifierQuery","hashIndex","indexOf","queryIndex","cutIndex","Math","min","path","suffix","slice","hasRawQuery","queryEnd","query","trim","split","some","part","ScriptRegistry","_vfs","_scriptsRoot","_built","_building","_builtDeps","vfs","scriptsRoot","Map","VFS","clear","invalidate","moduleId","normalized","variants","Set","endsWith","add","key","delete","entryId","deps","variant","has","fetchSource","type","pathWithExt","exists","stat","isDirectory","types","t","stats","isFile","code","readFile","encoding","resolveRuntimeUrl","resolveLogicalId","build","getApp","editorMode","getDependencies","fromId","dependencies","reStatic","reDynamic","normalizedId","srcPath","resolveSourcePath","undefined","gather","input","re","m","exec","entry","resolveModuleInfo","cached","get","pending","task","buildBundle","set","url","modules","collectModule","chunks","getSystemBundleRuntime","module","values","push","JSON","stringify","systemCode","join","keys","source","esmCode","transpileToESModule","rewritten","rewriteImportsToLogicalIds","transpileToSystemModule","dep","normalizePath","getTypeScriptRuntime","ts","window","Error","_id","logicalId","res","transpileModule","compilerOptions","target","ScriptTarget","ES2015","ModuleKind","ESNext","experimentalDecorators","useDefineForClassFields","fileName","outputText","allowJs","System","esModuleInterop","init","imports","parse","list","sort","a","b","s","out","last","im","d","hasQuote","ss","se","e","resolved","resolveImportTarget","replacement","depId","baseSpec","fromPath","dirname","replace","libRoot","depsLockPath","depsExists","content","depsInfo","normalizedLogicalId"],"mappings":";;;;AAMA;;;;;;;AAOC,IACD,SAASA,SAAAA,CAAUC,EAAU,EAAEC,EAAU,EAAA;AACvC,IAAA,MAAMC,MAAMC,YAAaH,CAAAA,EAAAA,CAAAA;IACzB,OAAO,CAAC,4BAA4B,EAAEE,GAAAA,CAAI,CAAC,EAAEE,kBAAAA,CAAmBC,OAAOJ,EAAM,CAAA,CAAA,CAAA,CAAA;AAC/E;AAEA;;;IAIA,SAASK,cAAcC,IAAY,EAAA;IACjC,OAAO,eAAA,CAAgBC,IAAI,CAACD,IAAAA,CAAAA;AAC9B;AAEA;;;IAIA,SAASE,aAAaF,IAAY,EAAA;IAChC,OAAO,gBAAA,CAAiBC,IAAI,CAACD,IAAAA,CAAAA;AAC/B;AAEA;;;IAIA,SAASG,aAAaH,IAAY,EAAA;AAChC,IAAA,OAAO,CAACA,IAAKI,CAAAA,UAAU,CAAC,IAAS,CAAA,IAAA,CAACJ,KAAKI,UAAU,CAAC,KAAU,CAAA,IAAA,CAACJ,KAAKI,UAAU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,CAAC0B,MAAM,CAACD,WAAAA,CAAAA;AACtC,gBAAA,IAAIC,MAAQ,EAAA;AACV,oBAAA,MAAMK,QAAQ,MAAM,IAAI,CAAC/B,IAAI,CAAC2B,IAAI,CAACF,WAAAA,CAAAA;oBACnC,IAAIM,KAAAA,CAAMC,MAAM,EAAE;wBAChBR,IAAOM,GAAAA,CAAAA,KAAM,OAAO,IAAO,GAAA,IAAA;AAC3B,wBAAA;AACF;AACF;AACF;AACF;AACA,QAAA,OAAON,IAAO,GAAA;AAAEA,YAAAA,IAAAA;YAAMnC,IAAMoC,EAAAA;SAAgB,GAAA,IAAA;AAC9C;AACF;;;;"}
1
+ {"version":3,"file":"scriptregistry.js","sources":["../../src/app/scriptregistry.ts"],"sourcesContent":["import type * as TS from 'typescript';\r\nimport type { Nullable, VFS } from '@zephyr3d/base';\r\nimport { textToBase64 } from '@zephyr3d/base';\r\nimport { init, parse } from 'es-module-lexer';\r\nimport { getApp } from './api';\r\n\r\n/**\r\n * Converts JavaScript source to a data URL tied to a logical module id.\r\n *\r\n * @param js - The JavaScript source code to embed.\r\n * @param id - Logical module identifier (used only for sourceURL tagging).\r\n * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.\r\n * @internal\r\n */\r\nfunction toDataUrl(js: string, id: string) {\r\n const b64 = textToBase64(js);\r\n return `data:text/javascript;base64,${b64}#${encodeURIComponent(String(id))}`;\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is an absolute HTTP(S) URL.\r\n * @internal\r\n */\r\nfunction isAbsoluteUrl(spec: string) {\r\n return /^https?:\\/\\//i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a special URL (data: or blob:).\r\n * @internal\r\n */\r\nfunction isSpecialUrl(spec: string) {\r\n return /^(data|blob):/i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).\r\n * @internal\r\n */\r\nfunction isBareModule(spec: string) {\r\n return !spec.startsWith('./') && !spec.startsWith('../') && !spec.startsWith('/') && !spec.startsWith('#/');\r\n}\r\n\r\nfunction splitSpecifierQuery(spec: string) {\r\n const hashIndex = spec.indexOf('#');\r\n const queryIndex = spec.indexOf('?');\r\n const cutIndex =\r\n queryIndex >= 0 && hashIndex >= 0\r\n ? Math.min(queryIndex, hashIndex)\r\n : queryIndex >= 0\r\n ? queryIndex\r\n : hashIndex;\r\n if (cutIndex < 0) {\r\n return {\r\n path: spec,\r\n suffix: ''\r\n };\r\n }\r\n return {\r\n path: spec.slice(0, cutIndex),\r\n suffix: spec.slice(cutIndex)\r\n };\r\n}\r\n\r\nfunction hasRawQuery(spec: string) {\r\n const { suffix } = splitSpecifierQuery(spec);\r\n if (!suffix || suffix[0] !== '?') {\r\n return false;\r\n }\r\n const queryEnd = suffix.indexOf('#');\r\n const query = (queryEnd >= 0 ? suffix.slice(1, queryEnd) : suffix.slice(1)).trim();\r\n if (!query) {\r\n return false;\r\n }\r\n return query.split('&').some((part) => part.trim() === 'raw');\r\n}\r\n\r\ntype ScriptModuleType = 'js' | 'ts';\r\n\r\ntype ScriptModuleInfo = {\r\n id: string;\r\n path: string;\r\n type: ScriptModuleType;\r\n deps: string[];\r\n systemCode: string;\r\n};\r\n\r\n/**\r\n * Resolves, builds, and serves runtime modules using a VFS.\r\n *\r\n * Responsibilities:\r\n * - Resolve logical module IDs to physical paths or URLs.\r\n * - In editor mode, bundle local script modules into a single data URL after transpile.\r\n * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).\r\n * - Gather static and dynamic import dependencies for tooling.\r\n *\r\n * Modes:\r\n * - Editor mode (`editorMode === true`): local script graphs are bundled to data URLs.\r\n * - Runtime mode (`editorMode === false`): returns .js/.mjs URLs directly (with .ts -\\> .js mapping).\r\n *\r\n * Caching:\r\n * - Built bundles are memoized in `_built` map keyed by canonical source path.\r\n *\r\n * @public\r\n */\r\nexport class ScriptRegistry {\r\n private _vfs: VFS;\r\n private _scriptsRoot: string;\r\n private _built: Map<string, string>; // logicalId -> dataURL\r\n private _building: Map<string, Promise<string>>;\r\n private _builtDeps: Map<string, Set<string>>;\r\n\r\n /**\r\n * @param vfs - The virtual file system for existence checks, reads, and path ops.\r\n * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).\r\n */\r\n constructor(vfs: VFS, scriptsRoot: string) {\r\n this._vfs = vfs;\r\n this._scriptsRoot = scriptsRoot;\r\n this._built = new Map();\r\n this._building = new Map();\r\n this._builtDeps = new Map();\r\n }\r\n\r\n /**\r\n * The active virtual file system.\r\n *\r\n * Assigning a new VFS clears the build cache.\r\n */\r\n get VFS() {\r\n return this._vfs;\r\n }\r\n set VFS(vfs: VFS) {\r\n if (vfs !== this._vfs) {\r\n this._vfs = vfs;\r\n this._built.clear();\r\n this._building.clear();\r\n this._builtDeps.clear();\r\n }\r\n }\r\n\r\n /**\r\n * The root path used by `#/` specifiers.\r\n */\r\n get scriptsRoot() {\r\n return this._scriptsRoot;\r\n }\r\n set scriptsRoot(path: string) {\r\n this._scriptsRoot = path;\r\n }\r\n\r\n /**\r\n * Invalidates cached built module output for one logical module id, or clears the full cache.\r\n *\r\n * Pass the same logical id shape that callers use with {@link ScriptRegistry.resolveRuntimeUrl},\r\n * for example `/assets/scripts/foo.ts`, `/assets/scripts/foo.js`, or `/assets/scripts/foo`.\r\n *\r\n * @param moduleId - Optional logical module id to invalidate. Omit to clear the entire build cache.\r\n */\r\n invalidate(moduleId?: string) {\r\n if (!moduleId) {\r\n this._built.clear();\r\n this._building.clear();\r\n this._builtDeps.clear();\r\n return;\r\n }\r\n const normalized = String(moduleId);\r\n const variants = new Set([normalized]);\r\n if (normalized.endsWith('.ts') || normalized.endsWith('.js')) {\r\n variants.add(normalized.slice(0, -3));\r\n } else if (normalized.endsWith('.mjs')) {\r\n variants.add(normalized.slice(0, -4));\r\n } else {\r\n variants.add(`${normalized}.ts`);\r\n variants.add(`${normalized}.js`);\r\n variants.add(`${normalized}.mjs`);\r\n }\r\n for (const key of variants) {\r\n this._built.delete(key);\r\n this._building.delete(key);\r\n this._builtDeps.delete(key);\r\n }\r\n for (const [entryId, deps] of [...this._builtDeps]) {\r\n for (const variant of variants) {\r\n if (deps.has(variant)) {\r\n this._built.delete(entryId);\r\n this._building.delete(entryId);\r\n this._builtDeps.delete(entryId);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Fetches raw source for a logical module id by probing known extensions.\r\n *\r\n * Search order:\r\n * - If `id` already ends with `.ts`, `.js`, or `.mjs` and is a file -\\> return it.\r\n * - Else try `.id.ts`, then `.id.js`, then `.id.mjs`.\r\n *\r\n * @param id - Logical module identifier (absolute or logical path-like).\r\n * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.\r\n */\r\n protected async fetchSource(id: string) {\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (id.endsWith('.ts')) {\r\n pathWithExt = id;\r\n type = 'ts';\r\n } else if (id.endsWith('.js') || id.endsWith('.mjs')) {\r\n pathWithExt = id;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js'] as const;\r\n if (!type) {\r\n for (const t of [...types, 'mjs'] as const) {\r\n pathWithExt = `${id}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t === 'ts' ? 'ts' : 'js';\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (type) {\r\n const code = (await this._vfs.readFile(pathWithExt, { encoding: 'utf8' })) as string;\r\n return { code, type, path: pathWithExt };\r\n }\r\n }\r\n\r\n /**\r\n * Resolves a module entry to a URL suitable for dynamic import.\r\n *\r\n * Behavior:\r\n * - In editor mode, builds the module to a data URL.\r\n * - Otherwise, returns `.js` or `.mjs` URL directly:\r\n * - If `id` ends with `.js`: return as-is.\r\n * - If `id` ends with `.mjs`: return as-is.\r\n * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).\r\n * - Else: append `.js`.\r\n *\r\n * @param entryId - Entry module identifier (logical or path-like).\r\n * @returns A URL string that can be used in `import(...)`.\r\n */\r\n async resolveRuntimeUrl(entryId: string) {\r\n const id = await this.resolveLogicalId(entryId);\r\n if (id.startsWith('/assets/@builtins/')) {\r\n return await this.build(String(id));\r\n }\r\n return getApp().editorMode !== 'none'\r\n ? await this.build(String(id))\r\n : id.endsWith('.js') || id.endsWith('.mjs')\r\n ? id\r\n : id.endsWith('.ts')\r\n ? `${id.slice(0, -3)}.js`\r\n : `${id}.js`;\r\n }\r\n\r\n /**\r\n * Recursively gathers direct static and dynamic import dependencies for a module.\r\n *\r\n * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare\r\n * module specifiers are ignored here.\r\n *\r\n * @param entryId - The starting (possibly relative) specifier from `fromId`.\r\n * @param fromId - The logical id of the module containing `entryId`.\r\n * @param dependencies - Output map of `resolvedSourcePath -\\> file contents`.\r\n */\r\n async getDependencies(entryId: string, fromId: string, dependencies: Record<string, string>) {\r\n const reStatic = /\\b(?:import|export)\\s+[^\"']*?from\\s+(['\"])([^'\"]+)\\1/g;\r\n const reDynamic = /\\bimport\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/g;\r\n\r\n const normalizedId = await this.resolveLogicalId(entryId, fromId);\r\n const srcPath = await this.resolveSourcePath(normalizedId);\r\n if (!srcPath || dependencies[srcPath.path] !== undefined) {\r\n return;\r\n }\r\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\r\n dependencies[srcPath.path] = code;\r\n\r\n const gather = async (input: string, re: RegExp) => {\r\n for (;;) {\r\n const m = re.exec(input);\r\n if (!m) {\r\n break;\r\n }\r\n\r\n const spec = m[2];\r\n\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n await this.getDependencies(spec, normalizedId, dependencies);\r\n }\r\n }\r\n };\r\n\r\n await gather(code, reStatic);\r\n await gather(code, reDynamic);\r\n }\r\n\r\n /**\r\n * Builds a logical module id into a bundled data URL (editor mode pipeline).\r\n *\r\n * Steps:\r\n * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.\r\n * - Collect reachable local imports without recursively building data URLs.\r\n * - Transpile local modules to `System.register`.\r\n * - Emit a single `data:` URL with a small module loader and memoize it in `_built`.\r\n *\r\n * @param id - Logical module id to build.\r\n * @returns Data URL string for dynamic import, or empty string if not found.\r\n */\r\n private async build(id: string) {\r\n const entry = await this.resolveModuleInfo(String(id));\r\n if (!entry) {\r\n return '';\r\n }\r\n\r\n const key = entry.id;\r\n const cached = this._built.get(key);\r\n if (cached) {\r\n return cached;\r\n }\r\n const pending = this._building.get(key);\r\n if (pending) {\r\n return await pending;\r\n }\r\n\r\n const task = this.buildBundle(key);\r\n this._building.set(key, task);\r\n try {\r\n const url = await task;\r\n if (url) {\r\n this._built.set(key, url);\r\n }\r\n return url;\r\n } finally {\r\n this._building.delete(key);\r\n }\r\n }\r\n\r\n private async buildBundle(entryId: string) {\r\n const modules = new Map<string, ScriptModuleInfo>();\r\n const entry = await this.collectModule(entryId, modules);\r\n if (!entry) {\r\n return '';\r\n }\r\n\r\n const chunks = [this.getSystemBundleRuntime()];\r\n for (const module of modules.values()) {\r\n chunks.push(`__z3dRegister(${JSON.stringify(module.id)}, () => {\\n${module.systemCode}\\n});`);\r\n }\r\n chunks.push(\r\n `const __z3dEntry = await __z3dLoad(${JSON.stringify(entry.id)});\\n` +\r\n `const plugin = __z3dEntry.plugin;\\n` +\r\n `const __z3dDefault = __z3dEntry.default ?? __z3dEntry.plugin ?? __z3dEntry;\\n` +\r\n `export { plugin };\\n` +\r\n `export default __z3dDefault;\\n` +\r\n `//# sourceURL=${entry.id}`\r\n );\r\n\r\n const url = toDataUrl(chunks.join('\\n'), entry.id);\r\n this._builtDeps.set(entry.id, new Set(modules.keys()));\r\n return url;\r\n }\r\n\r\n private async collectModule(id: string, modules: Map<string, ScriptModuleInfo>) {\r\n const module = await this.resolveModuleInfo(id);\r\n if (!module) {\r\n return null;\r\n }\r\n if (modules.has(module.id)) {\r\n return modules.get(module.id)!;\r\n }\r\n\r\n modules.set(module.id, module);\r\n\r\n const source = (await this._vfs.readFile(module.path, { encoding: 'utf8' })) as string;\r\n const esmCode = hasRawQuery(module.id)\r\n ? `export default ${JSON.stringify(source)};\\n`\r\n : await this.transpileToESModule(source, module.id, module.type);\r\n const rewritten = await this.rewriteImportsToLogicalIds(esmCode, module.id);\r\n module.deps = rewritten.deps;\r\n module.systemCode = await this.transpileToSystemModule(rewritten.code, module.id);\r\n\r\n for (const dep of module.deps) {\r\n await this.collectModule(dep, modules);\r\n }\r\n return module;\r\n }\r\n\r\n private async resolveModuleInfo(id: string): Promise<Nullable<ScriptModuleInfo>> {\r\n const srcPath = await this.resolveSourcePath(id);\r\n if (!srcPath) {\r\n return null;\r\n }\r\n const { suffix } = splitSpecifierQuery(String(id));\r\n const path = this._vfs.normalizePath(srcPath.path);\r\n return {\r\n id: `${path}${suffix}`,\r\n path,\r\n type: srcPath.type,\r\n deps: [],\r\n systemCode: ''\r\n };\r\n }\r\n\r\n private getTypeScriptRuntime() {\r\n const ts = (window as any).ts as typeof TS;\r\n if (!ts) {\r\n throw new Error('TypeScript runtime (window.ts) not found. Load typescript.js first.');\r\n }\r\n return ts;\r\n }\r\n\r\n private async transpileToESModule(code: string, _id: string, type: ScriptModuleType) {\r\n const logicalId = String(_id);\r\n\r\n if (type === 'js') {\r\n return code;\r\n }\r\n\r\n const ts = this.getTypeScriptRuntime();\r\n\r\n const res = ts.transpileModule(code, {\r\n compilerOptions: {\r\n target: ts.ScriptTarget.ES2020,\r\n module: ts.ModuleKind.ESNext,\r\n experimentalDecorators: true,\r\n useDefineForClassFields: false\r\n },\r\n fileName: logicalId\r\n });\r\n\r\n return res.outputText || '';\r\n }\r\n\r\n private async transpileToSystemModule(code: string, _id: string) {\r\n const logicalId = String(_id);\r\n const ts = this.getTypeScriptRuntime();\r\n const res = ts.transpileModule(code, {\r\n compilerOptions: {\r\n allowJs: true,\r\n // Keep modern syntax such as async generators, class fields, and private fields intact.\r\n target: ts.ScriptTarget.ES2022,\r\n module: ts.ModuleKind.System,\r\n esModuleInterop: true,\r\n experimentalDecorators: true,\r\n useDefineForClassFields: true\r\n },\r\n fileName: logicalId\r\n });\r\n return res.outputText || '';\r\n }\r\n\r\n /**\r\n * Rewrites local ESM specifiers to canonical source paths and records local deps.\r\n * External URLs and package imports are left for the native dynamic import path.\r\n */\r\n private async rewriteImportsToLogicalIds(code: string, fromId: string) {\r\n await init;\r\n const [imports] = parse(code);\r\n const list = [...imports].sort((a, b) => (a.s || 0) - (b.s || 0));\r\n const deps = new Set<string>();\r\n let out = '';\r\n let last = 0;\r\n\r\n for (const im of list) {\r\n // Skip import.meta entries reported by es-module-lexer.\r\n // Their \"specifier\" span points to the whole \"import.meta\" expression,\r\n // which must remain untouched.\r\n if (im.d === -2) {\r\n continue;\r\n }\r\n // must have quotes\r\n const hasQuote = im.ss != null && im.se != null;\r\n if (!hasQuote || im.se <= im.ss) {\r\n continue;\r\n }\r\n // must have contents\r\n if (im.e <= im.s) {\r\n continue;\r\n }\r\n // append [last, s)\r\n out += code.slice(last, im.s);\r\n\r\n const spec = code.slice(im.s, im.e); // original spec\r\n const resolved = await this.resolveImportTarget(spec, String(fromId));\r\n const replacement = resolved.id ?? spec;\r\n if (resolved.id) {\r\n deps.add(resolved.id);\r\n }\r\n out += replacement; // Do not wrap in quotes\r\n last = im.e;\r\n }\r\n out += code.slice(last);\r\n return { code: out, deps: [...deps] };\r\n }\r\n\r\n private async resolveImportTarget(spec: string, fromId: string) {\r\n if (isAbsoluteUrl(spec) || isSpecialUrl(spec) || spec.startsWith('@zephyr3d/')) {\r\n return { id: null };\r\n }\r\n\r\n const depId = await this.resolveLogicalId(spec, isBareModule(spec) ? undefined : fromId);\r\n const module = await this.resolveModuleInfo(depId);\r\n return { id: module?.id ?? null };\r\n }\r\n\r\n private getSystemBundleRuntime() {\r\n return `\r\nconst __z3dRegistry = new Map();\r\nlet __z3dCurrentId = '';\r\nconst System = {\r\n register(deps, declare) {\r\n if (!__z3dCurrentId) {\r\n throw new Error('System.register called without module id');\r\n }\r\n __z3dRegistry.set(__z3dCurrentId, {\r\n id: __z3dCurrentId,\r\n deps,\r\n declare,\r\n exports: Object.create(null),\r\n setters: [],\r\n execute: null,\r\n importers: [],\r\n state: 0\r\n });\r\n }\r\n};\r\nfunction __z3dRegister(id, factory) {\r\n const prev = __z3dCurrentId;\r\n __z3dCurrentId = id;\r\n try {\r\n factory();\r\n } finally {\r\n __z3dCurrentId = prev;\r\n }\r\n}\r\nfunction __z3dResolve(spec, parentId) {\r\n if (__z3dRegistry.has(spec)) {\r\n return spec;\r\n }\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n const base = parentId.slice(0, parentId.lastIndexOf('/') + 1);\r\n return new URL(spec, 'file://' + base).pathname;\r\n }\r\n return spec;\r\n}\r\nfunction __z3dExport(record, name, value) {\r\n if (name && typeof name === 'object') {\r\n for (const key of Object.keys(name)) {\r\n __z3dExport(record, key, name[key]);\r\n }\r\n return name;\r\n }\r\n record.exports[name] = value;\r\n for (const notify of record.importers) {\r\n notify(record.exports);\r\n }\r\n return value;\r\n}\r\nasync function __z3dLoad(spec, parentId = '') {\r\n const id = parentId ? __z3dResolve(spec, parentId) : spec;\r\n const record = __z3dRegistry.get(id);\r\n if (!record) {\r\n return await import(id);\r\n }\r\n if (record.state === 2 || record.state === 1) {\r\n return record.exports;\r\n }\r\n record.state = 1;\r\n const declaration = record.declare((name, value) => __z3dExport(record, name, value), {\r\n id,\r\n import: (dep) => __z3dLoad(dep, id),\r\n meta: { url: id }\r\n }) || {};\r\n record.setters = declaration.setters || [];\r\n record.execute = declaration.execute || (() => {});\r\n for (let i = 0; i < record.deps.length; i++) {\r\n const depId = __z3dResolve(record.deps[i], id);\r\n const depRecord = __z3dRegistry.get(depId);\r\n const depExports = depRecord ? await __z3dLoad(depId) : await import(depId);\r\n const setter = record.setters[i];\r\n if (typeof setter === 'function') {\r\n setter(depExports);\r\n if (depRecord) {\r\n depRecord.importers.push((exports) => setter(exports));\r\n }\r\n }\r\n }\r\n const result = record.execute();\r\n if (result && typeof result.then === 'function') {\r\n await result;\r\n }\r\n record.state = 2;\r\n return record.exports;\r\n}\r\n`;\r\n }\r\n\r\n /**\r\n * Resolves a specifier to a logical id suitable for further processing.\r\n *\r\n * Resolution rules:\r\n * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.\r\n * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).\r\n * - `/absolute`: treated as absolute from root (normalized).\r\n * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,\r\n * map to the dependency's `entry` path; otherwise return as-is.\r\n * - Else (non-editor bare module): return `spec` unchanged (external).\r\n *\r\n * @param spec - Import specifier string.\r\n * @param fromId - Optional base logical id used for relative resolution.\r\n * @returns A normalized logical id or an external specifier string.\r\n * @throws If a relative import is provided without `fromId`.\r\n */\r\n async resolveLogicalId(spec: string, fromId?: string) {\r\n const { path: baseSpec, suffix } = splitSpecifierQuery(spec);\r\n if (baseSpec.startsWith('#/')) {\r\n return `${this._vfs.normalizePath(this._vfs.join(this._scriptsRoot, baseSpec.slice(2)))}${suffix}`;\r\n } else if (baseSpec.startsWith('./') || baseSpec.startsWith('../')) {\r\n if (!fromId) {\r\n throw new Error(`Relative import \"${spec}\" requires fromId`);\r\n }\r\n const fromPath = splitSpecifierQuery(this._vfs.normalizePath(fromId)).path;\r\n return `${this._vfs.normalizePath(this._vfs.join(this._vfs.dirname(fromPath), baseSpec))}${suffix}`;\r\n } else if (baseSpec.startsWith('/')) {\r\n return `${baseSpec.replace(/^\\/+/, '/')}${suffix}`;\r\n } else if (getApp().editorMode !== 'none') {\r\n const libRoot = '/'; //this._vfs.normalizePath(this._scriptsRoot || '/');\r\n // naked module, checking if it is a installed module in editor mode\r\n let depsLockPath = this._vfs.normalizePath(this._vfs.join(libRoot, 'libs/deps.lock.json'));\r\n let depsExists = await this._vfs.exists(depsLockPath);\r\n if (depsExists) {\r\n const content = (await this._vfs.readFile(depsLockPath, { encoding: 'utf8' })) as string;\r\n const depsInfo = JSON.parse(content) as { dependencies: Record<string, { entry: string }> };\r\n if (depsInfo?.dependencies[baseSpec]) {\r\n return `${this._vfs.normalizePath(this._vfs.join(libRoot, depsInfo.dependencies[baseSpec].entry))}${suffix}`;\r\n }\r\n }\r\n }\r\n return spec;\r\n }\r\n\r\n /**\r\n * Resolves a logical id to a concrete source path and type by probing extensions.\r\n *\r\n * Rules:\r\n * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.\r\n * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.\r\n * - Maps `.mjs` to type `'js'`.\r\n *\r\n * @param logicalId - The normalized logical module id (path-like).\r\n * @returns `{ type, path }` or `null` if not found.\r\n */\r\n async resolveSourcePath(logicalId: string) {\r\n const { path: normalizedLogicalId } = splitSpecifierQuery(logicalId);\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (normalizedLogicalId.endsWith('.ts')) {\r\n pathWithExt = normalizedLogicalId;\r\n type = 'ts';\r\n } else if (normalizedLogicalId.endsWith('.js') || normalizedLogicalId.endsWith('.mjs')) {\r\n pathWithExt = normalizedLogicalId;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js', 'mjs'] as const;\r\n if (!type) {\r\n for (const t of types) {\r\n pathWithExt = `${normalizedLogicalId}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t === 'ts' ? 'ts' : 'js';\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return type ? { type, path: pathWithExt } : null;\r\n }\r\n}\r\n"],"names":["toDataUrl","js","id","b64","textToBase64","encodeURIComponent","String","isAbsoluteUrl","spec","test","isSpecialUrl","isBareModule","startsWith","splitSpecifierQuery","hashIndex","indexOf","queryIndex","cutIndex","Math","min","path","suffix","slice","hasRawQuery","queryEnd","query","trim","split","some","part","ScriptRegistry","_vfs","_scriptsRoot","_built","_building","_builtDeps","vfs","scriptsRoot","Map","VFS","clear","invalidate","moduleId","normalized","variants","Set","endsWith","add","key","delete","entryId","deps","variant","has","fetchSource","type","pathWithExt","exists","stat","isDirectory","types","t","stats","isFile","code","readFile","encoding","resolveRuntimeUrl","resolveLogicalId","build","getApp","editorMode","getDependencies","fromId","dependencies","reStatic","reDynamic","normalizedId","srcPath","resolveSourcePath","undefined","gather","input","re","m","exec","entry","resolveModuleInfo","cached","get","pending","task","buildBundle","set","url","modules","collectModule","chunks","getSystemBundleRuntime","module","values","push","JSON","stringify","systemCode","join","keys","source","esmCode","transpileToESModule","rewritten","rewriteImportsToLogicalIds","transpileToSystemModule","dep","normalizePath","getTypeScriptRuntime","ts","window","Error","_id","logicalId","res","transpileModule","compilerOptions","target","ScriptTarget","ES2020","ModuleKind","ESNext","experimentalDecorators","useDefineForClassFields","fileName","outputText","allowJs","ES2022","System","esModuleInterop","init","imports","parse","list","sort","a","b","s","out","last","im","d","hasQuote","ss","se","e","resolved","resolveImportTarget","replacement","depId","baseSpec","fromPath","dirname","replace","libRoot","depsLockPath","depsExists","content","depsInfo","normalizedLogicalId"],"mappings":";;;;AAMA;;;;;;;AAOC,IACD,SAASA,SAAAA,CAAUC,EAAU,EAAEC,EAAU,EAAA;AACvC,IAAA,MAAMC,MAAMC,YAAaH,CAAAA,EAAAA,CAAAA;IACzB,OAAO,CAAC,4BAA4B,EAAEE,GAAAA,C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;AACtC,YAAA,IAAI,CAACC,MAAQ,EAAA;gBACXF,IAAO,GAAA,IAAA;AACT;AACA,YAAA,MAAMG,OAAO,MAAM,IAAI,CAAC3B,IAAI,CAAC2B,IAAI,CAACF,WAAAA,CAAAA;YAClC,IAAIE,IAAAA,CAAKC,WAAW,EAAE;gBACpBJ,IAAO,GAAA,IAAA;AACT;AACF;AACA,QAAA,MAAMK,KAAQ,GAAA;AAAC,YAAA,IAAA;AAAM,YAAA,IAAA;AAAM,YAAA;AAAM,SAAA;AACjC,QAAA,IAAI,CAACL,IAAM,EAAA;YACT,KAAK,MAAMM,KAAKD,KAAO,CAAA;AACrBJ,gBAAAA,WAAAA,GAAc,CAAG8G,EAAAA,mBAAAA,CAAoB,CAAC,EAAEzG,CAAG,CAAA,CAAA;AAC3C,gBAAA,MAAMJ,SAAS,MAAM,IAAI,CAAC1B,IAAI,CAAC0B,MAAM,CAACD,WAAAA,CAAAA;AACtC,gBAAA,IAAIC,MAAQ,EAAA;AACV,oBAAA,MAAMK,QAAQ,MAAM,IAAI,CAAC/B,IAAI,CAAC2B,IAAI,CAACF,WAAAA,CAAAA;oBACnC,IAAIM,KAAAA,CAAMC,MAAM,EAAE;wBAChBR,IAAOM,GAAAA,CAAAA,KAAM,OAAO,IAAO,GAAA,IAAA;AAC3B,wBAAA;AACF;AACF;AACF;AACF;AACA,QAAA,OAAON,IAAO,GAAA;AAAEA,YAAAA,IAAAA;YAAMnC,IAAMoC,EAAAA;SAAgB,GAAA,IAAA;AAC9C;AACF;;;;"}
package/dist/index.d.ts CHANGED
@@ -10262,6 +10262,26 @@ declare const AnimationSet_base: (new (...args: any[]) => {
10262
10262
  dispose: [];
10263
10263
  })[K]): void;
10264
10264
  }) & typeof Disposable;
10265
+ /**
10266
+ * Animation set
10267
+ *
10268
+ * Manages a collection of named animation clips for a model and orchestrates:
10269
+ * - Playback state (time, loops, speed, weights, fade-in/out).
10270
+ * - Blending across multiple tracks targeting the same property via weighted averages.
10271
+ * - Skeleton usage and application for clips that drive skeletal animation.
10272
+ * - Active track registration and cleanup as clips start/stop.
10273
+ *
10274
+ * Usage:
10275
+ * - Create or retrieve `AnimationClip`s by name.
10276
+ * - Start playback with `playAnimation(name, options)`.
10277
+ * - Advance animation with `update(deltaSeconds)`.
10278
+ * - Optionally adjust weight while playing with `setAnimationWeight(name, weight)`.
10279
+ *
10280
+ * Lifetime:
10281
+ * - Disposing the set releases references to the model, clips, and clears active state.
10282
+ *
10283
+ * @public
10284
+ */
10265
10285
  declare class AnimationSet extends AnimationSet_base implements IDisposable {
10266
10286
  /**
10267
10287
  * Create an AnimationSet controlling the provided model.
@@ -11106,7 +11126,7 @@ declare class AnimationTimeline {
11106
11126
  /**
11107
11127
  * Runtime interpreter for an AnimationTimeline.
11108
11128
  *
11109
- * The interpreter is a synchronous frame-stack state machine advanced by {@link tick}, which is
11129
+ * The interpreter is a synchronous frame-stack state machine advanced by {@link AnimationTimelineRunner.tick}, which is
11110
11130
  * driven by `AnimationSet.update(dt)` on the same logical clock as the animations. There is no
11111
11131
  * `async`/`await` in the control flow, so the runtime state can be serialized and replayed.
11112
11132
  * @public
@@ -11186,7 +11206,7 @@ declare class AnimationTimelineRunner extends Observable<AnimationTimelineRunner
11186
11206
  enqueue(steps: AnimationTimelineStep[]): void;
11187
11207
  /**
11188
11208
  * Run `steps` concurrently with the current control flow (a true parallel branch). Unlike
11189
- * {@link enqueue}, these do not wait for the main stack to drain.
11209
+ * {@link AnimationTimelineRunner.enqueue}, these do not wait for the main stack to drain.
11190
11210
  *
11191
11211
  * @param steps - Steps to run immediately in an independent concurrent branch.
11192
11212
  * @returns void
@@ -11229,14 +11249,14 @@ declare class AnimationTimelineRunner extends Observable<AnimationTimelineRunner
11229
11249
  */
11230
11250
  serialize(): AnimationTimelineRunnerState;
11231
11251
  /**
11232
- * Restore runtime state previously produced by {@link serialize}.
11252
+ * Restore runtime state previously produced by {@link AnimationTimelineRunner.serialize}.
11233
11253
  *
11234
11254
  * Re-create the relevant active playbacks on the AnimationSet before calling this so that
11235
11255
  * playback-bound frames (play-wait, waitMarker, waitFrame) can re-attach by id.
11236
11256
  *
11237
11257
  * @param animationSet - Animation set containing any live playbacks referenced by the state.
11238
11258
  * @param timeline - Timeline definition to bind to the restored runner.
11239
- * @param state - Serialized state previously returned by {@link serialize}.
11259
+ * @param state - Serialized state previously returned by {@link AnimationTimelineRunner.serialize}.
11240
11260
  * @returns A runner restored to the supplied runtime state.
11241
11261
  * @public
11242
11262
  */
@@ -11252,7 +11272,7 @@ declare class AnimationTimelineRunner extends Observable<AnimationTimelineRunner
11252
11272
  */
11253
11273
  private tickFrames;
11254
11274
  /**
11255
- * Same as {@link tickFrames} but returns the time left unconsumed when the stack drains
11275
+ * Same as {@link AnimationTimelineRunner.tickFrames} but returns the time left unconsumed when the stack drains
11256
11276
  * completely (so a parent sequence can hand it to its next step).
11257
11277
  */
11258
11278
  private tickFramesWithLeftover;
@@ -19280,7 +19300,7 @@ declare class InputManager {
19280
19300
  *
19281
19301
  * Modes:
19282
19302
  * - Editor mode (`editorMode === true`): local script graphs are bundled to data URLs.
19283
- * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\> .js mapping).
19303
+ * - Runtime mode (`editorMode === false`): returns .js/.mjs URLs directly (with .ts -\> .js mapping).
19284
19304
  *
19285
19305
  * Caching:
19286
19306
  * - Built bundles are memoized in `_built` map keyed by canonical source path.
@@ -19323,8 +19343,8 @@ declare class ScriptRegistry {
19323
19343
  * Fetches raw source for a logical module id by probing known extensions.
19324
19344
  *
19325
19345
  * Search order:
19326
- * - If `id` already ends with `.ts` or `.js` and is a file -\> return it.
19327
- * - Else try `.id.ts`, then `.id.js`.
19346
+ * - If `id` already ends with `.ts`, `.js`, or `.mjs` and is a file -\> return it.
19347
+ * - Else try `.id.ts`, then `.id.js`, then `.id.mjs`.
19328
19348
  *
19329
19349
  * @param id - Logical module identifier (absolute or logical path-like).
19330
19350
  * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.
@@ -19339,8 +19359,9 @@ declare class ScriptRegistry {
19339
19359
  *
19340
19360
  * Behavior:
19341
19361
  * - In editor mode, builds the module to a data URL.
19342
- * - Otherwise, returns `.js` URL directly:
19362
+ * - Otherwise, returns `.js` or `.mjs` URL directly:
19343
19363
  * - If `id` ends with `.js`: return as-is.
19364
+ * - If `id` ends with `.mjs`: return as-is.
19344
19365
  * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).
19345
19366
  * - Else: append `.js`.
19346
19367
  *
@@ -4,11 +4,11 @@ import { mixinTextureProps } from './texture.js';
4
4
  import { mixinAlbedoColor } from './albedocolor.js';
5
5
  import { ShaderHelper } from '../shader/helper.js';
6
6
 
7
- /**
8
- * Light mixin
9
- * @param BaseCls - class to mix in
10
- * @returns Mixed class
11
- * @public
7
+ /**
8
+ * Light mixin
9
+ * @param BaseCls - class to mix in
10
+ * @returns Mixed class
11
+ * @public
12
12
  */ function mixinLight(BaseCls) {
13
13
  if (BaseCls.lightMixed) {
14
14
  return BaseCls;
@@ -51,31 +51,31 @@ import { ShaderHelper } from '../shader/helper.js';
51
51
  set doubleSidedLighting(val) {
52
52
  this.useFeature(FEATURE_DOUBLE_SIDED_LIGHTING, !!val);
53
53
  }
54
- /**
55
- * Calculates the normalized vector from world coordinates to the viewpoint.
56
- *
57
- * @param scope - Shader scope
58
- *
59
- * @returns The view vector
54
+ /**
55
+ * Calculates the normalized vector from world coordinates to the viewpoint.
56
+ *
57
+ * @param scope - Shader scope
58
+ *
59
+ * @returns The view vector
60
60
  */ calculateViewVector(scope, worldPos) {
61
61
  const pb = scope.$builder;
62
62
  return pb.normalize(pb.sub(ShaderHelper.getCameraPosition(scope), worldPos.xyz));
63
63
  }
64
- /**
65
- * Calculate the reflection vector of the view vector with respect to the normal.
66
- *
67
- * @param scope - Shader scope
68
- * @param normal - Surface normal
69
- * @param viewVec - The view vector
70
- * @returns The reflection vector
64
+ /**
65
+ * Calculate the reflection vector of the view vector with respect to the normal.
66
+ *
67
+ * @param scope - Shader scope
68
+ * @param normal - Surface normal
69
+ * @param viewVec - The view vector
70
+ * @returns The reflection vector
71
71
  */ calculateReflectionVector(scope, normal, viewVec) {
72
72
  const pb = scope.$builder;
73
73
  return pb.reflect(pb.neg(viewVec), normal);
74
74
  }
75
- /**
76
- * Calculate the normal vector for current fragment
77
- * @param scope - The shader scope
78
- * @returns Normal vector for current fragment
75
+ /**
76
+ * Calculate the normal vector for current fragment
77
+ * @param scope - The shader scope
78
+ * @returns Normal vector for current fragment
79
79
  */ calculateNormal(scope, worldPos, worldNormal, worldTangent, worldBinormal) {
80
80
  const pb = scope.$builder;
81
81
  const that = this;
@@ -115,17 +115,17 @@ import { ShaderHelper } from '../shader/helper.js';
115
115
  });
116
116
  return pb.getGlobalScope()[funcName](...args);
117
117
  }
118
- /**
119
- * Normal scale uniform
120
- * @return Normal scale uniform
118
+ /**
119
+ * Normal scale uniform
120
+ * @return Normal scale uniform
121
121
  */ getUniformNormalScale(scope) {
122
122
  return scope.zNormalScale;
123
123
  }
124
- /**
125
- * Calculate the normal vector for current fragment
126
- *
127
- * @param scope - The shader scope
128
- * @returns Structure that contains normal vector and TBN matrix
124
+ /**
125
+ * Calculate the normal vector for current fragment
126
+ *
127
+ * @param scope - The shader scope
128
+ * @returns Structure that contains normal vector and TBN matrix
129
129
  */ calculateNormalAndTBN(scope, worldPos, worldNormal, worldTangent, worldBinormal) {
130
130
  const pb = scope.$builder;
131
131
  const NormalStruct = pb.defineStruct([
@@ -169,11 +169,11 @@ import { ShaderHelper } from '../shader/helper.js';
169
169
  });
170
170
  return pb.getGlobalScope()[funcName](...args);
171
171
  }
172
- /**
173
- * Calculate the TBN matrix
174
- *
175
- * @param scope - The shader scope
176
- * @returns TBN matrix
172
+ /**
173
+ * Calculate the TBN matrix
174
+ *
175
+ * @param scope - The shader scope
176
+ * @returns TBN matrix
177
177
  */ calculateTBN(scope, worldPos, worldNormal, worldTangent, worldBinormal) {
178
178
  const pb = scope.$builder;
179
179
  const that = this;
@@ -253,9 +253,9 @@ import { ShaderHelper } from '../shader/helper.js';
253
253
  });
254
254
  return pb.getGlobalScope()[funcName](...args);
255
255
  }
256
- /**
257
- * {@inheritDoc MeshMaterial.applyUniformsValues}
258
- * @override
256
+ /**
257
+ * {@inheritDoc MeshMaterial.applyUniformsValues}
258
+ * @override
259
259
  */ applyUniformValues(bindGroup, ctx, pass) {
260
260
  super.applyUniformValues(bindGroup, ctx, pass);
261
261
  if (ctx.renderPass.type === RENDER_PASS_TYPE_LIGHT) {
@@ -264,20 +264,20 @@ import { ShaderHelper } from '../shader/helper.js';
264
264
  }
265
265
  }
266
266
  }
267
- /**
268
- * Check if the environment lighting should be calculated.
269
- *
270
- * @returns true Environment lighting should be calculated, otherwise false
267
+ /**
268
+ * Check if the environment lighting should be calculated.
269
+ *
270
+ * @returns true Environment lighting should be calculated, otherwise false
271
271
  */ needCalculateEnvLight() {
272
272
  return this.drawContext.renderPass.type === RENDER_PASS_TYPE_LIGHT && this.drawContext.drawEnvLight;
273
273
  }
274
- /**
275
- * Get irradiance of current environment light
276
- *
277
- * @param scope - Shader scope
278
- * @param normal - Fragment normal vector
279
- *
280
- * @returns Irradiance of current environment light of type vec3
274
+ /**
275
+ * Get irradiance of current environment light
276
+ *
277
+ * @param scope - Shader scope
278
+ * @param normal - Fragment normal vector
279
+ *
280
+ * @returns Irradiance of current environment light of type vec3
281
281
  */ getEnvLightIrradiance(scope, normal) {
282
282
  if (!this.needCalculateEnvLight()) {
283
283
  console.warn('getEnvLightIrradiance(): No need to calculate environment lighting');
@@ -285,14 +285,14 @@ import { ShaderHelper } from '../shader/helper.js';
285
285
  }
286
286
  return this.drawContext.env.light.envLight.hasIrradiance() ? scope.$builder.mul(this.drawContext.env.light.envLight.getIrradiance(scope, normal).rgb, ShaderHelper.getEnvLightStrength(scope)) : scope.$builder.vec3(0);
287
287
  }
288
- /**
289
- * Get Radiance of current environment light
290
- *
291
- * @param scope - Shader scope
292
- * @param reflectVec - The reflection vector
293
- * @param roughness - Roughness value of current fragment
294
- *
295
- * @returns Radiance of current environment light of type vec3
288
+ /**
289
+ * Get Radiance of current environment light
290
+ *
291
+ * @param scope - Shader scope
292
+ * @param reflectVec - The reflection vector
293
+ * @param roughness - Roughness value of current fragment
294
+ *
295
+ * @returns Radiance of current environment light of type vec3
296
296
  */ getEnvLightRadiance(scope, reflectVec, roughness) {
297
297
  if (!this.needCalculateEnvLight()) {
298
298
  console.warn('getEnvLightRadiance(): No need to calculate environment lighting');
@@ -300,19 +300,19 @@ import { ShaderHelper } from '../shader/helper.js';
300
300
  }
301
301
  return this.drawContext.env.light.envLight.hasRadiance() ? scope.$builder.mul(this.drawContext.env.light.envLight.getRadiance(scope, reflectVec, roughness).rgb, ShaderHelper.getEnvLightStrength(scope), ShaderHelper.getEnvLightSpecularStrength(scope)) : scope.$builder.vec3(0);
302
302
  }
303
- /**
304
- * Checks if shadow should be computed
305
- *
306
- * @returns true if shadow should be computed, other wise false
303
+ /**
304
+ * Checks if shadow should be computed
305
+ *
306
+ * @returns true if shadow should be computed, other wise false
307
307
  */ needCalculateShadow() {
308
308
  return this.drawContext.renderPass.type === RENDER_PASS_TYPE_LIGHT && !!this.drawContext.currentShadowLight;
309
309
  }
310
- /**
311
- * Calculates shadow of current fragment
312
- *
313
- * @param scope - Shader scope
314
- * @param NoL - NdotL vector
315
- * @returns Shadow of current fragment, 1 means no shadow and 0 means full shadowed.
310
+ /**
311
+ * Calculates shadow of current fragment
312
+ *
313
+ * @param scope - Shader scope
314
+ * @param NoL - NdotL vector
315
+ * @returns Shadow of current fragment, 1 means no shadow and 0 means full shadowed.
316
316
  */ calculateShadow(scope, worldPos, NoL) {
317
317
  const pb = scope.$builder;
318
318
  if (!this.needCalculateShadow()) {
@@ -343,10 +343,19 @@ import { ShaderHelper } from '../shader/helper.js';
343
343
  pb.vec3('worldPos'),
344
344
  pb.vec4('posRange')
345
345
  ], function() {
346
- this.$l.dist = pb.distance(this.posRange.xyz, this.worldPos);
347
- this.$l.falloff = pb.max(0, pb.sub(1, pb.div(this.dist, this.posRange.w)));
348
- this.$return(pb.mul(this.falloff, this.falloff));
349
- });
346
+ this.$l.d = pb.sub(this.worldPos, this.posRange.xyz);
347
+ this.$l.dist2 = pb.dot(this.d, this.d);
348
+ this.$l.lightAtten = pb.div(1, pb.max(this.dist2, 0.0001));
349
+ this.$l.range2 = pb.mul(this.posRange.w, this.posRange.w);
350
+ this.$l.f = pb.div(this.dist2, pb.max(this.range2, 0.0001));
351
+ this.$l.f2 = pb.clamp(pb.sub(1, pb.mul(this.f, this.f)), 0, 1);
352
+ this.$return(pb.mul(this.lightAtten, pb.mul(this.f2, this.f2)));
353
+ /*
354
+ this.$l.smooth = pb.clamp(pb.)
355
+ this.$l.dist = pb.distance(this.posRange.xyz, this.worldPos);
356
+ this.$l.falloff = pb.max(0, pb.sub(1, pb.div(this.dist, this.posRange.w)));
357
+ this.$return(pb.mul(this.falloff, this.falloff));
358
+ */ });
350
359
  return pb.getGlobalScope()[funcName](worldPos, posRange);
351
360
  }
352
361
  calculateSpotLightAttenuation(scope, worldPos, posRange, dirCutoff) {
@@ -449,11 +458,11 @@ import { ShaderHelper } from '../shader/helper.js';
449
458
  });
450
459
  }
451
460
  }
452
- /**
453
- * Fragment shader implementation
454
- *
455
- * @param scope - Shader scope
456
- * @returns Calucated fragment color
461
+ /**
462
+ * Fragment shader implementation
463
+ *
464
+ * @param scope - Shader scope
465
+ * @returns Calucated fragment color
457
466
  */ fragmentShader(scope) {
458
467
  super.fragmentShader(scope);
459
468
  const pb = scope.$builder;
@@ -463,9 +472,9 @@ import { ShaderHelper } from '../shader/helper.js';
463
472
  }
464
473
  }
465
474
  }
466
- /**
467
- * {@inheritDoc Material.supportLighting}
468
- * @override
475
+ /**
476
+ * {@inheritDoc Material.supportLighting}
477
+ * @override
469
478
  */ supportLighting() {
470
479
  return true;
471
480
  }