@needle-tools/gltf-build-pipeline 1.6.0-alpha.7 → 2.0.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.
@@ -171,7 +171,7 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
171
171
  logger.debug(`[${NAME}] Skipping because progressive extension is not available. ${textureIndex}`);
172
172
  continue;
173
173
  }
174
- const textureGuid = settings.guid?.length ? settings.guid : generateGuid(path + "_texture_" + index.toString());
174
+ const textureGuid = settings.guid?.length ? settings.guid : generateGuid(filename + "_texture_" + index.toString());
175
175
  const outPath = createTextureLod(doc, filePath, textureLodBasePath, 0, texture, slots, textureGuid, textureIndex);
176
176
  if (!outPath) {
177
177
  continue;
@@ -219,8 +219,8 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
219
219
  // }
220
220
  const newDoc = new Document();
221
221
  writeNeedleAsset(newDoc);
222
- newDoc.createScene();
223
- newDoc.createBuffer();
222
+ const scene = newDoc.createScene();
223
+ const buffer = newDoc.createBuffer();
224
224
  // add texture
225
225
  const newTexture = newDoc.createTexture();
226
226
  const img = texture.getImage();
@@ -231,6 +231,7 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
231
231
  console.warn(`WARN: No material slots found for texture at index ${textureIndex} (name: \"${texture.getName()}\") → will assume slot \"baseColorTexture\"`);
232
232
  slots = ["baseColorTexture"];
233
233
  }
234
+ let slot_index = 0;
234
235
  // create material adding the texture to the same slot
235
236
  for (const slot of slots) {
236
237
  const newMaterial = newDoc.createMaterial();
@@ -254,6 +255,8 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
254
255
  console.warn("WARN: Unknown texture slot: " + slot + " for texture " + textureIndex + " → can not load progressively");
255
256
  return null;
256
257
  }
258
+ // Make sure the material is used
259
+ createMeshForMaterial(newDoc, newMaterial, slot_index++);
257
260
  }
258
261
  const compressionSettings = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME);
259
262
  if (compressionSettings !== undefined && compressionSettings !== null && compressionSettings.getExtensionDefinition) {
@@ -285,6 +288,47 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
285
288
  newIo.write(outName, newDoc);
286
289
  return outName;
287
290
  }
291
+ function createMeshForMaterial(doc, mat, i) {
292
+ const buffer = doc.getRoot().listBuffers()[0];
293
+ const scene = doc.getRoot().listScenes()[0];
294
+ const node = doc.createNode();
295
+ const mesh = doc.createMesh();
296
+ const prim = doc.createPrimitive();
297
+ const accessor = doc.createAccessor();
298
+ accessor.setType('VEC3');
299
+ // create quad mesh
300
+ accessor.setArray(new Float32Array([
301
+ -.5, -.5, 0,
302
+ .5, -.5, 0,
303
+ -.5, .5, 0,
304
+ .5, .5, 0,
305
+ ]));
306
+ accessor.setBuffer(buffer);
307
+ prim.setAttribute('POSITION', accessor);
308
+ const indices = doc.createAccessor();
309
+ indices.setType('SCALAR');
310
+ indices.setArray(new Uint32Array([0, 1, 2, 2, 1, 3]));
311
+ indices.setBuffer(buffer);
312
+ prim.setIndices(indices);
313
+ const uv = doc.createAccessor();
314
+ uv.setType('VEC2');
315
+ uv.setArray(new Float32Array([
316
+ 0, 0,
317
+ 1, 0,
318
+ 0, 1,
319
+ 1, 1,
320
+ ]));
321
+ uv.setBuffer(buffer);
322
+ prim.setAttribute('TEXCOORD_0', uv);
323
+ prim.setMaterial(mat);
324
+ mesh.addPrimitive(prim);
325
+ node.setMesh(mesh);
326
+ scene.addChild(node);
327
+ node.setName(`Quad_${i}`);
328
+ const pos = [i, 0, 0];
329
+ node.setTranslation(pos);
330
+ return { node, mesh, prim };
331
+ }
288
332
  /** Resampling filter methods. LANCZOS3 is sharper, LANCZOS2 is smoother. */
289
333
  export var TextureResizeFilter;
290
334
  (function (TextureResizeFilter) {
@@ -292,7 +336,7 @@ export var TextureResizeFilter;
292
336
  TextureResizeFilter["LANCZOS3"] = "lanczos3";
293
337
  /** Lanczos2 (smooth) */
294
338
  TextureResizeFilter["LANCZOS2"] = "lanczos2";
295
- })(TextureResizeFilter || (TextureResizeFilter = {}));
339
+ })(TextureResizeFilter = TextureResizeFilter || (TextureResizeFilter = {}));
296
340
  export const TEXTURE_RESIZE_DEFAULTS = {
297
341
  size: [2048, 2048],
298
342
  filter: TextureResizeFilter.LANCZOS3,
@@ -1,14 +1,17 @@
1
- import { FileUtils, ImageUtils, uuid } from "@gltf-transform/core";
1
+ import { BufferUtils, FileUtils, ImageUtils, uuid } from "@gltf-transform/core";
2
+ import { listTextureSlots, getTextureChannelMask, fitPowerOfTwo, TextureResizeFilter } from "@gltf-transform/functions";
3
+ import { ETC1S_DEFAULTS, UASTC_DEFAULTS } from "@gltf-transform/cli";
2
4
  import { KHRTextureBasisu } from "@gltf-transform/extensions";
3
- import { checkKTXSoftware, createParams, ETC1S_DEFAULTS, Mode, UASTC_DEFAULTS } from "./toktx.js";
5
+ import { checkKTXSoftware, createParams, Mode } from "./toktx.js";
4
6
  import { existsSync, mkdirSync } from "fs";
5
- import { listTextureSlots, getTextureChannelMask } from "@gltf-transform/functions";
6
- import { spawn, waitExit } from './util.js';
7
+ import { formatBytes, spawn, waitExit } from './util.js';
7
8
  import fs from 'fs/promises';
8
9
  import os from 'os';
9
10
  import tmp from 'tmp';
10
11
  import pLimit from 'p-limit';
11
12
  import { replaceExtension } from "../utils/fileutils.js";
13
+ import { ceilMultipleOfFour, isMultipleOfFour } from "../utils/index.js";
14
+ import sharp from "sharp";
12
15
  const NUM_CPUS = os.cpus().length || 1; // microsoft/vscode#112122
13
16
  let didLogEnvironmentInfo = false;
14
17
  export class NeedleToktxContext {
@@ -94,26 +97,50 @@ export class NeedleToktxContext {
94
97
  const logger = doc.getLogger();
95
98
  const slots = listTextureSlots(texture);
96
99
  const channels = getTextureChannelMask(texture);
97
- const textureLabel = texture.getURI() ||
98
- texture.getName() ||
99
- `${index + 1}/${doc.getRoot().listTextures().length}`;
100
- const prefix = `toktx:texture(${textureLabel})`;
100
+ // const textureLabel =
101
+ // texture.getURI() ||
102
+ // texture.getName() ||
103
+ // `${index + 1}/${doc.getRoot().listTextures().length}`;
104
+ const prefix = `toktx:texture[${index}] ${texture.getName()}`;
105
+ let srcMimeType = texture.getMimeType();
106
+ if (srcMimeType === 'image/ktx2') {
107
+ logger.debug(`${prefix}: Skipping, already KTX.`);
108
+ return;
109
+ }
110
+ else if (srcMimeType !== 'image/png' && srcMimeType !== 'image/jpeg') {
111
+ logger.warn(`${prefix}: Skipping, unsupported texture type "${texture.getMimeType()}".`);
112
+ return;
113
+ }
101
114
  if (slots.length > 0)
102
115
  logger.debug(`${prefix}: Slots → [${slots.join(', ')}]`);
103
- const image = texture.getImage();
104
- const size = texture.getSize();
105
- if (!image || !size) {
116
+ let srcImage = texture.getImage();
117
+ let srcExtension = texture.getURI()
118
+ ? FileUtils.extension(texture.getURI())
119
+ : ImageUtils.mimeTypeToExtension(texture.getMimeType());
120
+ const srcSize = texture.getSize();
121
+ const srcBytes = srcImage ? srcImage.byteLength : null;
122
+ if (!srcImage || !srcSize || !srcBytes) {
106
123
  logger.warn(`${prefix}: Skipping, unreadable texture.`);
107
124
  return;
108
125
  }
109
- const extension = texture.getURI()
110
- ? FileUtils.extension(texture.getURI())
111
- : ImageUtils.mimeTypeToExtension(texture.getMimeType());
126
+ if (!isMultipleOfFour(srcSize[0]) || !isMultipleOfFour(srcSize[1])) {
127
+ const limitInputPixels = true;
128
+ const instance = sharp(srcImage, { limitInputPixels }).toFormat('png');
129
+ const srcSize = ImageUtils.getSize(srcImage, srcMimeType);
130
+ const dstSize = fitPowerOfTwo(srcSize, 'nearest-pot');
131
+ dstSize[0] = ceilMultipleOfFour(dstSize[0]);
132
+ dstSize[1] = ceilMultipleOfFour(dstSize[1]);
133
+ logger.warn(`${prefix}: Resizing ${srcSize.join('x')} → ${dstSize.join('x')}px`);
134
+ instance.resize(dstSize[0], dstSize[1], { fit: 'fill', kernel: TextureResizeFilter.LANCZOS3 });
135
+ srcImage = BufferUtils.toView(await instance.toBuffer());
136
+ srcExtension = 'png';
137
+ srcMimeType = 'image/png';
138
+ }
112
139
  const tmpName = this.tmpPathBase + "_" + index;
113
- const inPath = tmpName + '.' + extension;
140
+ const inPath = tmpName + '.' + srcExtension;
114
141
  const outPath = tmpName + '.ktx2';
115
142
  // const inBytes = image.byteLength;
116
- await fs.writeFile(inPath, Buffer.from(image));
143
+ await fs.writeFile(inPath, Buffer.from(srcImage));
117
144
  let mode = Mode.ETC1S;
118
145
  let quality = 128;
119
146
  let compression = 1;
@@ -149,18 +176,19 @@ export class NeedleToktxContext {
149
176
  }
150
177
  const defaults = mode === Mode.ETC1S ? ETC1S_DEFAULTS : UASTC_DEFAULTS;
151
178
  //@ts-ignore
152
- const toktxParams = createParams(slots, channels, size, logger, this.numTextures, { ...defaults, mode, quality, compression }, this.version);
179
+ const toktxParams = createParams(texture, slots, channels, srcSize, logger, this.numTextures, { ...defaults, mode, quality, compression });
180
+ await fs.writeFile(inPath, Buffer.from(srcImage));
153
181
  const params = [
182
+ 'create',
154
183
  ...toktxParams,
155
- outPath,
156
184
  inPath,
185
+ outPath,
157
186
  ];
158
187
  logger.debug(`${prefix}: Spawning → toktx ${mode.toUpperCase()} ${params.join(' ')}`);
159
188
  try {
160
- // COMPRESS: Run `toktx` CLI tool.
189
+ // COMPRESS: Run `ktx create` CLI tool.
161
190
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
162
- //@ts-ignore
163
- const [status, stdout, stderr] = await waitExit(spawn('toktx', params, { env: this.env }));
191
+ const [status, stdout, stderr] = await waitExit(spawn('ktx', params, { env: this.env }));
164
192
  if (status !== 0) {
165
193
  logger.error(`${prefix}: Failed → \n\n${stderr.toString()}`);
166
194
  }
@@ -174,11 +202,13 @@ export class NeedleToktxContext {
174
202
  const newUri = replaceExtension(oldUri, 'ktx2');
175
203
  texture.setURI(newUri);
176
204
  }
205
+ const dstBytes = texture.getImage().byteLength;
206
+ logger.debug(`${prefix}: ${formatBytes(srcBytes)} → ${formatBytes(dstBytes)}`);
177
207
  return true;
178
208
  }
179
209
  }
180
210
  catch (err) {
181
- console.error("Error running toktx", err);
211
+ logger.error(`${prefix}: Toktx failed → ${err}`);
182
212
  }
183
213
  return false;
184
214
  };
@@ -1,11 +1,5 @@
1
+ import { ETC1SOptions, UASTCOptions } from "@gltf-transform/cli";
1
2
  import { Document, ILogger, vec2, Texture } from '@gltf-transform/core';
2
- /**********************************************************************************************
3
- * Interfaces.
4
- */
5
- export declare const Mode: {
6
- ETC1S: string;
7
- UASTC: string;
8
- };
9
3
  export declare const Filter: {
10
4
  BOX: string;
11
5
  TENT: string;
@@ -24,6 +18,13 @@ export declare const Filter: {
24
18
  QUADRATIC_APPROX: string;
25
19
  QUADRATIC_MIX: string;
26
20
  };
21
+ /**********************************************************************************************
22
+ * Interfaces.
23
+ */
24
+ export declare const Mode: {
25
+ ETC1S: string;
26
+ UASTC: string;
27
+ };
27
28
  export type TextureModeArgs = {
28
29
  doc: Document;
29
30
  texture: Texture;
@@ -42,36 +43,9 @@ export interface ToktxOptions {
42
43
  modifyOptions?: (args: TextureModeArgs) => void | boolean;
43
44
  modifyParams?: (args: TextureParamsArgs) => void;
44
45
  }
45
- export interface GlobalOptions {
46
- mode: string;
47
- slots?: string;
48
- filter?: string;
49
- filterScale?: number;
50
- powerOfTwo?: boolean;
51
- jobs?: number;
52
- }
53
- export interface ETC1SOptions extends GlobalOptions {
54
- quality?: number;
55
- compression?: number;
56
- maxEndpoints?: number;
57
- maxSelectors?: number;
58
- rdoOff?: boolean;
59
- rdoThreshold?: number;
60
- }
61
- export interface UASTCOptions extends GlobalOptions {
62
- level?: number;
63
- rdo?: number;
64
- rdoDictionarySize?: number;
65
- rdoBlockScale?: number;
66
- rdoStdDev?: number;
67
- rdoMultithreading?: boolean;
68
- zstd?: number;
69
- }
70
- export declare const ETC1S_DEFAULTS: Omit<ETC1SOptions, 'mode'>;
71
- export declare const UASTC_DEFAULTS: Omit<UASTCOptions, 'mode'>;
72
46
  /**********************************************************************************************
73
47
  * Utilities.
74
48
  */
75
49
  /** Create CLI parameters from the given options. Attempts to write only non-default options. */
76
- export declare function createParams(slots: string[], channels: number, size: vec2, logger: ILogger, numTextures: number, options: ETC1SOptions | UASTCOptions, version: string): (string | number)[];
50
+ export declare function createParams(texture: Texture, slots: string[], channels: number, size: vec2, logger: ILogger, numTextures: number, options: ETC1SOptions | UASTCOptions): (string | number)[];
77
51
  export declare function checkKTXSoftware(logger: ILogger, env?: any): Promise<string | null>;
@@ -2,11 +2,13 @@ import micromatch from 'micromatch';
2
2
  import os from 'os';
3
3
  import semver from 'semver';
4
4
  import tmp from 'tmp';
5
+ import { ETC1S_DEFAULTS, UASTC_DEFAULTS } from "@gltf-transform/cli";
5
6
  import { TextureChannel } from '@gltf-transform/core';
6
7
  // import { TextureBasisu } from '@gltf-transform/extensions';
7
8
  // import { getTextureChannelMask, listTextureSlots } from '@gltf-transform/functions';
8
9
  import { execSync } from 'child_process';
9
10
  import { spawn, commandExists, waitExit, MICROMATCH_OPTIONS } from './util.js';
11
+ import { TextureResizeFilter, getTextureColorSpace } from '@gltf-transform/functions';
10
12
  // import { existsSync, mkdirSync } from 'fs';
11
13
  // import { tryGetFromCache, getKey, addToCache } from '../cache';
12
14
  // import { resizeTextureIfNecessary } from "./needle_texture_transform"
@@ -14,14 +16,6 @@ tmp.setGracefulCleanup();
14
16
  const NUM_CPUS = os.cpus().length || 1; // microsoft/vscode#112122
15
17
  const KTX_SOFTWARE_VERSION_MIN = '4.0.0-rc1';
16
18
  const KTX_SOFTWARE_VERSION_ACTIVE = '4.1.0-rc1';
17
- const { R, G } = TextureChannel;
18
- /**********************************************************************************************
19
- * Interfaces.
20
- */
21
- export const Mode = {
22
- ETC1S: 'etc1s',
23
- UASTC: 'uastc',
24
- };
25
19
  export const Filter = {
26
20
  BOX: 'box',
27
21
  TENT: 'tent',
@@ -41,128 +35,115 @@ export const Filter = {
41
35
  QUADRATIC_MIX: 'quadratic_mix',
42
36
  };
43
37
  const GLOBAL_DEFAULTS = {
38
+ resizeFilter: TextureResizeFilter.LANCZOS3,
44
39
  filter: Filter.LANCZOS4,
45
40
  filterScale: 1,
46
- powerOfTwo: false,
47
- slots: '*',
41
+ pattern: null,
42
+ slots: null,
48
43
  // See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
49
44
  jobs: 2 * NUM_CPUS,
45
+ cleanup: true,
46
+ limitInputPixels: true,
50
47
  };
51
- export const ETC1S_DEFAULTS = {
52
- quality: 128,
53
- compression: 1,
54
- ...GLOBAL_DEFAULTS,
55
- };
56
- export const UASTC_DEFAULTS = {
57
- level: 2,
58
- rdo: 0,
59
- rdoDictionarySize: 32768,
60
- rdoBlockScale: 10.0,
61
- rdoStdDev: 18.0,
62
- rdoMultithreading: true,
63
- zstd: 18,
64
- ...GLOBAL_DEFAULTS,
48
+ const { R, G, A } = TextureChannel;
49
+ /**********************************************************************************************
50
+ * Interfaces.
51
+ */
52
+ export const Mode = {
53
+ ETC1S: 'etc1s',
54
+ UASTC: 'uastc',
65
55
  };
66
56
  /**********************************************************************************************
67
57
  * Utilities.
68
58
  */
69
59
  /** Create CLI parameters from the given options. Attempts to write only non-default options. */
70
- export function createParams(slots, channels, size, logger, numTextures, options, version) {
71
- const params = [];
72
- params.push('--genmipmap');
73
- if (options.filter !== GLOBAL_DEFAULTS.filter)
74
- params.push('--filter', options.filter);
60
+ export function createParams(texture, slots, channels, size, logger, numTextures, options) {
61
+ const colorSpace = getTextureColorSpace(texture);
62
+ const params = ['--generate-mipmap'];
63
+ if (options.filter !== GLOBAL_DEFAULTS.filter) {
64
+ params.push('--mipmap-filter', options.filter);
65
+ }
75
66
  if (options.filterScale !== GLOBAL_DEFAULTS.filterScale) {
76
- params.push('--fscale', options.filterScale);
67
+ params.push('--mipmap-filter-scale', options.filterScale);
77
68
  }
69
+ // See: https://github.com/KhronosGroup/KTX-Software/issues/600
70
+ const isNormalMap = slots.find((slot) => micromatch.isMatch(slot, '*normal*', MICROMATCH_OPTIONS));
78
71
  if (options.mode === Mode.UASTC) {
79
72
  const _options = options;
80
- params.push('--uastc', _options.level);
81
- if (_options.rdo !== UASTC_DEFAULTS.rdo) {
82
- params.push('--uastc_rdo_l', _options.rdo);
83
- }
84
- if (_options.rdoDictionarySize !== UASTC_DEFAULTS.rdoDictionarySize) {
85
- params.push('--uastc_rdo_d', _options.rdoDictionarySize);
86
- }
87
- if (_options.rdoBlockScale !== UASTC_DEFAULTS.rdoBlockScale) {
88
- params.push('--uastc_rdo_b', _options.rdoBlockScale);
89
- }
90
- if (_options.rdoStdDev !== UASTC_DEFAULTS.rdoStdDev) {
91
- params.push('--uastc_rdo_s', _options.rdoStdDev);
73
+ params.push('--encode', 'uastc');
74
+ params.push('--uastc-quality', _options.level);
75
+ if (_options.rdo && !isNormalMap) {
76
+ params.push('--uastc-rdo');
77
+ if (_options.rdoLambda !== UASTC_DEFAULTS.rdoLambda) {
78
+ params.push('--uastc-rdo-l', _options.rdoLambda);
79
+ }
80
+ if (_options.rdoDictionarySize !== UASTC_DEFAULTS.rdoDictionarySize) {
81
+ params.push('--uastc-rdo-d', _options.rdoDictionarySize);
82
+ }
83
+ if (_options.rdoBlockScale !== UASTC_DEFAULTS.rdoBlockScale) {
84
+ params.push('--uastc-rdo-b', _options.rdoBlockScale);
85
+ }
86
+ if (_options.rdoStdDev !== UASTC_DEFAULTS.rdoStdDev) {
87
+ params.push('--uastc-rdo-s', _options.rdoStdDev);
88
+ }
89
+ if (!_options.rdoMultithreading) {
90
+ params.push('--uastc-rdo-m');
91
+ }
92
+ }
93
+ if (_options.zstd && _options.zstd > 0) {
94
+ params.push('--zstd', _options.zstd);
92
95
  }
93
- if (!_options.rdoMultithreading) {
94
- params.push('--uastc_rdo_m');
95
- }
96
- if (_options.zstd && _options.zstd > 0)
97
- params.push('--zcmp', _options.zstd);
98
96
  }
99
97
  else {
100
98
  const _options = options;
101
- params.push('--bcmp');
99
+ params.push('--encode', 'basis-lz');
102
100
  if (_options.quality !== ETC1S_DEFAULTS.quality) {
103
101
  params.push('--qlevel', _options.quality);
104
102
  }
105
103
  if (_options.compression !== ETC1S_DEFAULTS.compression) {
106
104
  params.push('--clevel', _options.compression);
107
105
  }
108
- if (_options.maxEndpoints)
109
- params.push('--max_endpoints', _options.maxEndpoints);
110
- if (_options.maxSelectors)
111
- params.push('--max_selectors', _options.maxSelectors);
112
- if (_options.rdoOff) {
113
- params.push('--no_endpoint_rdo', '--no_selector_rdo');
106
+ if (_options.rdo && !isNormalMap) {
107
+ if (_options.maxEndpoints !== ETC1S_DEFAULTS.maxEndpoints) {
108
+ params.push('--max-endpoints', _options.maxEndpoints);
109
+ }
110
+ if (_options.maxSelectors !== ETC1S_DEFAULTS.maxSelectors) {
111
+ params.push('--max-selectors', _options.maxSelectors);
112
+ }
113
+ if (_options.rdoThreshold !== ETC1S_DEFAULTS.rdoThreshold) {
114
+ params.push('--endpoint-rdo-threshold', _options.rdoThreshold);
115
+ params.push('--selector-rdo-threshold', _options.rdoThreshold);
116
+ }
114
117
  }
115
- else if (_options.rdoThreshold) {
116
- params.push('--endpoint_rdo_threshold', _options.rdoThreshold);
117
- params.push('--selector_rdo_threshold', _options.rdoThreshold);
118
+ else {
119
+ params.push('--no-endpoint-rdo', '--no-selector-rdo');
118
120
  }
119
121
  }
120
- if (slots.find((slot) => micromatch.isMatch(slot, '*normal*', MICROMATCH_OPTIONS))) {
121
- // See: https://github.com/KhronosGroup/KTX-Software/issues/600
122
- if (semver.gte(version, KTX_SOFTWARE_VERSION_ACTIVE)) {
123
- params.push('--normal_mode', '--input_swizzle', 'rgb1');
124
- }
125
- else if (options.mode === Mode.ETC1S) {
126
- params.push('--normal_map');
127
- }
122
+ // See: https://github.com/donmccurdy/glTF-Transform/issues/215
123
+ if (colorSpace === 'srgb') {
124
+ params.push('--assign-oetf', 'srgb', '--assign-primaries', 'bt709');
128
125
  }
129
- if (slots.length && !slots.find((slot) => micromatch.isMatch(slot, '*{color,emissive}*', MICROMATCH_OPTIONS))) {
130
- // See: https://github.com/donmccurdy/glTF-Transform/issues/215
131
- params.push('--assign_oetf', 'linear', '--assign_primaries', 'none');
126
+ else if (colorSpace === 'srgb-linear') {
127
+ params.push('--assign-oetf', 'linear', '--assign-primaries', 'bt709');
128
+ }
129
+ else if (slots.length && !colorSpace) {
130
+ params.push('--assign-oetf', 'linear', '--assign-primaries', 'none');
132
131
  }
133
132
  if (channels === R) {
134
- params.push('--target_type', 'R');
133
+ params.push('--format', 'R8_UNORM');
135
134
  }
136
135
  else if (channels === G || channels === (R | G)) {
137
- params.push('--target_type', 'RG');
136
+ params.push('--format', 'R8G8_UNORM');
138
137
  }
139
- // Minimum size on any dimension is 4px.
140
- // See: https://github.com/donmccurdy/glTF-Transform/issues/502
141
- let width;
142
- let height;
143
- if (options.powerOfTwo) {
144
- width = preferredPowerOfTwo(size[0]);
145
- height = preferredPowerOfTwo(size[1]);
138
+ else if (!(channels & A)) {
139
+ params.push('--format', colorSpace === 'srgb' ? 'R8G8B8_SRGB' : 'R8G8B8_UNORM');
146
140
  }
147
141
  else {
148
- if (!isPowerOfTwo(size[0]) || !isPowerOfTwo(size[1])) {
149
- logger.warn(`toktx: Texture dimensions ${size[0]}x${size[1]} are NPOT, and may` +
150
- ' fail in older APIs (including WebGL 1.0) on certain devices.');
151
- }
152
- width = isMultipleOfFour(size[0]) ? size[0] : ceilMultipleOfFour(size[0]);
153
- height = isMultipleOfFour(size[1]) ? size[1] : ceilMultipleOfFour(size[1]);
154
- }
155
- if (width !== size[0] || height !== size[1]) {
156
- if (width > 4096 || height > 4096) {
157
- logger.warn(`toktx: Resizing to nearest power of two, ${width}x${height}px. Texture dimensions` +
158
- ' greater than 4096px may not render on some mobile devices.' +
159
- ' Resize to a lower resolution before compressing, if needed.');
160
- }
161
- params.push('--resize', `${width}x${height}`);
142
+ params.push('--format', colorSpace === 'srgb' ? 'R8G8B8A8_SRGB' : 'R8G8B8A8_UNORM');
162
143
  }
163
144
  if (options.jobs && options.jobs > 1 && numTextures > 1) {
164
145
  // See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
165
- const threads = Math.max(2, Math.min(NUM_CPUS, (3 * NUM_CPUS) / numTextures));
146
+ const threads = Math.max(2, Math.min(NUM_CPUS, Math.round((3 * NUM_CPUS) / numTextures)));
166
147
  params.push('--threads', threads);
167
148
  }
168
149
  return params;
@@ -1,4 +1,5 @@
1
1
  export declare function getFileName(filepath: string): string;
2
+ export declare function getDirName(filepath: string): string;
2
3
  export declare type GLTFFileCallback = (file: string) => void | Promise<void>;
3
4
  export declare function foreachGLTF(args: string | string[], callback: GLTFFileCallback): Promise<void>;
4
5
  export declare function replaceExtension(filepath: string, newExtension: string): string;
@@ -4,6 +4,15 @@ export function getFileName(filepath) {
4
4
  const parts = filepath.replaceAll("\\", "/").split("/");
5
5
  return parts[parts.length - 1];
6
6
  }
7
+ export function getDirName(filepath) {
8
+ // should work for paths that end with "/" or not
9
+ const parts = filepath.replaceAll("\\", "/").split("/");
10
+ let res = parts.pop();
11
+ if (res === "") {
12
+ res = parts.pop();
13
+ }
14
+ return res;
15
+ }
7
16
  export async function foreachGLTF(args, callback) {
8
17
  // get original directory this run was invoked from
9
18
  const initDir = process.env.INIT_CWD;
@@ -2,6 +2,7 @@ export * from "./compression_utils.js";
2
2
  export * from "./fileutils.js";
3
3
  export * from "./version.js";
4
4
  export * from "./mesh.js";
5
+ export * from "./texture.js";
5
6
  export * from "./guid.js";
6
7
  export * from "./nodeio.js";
7
8
  export * from "./stats.js";
@@ -2,6 +2,7 @@ export * from "./compression_utils.js";
2
2
  export * from "./fileutils.js";
3
3
  export * from "./version.js";
4
4
  export * from "./mesh.js";
5
+ export * from "./texture.js";
5
6
  export * from "./guid.js";
6
7
  export * from "./nodeio.js";
7
8
  export * from "./stats.js";
@@ -12,12 +12,17 @@ export type FileStats = {
12
12
  filename: string;
13
13
  /** Size in bytes */
14
14
  size: number;
15
+ /** Memory in bytes */
15
16
  gpu_memory: number;
16
- vertex_count: number;
17
17
  nodes: number;
18
18
  materials: number;
19
+ meshes: number;
20
+ textures: number;
21
+ vertex_count: number;
22
+ triangle_count: number;
19
23
  };
20
- export declare function createNewFilestats(file: string, document: Document, stats: {
21
- gpu_memory: number;
22
- }): FileStats;
24
+ /**
25
+ * Create a new filestats object from a file and a document
26
+ */
27
+ export declare function createNewFilestats(file: string, document: Document, stats: Pick<FileStats, "gpu_memory">): FileStats;
23
28
  export declare function writeFileStatsToFile(filestats: FileStats[], output_path: string): void;
@@ -10,22 +10,28 @@ export function printStats(stats, logger) {
10
10
  else
11
11
  console.log(msg);
12
12
  }
13
+ /**
14
+ * Create a new filestats object from a file and a document
15
+ */
13
16
  export function createNewFilestats(file, document, stats) {
14
17
  const filename = getFileName(file);
15
18
  const root = document.getRoot();
16
19
  const filestats = {
17
20
  filename,
18
21
  size: statSync(file).size,
19
- gpu_memory: stats.gpu_memory,
22
+ gpu_memory: Math.round(stats.gpu_memory),
20
23
  nodes: root.listNodes().length,
21
24
  materials: root.listMaterials().length,
25
+ meshes: root.listMeshes().length,
26
+ textures: root.listTextures().length,
22
27
  vertex_count: 0,
28
+ triangle_count: 0,
23
29
  };
24
30
  // Count vertices
25
31
  for (const mesh of root.listMeshes()) {
26
32
  filestats.vertex_count += mesh.listPrimitives().reduce((acc, p) => acc + p.getAttribute('POSITION').getCount(), 0);
27
33
  }
28
- filestats.vertex_count = Math.round(filestats.vertex_count / 3);
34
+ filestats.triangle_count = filestats.vertex_count / 3;
29
35
  return filestats;
30
36
  }
31
37
  export function writeFileStatsToFile(filestats, output_path) {
@@ -34,6 +40,6 @@ export function writeFileStatsToFile(filestats, output_path) {
34
40
  return;
35
41
  }
36
42
  console.log("Writing file stats to: " + output_path);
37
- const json = JSON.stringify(filestats, null, 2);
43
+ const json = JSON.stringify(filestats);
38
44
  writeFileSync(output_path, json);
39
45
  }
@@ -0,0 +1,2 @@
1
+ export declare function isMultipleOfFour(value: number): boolean;
2
+ export declare function ceilMultipleOfFour(value: number): number;
@@ -0,0 +1,8 @@
1
+ export function isMultipleOfFour(value) {
2
+ return value % 4 === 0;
3
+ }
4
+ export function ceilMultipleOfFour(value) {
5
+ if (value <= 4)
6
+ return 4;
7
+ return value % 4 ? value + 4 - (value % 4) : value;
8
+ }