@needle-tools/gltf-build-pipeline 2.15.0-next.a25e7ea → 2.15.0-next.adb3357

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,4 +1,5 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
+ /// <reference types="node" resolution-mode="require"/>
2
3
  import { ExtensibleProperty } from "@gltf-transform/core";
3
4
  import { Logger } from "@donmccurdy/caporal";
4
5
  /**
@@ -2,6 +2,7 @@ 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';
5
6
  const ALL_PROPERTY_TYPES = [];
6
7
  for (const key in PropertyType) {
7
8
  ALL_PROPERTY_TYPES.push(PropertyType[key]);
@@ -414,11 +415,16 @@ class TextureHandler {
414
415
  }
415
416
  }
416
417
  write(ctx) {
418
+ // If the texture was converted (e.g. EXR → KTX2 via PMREM), skip writing the old extension
419
+ if (this.key === "EXT_texture_exr" && this.textureRef.getMimeType() !== "image/exr") {
420
+ return;
421
+ }
417
422
  // Resolve the current image index from the gltf-transform graph reference.
418
423
  // This is stable even after dedup/prune operations that re-index images.
419
424
  const imageIndex = ctx.imageIndexMap.get(this.textureRef);
425
+ testAssert(imageIndex !== undefined || this.key === "EXT_texture_exr", `imageIndexMap missing texture ref for "${this.key}": ${this.textureRef.getName() || "<unnamed>"}`);
420
426
  if (imageIndex === undefined) {
421
- if (this.key !== "EXT_texture_exr" && this.debug) {
427
+ if (this.debug) {
422
428
  console.warn("WARN: failed to resolve image index for texture via imageIndexMap:", this.key, this.textureRef.getName() || "<unnamed>");
423
429
  }
424
430
  return;
@@ -430,10 +436,10 @@ class TextureHandler {
430
436
  return;
431
437
  const textureImageIndex = this.tryGetSourceIndex(textureDef);
432
438
  if (imageIndex === textureImageIndex) {
433
- if (!textureDef.extensions || !textureDef.extensions[this.key]) {
434
- // assign texture extension again
439
+ foundTexture = true;
440
+ if (!textureDef.extensions?.[this.key]) {
441
+ // assign texture extension
435
442
  textureDef.extensions = textureDef.extensions || {};
436
- foundTexture = true;
437
443
  if (this.debug)
438
444
  console.log("Re-Assign extension:", this.key, "at", i);
439
445
  const newExt = { ...this.ext };
@@ -441,10 +447,13 @@ class TextureHandler {
441
447
  newExt.source = imageIndex;
442
448
  textureDef.extensions[this.key] = newExt;
443
449
  }
450
+ // else: extension already written by another handler for the same image
451
+ // (happens when gltf-transform dedup merges texture defs that shared the same source)
444
452
  }
445
453
  });
454
+ 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
455
  if (foundTexture === false) {
447
- if (this.key !== "EXT_texture_exr" && this.debug) {
456
+ if (this.debug) {
448
457
  console.warn("WARN: failed to re-assign extension:", this.key, "imageIndex", imageIndex, textureDefs.length, this.textureRef.getName() || "<unnamed>", this.textureDefinition);
449
458
  }
450
459
  }
@@ -862,7 +871,8 @@ class TextureIndexResolver extends PointerResolver {
862
871
  resolve(context) {
863
872
  const imgIndex = context.imageIndexMap.get(this.inputObject);
864
873
  if (imgIndex === undefined) {
865
- console.error("ERR: image is missing", imgIndex);
874
+ testAssert(false, `imageIndexMap missing texture: ${this.inputObject.getName() || "<unnamed>"}`);
875
+ console.error("ERR: image is missing");
866
876
  return -1;
867
877
  }
868
878
  // ensure we have a texture array
@@ -883,10 +893,14 @@ class TextureIndexResolver extends PointerResolver {
883
893
  // create a new texture def entry
884
894
  if (this.debug)
885
895
  console.log("Could not find texture, creating a new one: " + this._debugName);
886
- // Remove settings-only extensions that are consumed during processing and should not appear in the output.
896
+ // Remove extensions that are consumed during processing and should not appear in the output.
887
897
  let extensions = this.inputDefinition.extensions ? { ...this.inputDefinition.extensions } : undefined;
888
898
  if (extensions) {
889
899
  delete extensions[NEEDLE_progressive_texture_settings.EXTENSION_NAME];
900
+ // Remove EXT_texture_exr if the texture was converted (e.g. EXR → KTX2 via PMREM)
901
+ if (extensions["EXT_texture_exr"] && this.inputObject.getMimeType() !== "image/exr") {
902
+ delete extensions["EXT_texture_exr"];
903
+ }
890
904
  if (Object.keys(extensions).length === 0)
891
905
  extensions = undefined;
892
906
  }
@@ -0,0 +1,19 @@
1
+ import { Extension, 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
+ read(): this;
17
+ /** @hidden */
18
+ write(context: WriterContext): this;
19
+ }
@@ -0,0 +1,44 @@
1
+ import { Extension } from '@gltf-transform/core';
2
+ const EXTENSION_NAME = 'NEEDLE_pmrem';
3
+ /**
4
+ * NEEDLE_pmrem extension for gltf-transform.
5
+ * Marks textures that have been pre-processed with PMREM (EXR → KTX2 HDR).
6
+ * At write time, adds `NEEDLE_pmrem: { source: imageIndex }` to each marked texture
7
+ * so the Needle Engine runtime can load them correctly with CubeUVReflectionMapping.
8
+ */
9
+ export class NEEDLE_pmrem extends Extension {
10
+ static EXTENSION_NAME = EXTENSION_NAME;
11
+ extensionName = EXTENSION_NAME;
12
+ /** Textures that were converted from EXR via PMREM */
13
+ pmremTextures = new Set();
14
+ /** Mark a texture as PMREM-converted */
15
+ addTexture(texture) {
16
+ this.pmremTextures.add(texture);
17
+ }
18
+ /** @hidden */
19
+ read() {
20
+ return this;
21
+ }
22
+ /** @hidden */
23
+ write(context) {
24
+ const jsonDoc = context.jsonDoc;
25
+ for (const texture of this.pmremTextures) {
26
+ const imageIndex = context.imageIndexMap.get(texture);
27
+ if (imageIndex === undefined)
28
+ continue;
29
+ // Find texture defs that reference this image
30
+ for (const textureDef of jsonDoc.json.textures ?? []) {
31
+ const source = textureDef.source
32
+ ?? textureDef.extensions?.['KHR_texture_basisu']?.source;
33
+ if (source === imageIndex) {
34
+ textureDef.extensions = textureDef.extensions || {};
35
+ textureDef.extensions[EXTENSION_NAME] = { source: imageIndex };
36
+ // Remove KHR_texture_basisu so the runtime NEEDLE_pmrem plugin handles loading
37
+ // (otherwise three.js's built-in KHR_texture_basisu handler intercepts it first)
38
+ delete textureDef.extensions['KHR_texture_basisu'];
39
+ }
40
+ }
41
+ }
42
+ return this;
43
+ }
44
+ }
@@ -4,4 +4,5 @@ export * from "./NEEDLE_compression_texture/index.js";
4
4
  export * from "./NEEDLE_progressive/index.js";
