@needle-tools/gltf-build-pipeline 2.15.0-next.0c5bc39 → 2.15.0-next.18cdb52

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.
@@ -415,6 +415,10 @@ class TextureHandler {
415
415
  }
416
416
  }
417
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
+ }
418
422
  // Resolve the current image index from the gltf-transform graph reference.
419
423
  // This is stable even after dedup/prune operations that re-index images.
420
424
  const imageIndex = ctx.imageIndexMap.get(this.textureRef);
@@ -889,10 +893,14 @@ class TextureIndexResolver extends PointerResolver {
889
893
  // create a new texture def entry
890
894
  if (this.debug)
891
895
  console.log("Could not find texture, creating a new one: " + this._debugName);
892
- // 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.
893
897
  let extensions = this.inputDefinition.extensions ? { ...this.inputDefinition.extensions } : undefined;
894
898
  if (extensions) {
895
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
+ }
896
904
  if (Object.keys(extensions).length === 0)
897
905
  extensions = undefined;
898
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,7 +5,7 @@ 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";
@@ -57,6 +57,7 @@ export async function packGLTF(inputFile, outputFile, options) {
57
57
  .registerExtensions([
58
58
  NEEDLE_compression_texture,
59
59
  NEEDLE_mesh_compression,
60
+ NEEDLE_pmrem,
60
61
  ])
61
62
  .registerDependencies({
62
63
  'draco3d.decoder': await draco3d.createDecoderModule(),
@@ -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,172 @@
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.debug('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.debug(`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
+ // Report size (< 100 KB report in KB otherwise in MB)
133
+ const sizeStr = image.byteLength < 100 * 1024
134
+ ? `${(image.byteLength / 1024).toFixed(0)} KB`
135
+ : `${(image.byteLength / (1024 * 1024)).toFixed(2)} MB`;
136
+ const dstSizestr = ktx2Bytes.length < 100 * 1024
137
+ ? `${(ktx2Bytes.length / 1024).toFixed(0)} KB`
138
+ : `${(ktx2Bytes.length / (1024 * 1024)).toFixed(2)} MB`;
139
+ this.logger.info(`pmrem:texture[${index}] ${name}: ${sizeStr} EXR → ${dstSizestr} KTX2`);
140
+ this.convertedTextures.push(texture);
141
+ this.processed++;
142
+ return true;
143
+ }
144
+ async finalize(document) {
145
+ if (this.processed > 0) {
146
+ // Register NEEDLE_pmrem extension and mark converted textures
147
+ // Note: we do NOT register KHR_texture_basisu here — the NEEDLE_pmrem extension
148
+ // writer removes KHR_texture_basisu from texture defs so the runtime NEEDLE_pmrem
149
+ // plugin handles loading instead of three.js's built-in handler.
150
+ const pmremExt = document.createExtension(NEEDLE_pmrem);
151
+ for (const tex of this.convertedTextures) {
152
+ pmremExt.addTexture(tex);
153
+ }
154
+ // If no textures use EXR anymore, remove the EXT_texture_exr extension from the document
155
+ const hasExr = document.getRoot().listTextures().some(t => t.getMimeType() === 'image/exr');
156
+ if (!hasExr) {
157
+ const exrExt = document.getRoot().listExtensionsUsed()
158
+ .find(e => e.extensionName === 'EXT_texture_exr');
159
+ if (exrExt) {
160
+ exrExt.dispose();
161
+ }
162
+ }
163
+ }
164
+ // Clean up temp directory
165
+ if (this.tmpDir && existsSync(this.tmpDir)) {
166
+ try {
167
+ rmSync(this.tmpDir, { recursive: true });
168
+ }
169
+ catch { /* ignore */ }
170
+ }
171
+ }
172
+ }
@@ -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);
@@ -1 +1 @@
1
- export declare const version = "2.15.0-next.0c5bc39";
1
+ export declare const version = "2.15.0-next.18cdb52";
@@ -1 +1 @@
1
- export const version = "2.15.0-next.0c5bc39";
1
+ export const version = "2.15.0-next.18cdb52";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@needle-tools/gltf-build-pipeline",
3
- "version": "2.15.0-next.0c5bc39",
3
+ "version": "2.15.0-next.18cdb52",
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",
@@ -21,6 +21,7 @@
21
21
  "files": [
22
22
  "dist",
23
23
  "scripts",
24
+ "tools/pmrem",
24
25
  "README.md",
25
26
  "CHANGELOG.md"
26
27
  ],
@@ -42,7 +43,8 @@
42
43
  "dev:pack-gltf": "npm run compile && node scripts/pack-gltf.mjs",
43
44
  "test": "tsx tests/utils/download-fixtures.ts && vitest run",
44
45
  "test:watch": "vitest",
45
- "test:setup": "tsx tests/utils/download-fixtures.ts"
46
+ "test:setup": "tsx tests/utils/download-fixtures.ts",
47
+ "update-pmrem": "node update-pmrem.mjs"
46
48
  },
47
49
  "devDependencies": {
48
50
  "@types/node": "^22.19.15",
Binary file
Binary file
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }