@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.
- package/CHANGELOG.md +39 -0
- package/README.md +18 -0
- package/dist/___config.json +3 -0
- package/dist/package.json +31 -25
- package/dist/src/cache/cache.d.ts +1 -0
- package/dist/src/cache/cache.js +1 -0
- package/dist/src/cli/index.js +44 -32
- package/dist/src/config/index.d.ts +6 -2
- package/dist/src/config/index.js +35 -37
- package/dist/src/extensions/NEEDLE_opaque/NEEDLE_opaque.d.ts +1 -1
- package/dist/src/extensions/NEEDLE_opaque/NEEDLE_opaque.js +74 -24
- package/dist/src/extensions/NEEDLE_progressive/NEEDLE_progressive.d.ts +5 -1
- package/dist/src/scripts/pack-gltf.js +15 -18
- package/dist/src/transforms/needle_mesh_transform.js +11 -12
- package/dist/src/transforms/needle_progressive.js +176 -66
- package/dist/src/transforms/needle_toktx.js +57 -23
- package/dist/src/transforms/toktx.d.ts +9 -35
- package/dist/src/transforms/toktx.js +73 -92
- package/dist/src/utils/fileutils.d.ts +1 -0
- package/dist/src/utils/fileutils.js +10 -1
- package/dist/src/utils/index.d.ts +1 -0
- package/dist/src/utils/index.js +1 -0
- package/dist/src/utils/stats.d.ts +12 -6
- package/dist/src/utils/stats.js +12 -6
- package/dist/src/utils/texture.d.ts +2 -0
- package/dist/src/utils/texture.js +8 -0
- package/package.json +32 -26
- package/scripts/pack-gltf.mjs +1 -1
- package/tsconfig.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { BufferUtils, Document, NodeIO, PropertyType } from '@gltf-transform/core';
|
|
2
|
-
import { SIMPLIFY_DEFAULTS, WELD_DEFAULTS, listTextureSlots, sparse } from '@gltf-transform/functions';
|
|
1
|
+
import { BufferUtils, Document, NodeIO, PropertyType, TextureChannel, Verbosity } from '@gltf-transform/core';
|
|
2
|
+
import { SIMPLIFY_DEFAULTS, WELD_DEFAULTS, listTextureChannels, listTextureSlots, sparse } from '@gltf-transform/functions';
|
|
3
3
|
import draco3d from 'draco3dgltf';
|
|
4
4
|
import { NEEDLE_PROGRESSIVE_EXTENSION_NAME, NEEDLE_progressive } from "../extensions/NEEDLE_progressive/index.js";
|
|
5
5
|
import { createOpaqueExtension, currentGenerator, NEEDLE_compression_texture, NEEDLE_mesh_compression, NEEDLE_progressive_mesh_settings, NEEDLE_progressive_texture_settings, registerExtensions as registerDefaultExtensions } from '../extensions/index.js';
|
|
6
6
|
import path, { basename, resolve } from 'path';
|
|
7
7
|
import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
|
|
8
|
-
import { addMetaToCache, addToCache, getHash,
|
|
8
|
+
import { addMetaToCache, addToCache, getHash, getKey, tryGetFromCache, tryGetMetaFromCache } from '../cache/index.js';
|
|
9
9
|
import sharp from "sharp";
|
|
10
10
|
import { detectTextureCompressionMode, foreachGLTF, generateGuid, writeNodeIO } from '../utils/index.js';
|
|
11
11
|
import { needle_asset, writeNeedleAsset } from './needle_asset.js';
|
|
@@ -55,18 +55,13 @@ async function onProcess(file, opts) {
|
|
|
55
55
|
});
|
|
56
56
|
let document = await io.read(file);
|
|
57
57
|
if (document) {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
58
|
+
const logger = document.getLogger();
|
|
59
|
+
//@ts-ignore
|
|
60
|
+
logger.verbosity = opts.debug ? Verbosity.DEBUG : Verbosity.WARN;
|
|
64
61
|
let smallesTextureSize = 128;
|
|
65
62
|
if (opts.config.usecase === "product") {
|
|
66
63
|
smallesTextureSize = 512;
|
|
67
64
|
}
|
|
68
|
-
//@ts-ignore
|
|
69
|
-
document.getLogger().verbosity = 0;
|
|
70
65
|
const transforms = [
|
|
71
66
|
needle_asset(),
|
|
72
67
|
make_progressive_textures(file, { size: [smallesTextureSize, smallesTextureSize] }, opts),
|
|
@@ -77,8 +72,8 @@ async function onProcess(file, opts) {
|
|
|
77
72
|
transforms.push(make_progressive_meshes(file, {}, opts));
|
|
78
73
|
}
|
|
79
74
|
else
|
|
80
|
-
|
|
81
|
-
|
|
75
|
+
logger.warn("WARN: Progressive meshes are not supported for VRM files yet");
|
|
76
|
+
logger.info("→ Transforming: " + file);
|
|
82
77
|
await document.transform(...transforms);
|
|
83
78
|
let filename = file;
|
|
84
79
|
if (opts.debug === true) {
|
|
@@ -91,7 +86,7 @@ async function onProcess(file, opts) {
|
|
|
91
86
|
}
|
|
92
87
|
await writeNodeIO(io, filename, document);
|
|
93
88
|
opts.results.push(filename);
|
|
94
|
-
|
|
89
|
+
logger.info("← Transforming done: " + filename);
|
|
95
90
|
}
|
|
96
91
|
}
|
|
97
92
|
catch (err) {
|
|
@@ -108,7 +103,6 @@ export function createTransform(name, fn) {
|
|
|
108
103
|
}
|
|
109
104
|
const NAME = 'NEEDLE_progressive';
|
|
110
105
|
export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DEFAULTS, opts) {
|
|
111
|
-
console.log("Make progressive: " + filePath);
|
|
112
106
|
const startTime = Date.now();
|
|
113
107
|
const filename = basename(filePath);
|
|
114
108
|
const options = { ...TEXTURE_RESIZE_DEFAULTS, ..._options };
|
|
@@ -117,6 +111,10 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
|
|
|
117
111
|
const textureLodBasePath = directory + "/";
|
|
118
112
|
return createTransform(NAME, async (doc) => {
|
|
119
113
|
const logger = doc.getLogger();
|
|
114
|
+
if (isLOD(filePath)) {
|
|
115
|
+
logger.info("Progressive Image Transform: skip lod at " + filePath);
|
|
116
|
+
return Promise.resolve();
|
|
117
|
+
}
|
|
120
118
|
let index = 0;
|
|
121
119
|
for (const texture of doc.getRoot().listTextures()) {
|
|
122
120
|
const textureIndex = index++;
|
|
@@ -159,8 +157,6 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
|
|
|
159
157
|
logger.warn(`[${NAME}] Skipping texture[${textureIndex}], settings are invalid (maxSize: ${settings.maxSize})`);
|
|
160
158
|
continue;
|
|
161
159
|
}
|
|
162
|
-
options.size[0] = settings.maxSize;
|
|
163
|
-
options.size[1] = settings.maxSize;
|
|
164
160
|
const existingExtension = texture.getExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME);
|
|
165
161
|
if (existingExtension !== undefined && existingExtension !== null) {
|
|
166
162
|
logger.debug(`[${NAME}] Skipping, texture is already progressive ${textureIndex}`);
|
|
@@ -171,26 +167,63 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
|
|
|
171
167
|
logger.debug(`[${NAME}] Skipping because progressive extension is not available. ${textureIndex}`);
|
|
172
168
|
continue;
|
|
173
169
|
}
|
|
174
|
-
const textureGuid = settings.guid?.length ? settings.guid : generateGuid(
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
170
|
+
const textureGuid = settings.guid?.length ? settings.guid : generateGuid(filename + "_texture_" + index.toString());
|
|
171
|
+
/** This is the size of the texture that is embedded in the glTF. No LOD should be smaller than this */
|
|
172
|
+
const maxSize = settings.maxSize;
|
|
173
|
+
/** This is the current texture's size */
|
|
174
|
+
const currentSize = Math.min(...texture.getSize());
|
|
175
|
+
const LOD_LEVEL = new Array();
|
|
176
|
+
LOD_LEVEL.push({ size: currentSize });
|
|
177
|
+
let generateLods = opts.config?.usecase === "world";
|
|
178
|
+
// If lods are enabled in the config
|
|
179
|
+
generateLods ||= opts.config?.textures?.lods === true;
|
|
180
|
+
// Ensure that texture lods are not disabled by { textures: { lods: false } }
|
|
181
|
+
generateLods &&= opts.config?.textures?.lods !== false;
|
|
182
|
+
if (generateLods) {
|
|
183
|
+
const LEVEL = 6;
|
|
184
|
+
let lastSize = currentSize;
|
|
185
|
+
for (let i = 1; i < LEVEL; i++) {
|
|
186
|
+
const size = lastSize * .5;
|
|
187
|
+
if (size <= maxSize)
|
|
188
|
+
break;
|
|
189
|
+
lastSize = size;
|
|
190
|
+
LOD_LEVEL.push({ size: size });
|
|
191
|
+
}
|
|
178
192
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
193
|
+
const results = new Array();
|
|
194
|
+
for (let i = 0; i < LOD_LEVEL.length; i++) {
|
|
195
|
+
const level = LOD_LEVEL[i];
|
|
196
|
+
const lodResult = await createTextureLod({
|
|
197
|
+
doc,
|
|
198
|
+
file: filePath,
|
|
199
|
+
basePath: textureLodBasePath,
|
|
200
|
+
level: i,
|
|
201
|
+
texture,
|
|
202
|
+
slots,
|
|
203
|
+
guid: textureGuid,
|
|
204
|
+
textureIndex,
|
|
205
|
+
maxSize: level.size
|
|
206
|
+
}, opts);
|
|
207
|
+
if (!lodResult) {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const { 0: width, 1: height } = lodResult.texture.getSize();
|
|
211
|
+
const outpath = lodResult?.outpath;
|
|
212
|
+
const relName = path.relative(directory, outpath);
|
|
213
|
+
results.push({
|
|
214
|
+
path: relName,
|
|
215
|
+
hash: lodResult.hash,
|
|
216
|
+
width,
|
|
217
|
+
height,
|
|
218
|
+
});
|
|
219
|
+
opts.results.push(outpath);
|
|
220
|
+
}
|
|
221
|
+
const key = getKey(texture);
|
|
182
222
|
// TODO: this path should be added to the NEEDLE dependencies extension
|
|
183
223
|
const model = {
|
|
184
224
|
guid: textureGuid,
|
|
185
|
-
lods:
|
|
186
|
-
{
|
|
187
|
-
hash: hash.toString(),
|
|
188
|
-
path: relName,
|
|
189
|
-
}
|
|
190
|
-
],
|
|
225
|
+
lods: results,
|
|
191
226
|
};
|
|
192
|
-
// for backwards compatibility - this should be removed in the future
|
|
193
|
-
model["uri"] = relName;
|
|
194
227
|
texture.setExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME, progressiveExt.createTexture(model));
|
|
195
228
|
if (opts.useCache) {
|
|
196
229
|
const cached = tryGetFromCache(key);
|
|
@@ -200,6 +233,9 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
|
|
|
200
233
|
continue;
|
|
201
234
|
}
|
|
202
235
|
}
|
|
236
|
+
options.size[0] = settings.maxSize;
|
|
237
|
+
options.size[1] = settings.maxSize;
|
|
238
|
+
logger.debug(`[${NAME}] Resizing embedded texture[${index}] to ${options.size[0]}x${options.size[1]}`);
|
|
203
239
|
await resizeTexture(options, texture, logger, uri || name, slots);
|
|
204
240
|
if (opts?.useCache === false) {
|
|
205
241
|
}
|
|
@@ -209,31 +245,39 @@ export function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DE
|
|
|
209
245
|
logger.debug(`Progressive transform finished in ${((Date.now() - startTime) / 1000).toFixed(1)} sec.`);
|
|
210
246
|
});
|
|
211
247
|
}
|
|
212
|
-
function createTextureLod(
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
// const outPath = basePath + guid + "_" + level + ".png";
|
|
217
|
-
// writeFileSync(outPath, imageBytes);
|
|
218
|
-
// return outPath;
|
|
219
|
-
// }
|
|
248
|
+
async function createTextureLod(args, opts) {
|
|
249
|
+
const { doc, file, basePath, level, texture, guid, textureIndex } = args;
|
|
250
|
+
let slots = args.slots;
|
|
251
|
+
const logger = doc.getLogger();
|
|
220
252
|
const newDoc = new Document();
|
|
221
253
|
writeNeedleAsset(newDoc);
|
|
222
|
-
newDoc.createScene();
|
|
223
|
-
newDoc.createBuffer();
|
|
254
|
+
const scene = newDoc.createScene();
|
|
255
|
+
const buffer = newDoc.createBuffer();
|
|
224
256
|
// add texture
|
|
225
257
|
const newTexture = newDoc.createTexture();
|
|
226
258
|
const img = texture.getImage();
|
|
227
259
|
newTexture.setImage(img);
|
|
228
260
|
newTexture.setURI(texture.getURI());
|
|
229
261
|
newTexture.setMimeType(texture.getMimeType());
|
|
262
|
+
if (args.maxSize && args.maxSize >= 16) {
|
|
263
|
+
const currentSize = newTexture.getSize();
|
|
264
|
+
if (currentSize[0] > args.maxSize && currentSize[1] > args.maxSize) {
|
|
265
|
+
await resizeTexture({ size: [args.maxSize, args.maxSize] }, newTexture, logger, texture.getURI(), slots);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
230
268
|
if (!slots?.length) {
|
|
231
|
-
|
|
269
|
+
logger.warn(`WARN: No material slots found for texture at index ${textureIndex} (name: \"${texture.getName()}\") → will assume slot \"baseColorTexture\"`);
|
|
232
270
|
slots = ["baseColorTexture"];
|
|
233
271
|
}
|
|
272
|
+
let slot_index = 0;
|
|
234
273
|
// create material adding the texture to the same slot
|
|
235
274
|
for (const slot of slots) {
|
|
236
|
-
const newMaterial = newDoc.createMaterial();
|
|
275
|
+
const newMaterial = newDoc.createMaterial(newTexture.getName());
|
|
276
|
+
const channels = listTextureChannels(texture);
|
|
277
|
+
// Ensure that we use the alpha channel if it is present
|
|
278
|
+
if (channels.includes(TextureChannel.A)) {
|
|
279
|
+
newMaterial.setAlphaMode("BLEND");
|
|
280
|
+
}
|
|
237
281
|
switch (slot) {
|
|
238
282
|
case "baseColorTexture":
|
|
239
283
|
newMaterial.setBaseColorTexture(newTexture);
|
|
@@ -251,22 +295,38 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
|
|
|
251
295
|
newMaterial.setEmissiveTexture(newTexture);
|
|
252
296
|
break;
|
|
253
297
|
default:
|
|
254
|
-
|
|
298
|
+
if (slot.startsWith("/textures/")) {
|
|
299
|
+
// Ensure the texture is using the alpha channel since we don't know what slots the original texture was used for
|
|
300
|
+
// see https://linear.app/needle/issue/NE-4985
|
|
301
|
+
newMaterial.setAlphaMode("BLEND");
|
|
302
|
+
newMaterial.setBaseColorTexture(newTexture);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
logger.warn(`WARN: Unknown texture slot: ${slot} for texture ${textureIndex} → can not load progressively`);
|
|
255
306
|
return null;
|
|
256
307
|
}
|
|
308
|
+
// Make sure the material is used
|
|
309
|
+
createMeshForMaterial(newDoc, newMaterial, slot_index++);
|
|
257
310
|
}
|
|
258
311
|
const compressionSettings = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME);
|
|
259
312
|
if (compressionSettings !== undefined && compressionSettings !== null && compressionSettings.getExtensionDefinition) {
|
|
260
|
-
|
|
313
|
+
logger.info("> Pass compression extension to new texture");
|
|
261
314
|
const newExt = newDoc.createExtension(NEEDLE_compression_texture);
|
|
262
315
|
const def = compressionSettings.getExtensionDefinition();
|
|
263
|
-
|
|
316
|
+
switch (opts.config.usecase) {
|
|
317
|
+
// For world scenarios we use ETC1S
|
|
318
|
+
case "world":
|
|
319
|
+
def.mode = "ETC1S";
|
|
320
|
+
break;
|
|
321
|
+
case "product":
|
|
322
|
+
def.mode = detectTextureCompressionMode(slots);
|
|
323
|
+
def.quality = 100;
|
|
324
|
+
break;
|
|
325
|
+
default:
|
|
326
|
+
def.mode = detectTextureCompressionMode(slots);
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
264
329
|
def.slot = slots[0];
|
|
265
|
-
// for VRMS we just use webp
|
|
266
|
-
// if (file?.toLocaleLowerCase().endsWith(".vrm")) {
|
|
267
|
-
// def.mode = "webp";
|
|
268
|
-
// def.quality = 70;
|
|
269
|
-
// }
|
|
270
330
|
const newProp = newExt.create(def);
|
|
271
331
|
newTexture.setExtension(NEEDLE_compression_texture.EXTENSION_NAME, newProp);
|
|
272
332
|
}
|
|
@@ -281,9 +341,54 @@ function createTextureLod(doc, file, basePath, level, texture, slots, guid, text
|
|
|
281
341
|
const imageName = "image_" + level + "_" + guid;
|
|
282
342
|
const filename = imageName + ext;
|
|
283
343
|
const outName = basePath + filename;
|
|
284
|
-
|
|
344
|
+
logger.info(`Write texture LOD ${level} to \"${filename}\"`);
|
|
285
345
|
newIo.write(outName, newDoc);
|
|
286
|
-
return
|
|
346
|
+
return {
|
|
347
|
+
outpath: outName,
|
|
348
|
+
texture: newTexture,
|
|
349
|
+
hash: getHash(newTexture).toString(),
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
function createMeshForMaterial(doc, mat, i) {
|
|
353
|
+
const buffer = doc.getRoot().listBuffers()[0];
|
|
354
|
+
const scene = doc.getRoot().listScenes()[0];
|
|
355
|
+
const node = doc.createNode();
|
|
356
|
+
const mesh = doc.createMesh();
|
|
357
|
+
const prim = doc.createPrimitive();
|
|
358
|
+
const accessor = doc.createAccessor();
|
|
359
|
+
accessor.setType('VEC3');
|
|
360
|
+
// create quad mesh
|
|
361
|
+
accessor.setArray(new Float32Array([
|
|
362
|
+
-.5, -.5, 0,
|
|
363
|
+
.5, -.5, 0,
|
|
364
|
+
-.5, .5, 0,
|
|
365
|
+
.5, .5, 0,
|
|
366
|
+
]));
|
|
367
|
+
accessor.setBuffer(buffer);
|
|
368
|
+
prim.setAttribute('POSITION', accessor);
|
|
369
|
+
const indices = doc.createAccessor();
|
|
370
|
+
indices.setType('SCALAR');
|
|
371
|
+
indices.setArray(new Uint32Array([0, 1, 2, 2, 1, 3]));
|
|
372
|
+
indices.setBuffer(buffer);
|
|
373
|
+
prim.setIndices(indices);
|
|
374
|
+
const uv = doc.createAccessor();
|
|
375
|
+
uv.setType('VEC2');
|
|
376
|
+
uv.setArray(new Float32Array([
|
|
377
|
+
0, 0,
|
|
378
|
+
1, 0,
|
|
379
|
+
0, 1,
|
|
380
|
+
1, 1,
|
|
381
|
+
]));
|
|
382
|
+
uv.setBuffer(buffer);
|
|
383
|
+
prim.setAttribute('TEXCOORD_0', uv);
|
|
384
|
+
prim.setMaterial(mat);
|
|
385
|
+
mesh.addPrimitive(prim);
|
|
386
|
+
node.setMesh(mesh);
|
|
387
|
+
scene.addChild(node);
|
|
388
|
+
node.setName(`Quad_${i}`);
|
|
389
|
+
const pos = [i, 0, 0];
|
|
390
|
+
node.setTranslation(pos);
|
|
391
|
+
return { node, mesh, prim };
|
|
287
392
|
}
|
|
288
393
|
/** Resampling filter methods. LANCZOS3 is sharper, LANCZOS2 is smoother. */
|
|
289
394
|
export var TextureResizeFilter;
|
|
@@ -292,7 +397,7 @@ export var TextureResizeFilter;
|
|
|
292
397
|
TextureResizeFilter["LANCZOS3"] = "lanczos3";
|
|
293
398
|
/** Lanczos2 (smooth) */
|
|
294
399
|
TextureResizeFilter["LANCZOS2"] = "lanczos2";
|
|
295
|
-
})(TextureResizeFilter || (TextureResizeFilter = {}));
|
|
400
|
+
})(TextureResizeFilter = TextureResizeFilter || (TextureResizeFilter = {}));
|
|
296
401
|
export const TEXTURE_RESIZE_DEFAULTS = {
|
|
297
402
|
size: [2048, 2048],
|
|
298
403
|
filter: TextureResizeFilter.LANCZOS3,
|
|
@@ -325,6 +430,7 @@ async function resizeTexture(options, texture, logger, uri, slots) {
|
|
|
325
430
|
dstWidth = Math.floor(dstWidth * (maxHeight / dstHeight));
|
|
326
431
|
dstHeight = maxHeight;
|
|
327
432
|
}
|
|
433
|
+
logger.info("> Resize texture to " + dstWidth + "x" + dstHeight + " (from " + srcWidth + "x" + srcHeight + ")");
|
|
328
434
|
// https://sharp.pixelplumbing.com/api-resize
|
|
329
435
|
const buffer = await sharp(texture.getImage())
|
|
330
436
|
.resize(dstWidth, dstHeight, {
|
|
@@ -334,26 +440,30 @@ async function resizeTexture(options, texture, logger, uri, slots) {
|
|
|
334
440
|
})
|
|
335
441
|
.toBuffer();
|
|
336
442
|
texture.setImage(BufferUtils.toView(buffer));
|
|
443
|
+
return {
|
|
444
|
+
width: dstWidth,
|
|
445
|
+
height: dstHeight,
|
|
446
|
+
};
|
|
337
447
|
}
|
|
338
448
|
export function make_progressive_meshes(filePath, _options, opts) {
|
|
339
449
|
const directory = path.dirname(filePath);
|
|
340
450
|
// const fileNameWithoutExtension = path.basename(filePath, path.extname(filePath));
|
|
341
451
|
const outputDirectory = directory + "/";
|
|
342
452
|
return createTransform("PROGRESSIVE_MESHES", async (doc, _context) => {
|
|
453
|
+
const logger = doc.getLogger();
|
|
343
454
|
// this is to ensure we're not creating progressive meshes for engine versions that don't support loading them yet
|
|
344
455
|
// the generator should include the version or the app that produced the GLB too (needle engine repo: 2c00d0e304e205cf9d4ac0499faabb92a706a5c4)
|
|
345
456
|
if (currentGenerator == "Needle Engine") {
|
|
346
|
-
|
|
457
|
+
logger.warn("WARN: Skip creating mesh LODs - Unsupported generator found... Please update your editor integration");
|
|
347
458
|
return;
|
|
348
459
|
}
|
|
349
|
-
if (
|
|
350
|
-
|
|
460
|
+
if (isLOD(filePath)) {
|
|
461
|
+
logger.info("Progressive Mesh Transform: skip lod at " + filePath);
|
|
351
462
|
return Promise.resolve();
|
|
352
463
|
}
|
|
353
464
|
await MeshoptSimplifier.ready;
|
|
354
|
-
const logger = doc.getLogger();
|
|
355
465
|
const filename = path.basename(filePath);
|
|
356
|
-
|
|
466
|
+
logger.info(`[${NAME}]: Begin generating progressive meshes for \"${filename}\"`);
|
|
357
467
|
let index = 0;
|
|
358
468
|
// the lowest LOD (last entry) will be saved in the original file
|
|
359
469
|
let MAX_LODS = 6;
|
|
@@ -389,7 +499,7 @@ export function make_progressive_meshes(filePath, _options, opts) {
|
|
|
389
499
|
for (const mesh of meshes) {
|
|
390
500
|
await processMesh(mesh, { filename });
|
|
391
501
|
}
|
|
392
|
-
|
|
502
|
+
logger.info(`[${NAME}]: Finished generating progressive meshes for \"${filename}\"`);
|
|
393
503
|
async function processMesh(mesh, args) {
|
|
394
504
|
/** The size and vertex count of the original mesh */
|
|
395
505
|
const originalMeshInformation = getMeshInformation(mesh);
|
|
@@ -430,7 +540,7 @@ export function make_progressive_meshes(filePath, _options, opts) {
|
|
|
430
540
|
/** async simplification tasks... */
|
|
431
541
|
const tasks = new Array();
|
|
432
542
|
if (needsToGenerateLODs) {
|
|
433
|
-
|
|
543
|
+
logger.info(`[${NAME}] Begin generating mesh LODs for \"${mesh.getName()}\"`);
|
|
434
544
|
// produce LODS, skip the last level because it will be saved in the original file
|
|
435
545
|
for (let level = 0; level < LODS.length - 1; level++) {
|
|
436
546
|
const lod = LODS[level];
|
|
@@ -466,11 +576,11 @@ export function make_progressive_meshes(filePath, _options, opts) {
|
|
|
466
576
|
let shouldOmitLevel = false;
|
|
467
577
|
// if the mesh size on disc is identical to the last level, we can omit this level
|
|
468
578
|
if (sizeOnDisc <= 0) {
|
|
469
|
-
|
|
579
|
+
logger.info(`[${NAME}] Flag mesh LOD ${level}: size on disc is 0 → level will be omitted (if this mesh is is taken from cache it can mean that the LOD level was omitted before). \"${mesh.getName()}\" at \"${lodInfo.path}\"`);
|
|
470
580
|
shouldOmitLevel = true;
|
|
471
581
|
}
|
|
472
582
|
else if (diff == 0) {
|
|
473
|
-
|
|
583
|
+
logger.info(`[${NAME}] Flag mesh LOD ${level}: size on disc did not change compared to previous level → level will be omitted. \"${mesh.getName()}\" at \"${lodInfo.path}\"`);
|
|
474
584
|
shouldOmitLevel = true;
|
|
475
585
|
}
|
|
476
586
|
else if (!shouldOmitLevel) {
|
|
@@ -513,7 +623,7 @@ export function make_progressive_meshes(filePath, _options, opts) {
|
|
|
513
623
|
if (data != null) {
|
|
514
624
|
clonedData.primitives.push(data);
|
|
515
625
|
}
|
|
516
|
-
|
|
626
|
+
logger.info(`[${NAME}] Simplify mesh[${index}] primitive[${primitiveIndex}] (embedded)`);
|
|
517
627
|
const lastLod = LODS[lodLevelInFile];
|
|
518
628
|
// TODO: this should be run after simplification but then we need to change the runtime to use the LOD 0 density
|
|
519
629
|
const density = calculateMeshDensity(prim);
|
|
@@ -531,7 +641,7 @@ export function make_progressive_meshes(filePath, _options, opts) {
|
|
|
531
641
|
}
|
|
532
642
|
else if (difference < 32 || diff01 <= 0.05) {
|
|
533
643
|
// the lowest LOD has the same vertex count as the original mesh → we don't need to write the extension and can also delete previously generated LODs
|
|
534
|
-
|
|
644
|
+
logger.info(`[${NAME}]: Flag mesh LOD ${generatedLODInfos.length} (embedded): vertex count difference below threshold (removed ${difference} vertices, ${(-diff01 * 100).toFixed(2)} %) → will remove LOD. \"${mesh.getName()}\"`);
|
|
535
645
|
try {
|
|
536
646
|
for (const lodInfo of generatedLODInfos) {
|
|
537
647
|
rmSync(outputDirectory + "/" + lodInfo.path);
|
|
@@ -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,
|
|
5
|
+
import { checkKTXSoftware, createParams, Mode } from "./toktx.js";
|
|
4
6
|
import { existsSync, mkdirSync } from "fs";
|
|
5
|
-
import {
|
|
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 {
|
|
@@ -93,27 +96,51 @@ export class NeedleToktxContext {
|
|
|
93
96
|
const doc = this.document;
|
|
94
97
|
const logger = doc.getLogger();
|
|
95
98
|
const slots = listTextureSlots(texture);
|
|
96
|
-
|
|
97
|
-
const textureLabel =
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
let channels = getTextureChannelMask(texture);
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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 + '.' +
|
|
140
|
+
const inPath = tmpName + '.' + srcExtension;
|
|
114
141
|
const outPath = tmpName + '.ktx2';
|
|
115
142
|
// const inBytes = image.byteLength;
|
|
116
|
-
await fs.writeFile(inPath, Buffer.from(
|
|
143
|
+
await fs.writeFile(inPath, Buffer.from(srcImage));
|
|
117
144
|
let mode = Mode.ETC1S;
|
|
118
145
|
let quality = 128;
|
|
119
146
|
let compression = 1;
|
|
@@ -148,19 +175,24 @@ export class NeedleToktxContext {
|
|
|
148
175
|
}
|
|
149
176
|
}
|
|
150
177
|
const defaults = mode === Mode.ETC1S ? ETC1S_DEFAULTS : UASTC_DEFAULTS;
|
|
178
|
+
// TODO: should we ensure that the texture is using all channels? Unused channels are discarded anyways. The issue we have here is that textures that are solely used from pointers have unknown channels. We register them with RGBA when generating progressive assets as well as assign texture json pointers /textures/ to
|
|
179
|
+
// Alpha blended materials to make sure RGBA channels are used when progressive GLBs are compressed (in needle_progressive 377)
|
|
180
|
+
// https://linear.app/needle/issue/NE-4985
|
|
181
|
+
// channels = TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A;
|
|
151
182
|
//@ts-ignore
|
|
152
|
-
const toktxParams = createParams(slots, channels,
|
|
183
|
+
const toktxParams = createParams(texture, slots, channels, srcSize, logger, this.numTextures, { ...defaults, mode, quality, compression });
|
|
184
|
+
await fs.writeFile(inPath, Buffer.from(srcImage));
|
|
153
185
|
const params = [
|
|
186
|
+
'create',
|
|
154
187
|
...toktxParams,
|
|
155
|
-
outPath,
|
|
156
188
|
inPath,
|
|
189
|
+
outPath,
|
|
157
190
|
];
|
|
158
191
|
logger.debug(`${prefix}: Spawning → toktx ${mode.toUpperCase()} ${params.join(' ')}`);
|
|
159
192
|
try {
|
|
160
|
-
// COMPRESS: Run `
|
|
193
|
+
// COMPRESS: Run `ktx create` CLI tool.
|
|
161
194
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
162
|
-
|
|
163
|
-
const [status, stdout, stderr] = await waitExit(spawn('toktx', params, { env: this.env }));
|
|
195
|
+
const [status, stdout, stderr] = await waitExit(spawn('ktx', params, { env: this.env }));
|
|
164
196
|
if (status !== 0) {
|
|
165
197
|
logger.error(`${prefix}: Failed → \n\n${stderr.toString()}`);
|
|
166
198
|
}
|
|
@@ -174,11 +206,13 @@ export class NeedleToktxContext {
|
|
|
174
206
|
const newUri = replaceExtension(oldUri, 'ktx2');
|
|
175
207
|
texture.setURI(newUri);
|
|
176
208
|
}
|
|
209
|
+
const dstBytes = texture.getImage().byteLength;
|
|
210
|
+
logger.debug(`${prefix}: ${formatBytes(srcBytes)} → ${formatBytes(dstBytes)}`);
|
|
177
211
|
return true;
|
|
178
212
|
}
|
|
179
213
|
}
|
|
180
214
|
catch (err) {
|
|
181
|
-
|
|
215
|
+
logger.error(`${prefix}: Toktx failed → ${err}`);
|
|
182
216
|
}
|
|
183
217
|
return false;
|
|
184
218
|
};
|
|
@@ -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
|
|
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>;
|