5
5
  export * from "./NEEDLE_progressive_texture_settings/index.js";
6
6
  export * from "./NEEDLE_progressive_mesh_settings/index.js";
7
+ export * from "./NEEDLE_pmrem/index.js";
7
8
  export declare function registerExtensions(node: any): void;
@@ -5,6 +5,7 @@ export * from "./NEEDLE_compression_texture/index.js";
5
5
  export * from "./NEEDLE_progressive/index.js";
6
6
  export * from "./NEEDLE_progressive_texture_settings/index.js";
7
7
  export * from "./NEEDLE_progressive_mesh_settings/index.js";
8
+ export * from "./NEEDLE_pmrem/index.js";
8
9
  import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
9
10
  import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS } from "./NEEDLE_opaque/index.js";
10
11
  import { NEEDLE_progressive } from './NEEDLE_progressive/index.js';
@@ -5,10 +5,11 @@ import draco3d from 'draco3dgltf';
5
5
  import { existsSync, readFileSync, statSync, writeFileSync } from 'fs';
6
6
  import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
7
7
  import { dedup, metalRough, prune, resample } from '@gltf-transform/functions';
8
- import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS, NEEDLE_compression_texture, NEEDLE_mesh_compression, } from '../extensions/index.js';
8
+ import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS, NEEDLE_compression_texture, NEEDLE_mesh_compression, NEEDLE_pmrem, } from '../extensions/index.js';
9
9
  import { isLOD, isMeshLOD, needle_animation_transform, needle_asset, needle_mesh_transform, needle_texture_transform, } from '../transforms/index.js';
