@needle-tools/gltf-build-pipeline 2.15.0-next.a25e7ea → 2.15.0-next.b8502b7
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/dist/cache/cache.d.ts +1 -0
- package/dist/cache/cache.js +19 -15
- package/dist/cli/index.js +19 -0
- package/dist/extensions/NEEDLE_lightmaps/index.d.ts +41 -0
- package/dist/extensions/NEEDLE_lightmaps/index.js +249 -0
- package/dist/extensions/NEEDLE_opaque/NEEDLE_opaque.d.ts +1 -0
- package/dist/extensions/NEEDLE_opaque/NEEDLE_opaque.js +80 -7
- package/dist/extensions/NEEDLE_opaque/index.js +1 -1
- package/dist/extensions/NEEDLE_pmrem/index.d.ts +21 -0
- package/dist/extensions/NEEDLE_pmrem/index.js +95 -0
- package/dist/extensions/index.d.ts +2 -0
- package/dist/extensions/index.js +7 -1
- package/dist/scripts/pack-gltf.js +18 -5
- package/dist/transforms/needle_pmrem.d.ts +16 -0
- package/dist/transforms/needle_pmrem.js +185 -0
- package/dist/transforms/needle_progressive.js +14 -6
- package/dist/transforms/needle_texture_transform.d.ts +2 -0
- package/dist/transforms/needle_texture_transform.js +12 -2
- package/dist/transforms/needle_toktx.js +2 -3
- package/dist/utils/analytics.d.ts +24 -0
- package/dist/utils/analytics.js +111 -0
- package/dist/utils/test-assert.d.ts +8 -0
- package/dist/utils/test-assert.js +18 -0
- package/dist/utils/validate.js +1 -1
- package/dist/utils/version.gen.d.ts +1 -1
- package/dist/utils/version.gen.js +1 -1
- package/package.json +18 -4
- package/tools/pmrem/basis/linux/SHA_d8f36fcbb09e79614e96baaed5b1e1cd5d2f5e73.txt +1 -0
- package/tools/pmrem/basis/linux/basisu +0 -0
- package/tools/pmrem/basis/osx/SHA_d8f36fcbb09e79614e96baaed5b1e1cd5d2f5e73.txt +1 -0
- package/tools/pmrem/basis/osx/basisu +0 -0
- package/tools/pmrem/basis/package.json +3 -0
- package/tools/pmrem/basis/wasm/SHA_d8f36fcbb09e79614e96baaed5b1e1cd5d2f5e73.txt +1 -0
- package/tools/pmrem/basis/wasm/basis_encoder_threads.js +2 -0
- package/tools/pmrem/basis/wasm/basis_encoder_threads.wasm +0 -0
- package/tools/pmrem/basis/win/SHA_d8f36fcbb09e79614e96baaed5b1e1cd5d2f5e73.txt +1 -0
- package/tools/pmrem/basis/win/basisu.exe +0 -0
- package/tools/pmrem/basis/win/basisu_help.txt +0 -0
- package/tools/pmrem/basis/win/ocl_kernels.cl +1266 -0
- package/tools/pmrem/pkg/pmrem_wasm.d.ts +68 -0
- package/tools/pmrem/pkg/pmrem_wasm.js +401 -0
- package/tools/pmrem/pkg/pmrem_wasm_bg.wasm +0 -0
- package/tsconfig.json +0 -20
package/dist/cache/cache.d.ts
CHANGED
package/dist/cache/cache.js
CHANGED
|
@@ -191,8 +191,6 @@ export function getHash(property, level = 0) {
|
|
|
191
191
|
if (property instanceof ExtensibleProperty) {
|
|
192
192
|
const extensions = property.listExtensions();
|
|
193
193
|
const extras = property.getExtras();
|
|
194
|
-
// const slots = listTextureSlots(doc, texture);
|
|
195
|
-
// const channels = getTextureChannelMask(doc, texture);
|
|
196
194
|
hash += hashObject({
|
|
197
195
|
extensions,
|
|
198
196
|
extras,
|
|
@@ -269,38 +267,44 @@ function hashObject(obj, depth = 0) {
|
|
|
269
267
|
return hashString(String(obj));
|
|
270
268
|
}
|
|
271
269
|
try {
|
|
272
|
-
const
|
|
270
|
+
const seen = new WeakSet();
|
|
271
|
+
const str = JSON.stringify(obj, (_key, value) => {
|
|
272
|
+
if (typeof value === 'object' && value !== null) {
|
|
273
|
+
if (seen.has(value))
|
|
274
|
+
return undefined;
|
|
275
|
+
seen.add(value);
|
|
276
|
+
}
|
|
277
|
+
if (typeof value === 'function')
|
|
278
|
+
return undefined;
|
|
279
|
+
return value;
|
|
280
|
+
});
|
|
273
281
|
return hashString(str);
|
|
274
282
|
}
|
|
275
283
|
catch (err) {
|
|
276
284
|
console.warn("WARN: [Cache] error during hashing of object:\n" + err);
|
|
277
285
|
if (debugLogs)
|
|
278
286
|
debugger;
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
let fallbackHashj = 0;
|
|
282
|
-
if (typeof obj === 'object') {
|
|
283
|
-
if (obj === null)
|
|
284
|
-
return 0;
|
|
287
|
+
let fallbackHash = 0;
|
|
288
|
+
if (typeof obj === 'object' && obj !== null) {
|
|
285
289
|
for (const key in obj) {
|
|
286
290
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
287
291
|
const value = obj[key];
|
|
288
|
-
|
|
289
|
-
if (typeof value === 'object') {
|
|
292
|
+
fallbackHash += hashString(key);
|
|
293
|
+
if (typeof value === 'object' && value !== null) {
|
|
290
294
|
if (depth > 10) {
|
|
291
|
-
|
|
295
|
+
fallbackHash += hashString("[object]");
|
|
292
296
|
}
|
|
293
297
|
else {
|
|
294
|
-
|
|
298
|
+
fallbackHash += hashObject(value, depth + 1);
|
|
295
299
|
}
|
|
296
300
|
}
|
|
297
301
|
else {
|
|
298
|
-
|
|
302
|
+
fallbackHash += hashString(String(value));
|
|
299
303
|
}
|
|
300
304
|
}
|
|
301
305
|
}
|
|
302
306
|
}
|
|
303
|
-
return
|
|
307
|
+
return fallbackHash;
|
|
304
308
|
}
|
|
305
309
|
}
|
|
306
310
|
function hashBuffer(buffer, offset, length) {
|
package/dist/cli/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { existsSync } from 'fs';
|
|
|
10
10
|
import { ensureIsDirectory, foreachGLTF, isDirectory } from '../utils/fileutils.js';
|
|
11
11
|
import path, { resolve } from 'path';
|
|
12
12
|
import { ERROR_CODES } from '../constants.js';
|
|
13
|
+
import { trackPipelineStart, trackPipelineEnd, trackError } from '../utils/analytics.js';
|
|
13
14
|
// For testing / dev you can run `npm link` in the package directory
|
|
14
15
|
// For removing the link run `npm rm --global @needle-tools/gltf-build-pipeline`
|
|
15
16
|
program
|
|
@@ -73,6 +74,8 @@ Each version will be compressed and written to the output directory.
|
|
|
73
74
|
return;
|
|
74
75
|
}
|
|
75
76
|
logger.info(`[Needle Build Pipeline] v${getVersion()} — Transform '${args.input}'`);
|
|
77
|
+
const pipelineMode = [options.progressive && 'progressive', options.compress && 'compress'].filter(Boolean).join('+');
|
|
78
|
+
trackPipelineStart({ mode: pipelineMode, usecase: options.usecase?.toString() });
|
|
76
79
|
const stats = {
|
|
77
80
|
startTime: Date.now(),
|
|
78
81
|
totalGPUMemoryInMB: 0,
|
|
@@ -103,6 +106,7 @@ Each version will be compressed and written to the output directory.
|
|
|
103
106
|
const outputIsDirectory = output && isDirectory(output);
|
|
104
107
|
if (inputIsDirectory && output && !outputIsDirectory) {
|
|
105
108
|
logger.error("When <input> is a directory then <output> must also be a directory");
|
|
109
|
+
trackError(new Error('Invalid args: input is directory but output is not'), { mode: pipelineMode });
|
|
106
110
|
process.exit(ERROR_CODES.INVALID_ARGS);
|
|
107
111
|
}
|
|
108
112
|
// Handle the output bath being relative to the input path
|
|
@@ -126,6 +130,7 @@ Each version will be compressed and written to the output directory.
|
|
|
126
130
|
}
|
|
127
131
|
else {
|
|
128
132
|
logger.error(`ERR: Previously found file is now missing: \"${file}\"`);
|
|
133
|
+
trackError(new Error(`Lost file: ${file}`), { mode: pipelineMode, usecase: options.usecase?.toString(), file });
|
|
129
134
|
process.exit(ERROR_CODES.LOST_FILE);
|
|
130
135
|
}
|
|
131
136
|
}
|
|
@@ -148,8 +153,10 @@ Each version will be compressed and written to the output directory.
|
|
|
148
153
|
logger,
|
|
149
154
|
}).catch(err => {
|
|
150
155
|
logger.error(err);
|
|
156
|
+
trackError(err, { mode: pipelineMode, usecase: options.usecase?.toString(), file });
|
|
151
157
|
process.exit(ERROR_CODES.PROGRESSIVE_FAILED);
|
|
152
158
|
}) === false) {
|
|
159
|
+
trackError(new Error('Progressive processing returned false'), { mode: pipelineMode, usecase: options.usecase?.toString(), file });
|
|
153
160
|
process.exit(ERROR_CODES.PROGRESSIVE_FAILED);
|
|
154
161
|
}
|
|
155
162
|
if (verbose) {
|
|
@@ -170,6 +177,7 @@ Each version will be compressed and written to the output directory.
|
|
|
170
177
|
if (progressive_results.length > 0) {
|
|
171
178
|
for (const res of progressive_results) {
|
|
172
179
|
if (await packGLTF(res, res, opts) === false) {
|
|
180
|
+
trackError(new Error('Packing failed'), { mode: pipelineMode, usecase: options.usecase?.toString(), file: res });
|
|
173
181
|
process.exit(ERROR_CODES.PACKING_FAILED);
|
|
174
182
|
}
|
|
175
183
|
}
|
|
@@ -178,12 +186,22 @@ Each version will be compressed and written to the output directory.
|
|
|
178
186
|
// We can not just check if the file is in the list of results because the output path might have changed the name
|
|
179
187
|
else {
|
|
180
188
|
if (await packGLTF(file, output, opts) === false) {
|
|
189
|
+
trackError(new Error('Packing failed'), { mode: pipelineMode, usecase: options.usecase?.toString(), file });
|
|
181
190
|
process.exit(ERROR_CODES.PACKING_FAILED);
|
|
182
191
|
}
|
|
183
192
|
}
|
|
184
193
|
}
|
|
185
194
|
});
|
|
186
195
|
printStats(stats, logger, config);
|
|
196
|
+
trackPipelineEnd({
|
|
197
|
+
mode: pipelineMode,
|
|
198
|
+
usecase: config?.usecase?.toString(),
|
|
199
|
+
filesProcessed: stats.totalFilesProcessed,
|
|
200
|
+
sizeBefore_MB: stats.totalFileSizeInMBBefore,
|
|
201
|
+
sizeAfter_MB: stats.totalFileSizeInMB,
|
|
202
|
+
gpuMemory_MB: stats.totalGPUMemoryInMB,
|
|
203
|
+
duration_ms: Date.now() - stats.startTime,
|
|
204
|
+
});
|
|
187
205
|
if (useCache)
|
|
188
206
|
limitCacheSize();
|
|
189
207
|
});
|
|
@@ -194,5 +212,6 @@ program.run().catch(err => {
|
|
|
194
212
|
// ignore
|
|
195
213
|
return;
|
|
196
214
|
}
|
|
215
|
+
trackError(err);
|
|
197
216
|
throw err;
|
|
198
217
|
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Extension, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
|
|
2
|
+
/**
|
|
3
|
+
* NEEDLE_lightmaps gltf-transform extension.
|
|
4
|
+
*
|
|
5
|
+
* Handles both embedded (`/textures/N` pointer) and external (`sunrise.exr` pointer) lightmaps.
|
|
6
|
+
*
|
|
7
|
+
* - **preread(TEXTURE)**: Injects external EXR files into the JSON document so the core reader
|
|
8
|
+
* creates proper Texture objects from them.
|
|
9
|
+
* - **read()**: Resolves `/textures/N` pointers to Texture objects. Sets references so that
|
|
10
|
+
* gltf-transform doesn't prune/dedup referenced textures.
|
|
11
|
+
* - **write()**: Updates pointer strings:
|
|
12
|
+
* - Embedded textures: resolves to the new `/textures/N` index in the output.
|
|
13
|
+
* - External textures: uses the Texture's current URI (e.g. updated by PMREM to `.pmrem.ktx2`).
|
|
14
|
+
*/
|
|
15
|
+
export declare class NEEDLE_lightmaps_ext extends Extension {
|
|
16
|
+
static readonly EXTENSION_NAME = "NEEDLE_lightmaps";
|
|
17
|
+
readonly extensionName = "NEEDLE_lightmaps";
|
|
18
|
+
readonly prereadTypes: PropertyType[];
|
|
19
|
+
readonly prewriteTypes: PropertyType[];
|
|
20
|
+
/** Set before io.read() to allow resolving external file paths in preread */
|
|
21
|
+
static inputFile: string;
|
|
22
|
+
/** The raw extension JSON from the input (mutated in-place during write) */
|
|
23
|
+
private extensionData;
|
|
24
|
+
/** Entries with resolved Texture references */
|
|
25
|
+
private resolved;
|
|
26
|
+
/** Image indices injected during preread (for external EXR files) */
|
|
27
|
+
private injectedImageIndices;
|
|
28
|
+
/** The ExtensionProperty that holds references to prevent dedup/prune */
|
|
29
|
+
private lightmapProp;
|
|
30
|
+
preread(context: ReaderContext, _propertyType: PropertyType): this;
|
|
31
|
+
read(context: ReaderContext): this;
|
|
32
|
+
prewrite(context: WriterContext, _propertyType: PropertyType): this;
|
|
33
|
+
write(context: WriterContext): this;
|
|
34
|
+
private pointersResolved;
|
|
35
|
+
private resolvePointers;
|
|
36
|
+
/**
|
|
37
|
+
* Find (or create) a texture def in the output JSON that references the given Texture.
|
|
38
|
+
* This replicates the logic from the opaque system's TextureIndexResolver.
|
|
39
|
+
*/
|
|
40
|
+
private findOrCreateTextureIndex;
|
|
41
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { Extension, ExtensionProperty, PropertyType } from '@gltf-transform/core';
|
|
2
|
+
import { existsSync, readFileSync } from 'fs';
|
|
3
|
+
import { join, dirname } from 'path';
|
|
4
|
+
import { isLightmap } from '../../utils/texture.js';
|
|
5
|
+
const EXTENSION_NAME = 'NEEDLE_lightmaps';
|
|
6
|
+
/**
|
|
7
|
+
* Opaque-like ExtensionProperty that holds NEEDLE_lightmaps data on the Root.
|
|
8
|
+
* This keeps gltf-transform from garbage-collecting referenced textures.
|
|
9
|
+
*/
|
|
10
|
+
class LightmapProperty extends ExtensionProperty {
|
|
11
|
+
static EXTENSION_NAME = EXTENSION_NAME;
|
|
12
|
+
propertyType = 'LightmapProperty';
|
|
13
|
+
parentTypes = [PropertyType.ROOT];
|
|
14
|
+
init() {
|
|
15
|
+
this.extensionName = EXTENSION_NAME;
|
|
16
|
+
}
|
|
17
|
+
getDefaults() {
|
|
18
|
+
return Object.assign(super.getDefaults(), {});
|
|
19
|
+
}
|
|
20
|
+
/** Public wrapper around protected setRef to register references */
|
|
21
|
+
setReference(name, value) {
|
|
22
|
+
this.setRef(name, value);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* NEEDLE_lightmaps gltf-transform extension.
|
|
27
|
+
*
|
|
28
|
+
* Handles both embedded (`/textures/N` pointer) and external (`sunrise.exr` pointer) lightmaps.
|
|
29
|
+
*
|
|
30
|
+
* - **preread(TEXTURE)**: Injects external EXR files into the JSON document so the core reader
|
|
31
|
+
* creates proper Texture objects from them.
|
|
32
|
+
* - **read()**: Resolves `/textures/N` pointers to Texture objects. Sets references so that
|
|
33
|
+
* gltf-transform doesn't prune/dedup referenced textures.
|
|
34
|
+
* - **write()**: Updates pointer strings:
|
|
35
|
+
* - Embedded textures: resolves to the new `/textures/N` index in the output.
|
|
36
|
+
* - External textures: uses the Texture's current URI (e.g. updated by PMREM to `.pmrem.ktx2`).
|
|
37
|
+
*/
|
|
38
|
+
export class NEEDLE_lightmaps_ext extends Extension {
|
|
39
|
+
static EXTENSION_NAME = EXTENSION_NAME;
|
|
40
|
+
extensionName = EXTENSION_NAME;
|
|
41
|
+
prereadTypes = [PropertyType.TEXTURE];
|
|
42
|
+
prewriteTypes = [PropertyType.MATERIAL];
|
|
43
|
+
/** Set before io.read() to allow resolving external file paths in preread */
|
|
44
|
+
static inputFile = '';
|
|
45
|
+
/** The raw extension JSON from the input (mutated in-place during write) */
|
|
46
|
+
extensionData = null;
|
|
47
|
+
/** Entries with resolved Texture references */
|
|
48
|
+
resolved = [];
|
|
49
|
+
/** Image indices injected during preread (for external EXR files) */
|
|
50
|
+
injectedImageIndices = new Map();
|
|
51
|
+
/** The ExtensionProperty that holds references to prevent dedup/prune */
|
|
52
|
+
lightmapProp = null;
|
|
53
|
+
// ── preread ──────────────────────────────────────────────────
|
|
54
|
+
preread(context, _propertyType) {
|
|
55
|
+
const json = context.jsonDoc.json;
|
|
56
|
+
const ext = json.extensions?.[EXTENSION_NAME];
|
|
57
|
+
if (!ext?.textures)
|
|
58
|
+
return this;
|
|
59
|
+
const inputFile = NEEDLE_lightmaps_ext.inputFile;
|
|
60
|
+
const inputDir = inputFile ? dirname(inputFile) : '';
|
|
61
|
+
for (const entry of ext.textures) {
|
|
62
|
+
// Skip embedded pointers — handled in read()
|
|
63
|
+
if (entry.pointer.startsWith('/') || entry.pointer.startsWith('textures/'))
|
|
64
|
+
continue;
|
|
65
|
+
// External file path (e.g. "sunrise.exr")
|
|
66
|
+
if (!entry.pointer.match(/\.exr$/i))
|
|
67
|
+
continue;
|
|
68
|
+
const exrPath = inputDir ? join(inputDir, entry.pointer) : '';
|
|
69
|
+
if (!exrPath || !existsSync(exrPath)) {
|
|
70
|
+
this.document.getLogger().warn(`NEEDLE_lightmaps: External EXR not found: ${exrPath || entry.pointer}`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
// Read EXR bytes and inject into JSON so the core reader creates a Texture
|
|
74
|
+
const exrBytes = readFileSync(exrPath);
|
|
75
|
+
json.images = json.images || [];
|
|
76
|
+
json.textures = json.textures || [];
|
|
77
|
+
const imageIndex = json.images.length;
|
|
78
|
+
json.images.push({
|
|
79
|
+
uri: entry.pointer,
|
|
80
|
+
mimeType: 'image/exr',
|
|
81
|
+
name: entry.pointer,
|
|
82
|
+
});
|
|
83
|
+
json.textures.push({
|
|
84
|
+
source: imageIndex,
|
|
85
|
+
name: entry.pointer,
|
|
86
|
+
});
|
|
87
|
+
context.jsonDoc.resources[entry.pointer] = new Uint8Array(exrBytes);
|
|
88
|
+
this.injectedImageIndices.set(entry.pointer, imageIndex);
|
|
89
|
+
this.document.getLogger().info(`NEEDLE_lightmaps: Registered external EXR "${entry.pointer}" as image[${imageIndex}]`);
|
|
90
|
+
}
|
|
91
|
+
return this;
|
|
92
|
+
}
|
|
93
|
+
// ── read ─────────────────────────────────────────────────────
|
|
94
|
+
read(context) {
|
|
95
|
+
const json = context.jsonDoc.json;
|
|
96
|
+
const ext = json.extensions?.[EXTENSION_NAME];
|
|
97
|
+
if (!ext?.textures)
|
|
98
|
+
return this;
|
|
99
|
+
// Store the raw extension data — we'll mutate the pointers during write
|
|
100
|
+
this.extensionData = ext;
|
|
101
|
+
// Create the property and attach to root
|
|
102
|
+
const root = this.document.getRoot();
|
|
103
|
+
this.lightmapProp = new LightmapProperty(this.document.getGraph());
|
|
104
|
+
root.setExtension(EXTENSION_NAME, this.lightmapProp);
|
|
105
|
+
const textureDefs = json.textures || [];
|
|
106
|
+
const logger = this.document.getLogger();
|
|
107
|
+
for (const entry of ext.textures) {
|
|
108
|
+
let texture = null;
|
|
109
|
+
let inputTextureDef;
|
|
110
|
+
if (entry.pointer.startsWith('/textures/') || entry.pointer.startsWith('textures/')) {
|
|
111
|
+
// Embedded pointer — resolve to Texture via the JSON texture definition
|
|
112
|
+
const prefix = entry.pointer.startsWith('/') ? '/textures/' : 'textures/';
|
|
113
|
+
const texIndex = parseInt(entry.pointer.substring(prefix.length));
|
|
114
|
+
const texDef = textureDefs[texIndex];
|
|
115
|
+
if (texDef) {
|
|
116
|
+
inputTextureDef = texDef;
|
|
117
|
+
const imageIndex = texDef.source
|
|
118
|
+
?? texDef.extensions?.['EXT_texture_exr']?.source
|
|
119
|
+
?? texDef.extensions?.['KHR_texture_basisu']?.source;
|
|
120
|
+
if (imageIndex !== undefined) {
|
|
121
|
+
texture = context.textures[imageIndex] ?? null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else if (entry.pointer.match(/\.exr$/i)) {
|
|
126
|
+
// External pointer — find the Texture created from our injected image
|
|
127
|
+
const imageIndex = this.injectedImageIndices.get(entry.pointer);
|
|
128
|
+
if (imageIndex !== undefined) {
|
|
129
|
+
texture = context.textures[imageIndex] ?? null;
|
|
130
|
+
inputTextureDef = textureDefs.find(t => t.source === imageIndex);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (texture) {
|
|
134
|
+
this.resolved.push({ entry, texture, inputTextureDef });
|
|
135
|
+
// Set a reference so gltf-transform won't prune/dedup this texture
|
|
136
|
+
const refName = `lightmap_${entry.pointer}`;
|
|
137
|
+
this.lightmapProp.setReference(refName, texture);
|
|
138
|
+
// Also keep a reference to the buffer
|
|
139
|
+
const buffer = this.document.getRoot().listBuffers()[0];
|
|
140
|
+
if (buffer) {
|
|
141
|
+
this.lightmapProp.setReference('buffer', buffer);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
logger.warn(`NEEDLE_lightmaps: Could not resolve texture for pointer "${entry.pointer}"`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// Lightmap workaround: prevent compression on lightmap textures (non-EXR)
|
|
149
|
+
const textures = this.document.getRoot().listTextures();
|
|
150
|
+
for (const tex of textures) {
|
|
151
|
+
if (isLightmap(tex) && tex.getMimeType() !== 'image/exr') {
|
|
152
|
+
const refName = `lightmapTexture_${tex.getName()}`;
|
|
153
|
+
this.lightmapProp.setReference(refName, tex);
|
|
154
|
+
logger.info(`Found lightmap texture "${tex.getName()}" (${tex.getMimeType()}) in ${EXTENSION_NAME}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return this;
|
|
158
|
+
}
|
|
159
|
+
// ── prewrite ─────────────────────────────────────────────────
|
|
160
|
+
prewrite(context, _propertyType) {
|
|
161
|
+
// Resolve pointers early so json.textures is populated for textures
|
|
162
|
+
// not used by any material (same pattern as opaque system)
|
|
163
|
+
this.resolvePointers(context);
|
|
164
|
+
return this;
|
|
165
|
+
}
|
|
166
|
+
// ── write ────────────────────────────────────────────────────
|
|
167
|
+
write(context) {
|
|
168
|
+
if (!this.extensionData)
|
|
169
|
+
return this;
|
|
170
|
+
// Resolve any remaining pointers
|
|
171
|
+
this.resolvePointers(context);
|
|
172
|
+
// Write the extension data to the output JSON
|
|
173
|
+
context.jsonDoc.json.extensions = context.jsonDoc.json.extensions || {};
|
|
174
|
+
context.jsonDoc.json.extensions[EXTENSION_NAME] = this.extensionData;
|
|
175
|
+
return this;
|
|
176
|
+
}
|
|
177
|
+
// ── private ──────────────────────────────────────────────────
|
|
178
|
+
pointersResolved = false;
|
|
179
|
+
resolvePointers(context) {
|
|
180
|
+
if (this.pointersResolved)
|
|
181
|
+
return;
|
|
182
|
+
this.pointersResolved = true;
|
|
183
|
+
for (const { entry, texture, inputTextureDef } of this.resolved) {
|
|
184
|
+
if (entry.pointer.startsWith('/textures/') || entry.pointer.startsWith('textures/')) {
|
|
185
|
+
// Embedded: find the new texture index in the output JSON
|
|
186
|
+
const newIndex = this.findOrCreateTextureIndex(context, texture, inputTextureDef);
|
|
187
|
+
if (newIndex !== undefined) {
|
|
188
|
+
entry.pointer = `/textures/${newIndex}`;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
// External: use the texture's current URI (may have been updated by PMREM)
|
|
193
|
+
const uri = texture.getURI();
|
|
194
|
+
if (uri) {
|
|
195
|
+
entry.pointer = uri;
|
|
196
|
+
// Ensure the image definition in the output JSON has the URI set.
|
|
197
|
+
// When PMREM clears image data (setImage(null)) for external textures,
|
|
198
|
+
// gltf-transform's core writer won't set a uri or bufferView on the image.
|
|
199
|
+
const imageIndex = context.imageIndexMap.get(texture);
|
|
200
|
+
if (imageIndex !== undefined) {
|
|
201
|
+
const images = context.jsonDoc.json.images;
|
|
202
|
+
if (images && images[imageIndex]) {
|
|
203
|
+
images[imageIndex].uri = uri;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Find (or create) a texture def in the output JSON that references the given Texture.
|
|
212
|
+
* This replicates the logic from the opaque system's TextureIndexResolver.
|
|
213
|
+
*/
|
|
214
|
+
findOrCreateTextureIndex(context, texture, inputTextureDef) {
|
|
215
|
+
const imageIndex = context.imageIndexMap.get(texture);
|
|
216
|
+
if (imageIndex === undefined)
|
|
217
|
+
return undefined;
|
|
218
|
+
const textures = context.jsonDoc.json.textures = context.jsonDoc.json.textures || [];
|
|
219
|
+
// Try to find an existing texture def pointing to the same image
|
|
220
|
+
for (let i = 0; i < textures.length; i++) {
|
|
221
|
+
const texDef = textures[i];
|
|
222
|
+
const source = texDef.source
|
|
223
|
+
?? texDef.extensions?.['KHR_texture_basisu']?.source
|
|
224
|
+
?? texDef.extensions?.['NEEDLE_pmrem']?.source;
|
|
225
|
+
if (source === imageIndex) {
|
|
226
|
+
return i;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// Not found — create a new texture definition
|
|
230
|
+
let extensions = inputTextureDef?.extensions ? { ...inputTextureDef.extensions } : undefined;
|
|
231
|
+
if (extensions) {
|
|
232
|
+
// Remove consumed extensions
|
|
233
|
+
delete extensions['NEEDLE_progressive_texture_settings'];
|
|
234
|
+
// Remove EXT_texture_exr if texture was converted
|
|
235
|
+
if (extensions['EXT_texture_exr'] && texture.getMimeType() !== 'image/exr') {
|
|
236
|
+
delete extensions['EXT_texture_exr'];
|
|
237
|
+
}
|
|
238
|
+
if (Object.keys(extensions).length === 0)
|
|
239
|
+
extensions = undefined;
|
|
240
|
+
}
|
|
241
|
+
const hasExtSource = extensions && Object.values(extensions).some((v) => v?.source !== undefined);
|
|
242
|
+
const texDef = {
|
|
243
|
+
source: hasExtSource ? undefined : imageIndex,
|
|
244
|
+
extensions,
|
|
245
|
+
};
|
|
246
|
+
textures.push(texDef);
|
|
247
|
+
return textures.length - 1;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -23,5 +23,6 @@ export interface IExtensionWriter {
|
|
|
23
23
|
write(context: WriterContext, prop: IExtensibleProperty): void;
|
|
24
24
|
}
|
|
25
25
|
export declare let currentGenerator: string;
|
|
26
|
+
export declare function setOpaqueInputFile(path: string): void;
|
|
26
27
|
export declare function createOpaqueExtension(name: string, types: PropertyType | PropertyType[], opts?: Options): IOpaqueExtension;
|
|
27
28
|
export {};
|
|
@@ -2,11 +2,17 @@ import { Extension, ExtensionProperty, PropertyType, Node, TextureChannel } from
|
|
|
2
2
|
import { getTexture, tryGetInArray, writeExtension } from '../utils.js';
|
|
3
3
|
import { isLightmap } from '../../utils/texture.js';
|
|
4
4
|
import { NEEDLE_progressive_texture_settings } from '../NEEDLE_progressive_texture_settings/index.js';
|
|
5
|
+
import { testAssert } from '../../utils/test-assert.js';
|
|
6
|
+
import { existsSync, readFileSync } from 'fs';
|
|
7
|
+
import { dirname, join } from 'path';
|
|
5
8
|
const ALL_PROPERTY_TYPES = [];
|
|
6
9
|
for (const key in PropertyType) {
|
|
7
10
|
ALL_PROPERTY_TYPES.push(PropertyType[key]);
|
|
8
11
|
}
|
|
9
12
|
export let currentGenerator = "";
|
|
13
|
+
/** Set before io.read() to allow resolving external file paths (e.g. .exr) in component data */
|
|
14
|
+
let _opaqueInputFile = "";
|
|
15
|
+
export function setOpaqueInputFile(path) { _opaqueInputFile = path; }
|
|
10
16
|
// an opaque extension can be used to pass data through the gltf transform process
|
|
11
17
|
// it should also be able to re-write/fix json pointers after the transformation which might have shuffled them around
|
|
12
18
|
export function createOpaqueExtension(name, types, opts) {
|
|
@@ -414,11 +420,16 @@ class TextureHandler {
|
|
|
414
420
|
}
|
|
415
421
|
}
|
|
416
422
|
write(ctx) {
|
|
423
|
+
// If the texture was converted (e.g. EXR → KTX2 via PMREM), skip writing the old extension
|
|
424
|
+
if (this.key === "EXT_texture_exr" && this.textureRef.getMimeType() !== "image/exr") {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
417
427
|
// Resolve the current image index from the gltf-transform graph reference.
|
|
418
428
|
// This is stable even after dedup/prune operations that re-index images.
|
|
419
429
|
const imageIndex = ctx.imageIndexMap.get(this.textureRef);
|
|
430
|
+
testAssert(imageIndex !== undefined || this.key === "EXT_texture_exr", `imageIndexMap missing texture ref for "${this.key}": ${this.textureRef.getName() || "<unnamed>"}`);
|
|
420
431
|
if (imageIndex === undefined) {
|
|
421
|
-
if (this.
|
|
432
|
+
if (this.debug) {
|
|
422
433
|
console.warn("WARN: failed to resolve image index for texture via imageIndexMap:", this.key, this.textureRef.getName() || "<unnamed>");
|
|
423
434
|
}
|
|
424
435
|
return;
|
|
@@ -430,10 +441,10 @@ class TextureHandler {
|
|
|
430
441
|
return;
|
|
431
442
|
const textureImageIndex = this.tryGetSourceIndex(textureDef);
|
|
432
443
|
if (imageIndex === textureImageIndex) {
|
|
433
|
-
|
|
434
|
-
|
|
444
|
+
foundTexture = true;
|
|
445
|
+
if (!textureDef.extensions?.[this.key]) {
|
|
446
|
+
// assign texture extension
|
|
435
447
|
textureDef.extensions = textureDef.extensions || {};
|
|
436
|
-
foundTexture = true;
|
|
437
448
|
if (this.debug)
|
|
438
449
|
console.log("Re-Assign extension:", this.key, "at", i);
|
|
439
450
|
const newExt = { ...this.ext };
|
|
@@ -441,10 +452,13 @@ class TextureHandler {
|
|
|
441
452
|
newExt.source = imageIndex;
|
|
442
453
|
textureDef.extensions[this.key] = newExt;
|
|
443
454
|
}
|
|
455
|
+
// else: extension already written by another handler for the same image
|
|
456
|
+
// (happens when gltf-transform dedup merges texture defs that shared the same source)
|
|
444
457
|
}
|
|
445
458
|
});
|
|
459
|
+
testAssert(foundTexture || this.key === "EXT_texture_exr", `failed to match texture for extension "${this.key}", imageIndex=${imageIndex}, textures=${textureDefs.length}, name=${this.textureRef.getName() || "<unnamed>"}, type=${this.textureRef.getMimeType()}`);
|
|
446
460
|
if (foundTexture === false) {
|
|
447
|
-
if (this.
|
|
461
|
+
if (this.debug) {
|
|
448
462
|
console.warn("WARN: failed to re-assign extension:", this.key, "imageIndex", imageIndex, textureDefs.length, this.textureRef.getName() || "<unnamed>", this.textureDefinition);
|
|
449
463
|
}
|
|
450
464
|
}
|
|
@@ -530,6 +544,10 @@ class JsonPointerHandler {
|
|
|
530
544
|
debug = false;
|
|
531
545
|
breakPoint = false;
|
|
532
546
|
VRM_0_MaterialIndexRegex = new RegExp(/materialProperties\/(?<material_index>\d+)\//g);
|
|
547
|
+
/** Cache of external EXR files already injected as Textures (keyed by filename) */
|
|
548
|
+
externalExrTextures = new Map();
|
|
549
|
+
/** External EXR references that need URI resolution at write time */
|
|
550
|
+
externalExrPointers = [];
|
|
533
551
|
constructor(document, extension_name) {
|
|
534
552
|
this.document = document;
|
|
535
553
|
this.extension_name = extension_name;
|
|
@@ -611,6 +629,37 @@ class JsonPointerHandler {
|
|
|
611
629
|
else
|
|
612
630
|
console.warn("WARN: failed registering pointer", fullPath, value);
|
|
613
631
|
}
|
|
632
|
+
// External EXR file reference (e.g. "StudioHDRI_ferndale_studio_04_1k.exr" in a ReflectionProbe)
|
|
633
|
+
// Inject the file into the document as a Texture so PMREM can process it
|
|
634
|
+
if (!isTexturePointer && value.match(/\.exr$/i)) {
|
|
635
|
+
const inputDir = _opaqueInputFile ? dirname(_opaqueInputFile) : '';
|
|
636
|
+
const exrPath = inputDir ? join(inputDir, value) : '';
|
|
637
|
+
if (exrPath && existsSync(exrPath)) {
|
|
638
|
+
// Check if we already injected this file
|
|
639
|
+
let texture = this.externalExrTextures.get(value);
|
|
640
|
+
if (!texture) {
|
|
641
|
+
const exrBytes = readFileSync(exrPath);
|
|
642
|
+
texture = this.document.createTexture(value)
|
|
643
|
+
.setImage(new Uint8Array(exrBytes))
|
|
644
|
+
.setMimeType('image/exr')
|
|
645
|
+
.setURI(value);
|
|
646
|
+
this.externalExrTextures.set(value, texture);
|
|
647
|
+
if (this.debug)
|
|
648
|
+
console.log(`Injected external EXR "${value}" as Texture`);
|
|
649
|
+
}
|
|
650
|
+
// Set a reference so gltf-transform doesn't prune it
|
|
651
|
+
prop.setReference(`exr_${value}`, texture, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
|
|
652
|
+
const buffer = this.document.getRoot().listBuffers()[0];
|
|
653
|
+
if (buffer)
|
|
654
|
+
prop.setReference(`exr_buffer_${value}`, buffer);
|
|
655
|
+
// At write time, update the property to the texture's current URI
|
|
656
|
+
// (PMREM will have updated it from "foo.exr" to "foo.pmrem.ktx2")
|
|
657
|
+
this.externalExrPointers.push({ obj, key, texture });
|
|
658
|
+
}
|
|
659
|
+
else if (exrPath) {
|
|
660
|
+
console.warn(`WARN: External EXR not found: ${exrPath}`);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
614
663
|
if (value.startsWith("/materials/")) {
|
|
615
664
|
if (this.debug)
|
|
616
665
|
console.log("Read pointer", value);
|
|
@@ -768,6 +817,25 @@ class JsonPointerHandler {
|
|
|
768
817
|
if (ptr.resolve(context, step))
|
|
769
818
|
ptr.write();
|
|
770
819
|
});
|
|
820
|
+
// Resolve external EXR pointers: update component data with the texture's current URI
|
|
821
|
+
for (const { obj, key, texture } of this.externalExrPointers) {
|
|
822
|
+
const uri = texture.getURI() || texture.getName() || '';
|
|
823
|
+
if (uri) {
|
|
824
|
+
if (this.debug)
|
|
825
|
+
console.log(`< Resolved external EXR: ${obj[key]} → ${uri}`);
|
|
826
|
+
obj[key] = uri;
|
|
827
|
+
// Ensure the image definition in the output JSON has the URI set.
|
|
828
|
+
// When PMREM clears image data (setImage(null)) for external textures,
|
|
829
|
+
// gltf-transform's core writer won't set a uri or bufferView on the image.
|
|
830
|
+
const imageIndex = context.imageIndexMap.get(texture);
|
|
831
|
+
if (imageIndex !== undefined) {
|
|
832
|
+
const images = context.jsonDoc.json.images;
|
|
833
|
+
if (images && images[imageIndex] && !images[imageIndex].uri) {
|
|
834
|
+
images[imageIndex].uri = uri;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
771
839
|
}
|
|
772
840
|
}
|
|
773
841
|
class JsonPointer {
|
|
@@ -862,7 +930,8 @@ class TextureIndexResolver extends PointerResolver {
|
|
|
862
930
|
resolve(context) {
|
|
863
931
|
const imgIndex = context.imageIndexMap.get(this.inputObject);
|
|
864
932
|
if (imgIndex === undefined) {
|
|
865
|
-
|
|
933
|
+
testAssert(false, `imageIndexMap missing texture: ${this.inputObject.getName() || "<unnamed>"}`);
|
|
934
|
+
console.error("ERR: image is missing");
|
|
866
935
|
return -1;
|
|
867
936
|
}
|
|
868
937
|
// ensure we have a texture array
|
|
@@ -883,10 +952,14 @@ class TextureIndexResolver extends PointerResolver {
|
|
|
883
952
|
// create a new texture def entry
|
|
884
953
|
if (this.debug)
|
|
885
954
|
console.log("Could not find texture, creating a new one: " + this._debugName);
|
|
886
|
-
// Remove
|
|
955
|
+
// Remove extensions that are consumed during processing and should not appear in the output.
|
|
887
956
|
let extensions = this.inputDefinition.extensions ? { ...this.inputDefinition.extensions } : undefined;
|
|
888
957
|
if (extensions) {
|
|
889
958
|
delete extensions[NEEDLE_progressive_texture_settings.EXTENSION_NAME];
|
|
959
|
+
// Remove EXT_texture_exr if the texture was converted (e.g. EXR → KTX2 via PMREM)
|
|
960
|
+
if (extensions["EXT_texture_exr"] && this.inputObject.getMimeType() !== "image/exr") {
|
|
961
|
+
delete extensions["EXT_texture_exr"];
|
|
962
|
+
}
|
|
890
963
|
if (Object.keys(extensions).length === 0)
|
|
891
964
|
extensions = undefined;
|
|
892
965
|
}
|
|
@@ -10,7 +10,7 @@ export const ALL_EXTENSIONS = [
|
|
|
10
10
|
createOpaqueExtension("NEEDLE_gameobject_data", PropertyType.NODE, { ...opaqueOptions }),
|
|
11
11
|
createOpaqueExtension("NEEDLE_components", PropertyType.NODE, { ...opaqueOptions }),
|
|
12
12
|
createOpaqueExtension("NEEDLE_persistent_assets", PropertyType.ROOT, { ...opaqueOptions }),
|
|
13
|
-
|
|
13
|
+
// NEEDLE_lightmaps is now handled by its own dedicated extension (NEEDLE_lightmaps/index.ts)
|
|
14
14
|
createOpaqueExtension("NEEDLE_lighting_settings", PropertyType.ROOT, { ...opaqueOptions }),
|
|
15
15
|
createOpaqueExtension("NEEDLE_render_objects", PropertyType.ROOT, { ...opaqueOptions }),
|
|
16
16
|
createOpaqueExtension("NEEDLE_progressive", [PropertyType.TEXTURE, PropertyType.MATERIAL, PropertyType.MESH], { ...opaqueOptions }),
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Extension, PropertyType, ReaderContext, Texture, WriterContext } from '@gltf-transform/core';
|
|
2
|
+
/**
|
|
3
|
+
* NEEDLE_pmrem extension for gltf-transform.
|
|
4
|
+
* Marks textures that have been pre-processed with PMREM (EXR → KTX2 HDR).
|
|
5
|
+
* At write time, adds `NEEDLE_pmrem: { source: imageIndex }` to each marked texture
|
|
6
|
+
* so the Needle Engine runtime can load them correctly with CubeUVReflectionMapping.
|
|
7
|
+
*/
|
|
8
|
+
export declare class NEEDLE_pmrem extends Extension {
|
|
9
|
+
static readonly EXTENSION_NAME = "NEEDLE_pmrem";
|
|
10
|
+
readonly extensionName = "NEEDLE_pmrem";
|
|
11
|
+
/** Textures that were converted from EXR via PMREM */
|
|
12
|
+
private readonly pmremTextures;
|
|
13
|
+
/** Mark a texture as PMREM-converted */
|
|
14
|
+
addTexture(texture: Texture): void;
|
|
15
|
+
/** @hidden */
|
|
16
|
+
preread(context: ReaderContext, _propertyType: PropertyType): this;
|
|
17
|
+
/** @hidden */
|
|
18
|
+
read(context: ReaderContext): this;
|
|
19
|
+
/** @hidden */
|
|
20
|
+
write(context: WriterContext): this;
|
|
21
|
+
}
|