@ringozz/godot 4.7.1-1 → 4.7.1-11

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.
package/src/preload.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**********************************************************************
2
+ Copyright (c) Vladimir Davidovich. All rights reserved.
3
+ ***********************************************************************/
4
+
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { dirname, resolve } from 'node:path';
7
+ import { plugin } from 'bun';
8
+ import type { BunPlugin } from 'bun';
9
+
10
+ // Registers the godot-assets plugin: imports of Godot source assets become
11
+ // virtual modules (namespace `godot`) that call `loadAsset` (`@ringozz/godot/load`)
12
+ // and export the resulting `materialize` (own + deps' files) and load promise.
13
+ // `loadAsset` checks the engine's `ResourceCache` once; when the asset is
14
+ // already loaded (e.g. a re-evaluated module under web HMR) the load resolves to
15
+ // the cached instance and `materialize` short-circuits, skipping file staging
16
+ // and the threaded load. The load promise persists on the module's
17
+ // `import.meta.hot.data` (per-module state carried across hot replacements), so
18
+ // HMR re-evaluations return the *same* fulfilled promise object — React's `use()`
19
+ // keeps its tracked status and never re-suspends (no Suspense fallback flash); a
20
+ // rejected load is evicted from `data` so the next evaluation retries; on
21
+ // desktop `data` is `{}` and modules evaluate once. Dependencies are generated
22
+ // modules too, so a dep's load starts at module evaluation while the parent only
23
+ // waits for dep *files*. The default export is the single plugin — registered
24
+ // globally via bunfig preload and loaded by `[serve.static] plugins` for
25
+ // `Bun.serve` HTML routes.
26
+
27
+ const ROOT = process.cwd();
28
+ const NS = 'godot';
29
+
30
+ /** Format metadata: `cls` = Godot class (importable), `scan` = scan text refs, `native` = no `.import` sidecar. */
31
+ const FORMATS: Record<string, { cls?: string; scan?: boolean; native?: boolean }> = {
32
+ gltf: { cls: 'PackedScene', scan: true },
33
+ tscn: { cls: 'PackedScene', scan: true, native: true },
34
+ obj: { cls: 'PackedScene', scan: true },
35
+ jpg: { cls: 'CompressedTexture2D' },
36
+ jpeg: { cls: 'CompressedTexture2D' },
37
+ png: { cls: 'CompressedTexture2D' },
38
+ webp: { cls: 'CompressedTexture2D' },
39
+ svg: { cls: 'Texture2D' },
40
+ exr: { cls: 'TextureLayered' },
41
+ hdr: { cls: 'TextureLayered' },
42
+ wav: { cls: 'AudioStreamWAV' },
43
+ ogg: { cls: 'AudioStreamOggVorbis' },
44
+ mp3: { cls: 'AudioStreamMP3' },
45
+ tres: { cls: 'Resource', scan: true, native: true },
46
+ po: { cls: 'Translation', native: true },
47
+ mtl: { scan: true },
48
+ };
49
+
50
+ const ASSET_RE = new RegExp(
51
+ `\\.(${Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k]) => k).join('|')})$`,
52
+ 'i',
53
+ );
54
+ const CLASS_BY_EXT: Record<string, string> = Object.fromEntries(
55
+ Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k, f]) => [k, f.cls!]),
56
+ );
57
+ const SCANNED = new Set(Object.entries(FORMATS).filter(([, f]) => f.scan).map(([k]) => k));
58
+ const NATIVE = new Set(Object.entries(FORMATS).filter(([, f]) => f.native).map(([k]) => k));
59
+
60
+ const extOf = (abs: string) => abs.slice(abs.lastIndexOf('.') + 1).toLowerCase();
61
+ const resOf = (abs: string) => 'res://' + abs.slice(ROOT.length + 1).replaceAll('\\', '/');
62
+ const isScannableText = (abs: string) => SCANNED.has(extOf(abs));
63
+ const isNativeText = (abs: string) => NATIVE.has(extOf(abs));
64
+ const isSourceAsset = (abs: string) => existsSync(abs + '.import') || isNativeText(abs);
65
+
66
+ /** Reads the imported destination (`dest_files`) out of an `.import` sidecar. */
67
+ function parseSidecarDest(text: string): string | null {
68
+ const deps = text.match(/^dest_files=\[([^\]]*)\]/m);
69
+ if (deps) {
70
+ const first = deps[1].match(/"([^"]+)"/);
71
+ if (first) {
72
+ return first[1];
73
+ }
74
+ }
75
+ const remap = text.match(/^path="([^"]+)"/m);
76
+ return remap ? remap[1] : null;
77
+ }
78
+
79
+ // Generalized reference extraction for text-based source assets: absolute
80
+ // `res://` paths (Godot scenes/resources) and relative path tokens ending in a
81
+ // known asset extension (glTF uris, OBJ/MTL textures). The literal dot before
82
+ // the extension avoids matching MIME types inside `data:` URIs.
83
+ const RES_RE = /res:\/\/[\w./\\-]+/g;
84
+ const REL_RE = new RegExp(`([\\w./\\\\-]+\\.(?:${Object.keys(FORMATS).join('|')}))`, 'g');
85
+
86
+ function extractRefs(text: string): string[] {
87
+ const refs: string[] = [];
88
+ for (const m of text.matchAll(RES_RE)) refs.push(m[0]);
89
+ for (const m of text.matchAll(REL_RE)) refs.push(m[1]);
90
+ return refs;
91
+ }
92
+
93
+ /**
94
+ * Adds a source asset's own files to `files`: imported assets contribute their
95
+ * `.import` sidecar (text) + imported product (file); native text formats
96
+ * (tscn/tres/po) contribute the file itself (text).
97
+ */
98
+ function addSource(srcAbs: string, files: Map<string, 'text' | 'file'>): void {
99
+ const impAbs = srcAbs + '.import';
100
+ if (existsSync(impAbs)) {
101
+ files.set(resOf(srcAbs) + '.import', 'text');
102
+ const dest = parseSidecarDest(readFileSync(impAbs, 'utf8'));
103
+ if (dest) {
104
+ files.set(dest, 'file');
105
+ }
106
+ } else if (isNativeText(srcAbs)) {
107
+ files.set(resOf(srcAbs), 'text');
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Collects the referenced source assets (deps) of a text source: source assets
113
+ * become dep modules (each handles its own transitive deps); raw text formats
114
+ * without a sidecar (`.mtl`) are recursed into. Buffers (`.bin`) are skipped.
115
+ */
116
+ function collectDeps(abs: string, visited: Set<string>, deps: string[]): void {
117
+ if (visited.has(abs)) {
118
+ return;
119
+ }
120
+ visited.add(abs);
121
+ if (!isScannableText(abs)) {
122
+ return;
123
+ }
124
+ for (const ref of extractRefs(readFileSync(abs, 'utf8'))) {
125
+ const refAbs = ref.startsWith('res://')
126
+ ? resolve(ROOT, ref.slice('res://'.length))
127
+ : resolve(dirname(abs), ref);
128
+ if (visited.has(refAbs)) {
129
+ continue;
130
+ }
131
+ if (isSourceAsset(refAbs)) {
132
+ deps.push(refAbs);
133
+ } else if (isScannableText(refAbs)) {
134
+ collectDeps(refAbs, visited, deps);
135
+ }
136
+ }
137
+ }
138
+
139
+ function analyze(abs: string): { files: Map<string, 'text' | 'file'>; deps: string[] } {
140
+ const files = new Map<string, 'text' | 'file'>();
141
+ const deps: string[] = [];
142
+ addSource(abs, files);
143
+ collectDeps(abs, new Set(), deps);
144
+ return { files, deps };
145
+ }
146
+
147
+ function ensureModule(abs: string): string {
148
+ const res = resOf(abs);
149
+ const cls = CLASS_BY_EXT[extOf(abs)] ?? 'Resource';
150
+ const { files, deps } = analyze(abs);
151
+
152
+ const imports = [
153
+ `import { loadAsset } from '@ringozz/godot/load';`,
154
+ `import { ${cls} } from '@ringozz/godot/${cls}';`,
155
+ ];
156
+ const map: string[] = [];
157
+ let ti = 0;
158
+ let fi = 0;
159
+ for (const [resPath, kind] of files) {
160
+ const absP = resolve(ROOT, resPath.slice('res://'.length));
161
+ const v = kind === 'text' ? `c${ti++}` : `f${fi++}`;
162
+ const type = kind === 'text' ? 'text' : 'file';
163
+ const field = kind === 'text' ? 'content' : 'path';
164
+ imports.push(`import ${v} from ${JSON.stringify(absP)} with { type: '${type}' };`);
165
+ map.push(` ${JSON.stringify(resPath)}: { ${field}: ${v} },`);
166
+ }
167
+ deps.forEach((dep, i) => imports.push(`import * as dep${i} from ${JSON.stringify(dep)};`));
168
+
169
+ const filesVar = files.size ? `const files = {\n${map.join('\n')}\n};` : `const files = {};`;
170
+ const loadAsset = `const { materialize, load } = loadAsset(${JSON.stringify(res)}, ${cls}, files, [${deps.map((_, i) => `dep${i}`).join(', ')}], import.meta.hot.data);`;
171
+ return imports.join('\n') + '\n' + filesVar + '\n' + loadAsset + '\n' + `export { materialize, load as default };` + '\n';
172
+ }
173
+
174
+ const assetPlugin: BunPlugin = {
175
+ name: 'godot-assets',
176
+ setup(build) {
177
+ build.onResolve({ filter: ASSET_RE }, (args) => {
178
+ const importerAbs = args.importer?.startsWith(`${NS}:`)
179
+ ? args.importer.slice(NS.length + 1)
180
+ : args.importer;
181
+ const base = importerAbs ? dirname(importerAbs) : (args.resolveDir ?? ROOT);
182
+ const abs = resolve(base, args.path);
183
+ // A module's own native-text source (e.g. `.tscn`) self-imports the
184
+ // same path — let it load as a real file.
185
+ if (abs === importerAbs) {
186
+ return;
187
+ }
188
+ return { path: abs, namespace: NS };
189
+ });
190
+ build.onLoad({ filter: /.*/, namespace: NS }, (args) => ({
191
+ contents: ensureModule(args.path),
192
+ loader: 'js',
193
+ }));
194
+ },
195
+ };
196
+
197
+ export default assetPlugin;
198
+ plugin(assetPlugin);
package/src/runtime.ts CHANGED
@@ -2,13 +2,23 @@
2
2
  Copyright (c) Vladimir Davidovich. All rights reserved.
3
3
  ***********************************************************************/
4
4
 
5
- const { platform, arch } = globalThis.process ?? {};
6
- const mapping: any = {
7
- 'darwin-arm64': 'macos-arm64',
8
- 'win32-x64': 'windows-x86_64',
9
- };
10
- const suffix = mapping[`${platform}-${arch}`];
11
- const { default: _mod } = await (suffix ? import(`@ringozz/godot-${suffix}`) : import('@ringozz/godot-web-wasm32'));
5
+ /** Shared runtime: platform-specific native-module selection lives in
6
+ * `boot.ts` (desktop) / `boot.browser.ts` (web, via the `exports` `./boot`
7
+ * entry's `browser` condition). `_mod` is the native module — the desktop
8
+ * addon's `module.exports` or the wasm module's `.default`.
9
+ *
10
+ * The boot leaf is imported by **package self-reference** (`@ringozz/godot/boot`),
11
+ * not by relative path: a bare specifier resolves through this package's own
12
+ * `exports` map (whose `./boot` entry's `browser` condition selects
13
+ * `boot.browser.ts` on web) exactly like the entrypoint's
14
+ * `import { preloadGodot } from '@ringozz/godot/boot'`, so both sides land on the
15
+ * same absolute path and share ONE `boot.browser.ts` module instance. (A relative
16
+ * `./boot.ts` import would let a consumer's bundler realpath it into
17
+ * `node_modules/.bun/...` while the entrypoint keeps the `node_modules/@ringozz/godot`
18
+ * path — two instances, and the preload handoff below would read `null`.)
19
+ */
20
+ import { getNativeModule } from '@ringozz/godot/boot';
21
+ const { default: _mod } = getNativeModule() as any;
12
22
 
13
23
  /** Godot instance */
14
24
  import type { GodotInstance } from '../gen/classes/GodotInstance.ts';
@@ -42,6 +52,9 @@ export const _set = _mod._set as (target: GodotVar, nameId: number, val: unknown
42
52
  /** Register Godot object wrapper. */
43
53
  export const _R = _mod._R as (typeId: number, ctor: Function) => string;
44
54
 
55
+ /** Stage bytes into the web MEMFS (Godot's `copyToFS`); undefined on desktop. */
56
+ export const stageFile = (_mod as any).stageFile as ((path: string, bytes: Uint8Array) => void) | undefined;
57
+
45
58
  /** Get a Signal value from an Object by signal name, or connect a callback when 3rd arg given. */
46
59
  export const _G = _mod._G as (target: GodotVar, signalNameId: number, callback?: unknown) => unknown;
47
60
 
@@ -0,0 +1,118 @@
1
+ /**********************************************************************
2
+ Copyright (c) Vladimir Davidovich. All rights reserved.
3
+ ***********************************************************************/
4
+
5
+ // Web-only: decode the embedded PNG/WebP blobs of a `.ctex` CompressedTexture2D
6
+ // container with the browser's `createImageBitmap`, and rebuild the container as
7
+ // a raw RGBA8 `DATA_FORMAT_IMAGE` ctex — so no image codec runs in wasm on web.
8
+ // Anything that isn't a PNG/WebP-embedded ctex is returned unchanged.
9
+
10
+ const CTEX_MAGIC = 'GST2';
11
+ const DATA_FORMAT_IMAGE = 0;
12
+ const DATA_FORMAT_PNG = 1;
13
+ const DATA_FORMAT_WEBP = 2;
14
+ const FORMAT_RGBA8 = 5;
15
+ const FORMAT_BIT_STREAM = 1 << 22;
16
+
17
+ // Outer header: magic(4) version(4) w(4) h(4) df(4) mipmap_limit(4) reserved(12).
18
+ const OUTER_HEADER_SIZE = 36;
19
+ // Sub-header: data_format(4) w(2) h(2) mipmaps(4) format(4).
20
+ const SUB_HEADER_OFFSET = OUTER_HEADER_SIZE;
21
+ const SUB_HEADER_SIZE = 16;
22
+ const BLOB_TABLE_OFFSET = SUB_HEADER_OFFSET + SUB_HEADER_SIZE;
23
+
24
+ interface DecodedBitmap {
25
+ width: number;
26
+ height: number;
27
+ data: Uint8Array;
28
+ }
29
+
30
+ async function decodeWebBitmap(blob: Uint8Array<ArrayBuffer>, type: string): Promise<DecodedBitmap> {
31
+ const bmp = await createImageBitmap(new Blob([blob], { type }), {
32
+ imageOrientation: 'none',
33
+ colorSpaceConversion: 'none',
34
+ premultiplyAlpha: 'none',
35
+ });
36
+ try {
37
+ const canvas = new OffscreenCanvas(bmp.width, bmp.height);
38
+ const ctx = canvas.getContext('2d', { colorSpace: 'srgb', willReadFrequently: true }) as
39
+ | OffscreenCanvasRenderingContext2D
40
+ | null;
41
+ if (!ctx) {
42
+ throw new Error('web-image: no 2d context for OffscreenCanvas');
43
+ }
44
+ ctx.drawImage(bmp, 0, 0);
45
+ const img = ctx.getImageData(0, 0, bmp.width, bmp.height);
46
+ return { width: bmp.width, height: bmp.height, data: new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength) };
47
+ } finally {
48
+ bmp.close();
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Decodes the embedded PNG/WebP blobs of a `.ctex` file with the browser's
54
+ * `createImageBitmap` and rebuilds it as a raw RGBA8 (`DATA_FORMAT_IMAGE`)
55
+ * container. Non-ctex bytes, streamable textures, and `DATA_FORMAT_IMAGE` /
56
+ * `DATA_FORMAT_BASIS_UNIVERSAL` containers are returned unchanged. Throws if an
57
+ * embedded blob can't be decoded or its dimensions don't match the expected
58
+ * mipmap layout, so a would-be undecodable texture fails loudly at materialize
59
+ * time. A no-op outside browsers (no `createImageBitmap`).
60
+ */
61
+ export async function decodeCtex(bytes: Uint8Array): Promise<Uint8Array> {
62
+ if (
63
+ typeof createImageBitmap !== 'function' ||
64
+ bytes.length < SUB_HEADER_OFFSET + SUB_HEADER_SIZE ||
65
+ String.fromCharCode(...bytes.subarray(0, 4)) !== CTEX_MAGIC
66
+ ) {
67
+ return bytes;
68
+ }
69
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
70
+ if (dv.getUint32(16, true) & FORMAT_BIT_STREAM) {
71
+ return bytes; // streamable layout differs; leave it to the engine
72
+ }
73
+ const dataFormat = dv.getUint32(SUB_HEADER_OFFSET, true);
74
+ if (dataFormat !== DATA_FORMAT_PNG && dataFormat !== DATA_FORMAT_WEBP) {
75
+ return bytes; // raw and BASIS_UNIVERSAL containers pass through
76
+ }
77
+ const w = dv.getUint16(SUB_HEADER_OFFSET + 4, true);
78
+ const h = dv.getUint16(SUB_HEADER_OFFSET + 6, true);
79
+ const mipmaps = dv.getUint32(SUB_HEADER_OFFSET + 8, true);
80
+ const type = dataFormat === DATA_FORMAT_WEBP ? 'image/webp' : 'image/png';
81
+
82
+ let ofs = BLOB_TABLE_OFFSET;
83
+ const levels: Uint8Array[] = [];
84
+ for (let i = 0; i <= mipmaps; i++) {
85
+ if (ofs + 4 > bytes.length) {
86
+ throw new Error(`web-image: truncated ctex at mipmap ${i}`);
87
+ }
88
+ const size = dv.getUint32(ofs, true);
89
+ ofs += 4;
90
+ if (ofs + size > bytes.length) {
91
+ throw new Error(`web-image: truncated ctex blob at mipmap ${i}`);
92
+ }
93
+ const bmp = await decodeWebBitmap(bytes.slice(ofs, ofs + size), type);
94
+ ofs += size;
95
+ const ew = Math.max(w >> i, 1);
96
+ const eh = Math.max(h >> i, 1);
97
+ if (bmp.width !== ew || bmp.height !== eh) {
98
+ throw new Error(`web-image: mipmap ${i} decoded as ${bmp.width}x${bmp.height}, expected ${ew}x${eh}`);
99
+ }
100
+ levels.push(bmp.data);
101
+ }
102
+
103
+ const dataSize = levels.reduce((n, level) => n + level.length, 0);
104
+ const out = new Uint8Array(BLOB_TABLE_OFFSET + dataSize);
105
+ out.set(bytes.subarray(0, OUTER_HEADER_SIZE)); // outer header verbatim
106
+ const odv = new DataView(out.buffer);
107
+ odv.setUint32(SUB_HEADER_OFFSET, DATA_FORMAT_IMAGE, true);
108
+ odv.setUint16(SUB_HEADER_OFFSET + 4, w, true);
109
+ odv.setUint16(SUB_HEADER_OFFSET + 6, h, true);
110
+ odv.setUint32(SUB_HEADER_OFFSET + 8, mipmaps, true);
111
+ odv.setUint32(SUB_HEADER_OFFSET + 12, FORMAT_RGBA8, true);
112
+ let p = BLOB_TABLE_OFFSET;
113
+ for (const level of levels) {
114
+ out.set(level, p);
115
+ p += level.length;
116
+ }
117
+ return out;
118
+ }