10
10
  import { getOutputPath, getVersion, ioTryReadWithMissingResources, writeNodeIO } from "../utils/index.js";
11
11
  import { addToCache, getHash, tryGetFromCache, } from "../cache/index.js";
12
+ import { TestAssertionError } from '../utils/test-assert.js';
12
13
  /** Compress a glTF file
13
14
  */
14
15
  export async function packGLTF(inputFile, outputFile, options) {
@@ -56,6 +57,7 @@ export async function packGLTF(inputFile, outputFile, options) {
56
57
  .registerExtensions([
57
58
  NEEDLE_compression_texture,
58
59
  NEEDLE_mesh_compression,
60
+ NEEDLE_pmrem,
59
61
  ])
60
62
  .registerDependencies({
61
63
  'draco3d.decoder': await draco3d.createDecoderModule(),
@@ -64,8 +66,13 @@ export async function packGLTF(inputFile, outputFile, options) {
64
66
  'meshopt.encoder': MeshoptEncoder,
65
67
  });
66
68
  const document = await ioTryReadWithMissingResources(io, inputFile); // await io.read(inputFile);
67
- /** @ts-ignore */
68
- document.getLogger().verbosity = options.verbose ? Verbosity.DEBUG : options.debug ? Verbosity.INFO : Verbosity.WARN;
69
+ if (options.logger) {
70
+ document.setLogger(options.logger);
71
+ }
72
+ else {
73
+ /** @ts-ignore */
74
+ document.getLogger().verbosity = options.verbose ? Verbosity.DEBUG : options.debug ? Verbosity.INFO : Verbosity.WARN;
75
+ }
69
76
  let totalGPUTextureMemory = 0;
70
77
  /** @type {Array<import('@gltf-transform/core').Transform>} */
71
78
  const transforms = [
@@ -128,6 +135,8 @@ export async function packGLTF(inputFile, outputFile, options) {
128
135
  return true;
129
136
  }
130
137
  catch (err) {
138
+ if (err instanceof TestAssertionError)
139
+ throw err;
131
140
  const shortedStackTrace = err instanceof Error && err.stack ? err.stack.split('\n').slice(0, 2).join('\n') : '';
132
141
  logger.error(`Packing of "${path.basename(inputFile)}" using version ${getVersion()} failed with error:\n${err.message}\n${shortedStackTrace}`);
133
142
  if (debug)
@@ -0,0 +1,16 @@
1
+ import { Document, Texture } from '@gltf-transform/core';
2
+ import { NEEDLE_compression_texture_schema } from '../extensions/index.js';
3
+ import { INeedleTextureTransformContext, NeedleTransformContext } from './needle_common.js';
4
+ export declare class NeedlePmremContext implements INeedleTextureTransformContext {
5
+ private wasmModule;
6
+ private pmremDir;
7
+ private basisuExe;
8
+ private tmpDir;
9
+ private processed;
10
+ private available;
11
+ private logger;
12
+ private readonly convertedTextures;
13
+ prepare(document: Document): Promise<boolean>;
14
+ process(index: number, texture: Texture, _settings: NEEDLE_compression_texture_schema | null, _context: NeedleTransformContext): Promise<boolean>;
15
+ finalize(document: Document): Promise<void>;
16
+ }
@@ -0,0 +1,167 @@
1
+ import { NEEDLE_pmrem } from '../extensions/index.js';
2
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, chmodSync } from 'fs';
3
+ import { join, dirname } from 'path';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
+ import { execFile } from 'child_process';
6
+ import { v4 as uuid } from 'uuid';
7
+ import tmp from 'tmp';
8
+ /** Resolve the tools/pmrem/ directory relative to this file.
9
+ * At runtime this file is at dist/transforms/needle_pmrem.js,
10
+ * so tools/pmrem/ is at ../../tools/pmrem/ */
11
+ function getPmremDir() {
12
+ const thisDir = dirname(fileURLToPath(import.meta.url));
13
+ return join(thisDir, '..', '..', 'tools', 'pmrem');
14
+ }
15
+ function resolveBasisuExe(pmremDir) {
16
+ const platform = process.platform;
17
+ const base = join(pmremDir, 'basis');
18
+ if (platform === 'win32')
19
+ return join(base, 'win', 'basisu.exe');
20
+ if (platform === 'darwin')
21
+ return join(base, 'osx', 'basisu');
22
+ return join(base, 'linux', 'basisu');
23
+ }
24
+ function encodeKTX2WithBasisu(basisuExe, exrPath, outPath, variant, mipmaps) {
25
+ return new Promise((resolve, reject) => {
26
+ const args = [];
27
+ args.push(variant === 'hdr6x6' ? '-hdr_6x6' : '-hdr_4x4');
28
+ if (mipmaps)
29
+ args.push('-mipmap');
30
+ args.push('-file', exrPath, '-output_file', outPath, '-y_flip');
31
+ execFile(basisuExe, args, { windowsHide: true, encoding: 'utf8' }, (err, _stdout, stderr) => {
32
+ if (err) {
33
+ reject(new Error(`basisu failed: ${stderr || err.message}`));
34
+ return;
35
+ }
36
+ resolve();
37
+ });
38
+ });
39
+ }
40
+ export class NeedlePmremContext {
41
+ wasmModule = null;
42
+ pmremDir = '';
43
+ basisuExe = '';
44
+ tmpDir = '';
45
+ processed = 0;
46
+ available = false;
47
+ logger;
48
+ convertedTextures = [];
49
+ async prepare(document) {
50
+ this.logger = document.getLogger();
51
+ this.processed = 0;
52
+ this.pmremDir = getPmremDir();
53
+ // Check WASM exists
54
+ const wasmJsPath = join(this.pmremDir, 'pkg', 'pmrem_wasm.js');
55
+ const wasmBinPath = join(this.pmremDir, 'pkg', 'pmrem_wasm_bg.wasm');
56
+ if (!existsSync(wasmJsPath) || !existsSync(wasmBinPath)) {
57
+ this.logger.warn('pmrem: WASM not found — EXR textures will not be processed');
58
+ return false;
59
+ }
60
+ // Check basisu binary
61
+ this.basisuExe = resolveBasisuExe(this.pmremDir);
62
+ if (!existsSync(this.basisuExe)) {
63
+ this.logger.warn(`pmrem: basisu binary not found at ${this.basisuExe} — EXR textures will not be processed`);
64
+ return false;
65
+ }
66
+ // Set executable permission
67
+ if (process.platform !== 'win32') {
68
+ try {
69
+ chmodSync(this.basisuExe, 0o755);
70
+ }
71
+ catch { /* ignore */ }
72
+ }
73
+ // Load WASM
74
+ try {
75
+ const mod = await import(pathToFileURL(wasmJsPath).href);
76
+ const wasmBytes = readFileSync(wasmBinPath);
77
+ await mod.default({ module_or_path: wasmBytes });
78
+ this.wasmModule = mod;
79
+ }
80
+ catch (err) {
81
+ this.logger.warn(`pmrem: Failed to load WASM — ${err.message}`);
82
+ return false;
83
+ }
84
+ // Create temp directory
85
+ this.tmpDir = join(tmp.tmpdir, 'needle-pmrem');
86
+ mkdirSync(this.tmpDir, { recursive: true });
87
+ this.available = true;
88
+ this.logger.info('pmrem: Ready (WASM + basisu loaded)');
89
+ return true;
90
+ }
91
+ async process(index, texture, _settings, _context) {
92
+ if (!this.available)
93
+ return false;
94
+ if (texture.getMimeType() !== 'image/exr')
95
+ return false;
96
+ const image = texture.getImage();
97
+ if (!image)
98
+ return false;
99
+ const name = texture.getName() || `texture_${index}`;
100
+ const id = uuid();
101
+ // 1. Run PMREM on the EXR bytes
102
+ this.logger.info(`pmrem:texture[${index}] ${name}: Running PMREM...`);
103
+ const exrBytes = new Uint8Array(image.buffer, image.byteOffset, image.byteLength);
104
+ const pmremExrBytes = this.wasmModule.pmrem_exr(exrBytes);
105
+ // 2. Write PMREM EXR to temp file
106
+ const tempExr = join(this.tmpDir, `${id}.pmrem.exr`);
107
+ const tempKtx2 = join(this.tmpDir, `${id}.ktx2`);
108
+ writeFileSync(tempExr, Buffer.from(pmremExrBytes));
109
+ // 3. Encode to KTX2 HDR via basisu
110
+ this.logger.info(`pmrem:texture[${index}] ${name}: Encoding KTX2 HDR...`);
111
+ const variant = 'hdr4x4'; // 6x6 needs an update in Needle
112
+ await encodeKTX2WithBasisu(this.basisuExe, tempExr, tempKtx2, variant, true);
113
+ if (!existsSync(tempKtx2)) {
114
+ throw new Error(`pmrem:texture[${index}] ${name}: basisu did not produce output`);
115
+ }
116
+ // 4. Read KTX2 and update texture
117
+ const ktx2Bytes = readFileSync(tempKtx2);
118
+ texture.setImage(new Uint8Array(ktx2Bytes));
119
+ texture.setMimeType('image/ktx2');
120
+ // Remove EXT_texture_exr property since the texture is now KTX2
121
+ const exrProp = texture.getExtension('EXT_texture_exr');
122
+ if (exrProp) {
123
+ texture.setExtension('EXT_texture_exr', null);
124
+ exrProp.dispose();
125
+ }
126
+ // Update URI
127
+ const uri = texture.getURI();
128
+ if (uri) {
129
+ const newUri = uri.replace(/\.exr$/i, '.pmrem.ktx2');
130
+ texture.setURI(newUri !== uri ? newUri : uri + '.pmrem.ktx2');
131
+ }
132
+ const srcKB = (image.byteLength / 1024).toFixed(0);
133
+ const dstKB = (ktx2Bytes.byteLength / 1024).toFixed(0);
134
+ this.logger.info(`pmrem:texture[${index}] ${name}: ${srcKB} KB EXR → ${dstKB} KB KTX2`);
135
+ this.convertedTextures.push(texture);
136
+ this.processed++;
137
+ return true;
138
+ }
139
+ async finalize(document) {
140
+ if (this.processed > 0) {
141
+ // Register NEEDLE_pmrem extension and mark converted textures
142
+ // Note: we do NOT register KHR_texture_basisu here — the NEEDLE_pmrem extension
143
+ // writer removes KHR_texture_basisu from texture defs so the runtime NEEDLE_pmrem
144
+ // plugin handles loading instead of three.js's built-in handler.
145
+ const pmremExt = document.createExtension(NEEDLE_pmrem);
146
+ for (const tex of this.convertedTextures) {
147
+ pmremExt.addTexture(tex);
148
+ }
149
+ // If no textures use EXR anymore, remove the EXT_texture_exr extension from the document
150
+ const hasExr = document.getRoot().listTextures().some(t => t.getMimeType() === 'image/exr');
151
+ if (!hasExr) {
152
+ const exrExt = document.getRoot().listExtensionsUsed()
153
+ .find(e => e.extensionName === 'EXT_texture_exr');
154
+ if (exrExt) {
155
+ exrExt.dispose();
156
+ }
157
+ }
158
+ }
159
+ // Clean up temp directory
160
+ if (this.tmpDir && existsSync(this.tmpDir)) {
161
+ try {
162
+ rmSync(this.tmpDir, { recursive: true });
163
+ }
164
+ catch { /* ignore */ }
165
+ }
166
+ }
167
+ }
@@ -13,6 +13,7 @@ import { needle_asset, writeNeedleAsset } from './needle_asset.js';
13
13
  import { MeshoptDecoder, MeshoptEncoder, MeshoptSimplifier } from 'meshoptimizer';
14
14
  import { compressPrimitive, determineMeshCompression } from './needle_mesh_transform.js';
15
15
  import { calculateMeshDensity, getMeshInformation } from "../utils/mesh.js";
16
+ import { TestAssertionError } from '../utils/test-assert.js';
16
17
  export async function make_progressive(opts) {
17
18
  const file = opts.path;
18
19
  let success = true;
@@ -78,9 +79,14 @@ async function onProcess(file, opts) {
78
79
  });
79
80
  let document = await ioTryReadWithMissingResources(io, file); // await io.read(file);
80
81
  if (document) {
81
- const logger = document.getLogger();
82
- //@ts-ignore
83
- logger.verbosity = (opts.debug || opts.verbose) ? Verbosity.DEBUG : Verbosity.WARN;
82
+ if (opts.logger) {
83
+ document.setLogger(opts.logger);
84
+ }
85
+ else {
86
+ //@ts-ignore
87
+ document.getLogger().verbosity = (opts.debug || opts.verbose) ? Verbosity.DEBUG : Verbosity.WARN;
88
+ }
89
+ const logger = opts.logger || document.getLogger();
84
90
  let smallesTextureSize = 128;
85
91
  if (opts.config.usecase === "product") {
86
92
  smallesTextureSize = 512;
@@ -120,6 +126,8 @@ async function onProcess(file, opts) {
120
126
  }
121
127
  }
122
128
  catch (err) {
129
+ if (err instanceof TestAssertionError)
130
+ throw err;
123
131
  console.log("ERR: failed to process file \"" + file + "\", Reason: " + err.message, "\nStack:\n" + err.stack);
124
132
  return false;
125
133
  }
@@ -369,7 +377,7 @@ async function createTextureLod(args, opts) {
369
377
  // see https://linear.app/needle/issue/NE-4985
370
378
  newMaterial.setAlphaMode("BLEND");
371
379
  newMaterial.setBaseColorTexture(newTexture);
372
- continue;
380
+ break;
373
381
  }
374
382
  if (slot === "specularColorTexture") {
375
383
  logger.info("Pass-through KHR_materials_pbrSpecularGlossiness specularColorTexture");
@@ -377,7 +385,7 @@ async function createTextureLod(args, opts) {
377
385
  const prob = ext.createSpecular();
378
386
  prob.setSpecularColorTexture(newTexture);
379
387
  newMaterial.setExtension(KHRMaterialsSpecular.EXTENSION_NAME, prob);
380
- continue;
388
+ break;
381
389
  }
382
390
  else if (slot === "specularTexture") {
383
391
  logger.info("Pass-through KHR_materials_specular specularTexture");
@@ -385,7 +393,7 @@ async function createTextureLod(args, opts) {
385
393
  const prob = ext.createSpecular();
386
394
  prob.setSpecularTexture(newTexture);
387
395
  newMaterial.setExtension(KHRMaterialsSpecular.EXTENSION_NAME, prob);
388
- continue;
396
+ break;
389
397
  }
390
398
  logger.warn(`WARN: Unknown texture slot: ${slot} for texture ${textureIndex} → can not load progressively (all slots: ${slots.join(", ")})`);
391
399
  return null;
@@ -3,10 +3,12 @@ import { Transform } from '@gltf-transform/core';
3
3
  import { NeedleWebPContext } from "./needle_webp.js";
4
4
  import { NeedleTransformContext } from "./needle_common.js";
5
5
  import { NeedleToktxContext } from "./needle_toktx.js";
6
+ import { NeedlePmremContext } from "./needle_pmrem.js";
6
7
  export declare function resizeTextureIfNecessary(texture: Texture): Promise<void>;
7
8
  interface NeedleTextureTransformContext extends NeedleTransformContext {
8
9
  webPContext: NeedleWebPContext;
9
10
  toktxContext: NeedleToktxContext;
11
+ pmremContext: NeedlePmremContext;
10
12
  reportGPUMemory?: (bytes: number) => void;
11
13
  }
12
14
  export declare const needle_texture_transform: (options: NeedleTransformContext & Pick<NeedleTextureTransformContext, "reportGPUMemory">) => Transform;
@@ -4,6 +4,7 @@ import { NEEDLE_compression_texture } from '../extensions/index.js';
4
4
  import { addToCache, getHash, getKey, tryGetFromCache } from "../cache/index.js";
5
5
  import { NeedleWebPContext } from "./needle_webp.js";
6
6
  import { NeedleToktxContext } from "./needle_toktx.js";
7
+ import { NeedlePmremContext } from "./needle_pmrem.js";
7
8
  import { createTransform, listTextureSlots } from "@gltf-transform/functions";
8
9
  import { dirname } from "path";
9
10
  import { existsSync, rmSync } from "fs";
@@ -33,11 +34,13 @@ export const needle_texture_transform = function (options) {
33
34
  jobs: undefined,
34
35
  debug: options.debug,
35
36
  });
37
+ const pmremContext = new NeedlePmremContext();
36
38
  const context = {
37
39
  config: options.config,
38
40
  ...options,
39
41
  webPContext,
40
- toktxContext
42
+ toktxContext,
43
+ pmremContext
41
44
  };
42
45
  return createTransform("needle_texture_transform", async (document) => {
43
46
  await webPContext.prepare(document);
@@ -47,6 +50,7 @@ export const needle_texture_transform = function (options) {
47
50
  context.noToktx = true;
48
51
  }
49
52
  }
53
+ await pmremContext.prepare(document);
50
54
  try {
51
55
  const logger = document.getLogger();
52
56
  const textures = document.getRoot().listTextures();
@@ -79,6 +83,7 @@ export const needle_texture_transform = function (options) {
79
83
  await webPContext.finalize(document);
80
84
  if (context.noToktx !== true)
81
85
  await toktxContext.finalize(document);
86
+ await pmremContext.finalize(document);
82
87
  }
83
88
  });
84
89
  };
@@ -89,8 +94,13 @@ async function processTexture(texture, index, document, logger, context) {
89
94
  texture.setMimeType(validationResult.mimeType);
90
95
  }
91
96
  const originalMimeType = texture.getMimeType();
97
+ // Handle EXR textures via PMREM → KTX2 HDR
98
+ if (originalMimeType === "image/exr") {
99
+ await context.pmremContext.process(index, texture, null, context);
100
+ return;
101
+ }
92
102
  const isSupported = originalMimeType === "image/jpeg" || originalMimeType === "image/png" || originalMimeType === "image/webp";
93
- // dont try to transform EXR or already processed textures
103
+ // dont try to transform already processed textures
94
104
  if (!isSupported)
95
105
  return;
96
106
  const ext = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME);
@@ -0,0 +1,8 @@
1
+ export declare class TestAssertionError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ /**
5
+ * Lightweight assertion that throws under vitest and is a no-op in production.
6
+ * Use as a one-liner in pipeline code to catch regressions during tests.
7
+ */
8
+ export declare function testAssert(condition: boolean, message: string): void;
@@ -0,0 +1,18 @@
1
+ const IS_TEST = process.env.VITEST === 'true';
2
+ export class TestAssertionError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = 'TestAssertionError';
6
+ }
7
+ }
8
+ /**
9
+ * Lightweight assertion that throws under vitest and is a no-op in production.
10
+ * Use as a one-liner in pipeline code to catch regressions during tests.
11
+ */
12
+ export function testAssert(condition, message) {
13
+ if (condition)
14
+ return;
15
+ if (IS_TEST) {
16
+ throw new TestAssertionError(`Assertion failed: ${message}`);
17
+ }
18
+ }
@@ -1 +1 @@
1
- export declare const version = "2.15.0-next.a25e7ea";
1
+ export declare const version = "2.15.0-next.adb3357";
@@ -1 +1 @@
1
- export const version = "2.15.0-next.a25e7ea";
1
+ export const version = "2.15.0-next.adb3357";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/gltf-build-pipeline",
3
- "version": "2.15.0-next.a25e7ea",
3
+ "version": "2.15.0-next.adb3357",
4
4
  "description": "Pipeline and tools for optimizing gltf files using gltf-transform and compression settings within glTF extensions",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -18,6 +18,13 @@
18
18
  "gltf-build-pipeline": "dist/cli/index.js",
19
19
  "needle-gltf": "dist/cli/index.js"
20
20
  },
21
+ "files": [
22
+ "dist",
23
+ "scripts",
24
+ "tools/pmrem",
25
+ "README.md",
26
+ "CHANGELOG.md"
27
+ ],
21
28
  "imports": {
22
29
  "#package.json": "./package.json"
23
30
  },
@@ -33,12 +40,19 @@
33
40
  "transform:make-progressive": "node scripts/make-progressive.mjs",
34
41
  "transform:pack-gltf": "node --no-experimental-fetch scripts/pack-gltf.mjs",
35
42
  "pack-gltf": "node --no-experimental-fetch scripts/pack-gltf.mjs",
36
- "dev:pack-gltf": "npm run compile && node scripts/pack-gltf.mjs"
43
+ "dev:pack-gltf": "npm run compile && node scripts/pack-gltf.mjs",
44
+ "test": "tsx tests/utils/download-fixtures.ts && vitest run",
45
+ "test:watch": "vitest",
46
+ "test:setup": "tsx tests/utils/download-fixtures.ts",
47
+ "update-pmrem": "node update-pmrem.mjs"
37
48
  },
38
49
  "devDependencies": {
39
- "@types/node": "^18.7.23",
50
+ "@types/node": "^22.19.15",
51
+ "gltf-validator": "^2.0.0-dev.3.9",
40
52
  "npm-watch": "^0.13.0",
41
- "typescript": "^4.9.5"
53
+ "tsx": "^4.19.0",
54
+ "typescript": "^4.9.5",
55
+ "vitest": "^3.1.1"
42
56
  },
43
57
  "optionalDependencies": {
44
58
  "@img/sharp-darwin-arm64": "^0.33.4",
Binary file
Binary file
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }