@needle-tools/gltf-build-pipeline 1.6.0-alpha.7 → 2.1.0-alpha

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,4 @@
1
- import { Extension, ExtensionProperty, PropertyType } from '@gltf-transform/core';
1
+ import { Extension, ExtensionProperty, PropertyType, TextureChannel } from '@gltf-transform/core';
2
2
  import { getTexture, tryGetInArray, writeExtension } from '../utils.js';
3
3
  const ALL_PROPERTY_TYPES = [];
4
4
  for (const key in PropertyType) {
@@ -16,6 +16,7 @@ export function createOpaqueExtension(name, types, opts) {
16
16
  class NEEDLE_opaque extends Extension {
17
17
  extensionName = EXTENSION_NAME;
18
18
  static EXTENSION_NAME = EXTENSION_NAME;
19
+ prewriteTypes = [PropertyType.MATERIAL];
19
20
  // private roots: Array<OpaqueProperty> = [];
20
21
  jsonPointerHandler;
21
22
  read(context) {
@@ -118,8 +119,8 @@ export function createOpaqueExtension(name, types, opts) {
118
119
  console.log("WARN: could potentially not find gltf transform texture for " + index);
119
120
  texture = context.textures[index];
120
121
  }
121
- this.jsonPointerHandler.read(context, texture, ext);
122
122
  const prop = this.createExtension();
123
+ this.jsonPointerHandler.read(context, texture, ext, prop);
123
124
  texture.setExtension(EXTENSION_NAME, prop);
124
125
  const handler = new TextureHandler(this.document, textureDefinition, EXTENSION_NAME, ext, debugLog);
125
126
  prop.add(handler);
@@ -142,8 +143,8 @@ export function createOpaqueExtension(name, types, opts) {
142
143
  if (!ext)
143
144
  return;
144
145
  const primitive = primitives[primitiveIndex];
145
- this.jsonPointerHandler.read(context, primitive, ext);
146
146
  const prop = this.createExtension();
147
+ this.jsonPointerHandler.read(context, primitive, ext, prop);
147
148
  primitive.setExtension(EXTENSION_NAME, prop);
148
149
  // this is invoked on write
149
150
  prop.add(ctx => {
@@ -164,8 +165,8 @@ export function createOpaqueExtension(name, types, opts) {
164
165
  if (ext) {
165
166
  this.lightmapWorkaround(context);
166
167
  const root = this.document.getRoot();
167
- this.jsonPointerHandler.read(context, root, ext);
168
168
  const prop = this.createExtension();
169
+ this.jsonPointerHandler.read(context, root, ext, prop);
169
170
  root.setExtension(EXTENSION_NAME, prop);
170
171
  prop.add(ctx => {
171
172
  ctx.jsonDoc.json.extensions = ctx.jsonDoc.json.extensions || {};
@@ -224,6 +225,13 @@ export function createOpaqueExtension(name, types, opts) {
224
225
  console.error("ERR: " + error);
225
226
  }
226
227
  }
228
+ prewrite(context, _propertyType) {
229
+ // Attempt resolve textures here so that the json.textures is already populated for cases where a texture isn't used by any material
230
+ // this is e.g. the case for textures that are just referenced by a component but not used by any texture
231
+ // https://linear.app/needle/issue/NE-4928
232
+ this.jsonPointerHandler.resolveAndWrite(context, "prewrite");
233
+ return this;
234
+ }
227
235
  write(context) {
228
236
  if (opts?.breakpoint === true)
229
237
  debugger;
@@ -232,7 +240,7 @@ export function createOpaqueExtension(name, types, opts) {
232
240
  }
233
241
  if (debugLog)
234
242
  console.log("WRITE " + EXTENSION_NAME);
235
- this.jsonPointerHandler.resolveAndWrite(context);
243
+ this.jsonPointerHandler.resolveAndWrite(context, "write");
236
244
  const root = this.document.getRoot();
237
245
  // for (const rootExt of this.roots) {
238
246
  // rootExt.onWrite(context, root);
@@ -313,11 +321,11 @@ export function createOpaqueExtension(name, types, opts) {
313
321
  extensionName = typeof EXTENSION_NAME;
314
322
  parentTypes = ExtensionPropertyTypes;
315
323
  propertyType = "NEEDLE_opaque_property";
316
- setReference(name, value) {
317
- this.setRef(name, value, { modifyChild: true });
318
- }
319
324
  init() {
320
325
  }
326
+ setReference(name, value, attributes = { modifyChild: true }) {
327
+ this.setRef(name, value, attributes);
328
+ }
321
329
  writers = [];
322
330
  add(writer) {
323
331
  if (typeof writer === "function") {
@@ -520,7 +528,7 @@ class JsonPointerHandler {
520
528
  this.document = document;
521
529
  this.id = id;
522
530
  }
523
- read(context, prop, obj, ext, key, fullPath) {
531
+ read(context, extProp, obj, prop, key, fullPath) {
524
532
  const value = key !== undefined ? obj[key] : obj;
525
533
  // the pointer path contains the full path from the root object to the json pointer
526
534
  if (key !== undefined) {
@@ -535,7 +543,7 @@ class JsonPointerHandler {
535
543
  case 'object':
536
544
  if (value !== null && value !== undefined) {
537
545
  for (const key of Object.keys(value)) {
538
- this.read(context, prop, value, ext, key, fullPath);
546
+ this.read(context, extProp, value, prop, key, fullPath);
539
547
  }
540
548
  }
541
549
  break;
@@ -568,6 +576,15 @@ class JsonPointerHandler {
568
576
  pointer = new JsonPointer(path, res, value);
569
577
  pointer.debug = this.debug;
570
578
  this.map.set(value, pointer);
579
+ // Assume all texture slots are being used. The referenceName is the json pointer right now - usually this is e.g. `baseColorTexture` (the name ends up in the slots array)
580
+ const referenceName = value;
581
+ // const slots = listTextureSlots(object);
582
+ prop.setReference(referenceName, object, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
583
+ // make sure there's a reference to the buffer to avoid dedup or the buffer being removed because it MIGHT not be used by any node
584
+ // TODO: how do we get the buffer that the texture/image is currently using - here we just take the first buffer but this might not be correct
585
+ const buffer = this.document.getRoot().listBuffers()[0];
586
+ if (buffer)
587
+ prop.setReference("buffer", buffer);
571
588
  }
572
589
  else {
573
590
  console.warn("Texture not found", fullPath, value);
@@ -585,23 +602,45 @@ class JsonPointerHandler {
585
602
  if (this.debug)
586
603
  console.log("Read pointer", value);
587
604
  const index = parseInt(value.substring("/materials/".length));
588
- const mat = context.materials[index];
589
- if (mat) {
605
+ const object = context.materials[index];
606
+ if (object) {
590
607
  // set a reference to the material to avoid dedup or the material being removed because it MIGHT not be used by any node
591
608
  // BUT a component is referencing the material so we don't want it ever to be removed
592
609
  // see https://github.com/donmccurdy/glTF-Transform/issues/980#issuecomment-1585748202
593
- if (ext) {
594
- ext.setReference(value, mat);
610
+ if (prop) {
611
+ prop.setReference(value, object);
595
612
  }
596
613
  let pointer = this.map.get(value);
597
614
  if (!pointer) {
598
615
  const definition = context.jsonDoc.json.materials[index];
599
- const res = new MaterialIndexResolver(this.document, mat, definition);
616
+ const res = new MaterialIndexResolver(this.document, object, definition);
600
617
  res.debug = this.debug;
601
618
  res.init(context); // < init here otherwise the fields defined in the TexturePointer will be undefined (this caused e.g. finding the previous texture filter to fail)
602
619
  pointer = new JsonPointer("/materials/", res, value);
603
620
  pointer.debug = this.debug;
604
621
  this.map.set(value, pointer);
622
+ prop.setReference(value, object);
623
+ }
624
+ pointer?.register(obj, key, fullPath);
625
+ }
626
+ }
627
+ if (value.startsWith("/animations/")) {
628
+ if (this.debug)
629
+ console.log("Read pointer", value);
630
+ const index = parseInt(value.substring("/animations/".length));
631
+ const object = context.animations[index];
632
+ if (object) {
633
+ let pointer = this.map.get(value);
634
+ if (!pointer) {
635
+ // TODO: resolve animations + we need to set the reference properly so we can use prune. See https://linear.app/needle/issue/NE-4982
636
+ // const definition = context.jsonDoc.json.animations![index];
637
+ // const res = new AnimationIndexResolver(this.document, object, definition);
638
+ // res.debug = this.debug;
639
+ // res.init(context);
640
+ // pointer = new JsonPointer("/animations/", res, value);
641
+ // pointer.debug = this.debug;
642
+ // this.map.set(value, pointer);
643
+ prop.setReference(value, object);
605
644
  }
606
645
  pointer?.register(obj, key, fullPath);
607
646
  }
@@ -625,6 +664,7 @@ class JsonPointerHandler {
625
664
  pointer.debug = this.debug;
626
665
  pointer.register(obj, key, fullPath);
627
666
  this.map.set(dictKey, pointer);
667
+ prop.setReference(dictKey, object);
628
668
  }
629
669
  }
630
670
  else if (
@@ -663,9 +703,7 @@ class JsonPointerHandler {
663
703
  pointer.debug = this.debug;
664
704
  pointer.register(obj, key, fullPath);
665
705
  this.map.set(dictKey, pointer);
666
- if (ext) {
667
- ext.setReference(dictKey, object);
668
- }
706
+ prop.setReference(dictKey, object, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
669
707
  }
670
708
  }
671
709
  break;
@@ -673,10 +711,10 @@ class JsonPointerHandler {
673
711
  break;
674
712
  }
675
713
  }
676
- resolveAndWrite(context) {
714
+ resolveAndWrite(context, step) {
677
715
  this.map?.forEach(ptr => {
678
- ptr.resolve(context);
679
- ptr.write();
716
+ if (ptr.resolve(context, step))
717
+ ptr.write();
680
718
  });
681
719
  }
682
720
  }
@@ -698,8 +736,12 @@ class JsonPointer {
698
736
  this._props.push(prop);
699
737
  this._debugInfo.push(fullpath);
700
738
  }
701
- newPointer;
702
- resolve(context) {
739
+ newPointer = undefined;
740
+ resolve(context, step) {
741
+ // If the pointer was already resolved, we don't need to do it again
742
+ if (this.newPointer !== undefined) {
743
+ return true;
744
+ }
703
745
  //@ts-ignore
704
746
  this.resolver.debug = this.debug;
705
747
  const index = this.resolver.resolve(context);
@@ -712,12 +754,20 @@ class JsonPointer {
712
754
  }
713
755
  if (this.debug)
714
756
  console.log(`RESOLVED pointer ${this.oldPointer} to → ${this.newPointer}`);
757
+ return true;
715
758
  }
716
759
  else {
717
- console.log("ERR: 🧨 FAILED to resolve pointer", this.pointerBase, ` used by ${this._debugInfo.join(", ")}`);
760
+ // If the pointer could not be resolved during write we need to log an error
761
+ if (step === "write")
762
+ console.log("ERR: 🧨 FAILED to resolve pointer", this.pointerBase, ` used by ${this._debugInfo.join(", ")}`);
718
763
  }
764
+ return false;
719
765
  }
766
+ _didWrite = false;
720
767
  write() {
768
+ if (this._didWrite)
769
+ return;
770
+ this._didWrite = false;
721
771
  for (let i = 0; i < this._objects.length; i++) {
722
772
  const obj = this._objects[i];
723
773
  const prop = this._props[i];
@@ -12,8 +12,12 @@ type LodInfo = {
12
12
  /** Hash of the LOD file. It has been generated using the file content and settings */
13
13
  hash: string;
14
14
  };
15
+ export type ProgressiveTextureLodEntry = LodInfo & {
16
+ width: number;
17
+ height: number;
18
+ };
15
19
  export type ProgressiveTextureModel = ProgressiveLoadingInfo & {
16
- lods?: Array<LodInfo & {}>;
20
+ lods?: Array<ProgressiveTextureLodEntry>;
17
21
  };
18
22
  export type ProgressiveMeshModel = ProgressiveLoadingInfo & {
19
23
  /** LOD0 vertex density. TODO: remove this since we now have a LODs array. This is just for supporting older engine versions */
@@ -4,12 +4,11 @@ import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
4
4
  import draco3d from 'draco3dgltf';
5
5
  import { existsSync, readFileSync, statSync, writeFileSync } from 'fs';
6
6
  import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
7
- import { resample } from '@gltf-transform/functions';
7
+ import { dedup, prune, resample } from '@gltf-transform/functions';
8
8
  import { ALL_EXTENSIONS as NEEDLE_EXTENSIONS, NEEDLE_compression_texture, NEEDLE_mesh_compression, } from '../extensions/index.js';
9
- import { isMeshLOD, needle_animation_transform, needle_asset, needle_mesh_transform, needle_texture_transform, } from '../transforms/index.js';
9
+ import { isLOD, isMeshLOD, needle_animation_transform, needle_asset, needle_mesh_transform, needle_texture_transform, } from '../transforms/index.js';
10
10
  import { createNewFilestats, writeNodeIO } from "../utils/index.js";
11
11
  import { addToCache, getHash, tryGetFromCache, } from "../cache/index.js";
12
- import { getConfig } from '../config/index.js';
13
12
  /** Compress a glTF file
14
13
  */
15
14
  export async function packGLTF(inputFile, outputFile, options) {
@@ -21,9 +20,6 @@ export async function packGLTF(inputFile, outputFile, options) {
21
20
  logger.error("WARN: can not pack, file does not exist: " + inputFile);
22
21
  return false;
23
22
  }
24
- if (debug && inputFile.includes(".debug.")) {
25
- return true;
26
- }
27
23
  // check if it's in the cache.
28
24
  // We only need to check mesh LOD files because image LODs are cache via our toktx transform
29
25
  // We can not cache the main glTF files because the hash always changes for them
@@ -45,10 +41,9 @@ export async function packGLTF(inputFile, outputFile, options) {
45
41
  packedFiles.add(inputFile);
46
42
  }
47
43
  try {
48
- const config = options.config || getConfig();
44
+ const config = options.config;
49
45
  const prevSizeInMB = statSync(inputFile).size / 1024 / 1024;
50
46
  logger.info(`→ Compressing ${prevSizeInMB.toFixed(1)} MB: ${inputFile}`);
51
- // const isProgressiveAsset = isLOD(file);
52
47
  const startTime = Date.now();
53
48
  const io = new NodeIO()
54
49
  .registerExtensions(ALL_EXTENSIONS)
@@ -65,7 +60,7 @@ export async function packGLTF(inputFile, outputFile, options) {
65
60
  });
66
61
  const document = await io.read(inputFile);
67
62
  /** @ts-ignore */
68
- document.getLogger().verbosity = Verbosity.ERROR;
63
+ document.getLogger().verbosity = options.debug ? Verbosity.DEBUG : Verbosity.WARN;
69
64
  let totalGPUTextureMemory = 0;
70
65
  /** @type {Array<import('@gltf-transform/core').Transform>} */
71
66
  const transforms = [
@@ -83,18 +78,20 @@ export async function packGLTF(inputFile, outputFile, options) {
83
78
  needle_mesh_transform({ file: inputFile, config }, { ratio: 0.75, error: 0.0005 }),
84
79
  needle_animation_transform({}),
85
80
  resample(),
86
- // TODO: dedup removes skybox texture
87
- // dedup(),
81
+ dedup(),
82
+ // prune(),
88
83
  ];
89
- // TODO: progressive assets need to make sure that e.g. textures are used
90
- // if (!isProgressiveAsset) {
91
- // transforms.push(prune());
92
- // }
84
+ const isProgressiveAsset = isLOD(inputFile);
85
+ // TODO: progressive mesh LODs should not be pruned right now because it will remove e.g. UVs from meshes (and probably blend shapes too) (so we just not do it for any progressive asset)
86
+ if (!isProgressiveAsset) {
87
+ transforms.push(prune({
88
+ // Pruning animations is not supported yet (e.g. if the animation is only referenced by a component)
89
+ propertyTypes: ['MESH', 'MATERIAL', 'TEXTURE']
90
+ }));
91
+ }
93
92
  await document.transform(...transforms);
94
93
  if (!outputFile)
95
94
  outputFile = inputFile;
96
- if (debug)
97
- outputFile += ".debug.glb";
98
95
  await writeNodeIO(io, outputFile, document);
99
96
  if (useCache && cacheKey != undefined && existsSync(outputFile))
100
97
  addToCache(cacheKey, readFileSync(outputFile));
@@ -116,7 +113,7 @@ export async function packGLTF(inputFile, outputFile, options) {
116
113
  return true;
117
114
  }
118
115
  catch (err) {
119
- logger.error("ERR: packing " + inputFile + " failed: " + err.message);
116
+ logger.error(`packing ${path.basename(inputFile)} failed: ${err}`);
120
117
  if (debug)
121
118
  throw err;
122
119
  return false;
@@ -16,10 +16,10 @@ async function applyMeshCompression(document, transform_context, context) {
16
16
  const rootModel = rootExtension.model;
17
17
  if (rootModel.compression) {
18
18
  if (rootModel.compression === "none") {
19
- console.log(`[${NAME}]: NONE → will not apply mesh compression`);
19
+ document.getLogger().info(`[${NAME}]: NONE → will not apply mesh compression`);
20
20
  return;
21
21
  }
22
- console.log(`[${NAME}]: ${rootModel.compression.toUpperCase()} → will apply ${rootModel.compression} mesh compression`);
22
+ document.getLogger().info(`[${NAME}]: ${rootModel.compression.toUpperCase()} → will apply ${rootModel.compression} mesh compression`);
23
23
  if (rootModel.compression === "draco") {
24
24
  const transform = draco();
25
25
  return transform(document, transform_context);
@@ -31,13 +31,13 @@ async function applyMeshCompression(document, transform_context, context) {
31
31
  }
32
32
  }
33
33
  // If nothing is configured apply meshopt compression as long as we're running gltf-transform 3.x
34
- if (context.file.endsWith(".vrm")) {
35
- console.log(`[${NAME}]: VRM → will apply meshopt mesh compression`);
36
- const transform = meshopt({ encoder: MeshoptEncoder });
37
- return transform(document, transform_context);
38
- }
34
+ // if (context.file.endsWith(".vrm")) {
35
+ // document.getLogger().info(`[${NAME}]: VRM → will apply meshopt mesh compression`);
36
+ // const transform = meshopt({ encoder: MeshoptEncoder });
37
+ // return transform(document, transform_context);
38
+ // }
39
39
  // by default we still want to run draco if the root doesnt have a compression model configured
40
- console.log(`[${NAME}]: No compression model configured → will apply draco mesh compression`);
40
+ console.log(`[${NAME}]: → will apply draco mesh compression (default)`);
41
41
  return draco()(document, transform_context);
42
42
  }
43
43
  async function simplifierTransform(document, _context, _options) {
@@ -52,7 +52,6 @@ async function simplifierTransform(document, _context, _options) {
52
52
  options.simplifier = simplifier;
53
53
  const weldOptions = {
54
54
  ...WELD_DEFAULTS,
55
- tolerance: 0.00000000001,
56
55
  overwrite: true,
57
56
  };
58
57
  for (const mesh of document.getRoot().listMeshes()) {
@@ -99,8 +98,8 @@ async function simplifierTransform(document, _context, _options) {
99
98
  }
100
99
  export async function compressPrimitive(document, mesh, prim, index, weldOptions, meshOptions) {
101
100
  const logger = document.getLogger();
102
- logger.debug(`weld: primitive[${index}] of mesh "${mesh.getName()}" → tolerance: ${weldOptions.tolerance}`);
103
- weldPrimitive(document, prim, weldOptions);
101
+ logger.debug(`weld: primitive[${index}] of mesh "${mesh.getName()}"`);
102
+ weldPrimitive(prim, weldOptions);
104
103
  // make sure we wait for the mesh simplifier to be ready
105
104
  if (meshOptions.simplifier && meshOptions.simplifier?.ready instanceof Promise) {
106
105
  const res = await meshOptions.simplifier?.ready
@@ -116,7 +115,7 @@ export async function compressPrimitive(document, mesh, prim, index, weldOptions
116
115
  return;
117
116
  }
118
117
  logger.debug(`simplify: primitive[${index}] of mesh "${mesh.getName()}" → ratio: ${meshOptions.ratio}, error: ${meshOptions.error}, lockBorder: ${meshOptions.lockBorder}`);
119
- return simplifyPrimitive(document, prim, meshOptions);
118
+ return simplifyPrimitive(prim, meshOptions);
120
119
  }
121
120
  // function updatePrimitive(prim: Primitive, simplifier: any, positionArray, dstIndicesArray) {
122
121
  // const position = prim.getAttribute('POSITION')!;