@needle-tools/gltf-build-pipeline 2.16.0-next.fc19d36 → 3.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.
- package/CHANGELOG.md +25 -0
- package/README.md +41 -2
- package/dist/cli/index.js +4154 -232
- package/package.json +9 -14
- package/tools/pmrem/pkg/pmrem_wasm.d.ts +25 -0
- package/tools/pmrem/pkg/pmrem_wasm.js +110 -0
- package/tools/pmrem/pkg/pmrem_wasm_bg.wasm +0 -0
- package/dist/cache/cache.d.ts +0 -58
- package/dist/cache/cache.js +0 -330
- package/dist/cache/index.d.ts +0 -2
- package/dist/cache/index.js +0 -2
- package/dist/cache/job-cache.d.ts +0 -26
- package/dist/cache/job-cache.js +0 -84
- package/dist/cli/index.d.ts +0 -2
- package/dist/config/index.d.ts +0 -53
- package/dist/config/index.js +0 -156
- package/dist/constants.d.ts +0 -7
- package/dist/constants.js +0 -7
- package/dist/extensions/NEEDLE_compression_texture/NEEDLE_compression_texture.d.ts +0 -24
- package/dist/extensions/NEEDLE_compression_texture/NEEDLE_compression_texture.js +0 -54
- package/dist/extensions/NEEDLE_compression_texture/index.d.ts +0 -1
- package/dist/extensions/NEEDLE_compression_texture/index.js +0 -1
- package/dist/extensions/NEEDLE_lightmaps/index.d.ts +0 -39
- package/dist/extensions/NEEDLE_lightmaps/index.js +0 -257
- package/dist/extensions/NEEDLE_mesh_compression/NEEDLE_mesh_compression.d.ts +0 -27
- package/dist/extensions/NEEDLE_mesh_compression/NEEDLE_mesh_compression.js +0 -88
- package/dist/extensions/NEEDLE_mesh_compression/index.d.ts +0 -1
- package/dist/extensions/NEEDLE_mesh_compression/index.js +0 -1
- package/dist/extensions/NEEDLE_opaque/NEEDLE_opaque.d.ts +0 -27
- package/dist/extensions/NEEDLE_opaque/NEEDLE_opaque.js +0 -1048
- package/dist/extensions/NEEDLE_opaque/index.d.ts +0 -3
- package/dist/extensions/NEEDLE_opaque/index.js +0 -30
- package/dist/extensions/NEEDLE_pmrem/index.d.ts +0 -21
- package/dist/extensions/NEEDLE_pmrem/index.js +0 -95
- package/dist/extensions/NEEDLE_progressive/NEEDLE_progressive.d.ts +0 -48
- package/dist/extensions/NEEDLE_progressive/NEEDLE_progressive.js +0 -69
- package/dist/extensions/NEEDLE_progressive/index.d.ts +0 -1
- package/dist/extensions/NEEDLE_progressive/index.js +0 -1
- package/dist/extensions/NEEDLE_progressive_mesh_settings/index.d.ts +0 -23
- package/dist/extensions/NEEDLE_progressive_mesh_settings/index.js +0 -41
- package/dist/extensions/NEEDLE_progressive_texture_settings/index.d.ts +0 -25
- package/dist/extensions/NEEDLE_progressive_texture_settings/index.js +0 -38
- package/dist/extensions/index.d.ts +0 -15
- package/dist/extensions/index.js +0 -34
- package/dist/extensions/utils.d.ts +0 -9
- package/dist/extensions/utils.js +0 -79
- package/dist/functions/weld.3.d.ts +0 -76
- package/dist/functions/weld.3.js +0 -414
- package/dist/index.d.ts +0 -8
- package/dist/index.js +0 -8
- package/dist/scripts/index.d.ts +0 -2
- package/dist/scripts/index.js +0 -2
- package/dist/scripts/pack-gltf.d.ts +0 -17
- package/dist/scripts/pack-gltf.js +0 -152
- package/dist/scripts/stats.d.ts +0 -5
- package/dist/scripts/stats.js +0 -20
- package/dist/transforms/index.d.ts +0 -9
- package/dist/transforms/index.js +0 -9
- package/dist/transforms/needle_animation_transform.d.ts +0 -2
- package/dist/transforms/needle_animation_transform.js +0 -5
- package/dist/transforms/needle_asset.d.ts +0 -3
- package/dist/transforms/needle_asset.js +0 -50
- package/dist/transforms/needle_common.d.ts +0 -17
- package/dist/transforms/needle_common.js +0 -1
- package/dist/transforms/needle_mesh_transform.d.ts +0 -15
- package/dist/transforms/needle_mesh_transform.js +0 -223
- package/dist/transforms/needle_pmrem.d.ts +0 -21
- package/dist/transforms/needle_pmrem.js +0 -238
- package/dist/transforms/needle_progressive.d.ts +0 -45
- package/dist/transforms/needle_progressive.js +0 -1101
- package/dist/transforms/needle_texture_transform.d.ts +0 -15
- package/dist/transforms/needle_texture_transform.js +0 -267
- package/dist/transforms/needle_toktx.d.ts +0 -26
- package/dist/transforms/needle_toktx.js +0 -250
- package/dist/transforms/needle_webp.d.ts +0 -15
- package/dist/transforms/needle_webp.js +0 -53
- package/dist/transforms/toktx.d.ts +0 -52
- package/dist/transforms/toktx.js +0 -221
- package/dist/transforms/toktx_types.d.ts +0 -78
- package/dist/transforms/toktx_types.js +0 -62
- package/dist/transforms/util.d.ts +0 -21
- package/dist/transforms/util.js +0 -90
- package/dist/utils/analytics.d.ts +0 -24
- package/dist/utils/analytics.js +0 -128
- package/dist/utils/compression_utils.d.ts +0 -2
- package/dist/utils/compression_utils.js +0 -6
- package/dist/utils/fileutils.d.ts +0 -22
- package/dist/utils/fileutils.js +0 -195
- package/dist/utils/guid.d.ts +0 -1
- package/dist/utils/guid.js +0 -5
- package/dist/utils/index.d.ts +0 -10
- package/dist/utils/index.js +0 -10
- package/dist/utils/merge.d.ts +0 -12
- package/dist/utils/merge.js +0 -31
- package/dist/utils/mesh.d.ts +0 -13
- package/dist/utils/mesh.js +0 -124
- package/dist/utils/nodeio.d.ts +0 -11
- package/dist/utils/nodeio.js +0 -116
- package/dist/utils/stats.d.ts +0 -70
- package/dist/utils/stats.js +0 -265
- package/dist/utils/test-assert.d.ts +0 -8
- package/dist/utils/test-assert.js +0 -18
- package/dist/utils/texture.d.ts +0 -5
- package/dist/utils/texture.js +0 -14
- package/dist/utils/validate.d.ts +0 -6
- package/dist/utils/validate.js +0 -17
- package/dist/utils/version.d.ts +0 -1
- package/dist/utils/version.gen.d.ts +0 -1
- package/dist/utils/version.gen.js +0 -1
- package/dist/utils/version.js +0 -4
- package/scripts/clear-caches.mjs +0 -4
- package/scripts/defaults.mjs +0 -12
- package/scripts/fileutils.mjs +0 -6
- package/scripts/index.mjs +0 -41
- package/scripts/limit-caches.mjs +0 -4
- package/scripts/make-progressive.mjs +0 -16
- package/scripts/pack-gltf.mjs +0 -107
package/dist/cli/index.js
CHANGED
|
@@ -1,255 +1,4177 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import {
|
|
12
|
-
import
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
2
|
+
|
|
3
|
+
// src/cli/index.ts
|
|
4
|
+
import { program } from "@donmccurdy/caporal";
|
|
5
|
+
|
|
6
|
+
// src/scripts/pack-gltf.ts
|
|
7
|
+
import path5 from "path";
|
|
8
|
+
import { Logger, NodeIO as NodeIO2, PropertyType as PropertyType12, Verbosity as Verbosity2 } from "@gltf-transform/core";
|
|
9
|
+
import { ALL_EXTENSIONS as ALL_EXTENSIONS3 } from "@gltf-transform/extensions";
|
|
10
|
+
import draco3d2 from "draco3dgltf";
|
|
11
|
+
import { existsSync as existsSync11, readFileSync as readFileSync8, statSync as statSync5, writeFileSync as writeFileSync6 } from "fs";
|
|
12
|
+
import { MeshoptDecoder as MeshoptDecoder2, MeshoptEncoder as MeshoptEncoder3 } from "meshoptimizer";
|
|
13
|
+
import { dedup as dedup2, metalRough as metalRough2, prune as prune2, resample } from "@gltf-transform/functions";
|
|
14
|
+
|
|
15
|
+
// src/extensions/NEEDLE_opaque/index.ts
|
|
16
|
+
import { PropertyType as PropertyType3 } from "@gltf-transform/core";
|
|
17
|
+
|
|
18
|
+
// src/extensions/NEEDLE_opaque/NEEDLE_opaque.ts
|
|
19
|
+
import { Extension as Extension2, ExtensionProperty as ExtensionProperty2, PropertyType as PropertyType2, Node, TextureChannel } from "@gltf-transform/core";
|
|
20
|
+
|
|
21
|
+
// src/extensions/utils.ts
|
|
22
|
+
import { WriterContext } from "@gltf-transform/core";
|
|
23
|
+
function tryGetInArray(arr, index) {
|
|
24
|
+
return index === void 0 ? null : Array.isArray(arr) && arr.length > index ? arr[index] : null;
|
|
25
|
+
}
|
|
26
|
+
function writeExtension(prop, name, ext) {
|
|
27
|
+
prop !== null && ext && (prop.extensions || (prop.extensions = {}), prop.extensions[name] = ext);
|
|
28
|
+
}
|
|
29
|
+
function getTexture(context, tex) {
|
|
30
|
+
if (!context.jsonDoc.json.images) return null;
|
|
31
|
+
let source = findSource(tex);
|
|
32
|
+
return source !== void 0 ? context.textures[source] : (console.log("Could not find texture", tex), null);
|
|
33
|
+
}
|
|
34
|
+
function findSource(texDef) {
|
|
35
|
+
if (texDef.source !== void 0) return texDef.source;
|
|
36
|
+
if (texDef.extensions)
|
|
37
|
+
for (let key of Object.keys(texDef.extensions)) {
|
|
38
|
+
let ext = texDef.extensions[key];
|
|
39
|
+
if (ext && ext.source !== void 0) return ext.source;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function getTextureDefinition(context, tex) {
|
|
43
|
+
let textureDefinitions = context.jsonDoc.json.textures;
|
|
44
|
+
if (!textureDefinitions) return null;
|
|
45
|
+
if (context instanceof WriterContext) {
|
|
46
|
+
let imageIndex = context.imageIndexMap.get(tex);
|
|
47
|
+
for (let def of textureDefinitions)
|
|
48
|
+
if (def.source === imageIndex)
|
|
49
|
+
return def;
|
|
50
|
+
} else {
|
|
51
|
+
let textureIndex = context.textures.indexOf(tex);
|
|
52
|
+
for (let i = 0; i < textureDefinitions.length; i++) {
|
|
53
|
+
let textureDef = textureDefinitions[i];
|
|
54
|
+
if (textureDef.source === textureIndex)
|
|
55
|
+
return textureDef;
|
|
56
|
+
if (textureDef.extensions)
|
|
57
|
+
for (let key of Object.keys(textureDef.extensions)) {
|
|
58
|
+
let ext = textureDef.extensions[key];
|
|
59
|
+
if (ext && ext.source === textureIndex)
|
|
60
|
+
return textureDef;
|
|
49
61
|
}
|
|
50
|
-
|
|
51
|
-
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/utils/texture.ts
|
|
68
|
+
function isMultipleOfFour(value) {
|
|
69
|
+
return value % 4 === 0;
|
|
70
|
+
}
|
|
71
|
+
function ceilMultipleOfFour(value) {
|
|
72
|
+
return value <= 4 ? 4 : value % 4 ? value + 4 - value % 4 : value;
|
|
73
|
+
}
|
|
74
|
+
function isLightmap(texture) {
|
|
75
|
+
return texture.getName()?.startsWith("Lightmap");
|
|
76
|
+
}
|
|
77
|
+
function setLightmapName(texture) {
|
|
78
|
+
texture.setName("Lightmap");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/extensions/NEEDLE_progressive_texture_settings/index.ts
|
|
82
|
+
import { Extension, ExtensionProperty, PropertyType } from "@gltf-transform/core";
|
|
83
|
+
var EXTENSION_NAME = "NEEDLE_progressive_texture_settings", NEEDLE_progressive_texture_settings = class extends Extension {
|
|
84
|
+
static EXTENSION_NAME = EXTENSION_NAME;
|
|
85
|
+
extensionName = EXTENSION_NAME;
|
|
86
|
+
read(context) {
|
|
87
|
+
let textureDefinitions = context.jsonDoc.json.textures;
|
|
88
|
+
if (!textureDefinitions) return this;
|
|
89
|
+
for (let i = 0; i < textureDefinitions.length; i++) {
|
|
90
|
+
let texDef = textureDefinitions[i];
|
|
91
|
+
if (texDef.extensions && texDef.extensions[EXTENSION_NAME]) {
|
|
92
|
+
let ext = texDef.extensions[EXTENSION_NAME], prop = new NEEDLE_progressive_texture_settings_property(this.document.getGraph(), "");
|
|
93
|
+
Object.assign(prop, ext), context.textures[texDef.source].setExtension(EXTENSION_NAME, prop);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return this;
|
|
97
|
+
}
|
|
98
|
+
write(context) {
|
|
99
|
+
return this;
|
|
100
|
+
}
|
|
101
|
+
}, NEEDLE_progressive_texture_settings_property = class extends ExtensionProperty {
|
|
102
|
+
static EXTENSION_NAME = EXTENSION_NAME;
|
|
103
|
+
extensionName = EXTENSION_NAME;
|
|
104
|
+
parentTypes = [PropertyType.TEXTURE];
|
|
105
|
+
propertyType = EXTENSION_NAME;
|
|
106
|
+
init() {
|
|
107
|
+
}
|
|
108
|
+
get isValid() {
|
|
109
|
+
return this.maxSize !== void 0 && this.maxSize > 0;
|
|
110
|
+
}
|
|
111
|
+
maxSize;
|
|
112
|
+
guid;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// src/utils/test-assert.ts
|
|
116
|
+
var IS_TEST = process.env.VITEST === "true", TestAssertionError = class extends Error {
|
|
117
|
+
constructor(message) {
|
|
118
|
+
super(message), this.name = "TestAssertionError";
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
function testAssert(condition, message) {
|
|
122
|
+
if (!condition && IS_TEST)
|
|
123
|
+
throw new TestAssertionError(`Assertion failed: ${message}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/extensions/NEEDLE_opaque/NEEDLE_opaque.ts
|
|
127
|
+
import { existsSync, readFileSync } from "fs";
|
|
128
|
+
import { dirname, join } from "path";
|
|
129
|
+
|
|
130
|
+
// src/transforms/needle_audio_registry.ts
|
|
131
|
+
var _refs = [];
|
|
132
|
+
function registerAudioRef(ref) {
|
|
133
|
+
_refs.push(ref);
|
|
134
|
+
}
|
|
135
|
+
function listAudioRefs() {
|
|
136
|
+
return _refs;
|
|
137
|
+
}
|
|
138
|
+
function clearAudioRegistry() {
|
|
139
|
+
_refs = [];
|
|
140
|
+
}
|
|
141
|
+
var AUDIO_EXTENSIONS = [".wav", ".flac", ".aiff", ".aif"], _audioRegex = new RegExp(`(${AUDIO_EXTENSIONS.map((e) => "\\" + e).join("|")})$`, "i");
|
|
142
|
+
function isAudioUri(value) {
|
|
143
|
+
return _audioRegex.test(value);
|
|
144
|
+
}
|
|
145
|
+
function isRelativeAudioUri(value) {
|
|
146
|
+
return !(!value || /^[a-z]+:/i.test(value) || value.startsWith("//") || value.startsWith("/") || /^[a-z]:[\\/]/i.test(value));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/extensions/NEEDLE_opaque/NEEDLE_opaque.ts
|
|
150
|
+
var ALL_PROPERTY_TYPES = [];
|
|
151
|
+
for (let key in PropertyType2)
|
|
152
|
+
ALL_PROPERTY_TYPES.push(PropertyType2[key]);
|
|
153
|
+
var currentGenerator = "";
|
|
154
|
+
function createOpaqueExtension(name, types, opts) {
|
|
155
|
+
Array.isArray(types) || (types = [types]);
|
|
156
|
+
let EXTENSION_NAME7 = name, ExtensionPropertyTypes = ALL_PROPERTY_TYPES, debugLog3 = opts?.debug ?? !1;
|
|
157
|
+
class NEEDLE_opaque extends Extension2 {
|
|
158
|
+
extensionName = EXTENSION_NAME7;
|
|
159
|
+
static EXTENSION_NAME = EXTENSION_NAME7;
|
|
160
|
+
prewriteTypes = [PropertyType2.MATERIAL];
|
|
161
|
+
// private roots: Array<OpaqueProperty> = [];
|
|
162
|
+
jsonPointerHandler;
|
|
163
|
+
read(context) {
|
|
164
|
+
if (opts?.breakpoint === !0) debugger;
|
|
165
|
+
currentGenerator = context.jsonDoc.json.asset?.generator, debugLog3 && console.log("READ " + EXTENSION_NAME7), this.jsonPointerHandler = new JsonPointerHandler(this.document, EXTENSION_NAME7), this.jsonPointerHandler.debug = debugLog3, this.jsonPointerHandler.breakPoint = opts?.breakpoint;
|
|
166
|
+
for (let type of types)
|
|
167
|
+
switch (type) {
|
|
168
|
+
case PropertyType2.ACCESSOR:
|
|
169
|
+
this.onRead(context, "accessors", "accessorIndexMap");
|
|
170
|
+
break;
|
|
171
|
+
case PropertyType2.ANIMATION:
|
|
172
|
+
this.onRead(context, "animations", "animationIndexMap");
|
|
173
|
+
break;
|
|
174
|
+
case PropertyType2.ANIMATION_CHANNEL:
|
|
175
|
+
EXTENSION_NAME7 === "KHR_animation_pointer" && context.jsonDoc.json.animations?.forEach((animDef, animIndex) => {
|
|
176
|
+
let anim = context.animations[animIndex], channels = anim.listChannels();
|
|
177
|
+
animDef.channels?.forEach((channel, channelIndex) => {
|
|
178
|
+
let jsonTarget = channel.target, khr_animation = jsonTarget.extensions && jsonTarget.extensions[EXTENSION_NAME7];
|
|
179
|
+
if (!khr_animation) return;
|
|
180
|
+
let pointer = khr_animation.pointer;
|
|
181
|
+
if (pointer) {
|
|
182
|
+
let sections = pointer.split("/"), nodeIndex = parseInt(sections[2]), targetName = sections[3];
|
|
183
|
+
(targetName === "scale" || targetName === "translation" || targetName === "rotation") && (channels[channelIndex].setTargetNode(context.nodes[nodeIndex]), channels[channelIndex].setTargetPath(targetName));
|
|
184
|
+
}
|
|
185
|
+
let existing = anim.getExtension(EXTENSION_NAME7);
|
|
186
|
+
if (debugLog3 && console.log(">>>", EXTENSION_NAME7, "animation", animIndex, "channel", channelIndex, khr_animation), existing) {
|
|
187
|
+
assignChannels(existing);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
let prop = this.createExtension(), khr_animation_data = {};
|
|
191
|
+
khr_animation_data[channelIndex] = khr_animation, anim.setExtension(EXTENSION_NAME7, prop), assignChannels(prop);
|
|
192
|
+
function assignChannels(prop2) {
|
|
193
|
+
prop2.add((ctx) => {
|
|
194
|
+
let animations = ctx.jsonDoc.json.animations;
|
|
195
|
+
if (!animations) return;
|
|
196
|
+
let channel2 = animations[animIndex]?.channels[channelIndex];
|
|
197
|
+
channel2 ? (debugLog3 && console.log("<<<", EXTENSION_NAME7, "animation", animIndex, "channel", channelIndex, khr_animation), channel2.target = jsonTarget) : debugLog3 && console.log("WARN: ", EXTENSION_NAME7, "animation", animIndex, "channel", channelIndex, "not found");
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
break;
|
|
203
|
+
case PropertyType2.ANIMATION_SAMPLER:
|
|
204
|
+
break;
|
|
205
|
+
case PropertyType2.BUFFER:
|
|
206
|
+
this.onRead(context, "buffers", "bufferIndexMap");
|
|
207
|
+
break;
|
|
208
|
+
case PropertyType2.CAMERA:
|
|
209
|
+
this.onRead(context, "cameras", "cameraIndexMap");
|
|
210
|
+
break;
|
|
211
|
+
case PropertyType2.MATERIAL:
|
|
212
|
+
this.onRead(context, "materials", "materialIndexMap");
|
|
213
|
+
break;
|
|
214
|
+
case PropertyType2.TEXTURE:
|
|
215
|
+
context.jsonDoc.json.textures?.forEach((textureDefinition, index) => {
|
|
216
|
+
if (!textureDefinition.extensions) return;
|
|
217
|
+
let ext2 = textureDefinition.extensions[EXTENSION_NAME7];
|
|
218
|
+
if (!ext2) return;
|
|
219
|
+
let texture = getTexture(context, textureDefinition);
|
|
220
|
+
texture || (console.log("WARN: could potentially not find gltf transform texture for " + index), texture = context.textures[index]);
|
|
221
|
+
let prop = this.createExtension();
|
|
222
|
+
this.jsonPointerHandler.read(context, texture, ext2, prop), texture.setExtension(EXTENSION_NAME7, prop);
|
|
223
|
+
let handler = new TextureHandler(this.document, textureDefinition, EXTENSION_NAME7, ext2, debugLog3, texture);
|
|
224
|
+
prop.add(handler);
|
|
225
|
+
let sourceIndex = textureDefinition.source;
|
|
226
|
+
debugLog3 && console.log("Found texture with extension", EXTENSION_NAME7, "at index", index, "source image index", sourceIndex, "name", texture.getName() || "<unnamed>");
|
|
227
|
+
});
|
|
228
|
+
break;
|
|
229
|
+
case PropertyType2.NODE:
|
|
230
|
+
this.onRead(context, "nodes", "nodeIndexMap");
|
|
231
|
+
break;
|
|
232
|
+
case PropertyType2.MESH:
|
|
233
|
+
this.onRead(context, "meshes", "meshIndexMap");
|
|
234
|
+
break;
|
|
235
|
+
case PropertyType2.PRIMITIVE:
|
|
236
|
+
context.jsonDoc.json.meshes?.forEach((meshDefinition, meshIndex) => {
|
|
237
|
+
let mesh = context.meshes[meshIndex], primitives = mesh.listPrimitives();
|
|
238
|
+
meshDefinition.primitives?.forEach((primitiveDefinition, primitiveIndex) => {
|
|
239
|
+
if (!primitiveDefinition.extensions) return;
|
|
240
|
+
let ext2 = primitiveDefinition.extensions[EXTENSION_NAME7];
|
|
241
|
+
if (!ext2) return;
|
|
242
|
+
let primitive = primitives[primitiveIndex], prop = this.createExtension();
|
|
243
|
+
this.jsonPointerHandler.read(context, primitive, ext2, prop), primitive.setExtension(EXTENSION_NAME7, prop), prop.add((ctx) => {
|
|
244
|
+
let newMeshIndex = ctx.meshIndexMap.get(mesh), newPrimitive = ctx.jsonDoc.json.meshes[newMeshIndex].primitives[primitiveIndex];
|
|
245
|
+
newPrimitive.extensions = newPrimitive.extensions || {}, newPrimitive.extensions[EXTENSION_NAME7] = ext2;
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
break;
|
|
250
|
+
case PropertyType2.ROOT:
|
|
251
|
+
let sourceArray = context.jsonDoc.json.extensions;
|
|
252
|
+
if (!sourceArray) continue;
|
|
253
|
+
let ext = sourceArray[EXTENSION_NAME7];
|
|
254
|
+
if (ext) {
|
|
255
|
+
let root = this.document.getRoot(), prop = this.createExtension();
|
|
256
|
+
this.jsonPointerHandler.read(context, root, ext, prop), root.setExtension(EXTENSION_NAME7, prop), this.lightmapWorkaround(context, prop, this.document.getLogger()), prop.add((ctx) => {
|
|
257
|
+
ctx.jsonDoc.json.extensions = ctx.jsonDoc.json.extensions || {}, ctx.jsonDoc.json.extensions[EXTENSION_NAME7] = ext;
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
break;
|
|
52
261
|
}
|
|
262
|
+
return this;
|
|
53
263
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
.option("--cache", "Use \"--cache False\" to disable caching.\nWhen caching is enabled then previously processed files will be detected and loaded from disc cache instead of being processed again if settings or the file contents have not changed.", { validator: program.BOOLEAN, default: true })
|
|
69
|
-
.option("--debug", "Enable for more verbose outout with \"--debug True\"", { validator: program.BOOLEAN, default: false })
|
|
70
|
-
.option("--verbose", "Enable for more verbose outout with \"--verbose True\"", { validator: program.BOOLEAN, default: false })
|
|
71
|
-
.action(async ({ logger, args, options }) => {
|
|
72
|
-
logger.level = (options.debug || options.verbose) ? "debug" : "info";
|
|
73
|
-
// const logger = new Logger((options.debug || options.verbose) ? Verbosity.DEBUG : Verbosity.INFO);
|
|
74
|
-
if (options.compress === false && options.progressive === false) {
|
|
75
|
-
logger.error(`[Needle Build Pipeline] v${getVersion()} You need to enable at least one of the options: --compress or --progressive`);
|
|
76
|
-
return;
|
|
264
|
+
// this is temporarely here to prevent compression on textures named Lightmap
|
|
265
|
+
// until we have better control over the compression process
|
|
266
|
+
lightmapWorkaround(context, prop, logger) {
|
|
267
|
+
let textureDefinitions = context.jsonDoc.json.textures;
|
|
268
|
+
if (!textureDefinitions) return;
|
|
269
|
+
let textures = this.document.getRoot().listTextures();
|
|
270
|
+
for (let i = 0; i < textures.length; i++) {
|
|
271
|
+
let tex = textures[i];
|
|
272
|
+
if (isLightmap(tex) && tex.getMimeType() !== "image/exr") {
|
|
273
|
+
prop.setReference("lightmapTexture", tex, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
|
|
274
|
+
let texDef = textureDefinitions[i], name2 = tex.getName() || texDef?.name;
|
|
275
|
+
logger.debug(`Found lightmap texture "${name2}" (${tex.getMimeType()}) in ${EXTENSION_NAME7}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
77
278
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
config = { ...createConfig(options.usecase.toString()), ...config, };
|
|
95
|
-
if (config.usecase != "default" && config.usecase != options.usecase.toString()) {
|
|
96
|
-
logger.warn(`Conflicting usecase. Your specific config at \"${options.config}\" has a different usecase than the one provided by the CLI: \"${options.usecase}\". Using the usecase from the config file.`);
|
|
279
|
+
createExtension(name2 = "") {
|
|
280
|
+
return new OpaqueProperty(this.document.getGraph(), name2);
|
|
281
|
+
}
|
|
282
|
+
onRead(context, gltfField, map) {
|
|
283
|
+
if (gltfField !== void 0)
|
|
284
|
+
try {
|
|
285
|
+
let sourceArray = context.jsonDoc.json[gltfField], target = context[gltfField];
|
|
286
|
+
sourceArray?.forEach((def, index) => {
|
|
287
|
+
if (!def.extensions || !def.extensions[EXTENSION_NAME7]) return;
|
|
288
|
+
let ext = def.extensions[EXTENSION_NAME7];
|
|
289
|
+
debugLog3 && console.log("READ", index, ext);
|
|
290
|
+
let prop = this.createExtension();
|
|
291
|
+
target[index].setExtension(EXTENSION_NAME7, prop), this.jsonPointerHandler.read(context, target[index], ext, prop), prop.add(new OpaqueWriter(map, gltfField, ext));
|
|
292
|
+
});
|
|
293
|
+
} catch (error) {
|
|
294
|
+
console.error("ERR: " + error);
|
|
97
295
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
296
|
+
}
|
|
297
|
+
prewrite(context, _propertyType) {
|
|
298
|
+
return this.jsonPointerHandler.resolveAndWrite(context, "prewrite"), this;
|
|
299
|
+
}
|
|
300
|
+
write(context) {
|
|
301
|
+
if (opts?.breakpoint === !0) debugger;
|
|
302
|
+
if (opts?.write === !1)
|
|
303
|
+
return this;
|
|
304
|
+
debugLog3 && console.log("WRITE " + EXTENSION_NAME7), this.jsonPointerHandler.resolveAndWrite(context, "write");
|
|
305
|
+
let root = this.document.getRoot();
|
|
306
|
+
for (let type of types)
|
|
307
|
+
switch (type) {
|
|
308
|
+
case PropertyType2.ACCESSOR:
|
|
309
|
+
this.onWrite(context, () => root.listAccessors());
|
|
310
|
+
break;
|
|
311
|
+
case PropertyType2.ANIMATION:
|
|
312
|
+
this.onWrite(context, () => root.listAnimations());
|
|
313
|
+
break;
|
|
314
|
+
case PropertyType2.ANIMATION_CHANNEL:
|
|
315
|
+
break;
|
|
316
|
+
case PropertyType2.ANIMATION_SAMPLER:
|
|
317
|
+
break;
|
|
318
|
+
case PropertyType2.BUFFER:
|
|
319
|
+
this.onWrite(context, () => root.listBuffers());
|
|
320
|
+
break;
|
|
321
|
+
case PropertyType2.CAMERA:
|
|
322
|
+
this.onWrite(context, () => root.listCameras());
|
|
323
|
+
break;
|
|
324
|
+
case PropertyType2.MATERIAL:
|
|
325
|
+
this.onWrite(context, () => root.listMaterials());
|
|
326
|
+
break;
|
|
327
|
+
case PropertyType2.TEXTURE:
|
|
328
|
+
this.onWrite(context, () => root.listTextures());
|
|
329
|
+
break;
|
|
330
|
+
case PropertyType2.NODE:
|
|
331
|
+
this.onWrite(context, () => root.listNodes());
|
|
332
|
+
break;
|
|
333
|
+
case PropertyType2.MESH:
|
|
334
|
+
this.onWrite(context, () => root.listMeshes());
|
|
335
|
+
break;
|
|
336
|
+
case PropertyType2.PRIMITIVE:
|
|
337
|
+
let allPrimitives = root.listMeshes().flatMap((mesh) => mesh.listPrimitives());
|
|
338
|
+
for (let primitive of allPrimitives) {
|
|
339
|
+
let ext = primitive.getExtension(EXTENSION_NAME7);
|
|
340
|
+
ext instanceof OpaqueProperty && ext.onWrite(context, primitive);
|
|
137
341
|
}
|
|
342
|
+
break;
|
|
343
|
+
case PropertyType2.ROOT:
|
|
344
|
+
let prop = root.getExtension(EXTENSION_NAME7);
|
|
345
|
+
prop instanceof OpaqueProperty ? prop.onWrite(context, root) : debugLog3 && console.warn("WARN: no extension found on root", EXTENSION_NAME7);
|
|
346
|
+
break;
|
|
138
347
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
348
|
+
return this;
|
|
349
|
+
}
|
|
350
|
+
onWrite(context, get) {
|
|
351
|
+
let arr = get();
|
|
352
|
+
if (arr)
|
|
353
|
+
for (let entry of arr) {
|
|
354
|
+
let ext = entry.getExtension(EXTENSION_NAME7);
|
|
355
|
+
ext instanceof OpaqueProperty && ext.onWrite(context, entry);
|
|
143
356
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
class OpaqueProperty extends ExtensionProperty2 {
|
|
360
|
+
static EXTENSION_NAME = EXTENSION_NAME7;
|
|
361
|
+
extensionName = typeof EXTENSION_NAME7;
|
|
362
|
+
parentTypes = ExtensionPropertyTypes;
|
|
363
|
+
propertyType = "NEEDLE_opaque_property";
|
|
364
|
+
init() {
|
|
365
|
+
}
|
|
366
|
+
setReference(name2, value, attributes = { modifyChild: !0 }) {
|
|
367
|
+
this.setRef(name2, value, attributes);
|
|
368
|
+
}
|
|
369
|
+
writers = [];
|
|
370
|
+
add(writer) {
|
|
371
|
+
typeof writer == "function" && (writer = new GenericWriter(writer)), this.writers.push(writer);
|
|
372
|
+
}
|
|
373
|
+
onWrite(context, prop) {
|
|
374
|
+
for (let writer of this.writers)
|
|
375
|
+
writer.write?.call(writer, context, prop);
|
|
376
|
+
}
|
|
377
|
+
getExtensionDefinition() {
|
|
378
|
+
let ext = {};
|
|
379
|
+
for (let writer of this.writers)
|
|
380
|
+
writer.assignTo && writer.assignTo(ext);
|
|
381
|
+
return ext;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
class OpaqueWriter {
|
|
385
|
+
map;
|
|
386
|
+
gltfField;
|
|
387
|
+
ext;
|
|
388
|
+
assignTo(obj) {
|
|
389
|
+
Object.assign(obj, this.ext);
|
|
390
|
+
}
|
|
391
|
+
constructor(map, gltfField, ext) {
|
|
392
|
+
this.map = map, this.gltfField = gltfField, this.ext = ext;
|
|
393
|
+
}
|
|
394
|
+
write(context, prop) {
|
|
395
|
+
if (prop && this.gltfField !== void 0) {
|
|
396
|
+
let index = context[this.map].get(prop), result = tryGetInArray(context.jsonDoc.json[this.gltfField], index);
|
|
397
|
+
writeExtension(result, EXTENSION_NAME7, this.ext);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return NEEDLE_opaque;
|
|
402
|
+
}
|
|
403
|
+
var GenericWriter = class {
|
|
404
|
+
fn;
|
|
405
|
+
constructor(fn) {
|
|
406
|
+
this.fn = fn;
|
|
407
|
+
}
|
|
408
|
+
write(ctx) {
|
|
409
|
+
this.fn(ctx);
|
|
410
|
+
}
|
|
411
|
+
}, TextureHandler = class {
|
|
412
|
+
document;
|
|
413
|
+
textureDefinition;
|
|
414
|
+
key;
|
|
415
|
+
ext;
|
|
416
|
+
debug = !1;
|
|
417
|
+
/** Reference to the gltf-transform Texture object, used to resolve the current image index at write time via imageIndexMap */
|
|
418
|
+
textureRef;
|
|
419
|
+
assignTo(obj) {
|
|
420
|
+
Object.assign(obj, this.ext);
|
|
421
|
+
}
|
|
422
|
+
constructor(doc, def, key, ext, debug, textureRef) {
|
|
423
|
+
if (this.document = doc, this.textureDefinition = def, this.key = key, this.ext = ext, this.debug = debug, this.textureRef = textureRef, debug) {
|
|
424
|
+
let index = this.tryGetSourceIndex(this.textureDefinition);
|
|
425
|
+
console.log(index, this.textureDefinition);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
write(ctx) {
|
|
429
|
+
if (this.key === "EXT_texture_exr" && this.textureRef.getMimeType() !== "image/exr")
|
|
430
|
+
return;
|
|
431
|
+
let imageIndex = ctx.imageIndexMap.get(this.textureRef);
|
|
432
|
+
if (testAssert(imageIndex !== void 0 || this.key === "EXT_texture_exr", `imageIndexMap missing texture ref for "${this.key}": ${this.textureRef.getName() || "<unnamed>"}`), imageIndex === void 0) {
|
|
433
|
+
this.debug && console.warn("WARN: failed to resolve image index for texture via imageIndexMap:", this.key, this.textureRef.getName() || "<unnamed>");
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
let foundTexture = !1, textureDefs = ctx.jsonDoc.json.textures || [];
|
|
437
|
+
textureDefs?.forEach((textureDef, i) => {
|
|
438
|
+
if (foundTexture) return;
|
|
439
|
+
let textureImageIndex = this.tryGetSourceIndex(textureDef);
|
|
440
|
+
if (imageIndex === textureImageIndex && (foundTexture = !0, !textureDef.extensions?.[this.key])) {
|
|
441
|
+
textureDef.extensions = textureDef.extensions || {}, this.debug && console.log("Re-Assign extension:", this.key, "at", i);
|
|
442
|
+
let newExt = { ...this.ext };
|
|
443
|
+
newExt.source !== void 0 && (newExt.source = imageIndex), textureDef.extensions[this.key] = newExt;
|
|
444
|
+
}
|
|
445
|
+
}), testAssert(foundTexture || this.key === "EXT_texture_exr", `failed to match texture for extension "${this.key}", imageIndex=${imageIndex}, textures=${textureDefs.length}, name=${this.textureRef.getName() || "<unnamed>"}, type=${this.textureRef.getMimeType()}`), foundTexture === !1 && this.debug && console.warn("WARN: failed to re-assign extension:", this.key, "imageIndex", imageIndex, textureDefs.length, this.textureRef.getName() || "<unnamed>", this.textureDefinition);
|
|
446
|
+
}
|
|
447
|
+
tryGetSourceIndex(def) {
|
|
448
|
+
let index = def.source;
|
|
449
|
+
if (index !== void 0) return index;
|
|
450
|
+
if (def.extensions)
|
|
451
|
+
for (let ext of Object.keys(def.extensions)) {
|
|
452
|
+
let extDef = def.extensions[ext];
|
|
453
|
+
if (extDef.source !== void 0) {
|
|
454
|
+
index = extDef.source;
|
|
455
|
+
break;
|
|
169
456
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
457
|
+
}
|
|
458
|
+
return index;
|
|
459
|
+
}
|
|
460
|
+
}, JsonPointerHandler = class {
|
|
461
|
+
extension_name;
|
|
462
|
+
document;
|
|
463
|
+
map = /* @__PURE__ */ new Map();
|
|
464
|
+
debug = !1;
|
|
465
|
+
breakPoint = !1;
|
|
466
|
+
VRM_0_MaterialIndexRegex = new RegExp(/materialProperties\/(?<material_index>\d+)\//g);
|
|
467
|
+
/** Cache of external EXR files already injected as Textures (keyed by filename) */
|
|
468
|
+
externalExrTextures = /* @__PURE__ */ new Map();
|
|
469
|
+
/** External EXR references that need URI resolution at write time */
|
|
470
|
+
externalExrPointers = [];
|
|
471
|
+
constructor(document, extension_name) {
|
|
472
|
+
this.document = document, this.extension_name = extension_name;
|
|
473
|
+
}
|
|
474
|
+
read(context, extProp, obj, prop, key, fullPath) {
|
|
475
|
+
let value = key !== void 0 ? obj[key] : obj;
|
|
476
|
+
if (key !== void 0 && (fullPath ??= "", fullPath += "/" + key, this.breakPoint === "pointer:read"))
|
|
477
|
+
debugger;
|
|
478
|
+
switch (typeof value) {
|
|
479
|
+
case "object":
|
|
480
|
+
if (value != null)
|
|
481
|
+
if (Array.isArray(value))
|
|
482
|
+
for (let i = 0; i < value.length; i++)
|
|
483
|
+
this.read(context, extProp, value, prop, i.toString(), fullPath);
|
|
484
|
+
else
|
|
485
|
+
for (let key2 of Object.keys(value))
|
|
486
|
+
this.read(context, extProp, value, prop, key2, fullPath);
|
|
487
|
+
break;
|
|
488
|
+
case "string":
|
|
489
|
+
if (value && key) {
|
|
490
|
+
let prefix = "/textures/", isTexturePointer = value.startsWith(prefix);
|
|
491
|
+
if (isTexturePointer || (prefix = "textures/", isTexturePointer = value.startsWith(prefix)), isTexturePointer) {
|
|
492
|
+
this.debug && console.log("Read pointer", value);
|
|
493
|
+
let pointer = this.map.get(value);
|
|
494
|
+
if (!pointer) {
|
|
495
|
+
let length = prefix.length, index = parseInt(value.substring(length)), path8 = value.substring(0, length), definition = context.jsonDoc.json.textures[index], imageIndex = findSource(definition);
|
|
496
|
+
this.debug && console.log("Texture index", index, imageIndex, context.jsonDoc.json.textures.length, "Textures:" + context.textures.length);
|
|
497
|
+
let object = tryGetInArray(context.textures, imageIndex);
|
|
498
|
+
if (object) {
|
|
499
|
+
let res = new TextureIndexResolver(this.document, object, definition);
|
|
500
|
+
res.debug = this.debug, res.init(context), pointer = new JsonPointer(path8, res, value), pointer.debug = this.debug, this.map.set(value, pointer);
|
|
501
|
+
let referenceName = value;
|
|
502
|
+
prop.setReference(referenceName, object, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
|
|
503
|
+
let buffer = this.document.getRoot().listBuffers()[0];
|
|
504
|
+
buffer && prop.setReference("buffer", buffer);
|
|
505
|
+
} else
|
|
506
|
+
console.warn("Texture not found", fullPath, value);
|
|
507
|
+
}
|
|
508
|
+
pointer ? (this.debug && console.log("> Register pointer", this.extension_name + "/" + fullPath + " : " + value), pointer?.register(obj, key, fullPath)) : console.warn("WARN: failed registering pointer", fullPath, value);
|
|
509
|
+
}
|
|
510
|
+
if (!isTexturePointer && isAudioUri(value) && isRelativeAudioUri(value)) {
|
|
511
|
+
let inputDir = getExtensionInputFile() ? dirname(getExtensionInputFile()) : "", audioPath = inputDir ? join(inputDir, value) : "";
|
|
512
|
+
audioPath && existsSync(audioPath) ? (registerAudioRef({ obj, key, sourcePath: audioPath, sourceUri: value }), this.debug && console.log(`Registered external audio "${value}" at ${fullPath}`)) : audioPath && this.document.getLogger().warn(`NEEDLE_opaque: external audio not found: ${audioPath}`);
|
|
513
|
+
}
|
|
514
|
+
if (!isTexturePointer && value.match(/\.exr$/i)) {
|
|
515
|
+
let inputDir = getExtensionInputFile() ? dirname(getExtensionInputFile()) : "", exrPath = inputDir ? join(inputDir, value) : "";
|
|
516
|
+
if (exrPath && existsSync(exrPath)) {
|
|
517
|
+
let texture = this.externalExrTextures.get(value);
|
|
518
|
+
if (!texture) {
|
|
519
|
+
let exrBytes = readFileSync(exrPath);
|
|
520
|
+
texture = this.document.createTexture(value).setImage(new Uint8Array(exrBytes)).setMimeType("image/exr").setURI(value), this.externalExrTextures.set(value, texture), this.debug && console.log(`Injected external EXR "${value}" as Texture`);
|
|
521
|
+
}
|
|
522
|
+
prop.setReference(`exr_${value}`, texture, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
|
|
523
|
+
let buffer = this.document.getRoot().listBuffers()[0];
|
|
524
|
+
buffer && prop.setReference(`exr_buffer_${value}`, buffer), this.externalExrPointers.push({ obj, key, texture });
|
|
525
|
+
} else exrPath && (this.document.getLogger().error(`NEEDLE_opaque: External EXR not found: ${exrPath}`), testAssert(!1, `NEEDLE_opaque: External EXR not found: ${exrPath}`));
|
|
526
|
+
}
|
|
527
|
+
if (value.startsWith("/materials/")) {
|
|
528
|
+
this.debug && console.log("Read pointer", value);
|
|
529
|
+
let index = parseInt(value.substring(11)), object = context.materials[index];
|
|
530
|
+
if (object) {
|
|
531
|
+
prop && prop.setReference(value, object);
|
|
532
|
+
let pointer = this.map.get(value);
|
|
533
|
+
if (!pointer) {
|
|
534
|
+
let definition = context.jsonDoc.json.materials[index], res = new MaterialIndexResolver(this.document, object, definition);
|
|
535
|
+
res.debug = this.debug, res.init(context), pointer = new JsonPointer("/materials/", res, value), pointer.debug = this.debug, this.map.set(value, pointer), prop.setReference(value, object);
|
|
536
|
+
}
|
|
537
|
+
pointer?.register(obj, key, fullPath);
|
|
189
538
|
}
|
|
190
|
-
|
|
191
|
-
|
|
539
|
+
}
|
|
540
|
+
if (value.startsWith("/animations/")) {
|
|
541
|
+
this.debug && console.log("Read pointer", value);
|
|
542
|
+
let index = parseInt(value.substring(12)), object = context.animations[index];
|
|
543
|
+
if (object) {
|
|
544
|
+
let pointer = this.map.get(value);
|
|
545
|
+
pointer || prop.setReference(value, object), pointer?.register(obj, key, fullPath);
|
|
192
546
|
}
|
|
547
|
+
}
|
|
548
|
+
if (value.startsWith("/meshes/")) {
|
|
549
|
+
this.debug && console.log("Read pointer", value);
|
|
550
|
+
let index = parseInt(value.substring(8)), object = context.meshes[index];
|
|
551
|
+
if (object) {
|
|
552
|
+
let pointer = this.map.get(value);
|
|
553
|
+
if (!pointer) {
|
|
554
|
+
let definition = context.jsonDoc.json.meshes[index], res = new MeshIndexResolver(this.document, object, definition, prop);
|
|
555
|
+
res.debug = this.debug, res.init(context), pointer = new JsonPointer("/meshes/", res, value), pointer.debug = this.debug, this.map.set(value, pointer), prop.setReference(value, object);
|
|
556
|
+
}
|
|
557
|
+
pointer?.register(obj, key, fullPath);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
193
560
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
561
|
+
break;
|
|
562
|
+
case "number":
|
|
563
|
+
if (key === "node" || key === "mesh" || fullPath.match(/springs\/\d+\/center/g)) {
|
|
564
|
+
let object = context.nodes[value];
|
|
565
|
+
if (object) {
|
|
566
|
+
let res = new NodeIndexResolver(this.document, object, context.jsonDoc.json.nodes[value]);
|
|
567
|
+
res.debug = this.debug, res.init(context);
|
|
568
|
+
let dictKey = `/${key}/${value}`, pointer = this.map.get(dictKey);
|
|
569
|
+
pointer || (pointer = new JsonPointer(null, res, value)), pointer.debug = this.debug, pointer.register(obj, key, fullPath), this.map.set(dictKey, pointer), prop.setReference(dictKey, object);
|
|
570
|
+
}
|
|
571
|
+
} else if (
|
|
572
|
+
// key texture is matching for example for VRM meta/texture (AvatarSample_A)
|
|
573
|
+
key === "texture" || fullPath.match(/materialProperties\/(?<material_index>\d+)\/textureProperties/g) || fullPath.match(/meta\/thumbnailImage/g) || fullPath.match(/^\/textures\/\d{1,}$/)
|
|
574
|
+
) {
|
|
575
|
+
let index = value;
|
|
576
|
+
if (index < 0) {
|
|
577
|
+
console.warn(`WARN: texture index is negative ${index} at ${fullPath}`);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
let definition = context.jsonDoc.json.textures[index];
|
|
581
|
+
if (!definition) {
|
|
582
|
+
console.warn(`WARN: texture definition with index ${index} not found or does not exist. Set in "${fullPath}"`);
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
let imageIndex = findSource(definition);
|
|
586
|
+
this.debug && console.log("Texture index", index, imageIndex, context.jsonDoc.json.textures.length, "Textures:" + context.textures.length);
|
|
587
|
+
let object = tryGetInArray(context.textures, imageIndex);
|
|
588
|
+
if (object) {
|
|
589
|
+
this.debug && console.log("Found texture index at " + fullPath + ": " + value);
|
|
590
|
+
let res = new TextureIndexResolver(this.document, object, definition);
|
|
591
|
+
res.debug = this.debug, res.init(context);
|
|
592
|
+
let dictKey = `/textures/${value}`, pointer = this.map.get(dictKey);
|
|
593
|
+
pointer || (pointer = new JsonPointer(null, res, value)), pointer.debug = this.debug, pointer.register(obj, key, fullPath), this.map.set(dictKey, pointer), prop.setReference(dictKey, object, { channels: TextureChannel.R | TextureChannel.G | TextureChannel.B | TextureChannel.A });
|
|
594
|
+
}
|
|
595
|
+
let materialMatch = this.VRM_0_MaterialIndexRegex.exec(fullPath);
|
|
596
|
+
if (materialMatch) {
|
|
597
|
+
let materialIndex = parseInt(materialMatch.groups.material_index), material = context.materials[materialIndex];
|
|
598
|
+
prop.setReference(`/materials/${materialIndex}`, material);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
break;
|
|
602
|
+
default:
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
resolveAndWrite(context, step) {
|
|
607
|
+
this.map?.forEach((ptr) => {
|
|
608
|
+
ptr.resolve(context, step) && ptr.write();
|
|
609
|
+
});
|
|
610
|
+
for (let ref of listAudioRefs())
|
|
611
|
+
ref.newUri && ref.obj[ref.key] === ref.sourceUri && (this.debug && console.log(`< Resolved external audio: ${ref.sourceUri} \u2192 ${ref.newUri}`), ref.obj[ref.key] = ref.newUri);
|
|
612
|
+
for (let { obj, key, texture } of this.externalExrPointers) {
|
|
613
|
+
let uri = texture.getURI() || texture.getName() || "";
|
|
614
|
+
if (uri) {
|
|
615
|
+
this.debug && console.log(`< Resolved external EXR: ${obj[key]} \u2192 ${uri}`), obj[key] = uri;
|
|
616
|
+
let imageIndex = context.imageIndexMap.get(texture);
|
|
617
|
+
if (imageIndex !== void 0) {
|
|
618
|
+
let images = context.jsonDoc.json.images;
|
|
619
|
+
images && images[imageIndex] && !images[imageIndex].uri && (images[imageIndex].uri = uri);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}, JsonPointer = class {
|
|
625
|
+
debug = !1;
|
|
626
|
+
resolver;
|
|
627
|
+
pointerBase;
|
|
628
|
+
oldPointer;
|
|
629
|
+
constructor(pointerBase, resolver, oldPointer) {
|
|
630
|
+
this.pointerBase = pointerBase, this.resolver = resolver, this.oldPointer = oldPointer;
|
|
631
|
+
}
|
|
632
|
+
_objects = [];
|
|
633
|
+
_props = [];
|
|
634
|
+
_debugInfo = [];
|
|
635
|
+
register(obj, prop, fullpath) {
|
|
636
|
+
this._objects.push(obj), this._props.push(prop), this._debugInfo.push(fullpath);
|
|
637
|
+
}
|
|
638
|
+
newPointer = void 0;
|
|
639
|
+
resolve(context, step) {
|
|
640
|
+
if (this.newPointer !== void 0)
|
|
641
|
+
return !0;
|
|
642
|
+
this.resolver.debug = this.debug;
|
|
643
|
+
let index = this.resolver.resolve(context);
|
|
644
|
+
if (index != null)
|
|
645
|
+
return this.pointerBase != null ? this.newPointer = this.pointerBase + index : this.newPointer = index, !0;
|
|
646
|
+
if (step === "write" && (console.log(`ERR: \u{1F9E8} FAILED to resolve pointer "${this.oldPointer}" used by ${this._debugInfo.join(", ")}`), this.debug))
|
|
647
|
+
debugger;
|
|
648
|
+
return !1;
|
|
649
|
+
}
|
|
650
|
+
_didWrite = !1;
|
|
651
|
+
write() {
|
|
652
|
+
if (!this._didWrite) {
|
|
653
|
+
this._didWrite = !1;
|
|
654
|
+
for (let i = 0; i < this._objects.length; i++) {
|
|
655
|
+
let obj = this._objects[i], prop = this._props[i];
|
|
656
|
+
this.debug && console.log(`< Resolved pointer ${this._debugInfo[i]}: ${this.oldPointer} \u2192 ${this.newPointer}`), obj[prop] = this.newPointer;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}, PointerResolver = class {
|
|
661
|
+
document;
|
|
662
|
+
/* the object originally being referenced by the pointer */
|
|
663
|
+
inputObject;
|
|
664
|
+
/* the original json definition */
|
|
665
|
+
inputDefinition;
|
|
666
|
+
/** The graph property this pointer belongs to */
|
|
667
|
+
property;
|
|
668
|
+
constructor(doc, obj, def, prop) {
|
|
669
|
+
this.document = doc, this.inputObject = obj, this.inputDefinition = def, this.property = prop;
|
|
670
|
+
}
|
|
671
|
+
debug = !1;
|
|
672
|
+
}, TextureIndexResolver = class extends PointerResolver {
|
|
673
|
+
_debugName;
|
|
674
|
+
_samplerDef;
|
|
675
|
+
init(context) {
|
|
676
|
+
this._debugName = this.inputDefinition.name ?? this.inputDefinition.source?.toString() ?? "unknown";
|
|
677
|
+
let samplerIndex = this.inputDefinition.sampler;
|
|
678
|
+
samplerIndex !== void 0 && (this._samplerDef = context.jsonDoc.json.samplers[samplerIndex]), this.debug && console.log(this._debugName, this._samplerDef);
|
|
679
|
+
}
|
|
680
|
+
resolve(context) {
|
|
681
|
+
let imgIndex = context.imageIndexMap.get(this.inputObject);
|
|
682
|
+
if (imgIndex === void 0)
|
|
683
|
+
return testAssert(!1, `imageIndexMap missing texture: ${this.inputObject.getName() || "<unnamed>"}`), console.error("ERR: image is missing"), -1;
|
|
684
|
+
context.jsonDoc.json.textures = context.jsonDoc.json.textures || [];
|
|
685
|
+
for (let i = 0; i < context.jsonDoc.json.textures.length; i++) {
|
|
686
|
+
let textureDef2 = context.jsonDoc.json.textures[i];
|
|
687
|
+
if (findSource(textureDef2) === imgIndex)
|
|
688
|
+
return textureDef2.sampler === void 0 && (textureDef2.sampler = this.findOrCreateSampler(context.jsonDoc.json)), this.debug && console.log("Found texture def at " + i, "using image", imgIndex, textureDef2), i;
|
|
689
|
+
}
|
|
690
|
+
this.debug && console.log("Could not find texture, creating a new one: " + this._debugName);
|
|
691
|
+
let extensions = this.inputDefinition.extensions ? { ...this.inputDefinition.extensions } : void 0;
|
|
692
|
+
extensions && (delete extensions[NEEDLE_progressive_texture_settings.EXTENSION_NAME], extensions.EXT_texture_exr && this.inputObject.getMimeType() !== "image/exr" && delete extensions.EXT_texture_exr, Object.keys(extensions).length === 0 && (extensions = void 0));
|
|
693
|
+
let textureDef = {
|
|
694
|
+
source: extensions && Object.keys(extensions).some((key) => extensions[key]?.source !== void 0) ? void 0 : imgIndex,
|
|
695
|
+
sampler: this.findOrCreateSampler(context.jsonDoc.json),
|
|
696
|
+
extensions,
|
|
697
|
+
extras: this.inputDefinition.extras
|
|
698
|
+
};
|
|
699
|
+
return context.jsonDoc.json.textures.push(textureDef), context.jsonDoc.json.textures.length - 1;
|
|
700
|
+
}
|
|
701
|
+
findOrCreateSampler(json) {
|
|
702
|
+
if (json.samplers = json.samplers || [], this._samplerDef === void 0)
|
|
703
|
+
console.log("WARN: Creating default sampler", this._debugName), this._samplerDef = {
|
|
704
|
+
magFilter: 9729,
|
|
705
|
+
minFilter: 9729,
|
|
706
|
+
wrapS: 33648,
|
|
707
|
+
wrapT: 33648
|
|
708
|
+
};
|
|
709
|
+
else
|
|
710
|
+
for (let i = 0; i < json.samplers.length; i++) {
|
|
711
|
+
let sampler = json.samplers[i];
|
|
712
|
+
if (sampler.minFilter === this._samplerDef.minFilter && sampler.magFilter === this._samplerDef.magFilter && sampler.wrapS === this._samplerDef.wrapS && sampler.wrapT === this._samplerDef.wrapT)
|
|
713
|
+
return i;
|
|
714
|
+
}
|
|
715
|
+
return json.samplers.push(this._samplerDef), json.samplers.length - 1;
|
|
716
|
+
}
|
|
717
|
+
}, MaterialIndexResolver = class extends PointerResolver {
|
|
718
|
+
init(context) {
|
|
719
|
+
}
|
|
720
|
+
resolve(context) {
|
|
721
|
+
return context.materialIndexMap.get(this.inputObject);
|
|
722
|
+
}
|
|
723
|
+
}, NodeIndexResolver = class extends PointerResolver {
|
|
724
|
+
init(context) {
|
|
725
|
+
}
|
|
726
|
+
resolve(context) {
|
|
727
|
+
return context.nodeIndexMap.get(this.inputObject);
|
|
728
|
+
}
|
|
729
|
+
}, MeshIndexResolver = class extends PointerResolver {
|
|
730
|
+
init(context) {
|
|
731
|
+
}
|
|
732
|
+
resolve(context) {
|
|
733
|
+
let index = context.meshIndexMap.get(this.inputObject);
|
|
734
|
+
if (index >= 0)
|
|
735
|
+
return index;
|
|
736
|
+
let obj = null;
|
|
737
|
+
if (this.inputObject.isDisposed()) {
|
|
738
|
+
let parents = this.property?.listParents();
|
|
739
|
+
for (let parent of parents)
|
|
740
|
+
if (parent instanceof Node && (obj = parent.getMesh(), obj)) {
|
|
741
|
+
this.document.getLogger().info(`INFO: resolved mesh "${this.inputObject.getName()}" from parent node "${parent.getName()}"`);
|
|
742
|
+
break;
|
|
743
|
+
}
|
|
744
|
+
obj.isDisposed() && console.warn("WARN: mesh is disposed", this.inputObject.getName());
|
|
745
|
+
}
|
|
746
|
+
if (obj)
|
|
747
|
+
return context.meshIndexMap.get(obj);
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
// src/extensions/NEEDLE_opaque/index.ts
|
|
752
|
+
var opaqueOptions = {
|
|
753
|
+
debug: process.argv.includes("debug")
|
|
754
|
+
}, ALL_EXTENSIONS = [
|
|
755
|
+
createOpaqueExtension("KHR_animation_pointer", [PropertyType3.ANIMATION, PropertyType3.ANIMATION_CHANNEL], { ...opaqueOptions }),
|
|
756
|
+
createOpaqueExtension("NEEDLE_techniques_webgl", [PropertyType3.NODE, PropertyType3.MATERIAL, PropertyType3.ROOT], { ...opaqueOptions }),
|
|
757
|
+
createOpaqueExtension("NEEDLE_gameobject_data", PropertyType3.NODE, { ...opaqueOptions }),
|
|
758
|
+
createOpaqueExtension("NEEDLE_components", PropertyType3.NODE, { ...opaqueOptions }),
|
|
759
|
+
createOpaqueExtension("NEEDLE_persistent_assets", PropertyType3.ROOT, { ...opaqueOptions }),
|
|
760
|
+
// NEEDLE_lightmaps is now handled by its own dedicated extension (NEEDLE_lightmaps/index.ts)
|
|
761
|
+
createOpaqueExtension("NEEDLE_lighting_settings", PropertyType3.ROOT, { ...opaqueOptions }),
|
|
762
|
+
createOpaqueExtension("NEEDLE_render_objects", PropertyType3.ROOT, { ...opaqueOptions }),
|
|
763
|
+
createOpaqueExtension("NEEDLE_progressive", [PropertyType3.TEXTURE, PropertyType3.MATERIAL, PropertyType3.MESH], { ...opaqueOptions }),
|
|
764
|
+
createOpaqueExtension("EXT_texture_exr", [PropertyType3.TEXTURE], { ...opaqueOptions }),
|
|
765
|
+
createOpaqueExtension("NEEDLE_editor", [PropertyType3.NODE, PropertyType3.MATERIAL], { ...opaqueOptions }),
|
|
766
|
+
createOpaqueExtension("NEEDLE_gltf_dependencies", [PropertyType3.ROOT], { ...opaqueOptions }),
|
|
767
|
+
// MaterialX
|
|
768
|
+
createOpaqueExtension("NEEDLE_materials_mtlx", [PropertyType3.ROOT, PropertyType3.MATERIAL], { ...opaqueOptions }),
|
|
769
|
+
// VRM 0.0
|
|
770
|
+
createOpaqueExtension("VRM", [PropertyType3.ROOT], { ...opaqueOptions }),
|
|
771
|
+
// VRM 1.0 https://vrm.dev/en/vrm1/changed/
|
|
772
|
+
createOpaqueExtension("VRMC_vrm", [PropertyType3.ROOT], { ...opaqueOptions }),
|
|
773
|
+
createOpaqueExtension("VRMC_springBone", [PropertyType3.ROOT], { ...opaqueOptions }),
|
|
774
|
+
createOpaqueExtension("VRMC_node_constraint", [PropertyType3.NODE], { ...opaqueOptions })
|
|
775
|
+
// TODO: mtoon materials don't work yet
|
|
776
|
+
// createOpaqueExtension("VRMC_materials_mtoon", [PropertyType.MATERIAL], { ...opaqueOptions, debug: true, breakpoint: "pointer:read" },),
|
|
777
|
+
];
|
|
778
|
+
|
|
779
|
+
// src/extensions/NEEDLE_mesh_compression/NEEDLE_mesh_compression.ts
|
|
780
|
+
import { Extension as Extension3, ExtensionProperty as ExtensionProperty3, PropertyType as PropertyType4 } from "@gltf-transform/core";
|
|
781
|
+
var EXTENSION_NAME2 = "NEEDLE_mesh_compression", NEEDLE_mesh_compression_model_root = class {
|
|
782
|
+
compression;
|
|
783
|
+
constructor(compression) {
|
|
784
|
+
this.compression = compression;
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
var debugLog = !1, NEEDLE_mesh_compression = class extends Extension3 {
|
|
788
|
+
static EXTENSION_NAME = EXTENSION_NAME2;
|
|
789
|
+
extensionName = EXTENSION_NAME2;
|
|
790
|
+
create(model) {
|
|
791
|
+
let ext = new NEEDLE_mesh_compression_property(this.document.getGraph(), "");
|
|
792
|
+
return ext.model = model, ext;
|
|
793
|
+
}
|
|
794
|
+
read(context) {
|
|
795
|
+
debugLog && console.log("READ " + EXTENSION_NAME2);
|
|
796
|
+
let root = context.jsonDoc.json.extensions?.[EXTENSION_NAME2];
|
|
797
|
+
return root && this.document.getRoot().setExtension(EXTENSION_NAME2, this.create(root)), context.jsonDoc.json.meshes && context.meshes?.forEach((mesh, index) => {
|
|
798
|
+
let meshDefinition = context.jsonDoc.json.meshes[index];
|
|
799
|
+
if (!meshDefinition) return;
|
|
800
|
+
let primitives = mesh.listPrimitives();
|
|
801
|
+
for (let i = 0; i < primitives.length; i++) {
|
|
802
|
+
let primitive = meshDefinition.primitives[i];
|
|
803
|
+
if (primitive.extensions && primitive.extensions[EXTENSION_NAME2]) {
|
|
804
|
+
let model = primitive.extensions[EXTENSION_NAME2];
|
|
805
|
+
primitives[i].setExtension(EXTENSION_NAME2, this.create(model));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}), this;
|
|
809
|
+
}
|
|
810
|
+
write(ctx) {
|
|
811
|
+
debugLog && console.log("WRITE " + EXTENSION_NAME2);
|
|
812
|
+
let root = this.document.getRoot(), rootExtension = root.getExtension(EXTENSION_NAME2);
|
|
813
|
+
rootExtension && (ctx.jsonDoc.json.extensions = ctx.jsonDoc.json.extensions || {}, ctx.jsonDoc.json.extensions[EXTENSION_NAME2] = rootExtension.model);
|
|
814
|
+
for (let mesh of root.listMeshes()) {
|
|
815
|
+
let index = ctx.meshIndexMap.get(mesh), meshDef = ctx.jsonDoc.json.meshes[index], primitives = mesh.listPrimitives();
|
|
816
|
+
for (let i = 0; i < primitives.length; i++) {
|
|
817
|
+
let ext = primitives[i].getExtension(EXTENSION_NAME2);
|
|
818
|
+
if (ext) {
|
|
819
|
+
let prim = meshDef.primitives[i];
|
|
820
|
+
prim && (prim.extensions = prim.extensions || {}, prim.extensions[EXTENSION_NAME2] = ext.model);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return this;
|
|
825
|
+
}
|
|
826
|
+
}, NEEDLE_mesh_compression_property = class extends ExtensionProperty3 {
|
|
827
|
+
static EXTENSION_NAME = EXTENSION_NAME2;
|
|
828
|
+
extensionName = EXTENSION_NAME2;
|
|
829
|
+
parentTypes = [PropertyType4.ROOT, PropertyType4.PRIMITIVE, PropertyType4.MESH];
|
|
830
|
+
propertyType = EXTENSION_NAME2;
|
|
831
|
+
init() {
|
|
832
|
+
}
|
|
833
|
+
model;
|
|
834
|
+
copy(other, resolve4 = null) {
|
|
835
|
+
return this.model = { ...other.model }, super.copy(other, resolve4);
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
|
|
839
|
+
// src/extensions/NEEDLE_compression_texture/NEEDLE_compression_texture.ts
|
|
840
|
+
import { Extension as Extension4, ExtensionProperty as ExtensionProperty4, PropertyType as PropertyType5 } from "@gltf-transform/core";
|
|
841
|
+
var EXTENSION_NAME3 = "NEEDLE_compression_texture", debugLog2 = !1, NEEDLE_compression_texture = class extends Extension4 {
|
|
842
|
+
static EXTENSION_NAME = EXTENSION_NAME3;
|
|
843
|
+
extensionName = EXTENSION_NAME3;
|
|
844
|
+
create(toktxInfo) {
|
|
845
|
+
let ext = new NEEDLE_compression_texture_property(this.document.getGraph(), "");
|
|
846
|
+
return ext.model = toktxInfo, ext;
|
|
847
|
+
}
|
|
848
|
+
read(context) {
|
|
849
|
+
return debugLog2 && console.log("READ " + EXTENSION_NAME3), context.jsonDoc.json.textures ? (context.textures?.forEach((tex, _) => {
|
|
850
|
+
let textureDefinition = getTextureDefinition(context, tex);
|
|
851
|
+
if (textureDefinition?.extensions && textureDefinition.extensions[EXTENSION_NAME3]) {
|
|
852
|
+
let prop = new NEEDLE_compression_texture_property(this.document.getGraph(), EXTENSION_NAME3);
|
|
853
|
+
prop.model = textureDefinition.extensions[EXTENSION_NAME3], tex.setExtension(EXTENSION_NAME3, prop);
|
|
854
|
+
}
|
|
855
|
+
}), this) : this;
|
|
856
|
+
}
|
|
857
|
+
write(context) {
|
|
858
|
+
debugLog2 && console.log("WRITE " + EXTENSION_NAME3);
|
|
859
|
+
let textures = this.document.getRoot().listTextures();
|
|
860
|
+
for (let tex of textures) {
|
|
861
|
+
let ext = tex.getExtension(EXTENSION_NAME3);
|
|
862
|
+
if (ext) {
|
|
863
|
+
let def = getTextureDefinition(context, tex);
|
|
864
|
+
def && (def.extensions = def.extensions || {}, def.extensions[EXTENSION_NAME3] = ext.model);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
return this;
|
|
868
|
+
}
|
|
869
|
+
}, NEEDLE_compression_texture_property = class extends ExtensionProperty4 {
|
|
870
|
+
static EXTENSION_NAME = EXTENSION_NAME3;
|
|
871
|
+
init() {
|
|
872
|
+
this.extensionName = EXTENSION_NAME3, this.parentTypes = [PropertyType5.TEXTURE], this.propertyType = EXTENSION_NAME3;
|
|
873
|
+
}
|
|
874
|
+
model;
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
// src/extensions/NEEDLE_progressive/NEEDLE_progressive.ts
|
|
878
|
+
import { Extension as Extension5, ExtensionProperty as ExtensionProperty5, PropertyType as PropertyType6 } from "@gltf-transform/core";
|
|
879
|
+
var NEEDLE_PROGRESSIVE_EXTENSION_NAME = "NEEDLE_progressive", NEEDLE_progressive = class extends Extension5 {
|
|
880
|
+
static EXTENSION_NAME = NEEDLE_PROGRESSIVE_EXTENSION_NAME;
|
|
881
|
+
extensionName = NEEDLE_PROGRESSIVE_EXTENSION_NAME;
|
|
882
|
+
createTexture(data) {
|
|
883
|
+
let ext = new NEEDLE_progressive_property(this.document.getGraph());
|
|
884
|
+
return ext.model = data, ext;
|
|
885
|
+
}
|
|
886
|
+
createMesh(data) {
|
|
887
|
+
let ext = new NEEDLE_progressive_property(this.document.getGraph());
|
|
888
|
+
return ext.model = data, ext;
|
|
889
|
+
}
|
|
890
|
+
read(_context) {
|
|
891
|
+
return this;
|
|
892
|
+
}
|
|
893
|
+
write(context) {
|
|
894
|
+
let root = this.document.getRoot(), textureDefinitions = context.jsonDoc.json.textures;
|
|
895
|
+
if (textureDefinitions.length) {
|
|
896
|
+
let textures = root.listTextures(), textureImageIndexMap = context.imageIndexMap;
|
|
897
|
+
for (let tex of textures) {
|
|
898
|
+
let prop = tex.getExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME);
|
|
899
|
+
if (prop && prop.model) {
|
|
900
|
+
let imageIndex = textureImageIndexMap.get(tex);
|
|
901
|
+
for (let def of textureDefinitions)
|
|
902
|
+
def.source === imageIndex && (def.extensions = def.extensions || {}, def.extensions[NEEDLE_PROGRESSIVE_EXTENSION_NAME] = prop.model);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
let meshDefinitions = context.jsonDoc.json.meshes;
|
|
907
|
+
if (meshDefinitions?.length) {
|
|
908
|
+
let meshIndexMap = context.meshIndexMap, meshes = root.listMeshes();
|
|
909
|
+
for (let i = 0; i < meshes.length; i++) {
|
|
910
|
+
let mesh = meshes[i], meshIndex = meshIndexMap.get(mesh), meshExt = mesh.getExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME);
|
|
911
|
+
if (meshExt && meshExt.model) {
|
|
912
|
+
let meshDef = meshDefinitions[meshIndex];
|
|
913
|
+
meshDef.extensions = meshDef.extensions || {}, meshDef.extensions[NEEDLE_PROGRESSIVE_EXTENSION_NAME] = meshExt.model;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return this;
|
|
918
|
+
}
|
|
919
|
+
}, NEEDLE_progressive_property = class extends ExtensionProperty5 {
|
|
920
|
+
static EXTENSION_NAME = NEEDLE_PROGRESSIVE_EXTENSION_NAME;
|
|
921
|
+
extensionName = NEEDLE_PROGRESSIVE_EXTENSION_NAME;
|
|
922
|
+
parentTypes = [PropertyType6.TEXTURE, PropertyType6.MESH];
|
|
923
|
+
propertyType = "progressive_texture";
|
|
924
|
+
init() {
|
|
925
|
+
}
|
|
926
|
+
model;
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
// src/extensions/NEEDLE_progressive_mesh_settings/index.ts
|
|
930
|
+
import { Extension as Extension6, ExtensionProperty as ExtensionProperty6, PropertyType as PropertyType7 } from "@gltf-transform/core";
|
|
931
|
+
var EXTENSION_NAME4 = "NEEDLE_progressive_mesh_settings", NEEDLE_progressive_mesh_settings = class extends Extension6 {
|
|
932
|
+
static EXTENSION_NAME = EXTENSION_NAME4;
|
|
933
|
+
extensionName = EXTENSION_NAME4;
|
|
934
|
+
read(context) {
|
|
935
|
+
let definitions = context.jsonDoc.json.meshes;
|
|
936
|
+
if (!definitions) return this;
|
|
937
|
+
let meshes = this.document.getRoot().listMeshes();
|
|
938
|
+
for (let i = 0; i < definitions.length; i++) {
|
|
939
|
+
let def = definitions[i];
|
|
940
|
+
if (def.extensions && def.extensions[EXTENSION_NAME4]) {
|
|
941
|
+
let ext = def.extensions[EXTENSION_NAME4], prop = new NEEDLE_progressive_mesh_settings_property(this.document.getGraph(), "");
|
|
942
|
+
Object.assign(prop, ext);
|
|
943
|
+
let mesh = meshes[i];
|
|
944
|
+
mesh ? mesh.setExtension(EXTENSION_NAME4, prop) : console.warn(`WARN: Progressive mesh at index ${i} was not found in the glTF file. This might result in falsely loaded textures for ${ext.guid} / name "${def.name}"`);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
return this;
|
|
948
|
+
}
|
|
949
|
+
write(context) {
|
|
950
|
+
return this;
|
|
951
|
+
}
|
|
952
|
+
}, NEEDLE_progressive_mesh_settings_property = class extends ExtensionProperty6 {
|
|
953
|
+
static EXTENSION_NAME = EXTENSION_NAME4;
|
|
954
|
+
extensionName = EXTENSION_NAME4;
|
|
955
|
+
parentTypes = [PropertyType7.MESH];
|
|
956
|
+
propertyType = EXTENSION_NAME4;
|
|
957
|
+
init() {
|
|
958
|
+
}
|
|
959
|
+
generateLods;
|
|
960
|
+
guid;
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
// src/extensions/NEEDLE_pmrem/index.ts
|
|
964
|
+
import { Extension as Extension7 } from "@gltf-transform/core";
|
|
965
|
+
var EXTENSION_NAME5 = "NEEDLE_pmrem", NEEDLE_pmrem = class extends Extension7 {
|
|
966
|
+
static EXTENSION_NAME = EXTENSION_NAME5;
|
|
967
|
+
extensionName = EXTENSION_NAME5;
|
|
968
|
+
/** Textures that were converted from EXR via PMREM */
|
|
969
|
+
pmremTextures = /* @__PURE__ */ new Set();
|
|
970
|
+
/** Mark a texture as PMREM-converted */
|
|
971
|
+
addTexture(texture) {
|
|
972
|
+
this.pmremTextures.add(texture);
|
|
973
|
+
}
|
|
974
|
+
/** @hidden */
|
|
975
|
+
preread(context, _propertyType) {
|
|
976
|
+
let json = context.jsonDoc.json;
|
|
977
|
+
for (let textureDef of json.textures ?? []) {
|
|
978
|
+
let pmrem = textureDef.extensions?.[EXTENSION_NAME5];
|
|
979
|
+
pmrem?.source !== void 0 && textureDef.source === void 0 && (textureDef.source = pmrem.source);
|
|
980
|
+
}
|
|
981
|
+
for (let textureDef of json.textures ?? []) {
|
|
982
|
+
let pmrem = textureDef.extensions?.[EXTENSION_NAME5];
|
|
983
|
+
if (pmrem?.source !== void 0) {
|
|
984
|
+
let imageDef = json.images?.[pmrem.source];
|
|
985
|
+
imageDef && !imageDef.mimeType && (imageDef.mimeType = "image/ktx2");
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
return this;
|
|
989
|
+
}
|
|
990
|
+
/** @hidden */
|
|
991
|
+
read(context) {
|
|
992
|
+
let textureDefs = context.jsonDoc.json.textures ?? [], textures = this.document.getRoot().listTextures();
|
|
993
|
+
for (let i = 0; i < textureDefs.length; i++) {
|
|
994
|
+
if (textureDefs[i].extensions?.[EXTENSION_NAME5]?.source === void 0) continue;
|
|
995
|
+
let texture = textures[i];
|
|
996
|
+
texture && (texture.setMimeType("image/ktx2"), this.pmremTextures.add(texture));
|
|
997
|
+
}
|
|
998
|
+
return this;
|
|
999
|
+
}
|
|
1000
|
+
/** @hidden */
|
|
1001
|
+
write(context) {
|
|
1002
|
+
let jsonDoc = context.jsonDoc;
|
|
1003
|
+
for (let texture of this.pmremTextures) {
|
|
1004
|
+
let imageIndex = context.imageIndexMap.get(texture);
|
|
1005
|
+
if (imageIndex !== void 0)
|
|
1006
|
+
for (let textureDef of jsonDoc.json.textures ?? [])
|
|
1007
|
+
(textureDef.source ?? textureDef.extensions?.KHR_texture_basisu?.source) === imageIndex && (textureDef.extensions = textureDef.extensions || {}, textureDef.extensions[EXTENSION_NAME5] = { source: imageIndex }, delete textureDef.extensions.KHR_texture_basisu);
|
|
1008
|
+
}
|
|
1009
|
+
if (!(jsonDoc.json.textures ?? []).some(
|
|
1010
|
+
(t) => t.extensions?.KHR_texture_basisu
|
|
1011
|
+
)) {
|
|
1012
|
+
let remove = (arr) => {
|
|
1013
|
+
if (!arr) return;
|
|
1014
|
+
let idx = arr.indexOf("KHR_texture_basisu");
|
|
1015
|
+
idx >= 0 && arr.splice(idx, 1);
|
|
1016
|
+
};
|
|
1017
|
+
remove(jsonDoc.json.extensionsUsed), remove(jsonDoc.json.extensionsRequired);
|
|
1018
|
+
}
|
|
1019
|
+
return this;
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
|
|
1023
|
+
// src/extensions/NEEDLE_lightmaps/index.ts
|
|
1024
|
+
import { Extension as Extension8, ExtensionProperty as ExtensionProperty7, PropertyType as PropertyType9, TextureChannel as TextureChannel2 } from "@gltf-transform/core";
|
|
1025
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
1026
|
+
import { join as join2, dirname as dirname2 } from "path";
|
|
1027
|
+
var EXTENSION_NAME6 = "NEEDLE_lightmaps", LightmapProperty = class extends ExtensionProperty7 {
|
|
1028
|
+
static EXTENSION_NAME = EXTENSION_NAME6;
|
|
1029
|
+
propertyType = "LightmapProperty";
|
|
1030
|
+
parentTypes = [PropertyType9.ROOT];
|
|
1031
|
+
init() {
|
|
1032
|
+
this.extensionName = EXTENSION_NAME6;
|
|
1033
|
+
}
|
|
1034
|
+
getDefaults() {
|
|
1035
|
+
return Object.assign(super.getDefaults(), {});
|
|
1036
|
+
}
|
|
1037
|
+
/** Public wrapper around protected setRef to register references */
|
|
1038
|
+
setReference(name, value, attributes) {
|
|
1039
|
+
this.setRef(name, value, attributes);
|
|
1040
|
+
}
|
|
1041
|
+
}, NEEDLE_lightmaps_ext = class extends Extension8 {
|
|
1042
|
+
static EXTENSION_NAME = EXTENSION_NAME6;
|
|
1043
|
+
extensionName = EXTENSION_NAME6;
|
|
1044
|
+
prereadTypes = [PropertyType9.TEXTURE];
|
|
1045
|
+
prewriteTypes = [PropertyType9.MATERIAL];
|
|
1046
|
+
/** The raw extension JSON from the input (mutated in-place during write) */
|
|
1047
|
+
extensionData = null;
|
|
1048
|
+
/** Entries with resolved Texture references */
|
|
1049
|
+
resolved = [];
|
|
1050
|
+
/** Image indices injected during preread (for external EXR files) */
|
|
1051
|
+
injectedImageIndices = /* @__PURE__ */ new Map();
|
|
1052
|
+
/** The ExtensionProperty that holds references to prevent dedup/prune */
|
|
1053
|
+
lightmapProp = null;
|
|
1054
|
+
// ── preread ──────────────────────────────────────────────────
|
|
1055
|
+
preread(context, _propertyType) {
|
|
1056
|
+
let json = context.jsonDoc.json, ext = json.extensions?.[EXTENSION_NAME6];
|
|
1057
|
+
if (!ext?.textures) return this;
|
|
1058
|
+
let inputFile = getExtensionInputFile(), inputDir = inputFile ? dirname2(inputFile) : "";
|
|
1059
|
+
for (let entry of ext.textures) {
|
|
1060
|
+
if (entry.pointer.startsWith("/") || entry.pointer.startsWith("textures/") || !entry.pointer.match(/\.exr$/i)) continue;
|
|
1061
|
+
let exrPath = inputDir ? join2(inputDir, entry.pointer) : "";
|
|
1062
|
+
if (!exrPath || !existsSync2(exrPath)) {
|
|
1063
|
+
this.document.getLogger().error(`NEEDLE_lightmaps: External EXR not found: ${exrPath || entry.pointer}`), testAssert(!1, `NEEDLE_lightmaps: External EXR not found: ${exrPath || entry.pointer}`);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
let exrBytes = readFileSync2(exrPath);
|
|
1067
|
+
json.images = json.images || [], json.textures = json.textures || [];
|
|
1068
|
+
let imageIndex = json.images.length;
|
|
1069
|
+
json.images.push({
|
|
1070
|
+
uri: entry.pointer,
|
|
1071
|
+
mimeType: "image/exr",
|
|
1072
|
+
name: entry.pointer
|
|
1073
|
+
}), json.textures.push({
|
|
1074
|
+
source: imageIndex,
|
|
1075
|
+
name: entry.pointer
|
|
1076
|
+
}), context.jsonDoc.resources[entry.pointer] = new Uint8Array(exrBytes), this.injectedImageIndices.set(entry.pointer, imageIndex), this.document.getLogger().info(`NEEDLE_lightmaps: Registered external EXR "${entry.pointer}" as image[${imageIndex}]`);
|
|
1077
|
+
}
|
|
1078
|
+
return this;
|
|
1079
|
+
}
|
|
1080
|
+
// ── read ─────────────────────────────────────────────────────
|
|
1081
|
+
read(context) {
|
|
1082
|
+
let json = context.jsonDoc.json, ext = json.extensions?.[EXTENSION_NAME6];
|
|
1083
|
+
if (!ext?.textures) return this;
|
|
1084
|
+
this.extensionData = ext;
|
|
1085
|
+
let root = this.document.getRoot();
|
|
1086
|
+
this.lightmapProp = new LightmapProperty(this.document.getGraph()), root.setExtension(EXTENSION_NAME6, this.lightmapProp);
|
|
1087
|
+
let textureDefs = json.textures || [], logger = this.document.getLogger();
|
|
1088
|
+
for (let entry of ext.textures) {
|
|
1089
|
+
let texture = null, inputTextureDef;
|
|
1090
|
+
if (entry.pointer.startsWith("/textures/") || entry.pointer.startsWith("textures/")) {
|
|
1091
|
+
let prefix = entry.pointer.startsWith("/") ? "/textures/" : "textures/", texIndex = parseInt(entry.pointer.substring(prefix.length)), texDef = textureDefs[texIndex];
|
|
1092
|
+
texDef && (inputTextureDef = texDef, texture = getTexture(context, texDef) ?? null);
|
|
1093
|
+
} else if (entry.pointer.match(/\.exr$/i)) {
|
|
1094
|
+
let imageIndex = this.injectedImageIndices.get(entry.pointer);
|
|
1095
|
+
imageIndex !== void 0 && (texture = context.textures[imageIndex] ?? null, inputTextureDef = textureDefs.find((t) => findSource(t) === imageIndex));
|
|
1096
|
+
} else if (!entry.pointer.startsWith("/")) {
|
|
1097
|
+
let images = json.images ?? [];
|
|
1098
|
+
for (let i = 0; i < images.length; i++)
|
|
1099
|
+
if (images[i].uri === entry.pointer) {
|
|
1100
|
+
texture = context.textures[i] ?? null, inputTextureDef = textureDefs.find((t) => findSource(t) === i);
|
|
1101
|
+
break;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
if (texture) {
|
|
1105
|
+
this.resolved.push({ entry, texture, inputTextureDef });
|
|
1106
|
+
let refName = `lightmapTexture_${entry.pointer}`, channels = TextureChannel2.R | TextureChannel2.G | TextureChannel2.B | TextureChannel2.A;
|
|
1107
|
+
this.lightmapProp.setReference(refName, texture, { channels });
|
|
1108
|
+
let buffer = this.document.getRoot().listBuffers()[0];
|
|
1109
|
+
buffer && this.lightmapProp.setReference("buffer", buffer);
|
|
1110
|
+
} else
|
|
1111
|
+
this.document.getLogger().error(`NEEDLE_lightmaps: Could not resolve texture for pointer "${entry.pointer}"`), testAssert(!1, `NEEDLE_lightmaps: Could not resolve texture for pointer "${entry.pointer}"`);
|
|
1112
|
+
}
|
|
1113
|
+
let textures = this.document.getRoot().listTextures();
|
|
1114
|
+
for (let tex of textures)
|
|
1115
|
+
if (isLightmap(tex) && tex.getMimeType() !== "image/exr") {
|
|
1116
|
+
let refName = `lightmapTexture_${tex.getName()}`, channels = TextureChannel2.R | TextureChannel2.G | TextureChannel2.B | TextureChannel2.A;
|
|
1117
|
+
this.lightmapProp.setReference(refName, tex, { channels }), this.document.getLogger().debug(`[NEEDLE_lightmaps] Found lightmap texture "${tex.getName()}" (${tex.getMimeType()})`);
|
|
1118
|
+
}
|
|
1119
|
+
return this;
|
|
1120
|
+
}
|
|
1121
|
+
// ── prewrite ─────────────────────────────────────────────────
|
|
1122
|
+
prewrite(context, _propertyType) {
|
|
1123
|
+
return this.resolvePointers(context), this;
|
|
1124
|
+
}
|
|
1125
|
+
// ── write ────────────────────────────────────────────────────
|
|
1126
|
+
write(context) {
|
|
1127
|
+
return this.extensionData ? (this.resolvePointers(context), context.jsonDoc.json.extensions = context.jsonDoc.json.extensions || {}, context.jsonDoc.json.extensions[EXTENSION_NAME6] = this.extensionData, this) : this;
|
|
1128
|
+
}
|
|
1129
|
+
// ── private ──────────────────────────────────────────────────
|
|
1130
|
+
pointersResolved = !1;
|
|
1131
|
+
resolvePointers(context) {
|
|
1132
|
+
if (!this.pointersResolved) {
|
|
1133
|
+
this.pointersResolved = !0;
|
|
1134
|
+
for (let { entry, texture, inputTextureDef } of this.resolved)
|
|
1135
|
+
if (entry.pointer.startsWith("/textures/") || entry.pointer.startsWith("textures/")) {
|
|
1136
|
+
let newIndex = this.findOrCreateTextureIndex(context, texture, inputTextureDef);
|
|
1137
|
+
newIndex !== void 0 && (entry.pointer = `/textures/${newIndex}`);
|
|
1138
|
+
} else {
|
|
1139
|
+
let uri = texture.getURI();
|
|
1140
|
+
if (uri) {
|
|
1141
|
+
entry.pointer = uri;
|
|
1142
|
+
let imageIndex = context.imageIndexMap.get(texture);
|
|
1143
|
+
if (imageIndex !== void 0) {
|
|
1144
|
+
let images = context.jsonDoc.json.images;
|
|
1145
|
+
images && images[imageIndex] && (images[imageIndex].uri = uri);
|
|
215
1146
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Find (or create) a texture def in the output JSON that references the given Texture.
|
|
1153
|
+
* This replicates the logic from the opaque system's TextureIndexResolver.
|
|
1154
|
+
*/
|
|
1155
|
+
findOrCreateTextureIndex(context, texture, inputTextureDef) {
|
|
1156
|
+
let imageIndex = context.imageIndexMap.get(texture);
|
|
1157
|
+
if (imageIndex === void 0) return;
|
|
1158
|
+
let textures = context.jsonDoc.json.textures = context.jsonDoc.json.textures || [];
|
|
1159
|
+
for (let i = 0; i < textures.length; i++)
|
|
1160
|
+
if (findSource(textures[i]) === imageIndex)
|
|
1161
|
+
return i;
|
|
1162
|
+
let extensions = inputTextureDef?.extensions ? { ...inputTextureDef.extensions } : void 0;
|
|
1163
|
+
extensions && (delete extensions.NEEDLE_progressive_texture_settings, extensions.EXT_texture_exr && texture.getMimeType() !== "image/exr" && delete extensions.EXT_texture_exr, Object.keys(extensions).length === 0 && (extensions = void 0));
|
|
1164
|
+
let texDef = {
|
|
1165
|
+
source: extensions && Object.values(extensions).some((v) => v?.source !== void 0) ? void 0 : imageIndex,
|
|
1166
|
+
extensions
|
|
1167
|
+
};
|
|
1168
|
+
return textures.push(texDef), textures.length - 1;
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
|
|
1172
|
+
// src/extensions/index.ts
|
|
1173
|
+
import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";
|
|
1174
|
+
var _extensionInputFile = "";
|
|
1175
|
+
function setExtensionInputFile(filePath) {
|
|
1176
|
+
_extensionInputFile = filePath;
|
|
1177
|
+
}
|
|
1178
|
+
function getExtensionInputFile() {
|
|
1179
|
+
return _extensionInputFile;
|
|
1180
|
+
}
|
|
1181
|
+
function registerExtensions(node) {
|
|
1182
|
+
node.registerExtensions(ALL_EXTENSIONS2), node.registerExtensions(ALL_EXTENSIONS), node.registerExtensions([
|
|
1183
|
+
NEEDLE_progressive,
|
|
1184
|
+
NEEDLE_pmrem,
|
|
1185
|
+
NEEDLE_lightmaps_ext
|
|
1186
|
+
]);
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// src/transforms/needle_asset.ts
|
|
1190
|
+
import { createTransform } from "@gltf-transform/functions";
|
|
1191
|
+
|
|
1192
|
+
// src/utils/version.gen.ts
|
|
1193
|
+
var version = "3.0.0-alpha";
|
|
1194
|
+
|
|
1195
|
+
// src/utils/version.ts
|
|
1196
|
+
function getVersion(_marklocal = !0) {
|
|
1197
|
+
return version;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// src/transforms/needle_asset.ts
|
|
1201
|
+
var generatorName = "Needle Build Pipeline";
|
|
1202
|
+
function writeNeedleAsset(document, metadata) {
|
|
1203
|
+
let asset = document.getRoot().getAsset();
|
|
1204
|
+
if (asset) {
|
|
1205
|
+
asset.extras = writeNeedleExtras(asset.extras), metadata && (asset.extras = Object.assign(asset.extras, metadata));
|
|
1206
|
+
let version2 = getVersion();
|
|
1207
|
+
asset.generator = generatorName, version2?.length > 0 && (asset.generator += " " + version2);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
function needle_asset() {
|
|
1211
|
+
return createTransform("needle_asset_transform", (document) => {
|
|
1212
|
+
writeNeedleAsset(document);
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
function writeNeedleExtras(extras) {
|
|
1216
|
+
if (extras || (extras = {}), typeof extras == "object" && !extras.needle) {
|
|
1217
|
+
let generator = generatorName, version2 = getVersion();
|
|
1218
|
+
version2?.length > 0 && (generator += " " + version2);
|
|
1219
|
+
let time = (/* @__PURE__ */ new Date()).toISOString();
|
|
1220
|
+
extras.needle = {
|
|
1221
|
+
generator,
|
|
1222
|
+
created: time,
|
|
1223
|
+
updated: time,
|
|
1224
|
+
revision: 0
|
|
1225
|
+
};
|
|
1226
|
+
} else {
|
|
1227
|
+
let needle_Extras = extras.needle;
|
|
1228
|
+
needle_Extras && (needle_Extras.updated = (/* @__PURE__ */ new Date()).toISOString(), needle_Extras.revision = needle_Extras.revision + 1);
|
|
1229
|
+
}
|
|
1230
|
+
return extras;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// src/transforms/toktx.ts
|
|
1234
|
+
import micromatch from "micromatch";
|
|
1235
|
+
import os2 from "os";
|
|
1236
|
+
import semver from "semver";
|
|
1237
|
+
import tmp from "tmp";
|
|
1238
|
+
import { TextureChannel as TextureChannel4 } from "@gltf-transform/core";
|
|
1239
|
+
|
|
1240
|
+
// src/transforms/util.ts
|
|
1241
|
+
import { spawn as _spawn } from "child_process";
|
|
1242
|
+
import _commandExists from "command-exists";
|
|
1243
|
+
var MICROMATCH_OPTIONS = { nocase: !0, contains: !0 }, spawn = _spawn;
|
|
1244
|
+
var waitExit = _waitExit;
|
|
1245
|
+
async function _waitExit(process2) {
|
|
1246
|
+
let stdout = "";
|
|
1247
|
+
if (process2.stdout)
|
|
1248
|
+
for await (let chunk of process2.stdout)
|
|
1249
|
+
stdout += chunk;
|
|
1250
|
+
let stderr = "";
|
|
1251
|
+
if (process2.stderr)
|
|
1252
|
+
for await (let chunk of process2.stderr)
|
|
1253
|
+
stderr += chunk;
|
|
1254
|
+
return [await new Promise((resolve4, _) => {
|
|
1255
|
+
process2.on("close", resolve4);
|
|
1256
|
+
}), stdout, stderr];
|
|
1257
|
+
}
|
|
1258
|
+
function formatBytes(bytes, decimals = 2) {
|
|
1259
|
+
if (bytes === 0) return "0 Bytes";
|
|
1260
|
+
let k = 1e3, dm = decimals < 0 ? 0 : decimals, sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
1261
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// src/transforms/toktx.ts
|
|
1265
|
+
import { TextureResizeFilter as TextureResizeFilter2, getTextureColorSpace } from "@gltf-transform/functions";
|
|
1266
|
+
|
|
1267
|
+
// src/transforms/toktx_types.ts
|
|
1268
|
+
import os from "os";
|
|
1269
|
+
import { TextureChannel as TextureChannel3 } from "@gltf-transform/core";
|
|
1270
|
+
import { TextureResizeFilter } from "@gltf-transform/functions";
|
|
1271
|
+
var NUM_CPUS = os.cpus().length || 1;
|
|
1272
|
+
var { R, G, A } = TextureChannel3;
|
|
1273
|
+
var Filter = {
|
|
1274
|
+
BOX: "box",
|
|
1275
|
+
TENT: "tent",
|
|
1276
|
+
BELL: "bell",
|
|
1277
|
+
BSPLINE: "b-spline",
|
|
1278
|
+
MITCHELL: "mitchell",
|
|
1279
|
+
LANCZOS3: "lanczos3",
|
|
1280
|
+
LANCZOS4: "lanczos4",
|
|
1281
|
+
LANCZOS6: "lanczos6",
|
|
1282
|
+
LANCZOS12: "lanczos12",
|
|
1283
|
+
BLACKMAN: "blackman",
|
|
1284
|
+
KAISER: "kaiser",
|
|
1285
|
+
GAUSSIAN: "gaussian",
|
|
1286
|
+
CATMULLROM: "catmullrom",
|
|
1287
|
+
QUADRATIC_INTERP: "quadratic_interp",
|
|
1288
|
+
QUADRATIC_APPROX: "quadratic_approx",
|
|
1289
|
+
QUADRATIC_MIX: "quadratic_mix"
|
|
1290
|
+
}, GLOBAL_DEFAULTS = {
|
|
1291
|
+
resizeFilter: TextureResizeFilter.LANCZOS3,
|
|
1292
|
+
filter: Filter.LANCZOS4,
|
|
1293
|
+
filterScale: 1,
|
|
1294
|
+
pattern: null,
|
|
1295
|
+
slots: null,
|
|
1296
|
+
// See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
|
|
1297
|
+
jobs: 2 * NUM_CPUS,
|
|
1298
|
+
cleanup: !0,
|
|
1299
|
+
limitInputPixels: !0
|
|
1300
|
+
}, ETC1S_DEFAULTS = {
|
|
1301
|
+
quality: 128,
|
|
1302
|
+
compression: 1,
|
|
1303
|
+
rdo: !0,
|
|
1304
|
+
rdoThreshold: 1.25,
|
|
1305
|
+
maxSelectors: 0,
|
|
1306
|
+
maxEndpoints: 0,
|
|
1307
|
+
...GLOBAL_DEFAULTS
|
|
1308
|
+
}, UASTC_DEFAULTS = {
|
|
1309
|
+
level: 2,
|
|
1310
|
+
rdo: !1,
|
|
1311
|
+
rdoLambda: 1,
|
|
1312
|
+
rdoDictionarySize: 32768,
|
|
1313
|
+
rdoBlockScale: 10,
|
|
1314
|
+
rdoStdDev: 18,
|
|
1315
|
+
rdoMultithreading: !0,
|
|
1316
|
+
zstd: 18,
|
|
1317
|
+
...GLOBAL_DEFAULTS
|
|
1318
|
+
};
|
|
1319
|
+
|
|
1320
|
+
// src/transforms/toktx.ts
|
|
1321
|
+
tmp.setGracefulCleanup();
|
|
1322
|
+
var NUM_CPUS2 = os2.cpus().length || 1, KTX_SOFTWARE_VERSION_MIN = "4.3.0", Filter2 = {
|
|
1323
|
+
BOX: "box",
|
|
1324
|
+
TENT: "tent",
|
|
1325
|
+
BELL: "bell",
|
|
1326
|
+
BSPLINE: "b-spline",
|
|
1327
|
+
MITCHELL: "mitchell",
|
|
1328
|
+
LANCZOS3: "lanczos3",
|
|
1329
|
+
LANCZOS4: "lanczos4",
|
|
1330
|
+
LANCZOS6: "lanczos6",
|
|
1331
|
+
LANCZOS12: "lanczos12",
|
|
1332
|
+
BLACKMAN: "blackman",
|
|
1333
|
+
KAISER: "kaiser",
|
|
1334
|
+
GAUSSIAN: "gaussian",
|
|
1335
|
+
CATMULLROM: "catmullrom",
|
|
1336
|
+
QUADRATIC_INTERP: "quadratic_interp",
|
|
1337
|
+
QUADRATIC_APPROX: "quadratic_approx",
|
|
1338
|
+
QUADRATIC_MIX: "quadratic_mix"
|
|
1339
|
+
}, GLOBAL_DEFAULTS2 = {
|
|
1340
|
+
resizeFilter: TextureResizeFilter2.LANCZOS3,
|
|
1341
|
+
filter: Filter2.LANCZOS4,
|
|
1342
|
+
filterScale: 1,
|
|
1343
|
+
pattern: null,
|
|
1344
|
+
slots: null,
|
|
1345
|
+
// See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
|
|
1346
|
+
jobs: 2 * NUM_CPUS2,
|
|
1347
|
+
cleanup: !0,
|
|
1348
|
+
limitInputPixels: !0
|
|
1349
|
+
}, { R: R2, G: G2, A: A2 } = TextureChannel4, Mode = {
|
|
1350
|
+
ETC1S: "etc1s",
|
|
1351
|
+
UASTC: "uastc"
|
|
1352
|
+
};
|
|
1353
|
+
function createParams(texture, slots, channels, size, logger, numTextures, options) {
|
|
1354
|
+
let colorSpace = getTextureColorSpace(texture), params = ["--generate-mipmap"];
|
|
1355
|
+
options.filter !== GLOBAL_DEFAULTS2.filter && params.push("--mipmap-filter", options.filter), options.filterScale !== GLOBAL_DEFAULTS2.filterScale && params.push("--mipmap-filter-scale", options.filterScale);
|
|
1356
|
+
let isNormalMap = slots.find((slot) => micromatch.isMatch(slot, "*normal*", MICROMATCH_OPTIONS));
|
|
1357
|
+
if (options.mode === Mode.UASTC) {
|
|
1358
|
+
let _options = options;
|
|
1359
|
+
params.push("--encode", "uastc"), params.push("--uastc-quality", _options.level), _options.rdo && !isNormalMap && (params.push("--uastc-rdo"), _options.rdoLambda !== UASTC_DEFAULTS.rdoLambda && params.push("--uastc-rdo-l", _options.rdoLambda), _options.rdoDictionarySize !== UASTC_DEFAULTS.rdoDictionarySize && params.push("--uastc-rdo-d", _options.rdoDictionarySize), _options.rdoBlockScale !== UASTC_DEFAULTS.rdoBlockScale && params.push("--uastc-rdo-b", _options.rdoBlockScale), _options.rdoStdDev !== UASTC_DEFAULTS.rdoStdDev && params.push("--uastc-rdo-s", _options.rdoStdDev), _options.rdoMultithreading || params.push("--uastc-rdo-m")), _options.zstd && _options.zstd > 0 && params.push("--zstd", _options.zstd);
|
|
1360
|
+
} else {
|
|
1361
|
+
let _options = options;
|
|
1362
|
+
params.push("--encode", "basis-lz"), _options.quality !== ETC1S_DEFAULTS.quality && params.push("--qlevel", _options.quality), _options.compression !== ETC1S_DEFAULTS.compression && params.push("--clevel", _options.compression), _options.rdo && !isNormalMap ? (_options.maxEndpoints !== ETC1S_DEFAULTS.maxEndpoints && params.push("--max-endpoints", _options.maxEndpoints), _options.maxSelectors !== ETC1S_DEFAULTS.maxSelectors && params.push("--max-selectors", _options.maxSelectors), _options.rdoThreshold !== ETC1S_DEFAULTS.rdoThreshold && (params.push("--endpoint-rdo-threshold", _options.rdoThreshold), params.push("--selector-rdo-threshold", _options.rdoThreshold))) : params.push("--no-endpoint-rdo", "--no-selector-rdo");
|
|
1363
|
+
}
|
|
1364
|
+
if (colorSpace === "srgb" ? params.push("--assign-oetf", "srgb", "--assign-primaries", "bt709") : colorSpace === "srgb-linear" ? params.push("--assign-oetf", "linear", "--assign-primaries", "bt709") : slots.length && !colorSpace && params.push("--assign-oetf", "linear", "--assign-primaries", "none"), channels === R2 ? params.push("--format", "R8_UNORM") : channels === G2 || channels === (R2 | G2) ? params.push("--format", "R8G8_UNORM") : channels & A2 ? params.push("--format", colorSpace === "srgb" ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM") : params.push("--format", colorSpace === "srgb" ? "R8G8B8_SRGB" : "R8G8B8_UNORM"), options.jobs && options.jobs > 1 && numTextures > 1) {
|
|
1365
|
+
let threads = Math.max(2, Math.min(NUM_CPUS2, Math.round(3 * NUM_CPUS2 / numTextures)));
|
|
1366
|
+
params.push("--threads", threads);
|
|
1367
|
+
}
|
|
1368
|
+
return params;
|
|
1369
|
+
}
|
|
1370
|
+
var didLogKtxVersion = !1;
|
|
1371
|
+
async function checkKTXSoftware(logger, env) {
|
|
1372
|
+
let failedFindingKtx = !1, proc = spawn("ktx", ["--version"], { env });
|
|
1373
|
+
proc.on("error", (err) => {
|
|
1374
|
+
err.message.endsWith("ENOENT") && (failedFindingKtx = !0);
|
|
1375
|
+
});
|
|
1376
|
+
let [status, stdout, stderr] = await waitExit(proc);
|
|
1377
|
+
if (failedFindingKtx)
|
|
1378
|
+
return console.log('WARN: Unable to find "ktx". Confirm KTX-Software is installed from: https://github.com/KhronosGroup/KTX-Software.'), null;
|
|
1379
|
+
let versionMatch = (stdout || stderr).match(/v?(\d+\.\d+\.\d+)/), version2 = versionMatch ? versionMatch[1] : null;
|
|
1380
|
+
if (status !== 0 || !version2 || !semver.valid(version2))
|
|
1381
|
+
throw new Error(`Unable to find "ktx" version. Confirm KTX-Software is installed from:
|
|
1382
|
+
|
|
1383
|
+
https://github.com/KhronosGroup/KTX-Software.`);
|
|
1384
|
+
return semver.lt(version2, KTX_SOFTWARE_VERSION_MIN) ? (logger.warn(`ktx: Expected KTX-Software >= v${KTX_SOFTWARE_VERSION_MIN}, found ${version2}.`), null) : (didLogKtxVersion || logger.debug(`ktx: Found KTX-Software ${version2}.`), didLogKtxVersion = !0, version2);
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// src/transforms/needle_toktx.ts
|
|
1388
|
+
import { BufferUtils as BufferUtils2, FileUtils, ImageUtils as ImageUtils3, uuid as uuid2 } from "@gltf-transform/core";
|
|
1389
|
+
import { listTextureSlots as listTextureSlots2, getTextureChannelMask, fitPowerOfTwo, TextureResizeFilter as TextureResizeFilter3 } from "@gltf-transform/functions";
|
|
1390
|
+
import { KHRTextureBasisu } from "@gltf-transform/extensions";
|
|
1391
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync5 } from "fs";
|
|
1392
|
+
|
|
1393
|
+
// src/utils/fileutils.ts
|
|
1394
|
+
import { existsSync as existsSync3, statSync, readdirSync, readFileSync as readFileSync3, mkdirSync, rmSync } from "fs";
|
|
1395
|
+
import { setTimeout as setTimeout2 } from "timers/promises";
|
|
1396
|
+
import { dirname as dirname3, isAbsolute, join as join3 } from "path";
|
|
1397
|
+
function getOutputPath(filepath, outDirOrFile, opts) {
|
|
1398
|
+
if (!outDirOrFile)
|
|
1399
|
+
return filepath;
|
|
1400
|
+
if (!isDirectory(outDirOrFile))
|
|
1401
|
+
return outDirOrFile;
|
|
1402
|
+
let filename = getFileName(filepath);
|
|
1403
|
+
return opts?.create != !1 && !existsSync3(outDirOrFile) && mkdirSync(outDirOrFile, { recursive: !0 }), join3(outDirOrFile, filename);
|
|
1404
|
+
}
|
|
1405
|
+
function getFileName(filepath) {
|
|
1406
|
+
let parts = filepath.replaceAll("\\", "/").split("/");
|
|
1407
|
+
return parts[parts.length - 1];
|
|
1408
|
+
}
|
|
1409
|
+
function parseInputPaths(raw) {
|
|
1410
|
+
if (!raw.includes(",")) return [raw];
|
|
1411
|
+
let segments = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1412
|
+
return segments.length < 2 ? [raw] : !segments.some((s) => existsSync3(s)) && existsSync3(raw) ? [raw] : segments;
|
|
1413
|
+
}
|
|
1414
|
+
async function foreachGLTF(args, callback) {
|
|
1415
|
+
let initDir = process.env.INIT_CWD, context = {
|
|
1416
|
+
baseDirectory: initDir,
|
|
1417
|
+
files: []
|
|
1418
|
+
};
|
|
1419
|
+
if (Array.isArray(args))
|
|
1420
|
+
for (let arg of args)
|
|
1421
|
+
await testEntry(arg, context);
|
|
1422
|
+
else typeof args == "string" && await testEntry(args, context);
|
|
1423
|
+
if (context.files?.length <= 0 && context.baseDirectory) {
|
|
1424
|
+
let needleConfigPath = context.baseDirectory + "/needle.config.json";
|
|
1425
|
+
if (existsSync3(needleConfigPath)) {
|
|
1426
|
+
let buildDirectory = JSON.parse(readFileSync3(needleConfigPath, "utf8")).buildDirectory;
|
|
1427
|
+
if (buildDirectory?.length)
|
|
1428
|
+
if (existsSync3(buildDirectory))
|
|
1429
|
+
console.log("INFO: Using build directory from needle.config.json: " + buildDirectory), await testEntry(buildDirectory, context);
|
|
1430
|
+
else {
|
|
1431
|
+
let newPath = context.baseDirectory + "/" + buildDirectory;
|
|
1432
|
+
existsSync3(newPath) && (console.log("INFO: Using build directory from needle.config.json: " + newPath), await testEntry(newPath, context));
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
if (context.files.length <= 0)
|
|
1437
|
+
console.log(`WARN: No glTF files found. Make sure to invoke with a valid path to a glTF file or directory.
|
|
1438
|
+
Base Directory: ${context.baseDirectory}
|
|
1439
|
+
Paths can be relative to "${initDir}"`);
|
|
1440
|
+
else
|
|
1441
|
+
for (let file of context.files)
|
|
1442
|
+
await callback(file);
|
|
1443
|
+
}
|
|
1444
|
+
async function testEntry(entry, context) {
|
|
1445
|
+
if (entry.startsWith("--"))
|
|
1446
|
+
return !1;
|
|
1447
|
+
if ((entry === "." || entry === "./") && context.baseDirectory && (entry = context.baseDirectory), existsSync3(entry) === !1) {
|
|
1448
|
+
if (context.baseDirectory === void 0)
|
|
1449
|
+
return console.log("WARN: Path does not exist: " + entry), !1;
|
|
1450
|
+
let newPath = context.baseDirectory + "/" + entry;
|
|
1451
|
+
if (existsSync3(newPath) === !1)
|
|
1452
|
+
return console.log(`INFO: Resolved path failed: "${entry}" -> ${newPath} (doesnt exist or is locked by another process)`), !1;
|
|
1453
|
+
console.log(`INFO: Resolved path: ${entry} -> ${newPath}`), entry = newPath;
|
|
1454
|
+
} else if (!isAbsolute(entry) && context.baseDirectory) {
|
|
1455
|
+
let newPath = context.baseDirectory + "/" + entry;
|
|
1456
|
+
if (console.log(`INFO: Resolved path: ${entry} -> ${newPath}`), entry = newPath, !existsSync3(entry))
|
|
1457
|
+
return !1;
|
|
1458
|
+
}
|
|
1459
|
+
if (entry.endsWith(".glb") || entry.endsWith(".gltf") || entry.endsWith(".vrm"))
|
|
1460
|
+
context.files.push(entry);
|
|
1461
|
+
else if (statSync(entry).isDirectory()) {
|
|
1462
|
+
if (entry.endsWith("node_modules"))
|
|
1463
|
+
return !1;
|
|
1464
|
+
let files = readdirSync(entry);
|
|
1465
|
+
for (let file of files)
|
|
1466
|
+
await testEntry(entry + "/" + file, context);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
function replaceExtension(filepath, newExtension) {
|
|
1470
|
+
let parts = filepath.split(".");
|
|
1471
|
+
return parts.pop(), parts.join(".") + "." + newExtension;
|
|
1472
|
+
}
|
|
1473
|
+
function isDirectory(path8) {
|
|
1474
|
+
return path8 ? existsSync3(path8) ? statSync(path8).isDirectory() : !path8.replaceAll("\\", "/").split("/").pop()?.includes(".") : !1;
|
|
1475
|
+
}
|
|
1476
|
+
function ensureIsDirectory(path8) {
|
|
1477
|
+
return isDirectory(path8) || (path8 = dirname3(path8)), existsSync3(path8) || mkdirSync(path8, { recursive: !0 }), path8;
|
|
1478
|
+
}
|
|
1479
|
+
async function safeRmDir(dirPath, retries = 3, delayMs = 150) {
|
|
1480
|
+
for (let i = 0; i <= retries; i++)
|
|
1481
|
+
try {
|
|
1482
|
+
existsSync3(dirPath) && rmSync(dirPath, { recursive: !0 });
|
|
1483
|
+
return;
|
|
1484
|
+
} catch (err) {
|
|
1485
|
+
if (!(err?.code === "EBUSY" || err?.code === "EPERM") || i === retries) return;
|
|
1486
|
+
await setTimeout2(delayMs);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
// src/transforms/needle_toktx.ts
|
|
1491
|
+
import fs2 from "fs/promises";
|
|
1492
|
+
import os3 from "os";
|
|
1493
|
+
import tmp3 from "tmp";
|
|
1494
|
+
import pLimit from "p-limit";
|
|
1495
|
+
|
|
1496
|
+
// src/utils/compression_utils.ts
|
|
1497
|
+
function detectTextureCompressionMode(slots) {
|
|
1498
|
+
return slots.includes("normalTexture") || slots.includes("metallicRoughnessTexture") ? "UASTC" : "ETC1S";
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// src/utils/mesh.ts
|
|
1502
|
+
import { Mesh as Mesh2 } from "@gltf-transform/core";
|
|
1503
|
+
function getMeshInformation(mesh) {
|
|
1504
|
+
let maxVertexCount = 0, totalIndexCount = 0, totalVertexCount = 0;
|
|
1505
|
+
return mesh instanceof Mesh2 ? (totalVertexCount = mesh.listPrimitives().reduce((acc, prim) => {
|
|
1506
|
+
let indices = prim.getIndices()?.getCount() || 0;
|
|
1507
|
+
totalIndexCount += indices;
|
|
1508
|
+
let vertices = prim.getAttribute("POSITION")?.getCount() || 0;
|
|
1509
|
+
return maxVertexCount = Math.max(maxVertexCount, vertices), acc + vertices;
|
|
1510
|
+
}, 0), {
|
|
1511
|
+
maxVertexCount,
|
|
1512
|
+
totalVertexCount,
|
|
1513
|
+
totalIndexCount
|
|
1514
|
+
}) : (mesh.getRoot().listMeshes().forEach((mesh2) => {
|
|
1515
|
+
let info = getMeshInformation(mesh2);
|
|
1516
|
+
maxVertexCount = Math.max(maxVertexCount, info.maxVertexCount), totalVertexCount += info.totalVertexCount, totalIndexCount += info.totalIndexCount;
|
|
1517
|
+
}), {
|
|
1518
|
+
maxVertexCount,
|
|
1519
|
+
totalVertexCount,
|
|
1520
|
+
totalIndexCount
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
function calculateMeshDensity(prim) {
|
|
1524
|
+
let bounds = {
|
|
1525
|
+
min: [1 / 0, 1 / 0, 1 / 0],
|
|
1526
|
+
max: [-1 / 0, -1 / 0, -1 / 0]
|
|
1527
|
+
}, position = prim.getAttribute("POSITION");
|
|
1528
|
+
if (!position) return -1;
|
|
1529
|
+
let tempVec3 = [0, 0, 0];
|
|
1530
|
+
for (let i = 0; i < position.getCount(); i++)
|
|
1531
|
+
tempVec3 = position.getElement(i, tempVec3), expandBounds(tempVec3, bounds);
|
|
1532
|
+
let indices = prim.getIndices(), area = 0;
|
|
1533
|
+
if (indices) {
|
|
1534
|
+
let numIndices = indices.getCount(), indexArray = indices.getArray(), v0 = [0, 0, 0], v1 = [0, 0, 0], v2 = [0, 0, 0], e1 = [0, 0, 0], e2 = [0, 0, 0], boundSizeX = bounds.max[0] - bounds.min[0], boundSizeY = bounds.max[1] - bounds.min[1], boundSizeZ = bounds.max[2] - bounds.min[2], maxBounds = Math.max(boundSizeX, boundSizeY, boundSizeZ);
|
|
1535
|
+
for (let i = 0; i < numIndices; i += 3) {
|
|
1536
|
+
let i0 = indexArray[i + 0], i1 = indexArray[i + 1], i2 = indexArray[i + 2];
|
|
1537
|
+
position.getElement(i0, v0), position.getElement(i1, v1), position.getElement(i2, v2), e1[0] = v1[0] - v0[0], e1[1] = v1[1] - v0[1], e1[2] = v1[2] - v0[2], e2[0] = v2[0] - v0[0], e2[1] = v2[1] - v0[1], e2[2] = v2[2] - v0[2], e1[0] /= maxBounds, e1[1] /= maxBounds, e1[2] /= maxBounds, e2[0] /= maxBounds, e2[1] /= maxBounds, e2[2] /= maxBounds;
|
|
1538
|
+
let cross = [
|
|
1539
|
+
e1[1] * e2[2] - e1[2] * e2[1],
|
|
1540
|
+
e1[2] * e2[0] - e1[0] * e2[2],
|
|
1541
|
+
e1[0] * e2[1] - e1[1] * e2[0]
|
|
1542
|
+
];
|
|
1543
|
+
area += Math.sqrt(cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]) / 2;
|
|
1544
|
+
}
|
|
1545
|
+
return indices.getCount() / 3 / area;
|
|
1546
|
+
} else {
|
|
1547
|
+
let count = position.getCount(), size = [0, 0, 0];
|
|
1548
|
+
size[0] = bounds.max[0] - bounds.min[0], size[1] = bounds.max[1] - bounds.min[1], size[2] = bounds.max[2] - bounds.min[2];
|
|
1549
|
+
let volume = size[0] * size[1] * size[2];
|
|
1550
|
+
return count / volume;
|
|
1551
|
+
}
|
|
1552
|
+
return -1;
|
|
1553
|
+
function expandBounds(point, target) {
|
|
1554
|
+
for (let i = 0; i < 3; i++)
|
|
1555
|
+
target.min[i] = Math.min(point[i], target.min[i]), target.max[i] = Math.max(point[i], target.max[i]);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
// src/utils/guid.ts
|
|
1560
|
+
import { v5 as uuidv5 } from "uuid";
|
|
1561
|
+
var NEEDLE_BUILD_PIPELINE_NAMESPACE = "208dcaa6-1398-4d42-a625-8f5fc1cc1ccf";
|
|
1562
|
+
function generateGuid(key) {
|
|
1563
|
+
return uuidv5(key, NEEDLE_BUILD_PIPELINE_NAMESPACE);
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// src/utils/nodeio.ts
|
|
1567
|
+
import { cpSync, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
|
|
1568
|
+
import { writeFile } from "fs/promises";
|
|
1569
|
+
import path from "path";
|
|
1570
|
+
import sharp from "sharp";
|
|
1571
|
+
async function writeNodeIO(nodeio, filename, document) {
|
|
1572
|
+
let directoryPath = path.dirname(filename);
|
|
1573
|
+
if (existsSync4(directoryPath) || mkdirSync2(directoryPath), filename.endsWith(".vrm")) {
|
|
1574
|
+
let bin = await nodeio.writeBinary(document);
|
|
1575
|
+
await writeFile(filename, bin);
|
|
1576
|
+
} else
|
|
1577
|
+
await nodeio.write(filename, document);
|
|
1578
|
+
return filename;
|
|
1579
|
+
}
|
|
1580
|
+
var openFileRegex = /open \'(?<path>.+?)'/, createdFiles = /* @__PURE__ */ new Set();
|
|
1581
|
+
async function ioTryReadWithMissingResources(io, filepath, iteration = 0) {
|
|
1582
|
+
let document = await io.read(filepath).catch((err) => err);
|
|
1583
|
+
if (document instanceof Error) {
|
|
1584
|
+
let err = document;
|
|
1585
|
+
if (iteration < 100 && err.message?.includes("ENOENT"))
|
|
1586
|
+
try {
|
|
1587
|
+
let match = err.message.match(openFileRegex);
|
|
1588
|
+
if (match.groups?.path) {
|
|
1589
|
+
let missingPath = match.groups.path;
|
|
1590
|
+
if (missingPath.startsWith("http") || createdFiles.has(missingPath))
|
|
1591
|
+
throw err;
|
|
1592
|
+
createdFiles.add(missingPath), console.warn(`Creating empty file for missing resource: ${missingPath}`);
|
|
1593
|
+
let ext = missingPath.split(".").pop();
|
|
1594
|
+
if (!ext)
|
|
1595
|
+
throw console.warn(`Could not determine extension for ${missingPath}`), err;
|
|
1596
|
+
let extLower = ext?.toLowerCase(), retry = !1;
|
|
1597
|
+
switch (extLower) {
|
|
1598
|
+
case "jpeg":
|
|
1599
|
+
case "jpg":
|
|
1600
|
+
case "png":
|
|
1601
|
+
case "webp":
|
|
1602
|
+
case "tiff":
|
|
1603
|
+
case "gif":
|
|
1604
|
+
await sharp({
|
|
1605
|
+
create: {
|
|
1606
|
+
width: 64,
|
|
1607
|
+
height: 64,
|
|
1608
|
+
channels: 4,
|
|
1609
|
+
background: { r: 255, g: 255, b: 255, alpha: 1 }
|
|
222
1610
|
}
|
|
1611
|
+
}).toFormat(ext).toFile(missingPath), retry = !0;
|
|
1612
|
+
}
|
|
1613
|
+
if (retry)
|
|
1614
|
+
return console.warn(`Created empty file for missing resource: ${missingPath}`), ioTryReadWithMissingResources(io, filepath, iteration + 1);
|
|
1615
|
+
}
|
|
1616
|
+
} catch (internal_error) {
|
|
1617
|
+
console.warn(internal_error);
|
|
1618
|
+
}
|
|
1619
|
+
throw err;
|
|
1620
|
+
}
|
|
1621
|
+
return document;
|
|
1622
|
+
}
|
|
1623
|
+
function copyExternalResources(document, inputFile, outputFile) {
|
|
1624
|
+
let inputDir = path.resolve(path.dirname(inputFile)), outputDir = path.resolve(path.dirname(outputFile));
|
|
1625
|
+
if (inputDir !== outputDir) {
|
|
1626
|
+
for (let texture of document.getRoot().listTextures()) {
|
|
1627
|
+
let uri = texture.getURI();
|
|
1628
|
+
if (!uri || uri.startsWith("data:")) continue;
|
|
1629
|
+
let src = path.join(inputDir, uri), dst = path.join(outputDir, uri);
|
|
1630
|
+
!existsSync4(dst) && existsSync4(src) && cpSync(src, dst);
|
|
1631
|
+
}
|
|
1632
|
+
for (let buffer of document.getRoot().listBuffers()) {
|
|
1633
|
+
let uri = buffer.getURI();
|
|
1634
|
+
if (!uri || uri.startsWith("data:")) continue;
|
|
1635
|
+
let src = path.join(inputDir, uri), dst = path.join(outputDir, uri);
|
|
1636
|
+
!existsSync4(dst) && existsSync4(src) && cpSync(src, dst);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
// src/utils/stats.ts
|
|
1642
|
+
import { Document as Document8, ImageUtils } from "@gltf-transform/core";
|
|
1643
|
+
import { statSync as statSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
1644
|
+
|
|
1645
|
+
// src/transforms/needle_progressive.ts
|
|
1646
|
+
import { BufferUtils, Document as Document7, NodeIO, PropertyType as PropertyType11, TextureChannel as TextureChannel5, Verbosity } from "@gltf-transform/core";
|
|
1647
|
+
import { SIMPLIFY_DEFAULTS as SIMPLIFY_DEFAULTS2, WELD_DEFAULTS as WELD_DEFAULTS3, listTextureChannels, listTextureSlots, metalRough, sparse } from "@gltf-transform/functions";
|
|
1648
|
+
import { KHRMaterialsSpecular } from "@gltf-transform/extensions";
|
|
1649
|
+
import draco3d from "draco3dgltf";
|
|
1650
|
+
import path4, { basename, resolve } from "path";
|
|
1651
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
1652
|
+
|
|
1653
|
+
// src/cache/cache.ts
|
|
1654
|
+
import { ExtensibleProperty as ExtensibleProperty2, Texture as Texture6, Primitive as Primitive2, Accessor, Mesh as Mesh3 } from "@gltf-transform/core";
|
|
1655
|
+
import tmp2 from "tmp";
|
|
1656
|
+
import fs, { statSync as statSync2 } from "fs";
|
|
1657
|
+
import path2 from "path";
|
|
1658
|
+
import xxhash from "xxhash-wasm";
|
|
1659
|
+
var xxHashModule = null, xxHashReady = xxhash().then((module) => {
|
|
1660
|
+
xxHashModule = module;
|
|
1661
|
+
}).catch(() => {
|
|
1662
|
+
});
|
|
1663
|
+
function ensureHashReady() {
|
|
1664
|
+
return xxHashReady;
|
|
1665
|
+
}
|
|
1666
|
+
var buildPipelineVersion = getVersion(!1), debugLogs = process.argv.includes("--debug");
|
|
1667
|
+
function clearCache(logger) {
|
|
1668
|
+
let dir = getCacheDirectory(!0);
|
|
1669
|
+
fs.rmSync(dir, { recursive: !0 }), logger ? logger.info(`Cleared cache at ${dir}`) : console.log(`Cleared cache at ${dir}`);
|
|
1670
|
+
}
|
|
1671
|
+
var cacheSizeLimit = 1024 * 5;
|
|
1672
|
+
function limitCacheSize(maxSizeMB = cacheSizeLimit) {
|
|
1673
|
+
let dir = getCacheDirectory(!0);
|
|
1674
|
+
console.log(`Limit cache size to ${maxSizeMB.toFixed(2)} MB at ${dir}`);
|
|
1675
|
+
let totalSize = 0, files = new Array();
|
|
1676
|
+
function recurseDirectories(dir2) {
|
|
1677
|
+
fs.readdirSync(dir2).forEach((file) => {
|
|
1678
|
+
let path8 = `${dir2}/${file}`, stats = statSync2(path8);
|
|
1679
|
+
stats.isDirectory() ? recurseDirectories(path8) : (totalSize += stats.size, files.push({ path: path8, size: stats.size }));
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
recurseDirectories(dir);
|
|
1683
|
+
let maxSizeInBytes = maxSizeMB * 1024 * 1024;
|
|
1684
|
+
if (console.log(`Current cache size is ${(totalSize / (1024 * 1024)).toFixed(1)} MB`), totalSize < maxSizeInBytes) return;
|
|
1685
|
+
files.sort((a, b) => {
|
|
1686
|
+
let mtimeA = fs.statSync(a.path).mtimeMs, mtimeB = fs.statSync(b.path).mtimeMs;
|
|
1687
|
+
return mtimeA - mtimeB;
|
|
1688
|
+
});
|
|
1689
|
+
let targetSize = maxSizeInBytes * 0.9, filesRemoved = 0;
|
|
1690
|
+
for (; totalSize > targetSize; ) {
|
|
1691
|
+
let file = files.shift();
|
|
1692
|
+
if (!file) break;
|
|
1693
|
+
fs.statSync(file.path).isDirectory() || (filesRemoved++, fs.rmSync(file.path), totalSize -= file.size);
|
|
1694
|
+
}
|
|
1695
|
+
console.log(`Cache size reduced to ${(totalSize / (1024 * 1024)).toFixed(1)} MB (${filesRemoved} files removed)`);
|
|
1696
|
+
}
|
|
1697
|
+
function addToCache(key, bytes) {
|
|
1698
|
+
let path8 = `${getCacheDirectory()}/${key}.bin`;
|
|
1699
|
+
debugLogs && console.log(`Added ${(bytes.byteLength / 1024).toFixed(1)} KB to cache at "${path8}"`), bytes instanceof Buffer && (bytes = new Uint8Array(bytes)), fs.writeFileSync(path8, bytes);
|
|
1700
|
+
}
|
|
1701
|
+
function tryGetFromCache(key) {
|
|
1702
|
+
let path8 = `${getCacheDirectory()}/${key}.bin`;
|
|
1703
|
+
if (fs.existsSync(path8)) {
|
|
1704
|
+
let bytes = fs.readFileSync(path8);
|
|
1705
|
+
return bytes instanceof Buffer ? new Uint8Array(bytes) : bytes;
|
|
1706
|
+
}
|
|
1707
|
+
return null;
|
|
1708
|
+
}
|
|
1709
|
+
function addMetaToCache(key, meta) {
|
|
1710
|
+
let metaPath = `${getCacheDirectory()}/${key}.meta`;
|
|
1711
|
+
meta["needle-build-pipeline:version"] = buildPipelineVersion, fs.writeFileSync(metaPath, JSON.stringify(meta));
|
|
1712
|
+
}
|
|
1713
|
+
function tryGetMetaFromCache(key, ignoreVersion = !1) {
|
|
1714
|
+
try {
|
|
1715
|
+
let path8 = `${getCacheDirectory()}/${key}.meta`;
|
|
1716
|
+
if (fs.existsSync(path8)) {
|
|
1717
|
+
let bytes = fs.readFileSync(path8);
|
|
1718
|
+
if (bytes?.length > 0) {
|
|
1719
|
+
let text = bytes.toString("utf-8");
|
|
1720
|
+
if (text) {
|
|
1721
|
+
let obj = JSON.parse(text);
|
|
1722
|
+
if (ignoreVersion || obj["needle-build-pipeline:version"] === buildPipelineVersion) return obj;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
return null;
|
|
1727
|
+
} catch (e) {
|
|
1728
|
+
return console.error(`Error reading cache meta: ${e.message}`), null;
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
function getKey(property) {
|
|
1732
|
+
let prefix = "prop";
|
|
1733
|
+
property instanceof Texture6 && (prefix = "image");
|
|
1734
|
+
let hash = getHash(property);
|
|
1735
|
+
return `${prefix}-${hash}`;
|
|
1736
|
+
}
|
|
1737
|
+
function combineHash(seed, value) {
|
|
1738
|
+
return seed = seed ^ value + 2654435769 + (seed << 6 | 0) + (seed >>> 2) | 0, seed;
|
|
1739
|
+
}
|
|
1740
|
+
function getHash(property, level = 0) {
|
|
1741
|
+
let hash = 0;
|
|
1742
|
+
if (property instanceof ExtensibleProperty2) {
|
|
1743
|
+
let extensions = property.listExtensions(), extras = property.getExtras();
|
|
1744
|
+
if (hash = combineHash(hash, hashObject({
|
|
1745
|
+
extensions,
|
|
1746
|
+
extras
|
|
1747
|
+
})), property instanceof Texture6) {
|
|
1748
|
+
let image = property.getImage(), bytes = image?.buffer;
|
|
1749
|
+
bytes && (hash = combineHash(hash, hashBuffer(bytes, image.byteOffset, image.byteLength)));
|
|
1750
|
+
} else if (property instanceof Mesh3) {
|
|
1751
|
+
let weights = property.getWeights();
|
|
1752
|
+
hash = combineHash(hash, hashObject(weights));
|
|
1753
|
+
let primitives = property.listPrimitives();
|
|
1754
|
+
for (let prim of primitives)
|
|
1755
|
+
hash = combineHash(hash, hashString(getHash(prim, level + 1)));
|
|
1756
|
+
} else if (property instanceof Primitive2) {
|
|
1757
|
+
let indices = property.getIndices(), attributes = property.listAttributes(), targets = property.listTargets(), semantics = property.listSemantics(), semanticsNames = semantics.map((s) => ({
|
|
1758
|
+
name: s
|
|
1759
|
+
}));
|
|
1760
|
+
if (hash = combineHash(hash, hashObject({
|
|
1761
|
+
indices,
|
|
1762
|
+
attributes,
|
|
1763
|
+
targets,
|
|
1764
|
+
semantics: semanticsNames
|
|
1765
|
+
})), indices) {
|
|
1766
|
+
let indexBuffer = indices.getArray();
|
|
1767
|
+
indexBuffer && (hash = combineHash(hash, hashBuffer(indexBuffer.buffer, indexBuffer.byteOffset, indexBuffer.byteLength)));
|
|
1768
|
+
}
|
|
1769
|
+
for (let sem of semantics) {
|
|
1770
|
+
let arr = property.getAttribute(sem)?.getArray();
|
|
1771
|
+
arr && (hash = combineHash(hash, hashString(sem)), hash = combineHash(hash, hashBuffer(arr.buffer, arr.byteOffset, arr.byteLength)));
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
} else
|
|
1775
|
+
hash = combineHash(hash, hashObject(property));
|
|
1776
|
+
return String(hash);
|
|
1777
|
+
}
|
|
1778
|
+
var cleanBuildPipelineVersion = getVersion(!1).replace(/[^a-zA-Z0-9]/g, "_");
|
|
1779
|
+
function getCacheDirectory(root) {
|
|
1780
|
+
let tmpDir = path2.join(tmp2.tmpdir, "Needle", "build-pipeline-cache", root ? "" : cleanBuildPipelineVersion);
|
|
1781
|
+
return fs.existsSync(tmpDir) || fs.mkdirSync(tmpDir, { recursive: !0 }), tmpDir;
|
|
1782
|
+
}
|
|
1783
|
+
function hashObject(obj, depth = 0) {
|
|
1784
|
+
if (obj instanceof Accessor) {
|
|
1785
|
+
let buffer = obj.getArray();
|
|
1786
|
+
return hashBuffer(buffer.buffer);
|
|
1787
|
+
} else if (obj == null)
|
|
1788
|
+
return 0;
|
|
1789
|
+
if (typeof obj != "object")
|
|
1790
|
+
return hashString(String(obj));
|
|
1791
|
+
try {
|
|
1792
|
+
let seen = /* @__PURE__ */ new WeakSet(), str = JSON.stringify(obj, (_key, value) => {
|
|
1793
|
+
if (typeof value == "object" && value !== null) {
|
|
1794
|
+
if (seen.has(value)) return;
|
|
1795
|
+
seen.add(value);
|
|
1796
|
+
}
|
|
1797
|
+
if (typeof value != "function")
|
|
1798
|
+
return value;
|
|
1799
|
+
});
|
|
1800
|
+
return hashString(str);
|
|
1801
|
+
} catch (err) {
|
|
1802
|
+
if (console.warn(`WARN: [Cache] error during hashing of object:
|
|
1803
|
+
` + err), debugLogs) debugger;
|
|
1804
|
+
let fallbackHash = 0;
|
|
1805
|
+
if (typeof obj == "object" && obj !== null) {
|
|
1806
|
+
for (let key in obj)
|
|
1807
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
1808
|
+
let value = obj[key];
|
|
1809
|
+
fallbackHash += hashString(key), typeof value == "object" && value !== null ? depth > 10 ? fallbackHash += hashString("[object]") : fallbackHash += hashObject(value, depth + 1) : fallbackHash += hashString(String(value));
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
return fallbackHash;
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
function hashBuffer(buffer, offset, length) {
|
|
1816
|
+
if (xxHashModule) {
|
|
1817
|
+
let view2 = new Uint8Array(buffer, offset, length);
|
|
1818
|
+
return xxHashModule.h32Raw(view2);
|
|
1819
|
+
}
|
|
1820
|
+
let hash = 0, view = new Uint8Array(buffer, offset, length);
|
|
1821
|
+
for (let i = 0; i < view.length; i++)
|
|
1822
|
+
hash = (hash << 5) - hash + view[i], hash |= 0;
|
|
1823
|
+
return hash;
|
|
1824
|
+
}
|
|
1825
|
+
function hashString(str) {
|
|
1826
|
+
let hash = 0;
|
|
1827
|
+
for (let i = 0; i < str.length; i++)
|
|
1828
|
+
hash = (hash << 5) - hash + str.charCodeAt(i), hash |= 0;
|
|
1829
|
+
return hash;
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
// src/cache/job-cache.ts
|
|
1833
|
+
import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync as mkdirSync3 } from "fs";
|
|
1834
|
+
import path3 from "path";
|
|
1835
|
+
function computeJobKey(options, inputFilePath) {
|
|
1836
|
+
if (!inputFilePath.endsWith(".glb")) return null;
|
|
1837
|
+
let fileBytes = readFileSync4(inputFilePath), fileHash = hashBuffer(fileBytes.buffer, fileBytes.byteOffset, fileBytes.byteLength), optionsStr = JSON.stringify({
|
|
1838
|
+
compress: options.compress,
|
|
1839
|
+
progressive: options.progressive,
|
|
1840
|
+
config: options.config
|
|
1841
|
+
});
|
|
1842
|
+
return `job-${hashString(optionsStr)}-${fileHash}`;
|
|
1843
|
+
}
|
|
1844
|
+
function saveJobResult(jobKey, outputFiles, logger) {
|
|
1845
|
+
let entries = [];
|
|
1846
|
+
for (let i = 0; i < outputFiles.length; i++) {
|
|
1847
|
+
let filePath = outputFiles[i];
|
|
1848
|
+
if (!existsSync5(filePath)) continue;
|
|
1849
|
+
let cacheKey = `${jobKey}-f${i}`, content = readFileSync4(filePath);
|
|
1850
|
+
addToCache(cacheKey, content), entries.push({
|
|
1851
|
+
fileName: path3.basename(filePath),
|
|
1852
|
+
cacheKey
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
if (entries.length === 0) return;
|
|
1856
|
+
addMetaToCache(jobKey, { entries }), logger.debug(`[Job Cache] Saved ${entries.length} file(s) for job ${jobKey}`);
|
|
1857
|
+
}
|
|
1858
|
+
function tryRestoreJobResult(jobKey, outputDir, logger) {
|
|
1859
|
+
let manifest = tryGetMetaFromCache(jobKey);
|
|
1860
|
+
if (!manifest?.entries?.length) return null;
|
|
1861
|
+
let loaded = [];
|
|
1862
|
+
for (let entry of manifest.entries) {
|
|
1863
|
+
let cached = tryGetFromCache(entry.cacheKey);
|
|
1864
|
+
if (!cached)
|
|
1865
|
+
return logger.debug(`[Job Cache] Cache miss: missing entry ${entry.cacheKey}`), null;
|
|
1866
|
+
loaded.push({ entry, data: cached });
|
|
1867
|
+
}
|
|
1868
|
+
existsSync5(outputDir) || mkdirSync3(outputDir, { recursive: !0 });
|
|
1869
|
+
let restoredPaths = [];
|
|
1870
|
+
for (let { entry, data } of loaded) {
|
|
1871
|
+
let outPath = path3.join(outputDir, entry.fileName);
|
|
1872
|
+
writeFileSync(outPath, data), restoredPaths.push(outPath);
|
|
1873
|
+
}
|
|
1874
|
+
return logger.info(`[Job Cache] Restored ${restoredPaths.length} file(s) from cache`), restoredPaths;
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// src/transforms/needle_progressive.ts
|
|
1878
|
+
import sharp2 from "sharp";
|
|
1879
|
+
import { MeshoptDecoder, MeshoptEncoder as MeshoptEncoder2, MeshoptSimplifier as MeshoptSimplifier2 } from "meshoptimizer";
|
|
1880
|
+
|
|
1881
|
+
// src/transforms/needle_mesh_transform.ts
|
|
1882
|
+
import { Primitive as Primitive4 } from "@gltf-transform/core";
|
|
1883
|
+
import { meshopt, simplifyPrimitive, SIMPLIFY_DEFAULTS, WELD_DEFAULTS as WELD_DEFAULTS2, draco } from "@gltf-transform/functions";
|
|
1884
|
+
import { MeshoptEncoder, MeshoptSimplifier } from "meshoptimizer";
|
|
1885
|
+
|
|
1886
|
+
// src/functions/weld.3.ts
|
|
1887
|
+
import {
|
|
1888
|
+
Accessor as Accessor2,
|
|
1889
|
+
Document as Document5,
|
|
1890
|
+
Primitive as Primitive3,
|
|
1891
|
+
PropertyType as PropertyType10
|
|
1892
|
+
} from "@gltf-transform/core";
|
|
1893
|
+
import { createTransform as createTransform2, prune, dedup } from "@gltf-transform/functions";
|
|
1894
|
+
function createIndices(count, maxIndex = count) {
|
|
1895
|
+
let array = maxIndex <= 65534 ? new Uint16Array(count) : new Uint32Array(count);
|
|
1896
|
+
for (let i = 0; i < array.length; i++) array[i] = i;
|
|
1897
|
+
return array;
|
|
1898
|
+
}
|
|
1899
|
+
function formatLong(x) {
|
|
1900
|
+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1901
|
+
}
|
|
1902
|
+
function formatDelta(a, b, decimals = 2) {
|
|
1903
|
+
return (a > b ? "\u2013" : "+") + (Math.abs(a - b) / a * 100).toFixed(decimals) + "%";
|
|
1904
|
+
}
|
|
1905
|
+
function formatDeltaOp(a, b) {
|
|
1906
|
+
return `${formatLong(a)} \u2192 ${formatLong(b)} (${formatDelta(a, b)})`;
|
|
1907
|
+
}
|
|
1908
|
+
function cleanPrimitive(prim) {
|
|
1909
|
+
let indices = prim.getIndices();
|
|
1910
|
+
if (!indices) return;
|
|
1911
|
+
let tmpIndicesArray = [], maxIndex = -1 / 0;
|
|
1912
|
+
for (let i = 0, il = indices.getCount(); i < il; i += 3) {
|
|
1913
|
+
let a = indices.getScalar(i), b = indices.getScalar(i + 1), c = indices.getScalar(i + 2);
|
|
1914
|
+
a === b || a === c || b === c || (tmpIndicesArray.push(a, b, c), maxIndex = Math.max(maxIndex, a, b, c));
|
|
1915
|
+
}
|
|
1916
|
+
let dstIndicesArray = createIndices(tmpIndicesArray.length, maxIndex);
|
|
1917
|
+
dstIndicesArray.set(tmpIndicesArray), indices.setArray(dstIndicesArray);
|
|
1918
|
+
}
|
|
1919
|
+
var NAME = "weld", Tolerance = {
|
|
1920
|
+
DEFAULT: 1e-4,
|
|
1921
|
+
TEXCOORD: 1e-4,
|
|
1922
|
+
// [0, 1]
|
|
1923
|
+
COLOR: 0.01,
|
|
1924
|
+
// [0, 1]
|
|
1925
|
+
NORMAL: 0.05,
|
|
1926
|
+
// [-1, 1], ±3º
|
|
1927
|
+
JOINTS: 0,
|
|
1928
|
+
// [0, ∞]
|
|
1929
|
+
WEIGHTS: 0.01
|
|
1930
|
+
// [0, ∞]
|
|
1931
|
+
}, WELD_DEFAULTS = {
|
|
1932
|
+
tolerance: Tolerance.DEFAULT,
|
|
1933
|
+
toleranceNormal: Tolerance.NORMAL,
|
|
1934
|
+
overwrite: !0,
|
|
1935
|
+
exhaustive: !1
|
|
1936
|
+
// donmccurdy/glTF-Transform#886
|
|
1937
|
+
};
|
|
1938
|
+
function weldPrimitive(a, b = WELD_DEFAULTS, c = WELD_DEFAULTS) {
|
|
1939
|
+
let _document, _prim, _options;
|
|
1940
|
+
if (a instanceof Primitive3) {
|
|
1941
|
+
let graph = a.getGraph();
|
|
1942
|
+
_document = Document5.fromGraph(graph), _prim = a, _options = expandWeldOptions(b);
|
|
1943
|
+
} else
|
|
1944
|
+
_document = a, _prim = b, _options = expandWeldOptions(c);
|
|
1945
|
+
_prim.getIndices() && !_options.overwrite || _prim.getMode() !== Primitive3.Mode.POINTS && (_options.tolerance === 0 ? _indexPrimitive(_document, _prim) : _weldPrimitive(_document, _prim, _options));
|
|
1946
|
+
}
|
|
1947
|
+
function _indexPrimitive(doc, prim) {
|
|
1948
|
+
if (prim.getIndices()) return;
|
|
1949
|
+
let attr = prim.listAttributes()[0], numVertices = attr.getCount(), buffer = attr.getBuffer(), indices = doc.createAccessor().setBuffer(buffer).setType(Accessor2.Type.SCALAR).setArray(createIndices(numVertices));
|
|
1950
|
+
prim.setIndices(indices);
|
|
1951
|
+
}
|
|
1952
|
+
function _weldPrimitive(doc, prim, options) {
|
|
1953
|
+
let logger = doc.getLogger(), srcPosition = prim.getAttribute("POSITION"), srcIndices = prim.getIndices() || doc.createAccessor().setArray(createIndices(srcPosition.getCount())), uniqueIndices = new Uint32Array(new Set(srcIndices.getArray())).sort(), attributeTolerance = {};
|
|
1954
|
+
for (let semantic of prim.listSemantics()) {
|
|
1955
|
+
let attribute = prim.getAttribute(semantic);
|
|
1956
|
+
attributeTolerance[semantic] = getAttributeTolerance(semantic, attribute, options);
|
|
1957
|
+
}
|
|
1958
|
+
logger.debug(`${NAME}: Tolerance thresholds: ${formatKV(attributeTolerance)}`);
|
|
1959
|
+
let posA = [0, 0, 0], posB = [0, 0, 0], grid = {}, cellSize = attributeTolerance.POSITION;
|
|
1960
|
+
for (let i = 0; i < uniqueIndices.length; i++) {
|
|
1961
|
+
srcPosition.getElement(uniqueIndices[i], posA);
|
|
1962
|
+
let key = getGridKey(posA, cellSize);
|
|
1963
|
+
grid[key] = grid[key] || [], grid[key].push(uniqueIndices[i]);
|
|
1964
|
+
}
|
|
1965
|
+
let srcMaxIndex = uniqueIndices[uniqueIndices.length - 1], weldMap = createIndices(srcMaxIndex + 1), writeMap = new Array(uniqueIndices.length).fill(-1), srcVertexCount = srcPosition.getCount(), dstVertexCount = 0;
|
|
1966
|
+
for (let i = 0; i < uniqueIndices.length; i++) {
|
|
1967
|
+
let a = uniqueIndices[i];
|
|
1968
|
+
srcPosition.getElement(a, posA);
|
|
1969
|
+
let cellKeys = options.exhaustive ? getGridNeighborhoodKeys(posA, cellSize) : [getGridKey(posA, cellSize)];
|
|
1970
|
+
cells: for (let cellKey of cellKeys) {
|
|
1971
|
+
if (!grid[cellKey]) continue cells;
|
|
1972
|
+
neighbors: for (let j of grid[cellKey]) {
|
|
1973
|
+
let b = weldMap[j];
|
|
1974
|
+
if (a <= b) continue neighbors;
|
|
1975
|
+
srcPosition.getElement(b, posB);
|
|
1976
|
+
let isBaseMatch = prim.listSemantics().every((semantic) => {
|
|
1977
|
+
let attribute = prim.getAttribute(semantic), tolerance = attributeTolerance[semantic];
|
|
1978
|
+
return compareAttributes(attribute, a, b, tolerance, semantic);
|
|
1979
|
+
}), isTargetMatch = prim.listTargets().every((target) => target.listSemantics().every((semantic) => {
|
|
1980
|
+
let attribute = target.getAttribute(semantic), tolerance = attributeTolerance[semantic];
|
|
1981
|
+
return compareAttributes(attribute, a, b, tolerance, semantic);
|
|
1982
|
+
}));
|
|
1983
|
+
if (isBaseMatch && isTargetMatch) {
|
|
1984
|
+
weldMap[a] = b;
|
|
1985
|
+
break cells;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
weldMap[a] === a ? writeMap[a] = dstVertexCount++ : writeMap[a] = writeMap[weldMap[a]];
|
|
1990
|
+
}
|
|
1991
|
+
logger.debug(`${NAME}: ${formatDeltaOp(srcVertexCount, dstVertexCount)} vertices.`);
|
|
1992
|
+
let dstIndicesCount = srcIndices.getCount(), dstIndicesArray = createIndices(dstIndicesCount, uniqueIndices.length);
|
|
1993
|
+
for (let i = 0; i < dstIndicesCount; i++)
|
|
1994
|
+
dstIndicesArray[i] = writeMap[srcIndices.getScalar(i)];
|
|
1995
|
+
prim.setIndices(srcIndices.clone().setArray(dstIndicesArray)), srcIndices.listParents().length === 1 && srcIndices.dispose();
|
|
1996
|
+
for (let srcAttr of prim.listAttributes())
|
|
1997
|
+
swapAttributes(prim, srcAttr, writeMap, dstVertexCount);
|
|
1998
|
+
for (let target of prim.listTargets())
|
|
1999
|
+
for (let srcAttr of target.listAttributes())
|
|
2000
|
+
swapAttributes(target, srcAttr, writeMap, dstVertexCount);
|
|
2001
|
+
cleanPrimitive(prim);
|
|
2002
|
+
}
|
|
2003
|
+
function createArrayOfType(array, length) {
|
|
2004
|
+
let ArrayCtor = array.constructor;
|
|
2005
|
+
return new ArrayCtor(length);
|
|
2006
|
+
}
|
|
2007
|
+
function swapAttributes(parent, srcAttr, reorder, dstCount) {
|
|
2008
|
+
let dstAttrArray = createArrayOfType(srcAttr.getArray(), dstCount * srcAttr.getElementSize()), dstAttr = srcAttr.clone().setArray(dstAttrArray), done = new Uint8Array(dstCount);
|
|
2009
|
+
for (let i = 0, el = []; i < reorder.length; i++)
|
|
2010
|
+
done[reorder[i]] || (dstAttr.setElement(reorder[i], srcAttr.getElement(i, el)), done[reorder[i]] = 1);
|
|
2011
|
+
parent.swap(srcAttr, dstAttr), srcAttr.listParents().length === 1 && srcAttr.dispose();
|
|
2012
|
+
}
|
|
2013
|
+
var _a = [], _b = [];
|
|
2014
|
+
function getAttributeTolerance(semantic, attribute, options) {
|
|
2015
|
+
if (semantic === "NORMAL" || semantic === "TANGENT") return options.toleranceNormal;
|
|
2016
|
+
if (semantic.startsWith("COLOR_")) return Tolerance.COLOR;
|
|
2017
|
+
if (semantic.startsWith("TEXCOORD_")) return Tolerance.TEXCOORD;
|
|
2018
|
+
if (semantic.startsWith("JOINTS_")) return Tolerance.JOINTS;
|
|
2019
|
+
if (semantic.startsWith("WEIGHTS_")) return Tolerance.WEIGHTS;
|
|
2020
|
+
_a.length = _b.length = 0, attribute.getMinNormalized(_a), attribute.getMaxNormalized(_b);
|
|
2021
|
+
let diff = _b.map((bi, i) => bi - _a[i]), range = Math.max(...diff);
|
|
2022
|
+
return options.tolerance * range;
|
|
2023
|
+
}
|
|
2024
|
+
function compareAttributes(attribute, a, b, tolerance, _semantic) {
|
|
2025
|
+
attribute.getElement(a, _a), attribute.getElement(b, _b);
|
|
2026
|
+
for (let i = 0, il = attribute.getElementSize(); i < il; i++)
|
|
2027
|
+
if (Math.abs(_a[i] - _b[i]) > tolerance)
|
|
2028
|
+
return !1;
|
|
2029
|
+
return !0;
|
|
2030
|
+
}
|
|
2031
|
+
function formatKV(kv) {
|
|
2032
|
+
return Object.entries(kv).map(([k, v]) => `${k}=${v}`).join(", ");
|
|
2033
|
+
}
|
|
2034
|
+
var CELL_OFFSETS = [0, -1, 1];
|
|
2035
|
+
function getGridNeighborhoodKeys(p, cellSize) {
|
|
2036
|
+
let keys = [], _p = [0, 0, 0];
|
|
2037
|
+
for (let i of CELL_OFFSETS)
|
|
2038
|
+
for (let j of CELL_OFFSETS)
|
|
2039
|
+
for (let k of CELL_OFFSETS)
|
|
2040
|
+
_p[0] = p[0] + i * cellSize, _p[1] = p[1] + j * cellSize, _p[2] = p[2] + k * cellSize, keys.push(getGridKey(_p, cellSize));
|
|
2041
|
+
return keys;
|
|
2042
|
+
}
|
|
2043
|
+
function getGridKey(p, cellSize) {
|
|
2044
|
+
let cellX = Math.round(p[0] / cellSize), cellY = Math.round(p[1] / cellSize), cellZ = Math.round(p[2] / cellSize);
|
|
2045
|
+
return cellX + ":" + cellY + ":" + cellZ;
|
|
2046
|
+
}
|
|
2047
|
+
function expandWeldOptions(_options) {
|
|
2048
|
+
let options = { ...WELD_DEFAULTS, ..._options };
|
|
2049
|
+
if (options.tolerance < 0 || options.tolerance > 0.1)
|
|
2050
|
+
throw new Error(`${NAME}: Requires 0 <= tolerance <= 0.1`);
|
|
2051
|
+
if (options.toleranceNormal < 0 || options.toleranceNormal > Math.PI / 2)
|
|
2052
|
+
throw new Error(`${NAME}: Requires 0 <= toleranceNormal <= ${(Math.PI / 2).toFixed(2)}`);
|
|
2053
|
+
return options.tolerance > 0 && (options.tolerance = Math.max(options.tolerance, Number.EPSILON), options.toleranceNormal = Math.max(options.toleranceNormal, Number.EPSILON)), options;
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// src/transforms/needle_mesh_transform.ts
|
|
2057
|
+
var NAME2 = "needle_mesh_transform";
|
|
2058
|
+
function determineMeshCompression(document, filePath) {
|
|
2059
|
+
let rootExtension = document.getRoot().getExtension(NEEDLE_mesh_compression.EXTENSION_NAME);
|
|
2060
|
+
if (rootExtension) {
|
|
2061
|
+
let rootModel = rootExtension.model;
|
|
2062
|
+
if (rootModel) {
|
|
2063
|
+
if (!rootModel.compression)
|
|
2064
|
+
throw new Error(`[${NAME2}]: Invalid mesh compression model extension on root node of ${filePath}`);
|
|
2065
|
+
return rootModel;
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
if (filePath?.toLowerCase().endsWith(".vrm") && document.getRoot().listMeshes().some((mesh) => mesh.listPrimitives().some((prim) => prim.listTargets().length > 0)))
|
|
2069
|
+
return new NEEDLE_mesh_compression_model_root("meshopt");
|
|
2070
|
+
let sizeOfBlendshapes = 0, sizeOfMeshes = 0;
|
|
2071
|
+
for (let mesh of document.getRoot().listMeshes())
|
|
2072
|
+
for (let prim of mesh.listPrimitives()) {
|
|
2073
|
+
for (let target of prim.listTargets())
|
|
2074
|
+
sizeOfBlendshapes += target.getAttribute("POSITION").getArray().length;
|
|
2075
|
+
sizeOfMeshes += prim.getAttribute("POSITION").getArray().length;
|
|
2076
|
+
}
|
|
2077
|
+
return sizeOfBlendshapes > 0 ? (document.getLogger().debug(`[${NAME2}]: will apply meshopt mesh compression because the mesh contains blendshapes`), new NEEDLE_mesh_compression_model_root("meshopt")) : new NEEDLE_mesh_compression_model_root("draco");
|
|
2078
|
+
}
|
|
2079
|
+
var needle_mesh_transform = function(context) {
|
|
2080
|
+
return async (document, _context) => {
|
|
2081
|
+
await simplifierTransform(document, _context, context), await applyMeshCompression(document, _context, context);
|
|
2082
|
+
};
|
|
2083
|
+
};
|
|
2084
|
+
async function applyMeshCompression(document, transform_context, context) {
|
|
2085
|
+
let isLOD2 = isMeshLOD(context.file), compressionModel = determineMeshCompression(document, context.file);
|
|
2086
|
+
if (compressionModel && compressionModel.compression) {
|
|
2087
|
+
if (compressionModel.compression === "none") {
|
|
2088
|
+
document.getLogger().debug(`[${NAME2}]: NONE \u2192 will not apply mesh compression`);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
if (document.getLogger().debug(`[${NAME2}]: ${compressionModel.compression.toUpperCase()} \u2192 will apply ${compressionModel.compression} mesh compression`), compressionModel.compression === "draco")
|
|
2092
|
+
return draco({
|
|
2093
|
+
encodeSpeed: 8,
|
|
2094
|
+
decodeSpeed: 8,
|
|
2095
|
+
quantizationVolume: isLOD2 ? "scene" : void 0
|
|
2096
|
+
})(document, transform_context);
|
|
2097
|
+
if (compressionModel.compression === "meshopt")
|
|
2098
|
+
return meshopt({ encoder: MeshoptEncoder })(document, transform_context);
|
|
2099
|
+
}
|
|
2100
|
+
return document.getLogger().debug(`[${NAME2}]: \u2192 will apply draco mesh compression (default)`), draco({
|
|
2101
|
+
encodeSpeed: 8,
|
|
2102
|
+
decodeSpeed: 8,
|
|
2103
|
+
quantizationVolume: isLOD2 ? "scene" : void 0
|
|
2104
|
+
})(document, transform_context);
|
|
2105
|
+
}
|
|
2106
|
+
async function simplifierTransform(document, _context, meshContext) {
|
|
2107
|
+
let simplifier = MeshoptSimplifier;
|
|
2108
|
+
if (!simplifier)
|
|
2109
|
+
return document.getLogger().warn(`WARN: [${NAME2}] simplifier dependency required \u2014 install "meshoptimizer".`), !1;
|
|
2110
|
+
let logger = document.getLogger(), isVRM = meshContext.file?.toLowerCase().endsWith(".vrm"), options = {
|
|
2111
|
+
...SIMPLIFY_DEFAULTS,
|
|
2112
|
+
simplifier,
|
|
2113
|
+
ratio: 0.75,
|
|
2114
|
+
error: 5e-4
|
|
2115
|
+
}, weldOptions = {
|
|
2116
|
+
...WELD_DEFAULTS2,
|
|
2117
|
+
overwrite: !0
|
|
2118
|
+
};
|
|
2119
|
+
for (let mesh of document.getRoot().listMeshes()) {
|
|
2120
|
+
let i = 0;
|
|
2121
|
+
for (let prim of mesh.listPrimitives()) {
|
|
2122
|
+
let index = i++, ext = prim.getExtension(NEEDLE_mesh_compression.EXTENSION_NAME), mesh_compression = ext?.model, simplifyOpts = { ...options };
|
|
2123
|
+
if (isVRM) {
|
|
2124
|
+
let density = calculateMeshDensity(prim);
|
|
2125
|
+
if (density > 0) {
|
|
2126
|
+
let t = 1 / density * 2e3;
|
|
2127
|
+
simplifyOpts.ratio = Math.min(Math.max(0.1, t), 0.95), simplifyOpts.error = 15 / density, simplifyOpts.lockBorder = !0;
|
|
2128
|
+
} else
|
|
2129
|
+
simplifyOpts.ratio = 0.8, simplifyOpts.error = 1e-3, simplifyOpts.lockBorder = !0;
|
|
2130
|
+
logger.info(`${mesh.getName()}: Density: ${density.toFixed(2)}, Ratio: ${simplifyOpts.ratio.toFixed(2)}, Error: ${simplifyOpts.error}`);
|
|
2131
|
+
}
|
|
2132
|
+
if (!(!ext && !isVRM)) {
|
|
2133
|
+
if (mesh_compression) {
|
|
2134
|
+
if (mesh_compression.useSimplifier === !1) {
|
|
2135
|
+
logger.debug(`[${NAME2}]: Skipping primitive of mesh "${mesh.getName()}": useSimplifier is false.`);
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
mesh_compression.error >= 0 && (simplifyOpts.error = mesh_compression.error), mesh_compression.ratio >= 0 && (simplifyOpts.ratio = mesh_compression.ratio), simplifyOpts.lockBorder = mesh_compression.lockBorder;
|
|
2139
|
+
}
|
|
2140
|
+
if (prim.getMode() !== Primitive4.Mode.TRIANGLES) {
|
|
2141
|
+
logger.warn(
|
|
2142
|
+
`[${NAME2}]: Skipping primitive of mesh "${mesh.getName()}": Requires TRIANGLES draw mode.`
|
|
2143
|
+
);
|
|
2144
|
+
continue;
|
|
2145
|
+
}
|
|
2146
|
+
compressPrimitive(document, mesh, prim, index, weldOptions, simplifyOpts);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
return !0;
|
|
2151
|
+
}
|
|
2152
|
+
async function compressPrimitive(document, mesh, prim, index, weldOptions, meshOptions) {
|
|
2153
|
+
let logger = document.getLogger();
|
|
2154
|
+
if (logger.debug(`weld: primitive[${index}] of mesh "${mesh.getName()}"`), weldPrimitive(prim, weldOptions), !(meshOptions.simplifier && meshOptions.simplifier?.ready instanceof Promise && !await meshOptions.simplifier?.ready.then(() => !0).catch((err) => (console.error(`[${NAME2}]: Simplifier failed to load...
|
|
2155
|
+
${err}`), !1))))
|
|
2156
|
+
return logger.debug(`simplify: primitive[${index}] of mesh "${mesh.getName()}" \u2192 ratio: ${meshOptions.ratio}, error: ${meshOptions.error}, lockBorder: ${meshOptions.lockBorder}, regularize: ${meshOptions.regularize}, normalWeight: ${meshOptions.normalWeight}, colorWeight: ${meshOptions.colorWeight}, textureWeight: ${meshOptions.textureWeight}`), simplifyPrimitive(prim, meshOptions);
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
// src/transforms/needle_progressive.ts
|
|
2160
|
+
async function make_progressive(opts) {
|
|
2161
|
+
let file = opts.path, success = !0;
|
|
2162
|
+
if (await foreachGLTF(file, async (f) => {
|
|
2163
|
+
if (!success)
|
|
2164
|
+
return;
|
|
2165
|
+
if (isMeshLOD(f) || isImageLOD(f)) {
|
|
2166
|
+
opts.logger.info(`[Progressive Transform]: Ignore existing LOD file at ${f}`);
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
await onProcess(f, opts) || (success = !1);
|
|
2170
|
+
}), success) {
|
|
2171
|
+
let resultsCount = opts.results.length;
|
|
2172
|
+
for (let i = opts.results.length - 1; i >= 0; i--)
|
|
2173
|
+
existsSync6(opts.results[i]) || opts.results.splice(i, 1);
|
|
2174
|
+
let resultsChanged = resultsCount !== opts.results.length;
|
|
2175
|
+
opts.debug && console.log(`[Progressive Transform]: ${opts.results.length} files processed. ${resultsChanged ? "Some results were removed" : ""}`);
|
|
2176
|
+
}
|
|
2177
|
+
return success;
|
|
2178
|
+
}
|
|
2179
|
+
function registerExtensions2(io) {
|
|
2180
|
+
registerExtensions(io), io.registerExtensions([
|
|
2181
|
+
NEEDLE_progressive,
|
|
2182
|
+
NEEDLE_progressive_texture_settings,
|
|
2183
|
+
NEEDLE_progressive_mesh_settings,
|
|
2184
|
+
NEEDLE_mesh_compression,
|
|
2185
|
+
//@ts-ignore
|
|
2186
|
+
createOpaqueExtension(NEEDLE_compression_texture.EXTENSION_NAME, PropertyType11.TEXTURE)
|
|
2187
|
+
//@ts-ignore
|
|
2188
|
+
// createOpaqueExtension(NEEDLE_mesh_compression.EXTENSION_NAME, [PropertyType.ROOT, PropertyType.MESH, PropertyType.PRIMITIVE]),
|
|
2189
|
+
]);
|
|
2190
|
+
}
|
|
2191
|
+
async function onProcess(file, opts) {
|
|
2192
|
+
if (!file.endsWith(".glb") && !file.endsWith(".gltf") && !file.endsWith(".vrm"))
|
|
2193
|
+
return console.log("ERR: file is not gltf/glb"), !1;
|
|
2194
|
+
if (!existsSync6(file))
|
|
2195
|
+
return console.log("ERR: file does not exist: " + file), !1;
|
|
2196
|
+
try {
|
|
2197
|
+
let io = new NodeIO();
|
|
2198
|
+
registerExtensions2(io), io.registerDependencies({
|
|
2199
|
+
"meshopt.decoder": MeshoptDecoder,
|
|
2200
|
+
"meshopt.encoder": MeshoptEncoder2,
|
|
2201
|
+
"draco3d.decoder": await draco3d.createDecoderModule(),
|
|
2202
|
+
"draco3d.encoder": await draco3d.createEncoderModule()
|
|
2203
|
+
}), setExtensionInputFile(file);
|
|
2204
|
+
let document = await ioTryReadWithMissingResources(io, file);
|
|
2205
|
+
if (document) {
|
|
2206
|
+
opts.logger ? document.setLogger(opts.logger) : document.getLogger().verbosity = opts.debug || opts.verbose ? Verbosity.DEBUG : Verbosity.WARN;
|
|
2207
|
+
let logger = opts.logger || document.getLogger();
|
|
2208
|
+
opts.outpath && copyExternalResources(document, file, path4.join(opts.outpath, path4.basename(file)));
|
|
2209
|
+
let smallesTextureSize = 128;
|
|
2210
|
+
opts.config.usecase === "product" && (smallesTextureSize = 512);
|
|
2211
|
+
let transforms = [
|
|
2212
|
+
needle_asset()
|
|
2213
|
+
];
|
|
2214
|
+
(await io.readAsJSON(file)).json.extensionsUsed?.includes("KHR_materials_pbrSpecularGlossiness") && (logger.warn("Converting KHR_materials_pbrSpecularGlossiness to metal/rough workflow..."), await document.transform(
|
|
2215
|
+
metalRough()
|
|
2216
|
+
)), opts.config?.textures?.lods !== !1 && transforms.push(make_progressive_textures(file, { size: [smallesTextureSize, smallesTextureSize] }, opts));
|
|
2217
|
+
let isVRM = file.toLowerCase().endsWith(".vrm");
|
|
2218
|
+
!isVRM && opts.config?.meshes?.lods !== !1 ? transforms.push(make_progressive_meshes(file, {}, opts)) : isVRM && logger.warn("WARN: Progressive meshes are not supported for VRM files yet"), transforms.push(metalRough()), transforms.push(sparse()), logger.info("\u2192 Transforming: " + file), await document.transform(
|
|
2219
|
+
...transforms
|
|
2220
|
+
);
|
|
2221
|
+
let filename = getOutputPath(file, opts.outpath);
|
|
2222
|
+
await writeNodeIO(io, filename, document), opts.results.push(filename), logger.info("\u2190 Transforming done: " + filename);
|
|
2223
|
+
}
|
|
2224
|
+
} catch (err) {
|
|
2225
|
+
if (err instanceof TestAssertionError) throw err;
|
|
2226
|
+
return console.log('ERR: failed to process file "' + file + '", Reason: ' + err.message, `
|
|
2227
|
+
Stack:
|
|
2228
|
+
` + err.stack), !1;
|
|
2229
|
+
}
|
|
2230
|
+
return !0;
|
|
2231
|
+
}
|
|
2232
|
+
function createTransform3(name, fn) {
|
|
2233
|
+
return Object.defineProperty(fn, "name", { value: name }), fn;
|
|
2234
|
+
}
|
|
2235
|
+
var NAME3 = "NEEDLE_progressive";
|
|
2236
|
+
function make_progressive_textures(filePath, _options = TEXTURE_RESIZE_DEFAULTS, opts) {
|
|
2237
|
+
let startTime = Date.now(), filename = basename(filePath), options = { ...TEXTURE_RESIZE_DEFAULTS, ..._options }, directory = path4.dirname(filePath);
|
|
2238
|
+
opts.outpath && (directory = ensureIsDirectory(opts.outpath));
|
|
2239
|
+
let textureLodBasePath = directory + "/";
|
|
2240
|
+
return createTransform3(NAME3, async (doc) => {
|
|
2241
|
+
let logger = doc.getLogger();
|
|
2242
|
+
if (isLOD(filePath))
|
|
2243
|
+
return logger.info("Progressive Image Transform: skip lod at " + filePath), Promise.resolve();
|
|
2244
|
+
let index = 0, textureHashCache = /* @__PURE__ */ new Map();
|
|
2245
|
+
for (let texture of doc.getRoot().listTextures()) {
|
|
2246
|
+
let textureIndex = index++, name = texture.getName(), uri = texture.getURI();
|
|
2247
|
+
if (!(!options.pattern || options.pattern.test(name) || options.pattern.test(uri))) {
|
|
2248
|
+
logger.debug(`[${NAME3}] Skipping, excluded by "pattern" parameter. ${textureIndex}`);
|
|
2249
|
+
continue;
|
|
2250
|
+
}
|
|
2251
|
+
if (texture.getMimeType() !== "image/png" && texture.getMimeType() !== "image/jpeg") {
|
|
2252
|
+
logger.warn(`[${NAME3}] Skipping, unsupported texture type "${texture.getMimeType()} at ${textureIndex}".`);
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
let slots = listTextureSlots(texture);
|
|
2256
|
+
if (options.slots && !slots.some((slot) => options.slots?.test(slot))) {
|
|
2257
|
+
logger.debug(`[${NAME3}] Skipping, [${slots.join(", ")}] excluded by "slots" parameter. ${textureIndex}`);
|
|
2258
|
+
continue;
|
|
2259
|
+
}
|
|
2260
|
+
let settings = texture.getExtension(NEEDLE_progressive_texture_settings.EXTENSION_NAME);
|
|
2261
|
+
if (settings) {
|
|
2262
|
+
if (settings.generateLods === !1) {
|
|
2263
|
+
logger.debug(`[${NAME3}] Skipping texture[${textureIndex}]: progressive texture disabled`);
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
} else {
|
|
2267
|
+
let size = texture.getSize();
|
|
2268
|
+
if (size?.length >= 2 && size[0] <= options.size[0] && size[1] <= options.size[1]) {
|
|
2269
|
+
logger.warn(`[${NAME3}] Skipping texture[${textureIndex}], no settings found and the texture is already <= ${size[0]}x${size[1]}`);
|
|
2270
|
+
continue;
|
|
2271
|
+
} else
|
|
2272
|
+
textureHashCache.has(texture) || textureHashCache.set(texture, getHash(texture)), settings = {
|
|
2273
|
+
guid: generateGuid(textureHashCache.get(texture)),
|
|
2274
|
+
maxSize: _options.size[0]
|
|
2275
|
+
}, logger.debug(`[${NAME3}] No settings found for texture[${index}] - will use default settings (maxSize: ${settings.maxSize}, guid: ${settings.guid})`);
|
|
2276
|
+
}
|
|
2277
|
+
if (settings.maxSize == null || settings.maxSize <= 0) {
|
|
2278
|
+
logger.warn(`[${NAME3}] Skipping texture[${textureIndex}], settings are invalid (maxSize: ${settings.maxSize})`);
|
|
2279
|
+
continue;
|
|
2280
|
+
}
|
|
2281
|
+
let existingExtension = texture.getExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME);
|
|
2282
|
+
if (existingExtension != null) {
|
|
2283
|
+
logger.debug(`[${NAME3}] Skipping, texture is already progressive ${textureIndex}`);
|
|
2284
|
+
continue;
|
|
2285
|
+
}
|
|
2286
|
+
let progressiveExt = doc.createExtension(NEEDLE_progressive);
|
|
2287
|
+
if (!progressiveExt || !progressiveExt.createTexture) {
|
|
2288
|
+
logger.debug(`[${NAME3}] Skipping because progressive extension is not available. ${textureIndex}`);
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
let mimeTypeResult = validateImageMimeType(texture.getMimeType(), texture.getImage(), logger);
|
|
2292
|
+
mimeTypeResult?.error && (logger.warn(`[${NAME3}] Texture[${index}] has invalid mime type! Reported "${texture.getMimeType()}" but is actually "${mimeTypeResult.mimeType}": auto-fix`), texture.setMimeType(mimeTypeResult.mimeType));
|
|
2293
|
+
let currentSize = Math.min(...texture.getSize());
|
|
2294
|
+
if (currentSize <= settings.maxSize) {
|
|
2295
|
+
logger.debug(`[${NAME3}] Skipping, texture[${textureIndex}] is already smaller than the requested size: ${currentSize}px <= ${settings.maxSize}px`);
|
|
2296
|
+
continue;
|
|
2297
|
+
}
|
|
2298
|
+
if (!settings.guid?.length) {
|
|
2299
|
+
textureHashCache.has(texture) || textureHashCache.set(texture, getHash(texture));
|
|
2300
|
+
let hash = textureHashCache.get(texture);
|
|
2301
|
+
settings.guid = generateGuid(hash);
|
|
2302
|
+
}
|
|
2303
|
+
let textureGuid = settings.guid, maxSize = settings.maxSize, LOD_LEVEL = new Array();
|
|
2304
|
+
LOD_LEVEL.push({ size: currentSize });
|
|
2305
|
+
let generateLods = !0, _isLightmap = slots.includes("lightmapTexture") || isLightmap(texture);
|
|
2306
|
+
if (generateLods && !_isLightmap) {
|
|
2307
|
+
let lastSize = currentSize;
|
|
2308
|
+
for (let i = 1; i < 6; i++) {
|
|
2309
|
+
let size = lastSize * 0.5;
|
|
2310
|
+
if (size <= maxSize) break;
|
|
2311
|
+
lastSize = Math.round(size), LOD_LEVEL.push({ size });
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
let results = new Array();
|
|
2315
|
+
for (let i = 0; i < LOD_LEVEL.length; i++) {
|
|
2316
|
+
let level = LOD_LEVEL[i], lodResult = await createTextureLod({
|
|
2317
|
+
doc,
|
|
2318
|
+
inputFilepath: filePath,
|
|
2319
|
+
inputFilename: filename,
|
|
2320
|
+
basePath: textureLodBasePath,
|
|
2321
|
+
level: i,
|
|
2322
|
+
texture,
|
|
2323
|
+
slots,
|
|
2324
|
+
guid: textureGuid,
|
|
2325
|
+
textureIndex,
|
|
2326
|
+
maxSize: level.size
|
|
2327
|
+
}, opts);
|
|
2328
|
+
if (!lodResult)
|
|
2329
|
+
continue;
|
|
2330
|
+
let { 0: width, 1: height } = lodResult.texture.getSize(), outpath = lodResult?.outpath, relName = path4.relative(directory, outpath);
|
|
2331
|
+
results.push({
|
|
2332
|
+
path: relName,
|
|
2333
|
+
hash: lodResult.hash,
|
|
2334
|
+
width,
|
|
2335
|
+
height
|
|
2336
|
+
}), opts.results.push(outpath);
|
|
2337
|
+
}
|
|
2338
|
+
let cacheKey = getKey(texture), model = {
|
|
2339
|
+
guid: textureGuid,
|
|
2340
|
+
lods: results
|
|
2341
|
+
};
|
|
2342
|
+
if (texture.setExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME, progressiveExt.createTexture(model)), opts.useCache) {
|
|
2343
|
+
let cached = tryGetFromCache(cacheKey);
|
|
2344
|
+
if (cached) {
|
|
2345
|
+
logger.debug(`Progressive image ${index}: using cached preview version (size: ${options.size}))`), texture.setImage(cached);
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
if (results?.length) {
|
|
2350
|
+
let resizeOpts = { ...options, size: [settings.maxSize, settings.maxSize] };
|
|
2351
|
+
logger.debug(`[${NAME3}] Resizing embedded texture[${index}] to ${resizeOpts.size[0]}x${resizeOpts.size[1]}`), await resizeTexture(resizeOpts, texture, logger, uri || name, slots), opts?.useCache === !1 || addToCache(cacheKey, texture.getImage());
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
logger.debug(`Progressive transform finished in ${((Date.now() - startTime) / 1e3).toFixed(1)} sec.`);
|
|
2355
|
+
});
|
|
2356
|
+
}
|
|
2357
|
+
async function createTextureLod(args, opts) {
|
|
2358
|
+
let { doc, inputFilepath: file, basePath, level, texture, guid, textureIndex } = args, slots = args.slots, logger = doc.getLogger(), newDoc = new Document7();
|
|
2359
|
+
writeNeedleAsset(newDoc, {
|
|
2360
|
+
source: {
|
|
2361
|
+
filename: args.inputFilename
|
|
2362
|
+
}
|
|
2363
|
+
});
|
|
2364
|
+
let scene = newDoc.createScene(), buffer = newDoc.createBuffer(), newTexture = newDoc.createTexture(), img = texture.getImage();
|
|
2365
|
+
if (newTexture.setImage(img), newTexture.setURI(texture.getURI()), newTexture.setMimeType(texture.getMimeType()), newTexture.setName(texture.getName() || "LOD_" + textureIndex), args.maxSize && args.maxSize >= 16) {
|
|
2366
|
+
let currentSize = newTexture.getSize();
|
|
2367
|
+
currentSize[0] > args.maxSize && currentSize[1] > args.maxSize && await resizeTexture({ size: [args.maxSize, args.maxSize] }, newTexture, logger, texture.getURI(), slots);
|
|
2368
|
+
}
|
|
2369
|
+
slots?.length || (logger.warn(`WARN: No material slots found for texture at index ${textureIndex} (name: "${texture.getName()}") \u2192 will assume slot "baseColorTexture"`), slots = ["baseColorTexture"]);
|
|
2370
|
+
let slot_index = 0;
|
|
2371
|
+
for (let slot of slots) {
|
|
2372
|
+
let newMaterial = newDoc.createMaterial(newTexture.getName());
|
|
2373
|
+
switch (listTextureChannels(texture).includes(TextureChannel5.A) && newMaterial.setAlphaMode("BLEND"), slot) {
|
|
2374
|
+
case "baseColorTexture":
|
|
2375
|
+
newMaterial.setBaseColorTexture(newTexture);
|
|
2376
|
+
break;
|
|
2377
|
+
case "metallicRoughnessTexture":
|
|
2378
|
+
newMaterial.setMetallicRoughnessTexture(newTexture);
|
|
2379
|
+
break;
|
|
2380
|
+
case "normalTexture":
|
|
2381
|
+
newMaterial.setNormalTexture(newTexture);
|
|
2382
|
+
break;
|
|
2383
|
+
case "occlusionTexture":
|
|
2384
|
+
newMaterial.setOcclusionTexture(newTexture);
|
|
2385
|
+
break;
|
|
2386
|
+
case "emissiveTexture":
|
|
2387
|
+
newMaterial.setEmissiveTexture(newTexture);
|
|
2388
|
+
break;
|
|
2389
|
+
case "lightmapTexture":
|
|
2390
|
+
newMaterial.setBaseColorTexture(newTexture), setLightmapName(newTexture);
|
|
2391
|
+
break;
|
|
2392
|
+
default:
|
|
2393
|
+
if (slot.startsWith("lightmapTexture_") || slot.startsWith("lightmap_")) {
|
|
2394
|
+
newMaterial.setBaseColorTexture(newTexture), setLightmapName(newTexture);
|
|
2395
|
+
break;
|
|
2396
|
+
}
|
|
2397
|
+
if (slot.startsWith("/textures/")) {
|
|
2398
|
+
newMaterial.setAlphaMode("BLEND"), newMaterial.setBaseColorTexture(newTexture);
|
|
2399
|
+
break;
|
|
2400
|
+
}
|
|
2401
|
+
if (slot === "specularColorTexture") {
|
|
2402
|
+
logger.info("Pass-through KHR_materials_pbrSpecularGlossiness specularColorTexture");
|
|
2403
|
+
let prob = newDoc.createExtension(KHRMaterialsSpecular).createSpecular();
|
|
2404
|
+
prob.setSpecularColorTexture(newTexture), newMaterial.setExtension(KHRMaterialsSpecular.EXTENSION_NAME, prob);
|
|
2405
|
+
break;
|
|
2406
|
+
} else if (slot === "specularTexture") {
|
|
2407
|
+
logger.info("Pass-through KHR_materials_specular specularTexture");
|
|
2408
|
+
let prob = newDoc.createExtension(KHRMaterialsSpecular).createSpecular();
|
|
2409
|
+
prob.setSpecularTexture(newTexture), newMaterial.setExtension(KHRMaterialsSpecular.EXTENSION_NAME, prob);
|
|
2410
|
+
break;
|
|
2411
|
+
}
|
|
2412
|
+
return logger.warn(`WARN: Unknown texture slot: ${slot} for texture ${textureIndex} \u2192 can not load progressively (all slots: ${slots.join(", ")})`), null;
|
|
2413
|
+
}
|
|
2414
|
+
createMeshForMaterial(newDoc, newMaterial, slot_index++);
|
|
2415
|
+
}
|
|
2416
|
+
let compressionSettingsExt = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME);
|
|
2417
|
+
if (compressionSettingsExt != null && compressionSettingsExt.getExtensionDefinition) {
|
|
2418
|
+
logger.debug("> Pass compression extension to new texture");
|
|
2419
|
+
let newExt = newDoc.createExtension(NEEDLE_compression_texture), compressionSettings = compressionSettingsExt.getExtensionDefinition();
|
|
2420
|
+
if (!(compressionSettings?.mode === "none" || compressionSettings?.mode === "webp" || compressionSettings?.mode === "UASTC" || compressionSettings?.mode === "ETC1S"))
|
|
2421
|
+
switch (opts.config.usecase) {
|
|
2422
|
+
// For world scenarios we use ETC1S
|
|
2423
|
+
case "world":
|
|
2424
|
+
compressionSettings.mode = "ETC1S";
|
|
2425
|
+
break;
|
|
2426
|
+
case "product":
|
|
2427
|
+
compressionSettings.mode = detectTextureCompressionMode(slots), compressionSettings.quality = 100;
|
|
2428
|
+
break;
|
|
2429
|
+
default:
|
|
2430
|
+
compressionSettings.mode = detectTextureCompressionMode(slots);
|
|
2431
|
+
break;
|
|
2432
|
+
}
|
|
2433
|
+
compressionSettings.slot = slots[0];
|
|
2434
|
+
let newCompressionSettings = newExt.create(compressionSettings);
|
|
2435
|
+
newTexture.setExtension(NEEDLE_compression_texture.EXTENSION_NAME, newCompressionSettings);
|
|
2436
|
+
}
|
|
2437
|
+
let progressiveExt = newDoc.createExtension(NEEDLE_progressive);
|
|
2438
|
+
newTexture.setExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME, progressiveExt.createTexture(
|
|
2439
|
+
{
|
|
2440
|
+
guid
|
|
2441
|
+
}
|
|
2442
|
+
));
|
|
2443
|
+
let newIo = new NodeIO();
|
|
2444
|
+
registerExtensions2(newIo);
|
|
2445
|
+
let filename = "image_" + level + "_" + guid + ".glb", outName = path4.join(basePath, filename);
|
|
2446
|
+
existsSync6(basePath) || mkdirSync4(basePath, { recursive: !0 }), logger.info(`[${NAME3}] Write texture LOD ${level} to "${filename}"`), await newIo.write(outName, newDoc), logger.info(`[${NAME3}] Generate hash for texture LOD ${level}`);
|
|
2447
|
+
let hash = getHash(newTexture);
|
|
2448
|
+
return {
|
|
2449
|
+
outpath: outName,
|
|
2450
|
+
texture: newTexture,
|
|
2451
|
+
hash
|
|
2452
|
+
};
|
|
2453
|
+
}
|
|
2454
|
+
function createMeshForMaterial(doc, mat, i) {
|
|
2455
|
+
let buffer = doc.getRoot().listBuffers()[0], scene = doc.getRoot().listScenes()[0], node = doc.createNode(), mesh = doc.createMesh(), prim = doc.createPrimitive(), accessor = doc.createAccessor();
|
|
2456
|
+
accessor.setType("VEC3"), accessor.setArray(new Float32Array([
|
|
2457
|
+
-0.5,
|
|
2458
|
+
-0.5,
|
|
2459
|
+
0,
|
|
2460
|
+
0.5,
|
|
2461
|
+
-0.5,
|
|
2462
|
+
0,
|
|
2463
|
+
-0.5,
|
|
2464
|
+
0.5,
|
|
2465
|
+
0,
|
|
2466
|
+
0.5,
|
|
2467
|
+
0.5,
|
|
2468
|
+
0
|
|
2469
|
+
])), accessor.setBuffer(buffer), prim.setAttribute("POSITION", accessor);
|
|
2470
|
+
let indices = doc.createAccessor();
|
|
2471
|
+
indices.setType("SCALAR"), indices.setArray(new Uint32Array([0, 1, 2, 2, 1, 3])), indices.setBuffer(buffer), prim.setIndices(indices);
|
|
2472
|
+
let uv = doc.createAccessor();
|
|
2473
|
+
uv.setType("VEC2"), uv.setArray(new Float32Array([
|
|
2474
|
+
0,
|
|
2475
|
+
0,
|
|
2476
|
+
1,
|
|
2477
|
+
0,
|
|
2478
|
+
0,
|
|
2479
|
+
1,
|
|
2480
|
+
1,
|
|
2481
|
+
1
|
|
2482
|
+
])), uv.setBuffer(buffer), prim.setAttribute("TEXCOORD_0", uv), prim.setMaterial(mat), mesh.addPrimitive(prim), node.setMesh(mesh), scene.addChild(node), node.setName(`Quad_${i}`);
|
|
2483
|
+
let pos = [i, 0, 0];
|
|
2484
|
+
return node.setTranslation(pos), { node, mesh, prim };
|
|
2485
|
+
}
|
|
2486
|
+
var TEXTURE_RESIZE_DEFAULTS = {
|
|
2487
|
+
size: [2048, 2048],
|
|
2488
|
+
filter: "lanczos3" /* LANCZOS3 */,
|
|
2489
|
+
pattern: null,
|
|
2490
|
+
slots: null
|
|
2491
|
+
};
|
|
2492
|
+
async function resizeTextureToMax(texture, maxSize, logger) {
|
|
2493
|
+
let options = { ...TEXTURE_RESIZE_DEFAULTS };
|
|
2494
|
+
options.size = [maxSize, maxSize], await resizeTexture(options, texture, logger);
|
|
2495
|
+
}
|
|
2496
|
+
async function resizeTexture(options, texture, logger, uri, slots) {
|
|
2497
|
+
let mimeTypeResult = validateImageMimeType(texture.getMimeType(), texture.getImage(), logger);
|
|
2498
|
+
mimeTypeResult?.error && (logger.warn(`[${NAME3}] Texture[${uri}] has invalid mime type: ${mimeTypeResult.error}: auto-fix`), texture.setMimeType(mimeTypeResult.mimeType));
|
|
2499
|
+
let [maxWidth, maxHeight] = options.size, [srcWidth, srcHeight] = texture.getSize();
|
|
2500
|
+
if (srcWidth <= maxWidth && srcHeight <= maxHeight) {
|
|
2501
|
+
logger.debug(`[${NAME3}] Skipping, texture satisfies requested max size ${maxWidth}x${maxHeight}}`);
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2504
|
+
if (maxWidth <= 0 || maxHeight <= 0) {
|
|
2505
|
+
logger.debug(`${uri}: Skipping, invalid size range: ${maxWidth}x${maxHeight}`);
|
|
2506
|
+
return;
|
|
2507
|
+
}
|
|
2508
|
+
let dstWidth = srcWidth, dstHeight = srcHeight;
|
|
2509
|
+
dstWidth > maxWidth && (dstHeight = Math.floor(dstHeight * (maxWidth / dstWidth)), dstWidth = maxWidth), dstHeight > maxHeight && (dstWidth = Math.floor(dstWidth * (maxHeight / dstHeight)), dstHeight = maxHeight), dstWidth = Math.floor(dstWidth), dstHeight = Math.floor(dstHeight), logger.info(`\u2192 Resize texture (${uri || texture.getName() || slots?.join(", ")}) from ${srcWidth}x${srcHeight} to ${dstWidth}x${dstHeight}px`);
|
|
2510
|
+
let buffer = await sharp2(texture.getImage()).resize(dstWidth, dstHeight, {
|
|
2511
|
+
fit: "inside",
|
|
2512
|
+
kernel: "lanczos3",
|
|
2513
|
+
withoutEnlargement: !0
|
|
2514
|
+
}).toBuffer();
|
|
2515
|
+
return texture.setImage(BufferUtils.toView(buffer)), {
|
|
2516
|
+
width: dstWidth,
|
|
2517
|
+
height: dstHeight
|
|
2518
|
+
};
|
|
2519
|
+
}
|
|
2520
|
+
function make_progressive_meshes(filePath, _options, opts) {
|
|
2521
|
+
let directory = path4.dirname(filePath);
|
|
2522
|
+
opts.outpath && (directory = ensureIsDirectory(opts.outpath));
|
|
2523
|
+
let outputDirectory = directory + "/";
|
|
2524
|
+
return createTransform3("PROGRESSIVE_MESHES", async (doc, _context) => {
|
|
2525
|
+
let logger = doc.getLogger();
|
|
2526
|
+
if (currentGenerator == "Needle Engine") {
|
|
2527
|
+
logger.warn("WARN: Skip creating mesh LODs - Unsupported generator found... Please update your editor integration");
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
if (isLOD(filePath))
|
|
2531
|
+
return logger.info("Progressive Mesh Transform: skip lod at " + filePath), Promise.resolve();
|
|
2532
|
+
await MeshoptSimplifier2.ready;
|
|
2533
|
+
let filename = path4.basename(filePath);
|
|
2534
|
+
logger.info(`[${NAME3}]: Begin generating progressive meshes for "${filename}"`);
|
|
2535
|
+
let index = 0, MAX_LODS = 6;
|
|
2536
|
+
opts.config.usecase === "product" && (MAX_LODS = 3);
|
|
2537
|
+
let lod0_settings = {
|
|
2538
|
+
ratio: 1,
|
|
2539
|
+
error: 0,
|
|
2540
|
+
lockBorder: !0,
|
|
2541
|
+
normalWeight: 2,
|
|
2542
|
+
colorWeight: 1,
|
|
2543
|
+
textureWeight: 1
|
|
2544
|
+
}, errorLevel = [0, 3e-3, 5e-3, 0.01, 0.02], LODS = [lod0_settings];
|
|
2545
|
+
for (let l = 0; l < MAX_LODS; l++) {
|
|
2546
|
+
let t01 = l / (MAX_LODS - 1), ratio = LODS[LODS.length - 1].ratio * 0.5, error = errorLevel[Math.min(errorLevel.length - 1, l)];
|
|
2547
|
+
opts.config.usecase === "product" && (error *= 0.5);
|
|
2548
|
+
let normalWeight = lod0_settings.normalWeight, colorWeight = Math.max(0.2, Math.min(1, lod0_settings.colorWeight * (1 - t01))), textureWeight = Math.max(0.2, Math.min(10, lod0_settings.textureWeight * (1 - t01 * 2))), regularize = l > 1 && l < MAX_LODS - 2;
|
|
2549
|
+
LODS.push({
|
|
2550
|
+
ratio,
|
|
2551
|
+
error,
|
|
2552
|
+
lockBorder: !0,
|
|
2553
|
+
regularize,
|
|
2554
|
+
normalWeight,
|
|
2555
|
+
colorWeight,
|
|
2556
|
+
textureWeight
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
logger.debug(`[${NAME3}]: Generating mesh LODs:
|
|
2560
|
+
${JSON.stringify(LODS, void 0, 2)}`);
|
|
2561
|
+
let visited = /* @__PURE__ */ new Map(), meshes = doc.getRoot().listMeshes();
|
|
2562
|
+
for (let mesh of meshes)
|
|
2563
|
+
await processMesh(mesh, { filename });
|
|
2564
|
+
logger.info(`[${NAME3}]: Finished generating progressive meshes for "${filename}"`);
|
|
2565
|
+
async function processMesh(mesh, args) {
|
|
2566
|
+
let originalMeshInformation = getMeshInformation(mesh), { totalVertexCount: originalTotalVertexCount, maxVertexCount: originalMaxVertexCount } = originalMeshInformation, settings = mesh.getExtension(NEEDLE_progressive_mesh_settings.EXTENSION_NAME);
|
|
2567
|
+
if (settings) {
|
|
2568
|
+
if (settings.generateLods === !1) {
|
|
2569
|
+
logger.debug(`[${NAME3}] progressive mesh disabled for mesh at index ${index++}`);
|
|
2570
|
+
return;
|
|
2571
|
+
}
|
|
2572
|
+
} else if (originalMaxVertexCount < 32) {
|
|
2573
|
+
logger.debug(`[${NAME3}] Skipping, no settings found and no primitive with more than 32 vertices. mesh[${index}] has ${originalTotalVertexCount} vertices (max: ${originalMaxVertexCount})`);
|
|
2574
|
+
return;
|
|
2575
|
+
} else
|
|
2576
|
+
settings = {
|
|
2577
|
+
guid: generateGuid(args.filename + "_mesh_" + index.toString()),
|
|
2578
|
+
generateLods: !0
|
|
2579
|
+
}, logger.debug(`[${NAME3}] No settings found for mesh[${index}] with ${originalTotalVertexCount} vertices (max: ${originalMaxVertexCount}) - will use default settings (guid: ${settings.guid})`);
|
|
2580
|
+
let progressiveExt = doc.createExtension(NEEDLE_progressive);
|
|
2581
|
+
if (!progressiveExt || !progressiveExt.createMesh) {
|
|
2582
|
+
logger.debug(`[${NAME3}] Skipping because progressive extension is not available. ${index++}`);
|
|
2583
|
+
return;
|
|
2584
|
+
}
|
|
2585
|
+
let needsToGenerateLODs = !0, generatedLODInfos = new Array();
|
|
2586
|
+
if (visited.has(settings.guid)) {
|
|
2587
|
+
logger.debug(`[${NAME3}] Mesh has already been processed ${index} - will use previously generated LODs`), needsToGenerateLODs = !1;
|
|
2588
|
+
let existingPaths = visited.get(settings.guid);
|
|
2589
|
+
generatedLODInfos.push(...existingPaths.infos);
|
|
2590
|
+
}
|
|
2591
|
+
let tasks = new Array();
|
|
2592
|
+
if (needsToGenerateLODs) {
|
|
2593
|
+
logger.info(`[${NAME3}] Begin generating mesh LODs for "${mesh.getName()}"`);
|
|
2594
|
+
for (let level = 0; level < LODS.length - 1; level++) {
|
|
2595
|
+
let lod = LODS[level], guid = settings.guid, lodTask = createMeshLod(filename, doc, outputDirectory, level, mesh, originalMeshInformation, guid, lod, opts);
|
|
2596
|
+
lodTask.then((res) => {
|
|
2597
|
+
res?.success && (generatedLODInfos[level] = res);
|
|
2598
|
+
}), tasks.push(lodTask);
|
|
2599
|
+
}
|
|
2600
|
+
await Promise.all(tasks), tasks.length = 0;
|
|
2601
|
+
}
|
|
2602
|
+
let prevSize = -1 / 0;
|
|
2603
|
+
for (let i = 0; i < generatedLODInfos.length; i++) {
|
|
2604
|
+
let lodInfo = generatedLODInfos[i];
|
|
2605
|
+
if (!lodInfo) {
|
|
2606
|
+
console.log(`[${NAME3}] LOD ${i} doesnt exist`);
|
|
2607
|
+
continue;
|
|
2608
|
+
}
|
|
2609
|
+
let fullPath = outputDirectory + lodInfo.path;
|
|
2610
|
+
if (existsSync6(fullPath)) {
|
|
2611
|
+
let lastSize = prevSize, sizeOnDisc = statSync3(fullPath).size, diff = lastSize - sizeOnDisc, level = lodInfo.level, shouldOmitLevel = !1;
|
|
2612
|
+
if (sizeOnDisc <= 0)
|
|
2613
|
+
logger.info(`[${NAME3}] Flag mesh LOD ${level}: size on disc is 0 \u2192 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}"`), shouldOmitLevel = !0;
|
|
2614
|
+
else if (diff == 0)
|
|
2615
|
+
logger.info(`[${NAME3}] Flag mesh LOD ${level}: size on disc did not change compared to previous level \u2192 level will be omitted. "${mesh.getName()}" at "${lodInfo.path}"`), shouldOmitLevel = !0;
|
|
2616
|
+
else if (!shouldOmitLevel) {
|
|
2617
|
+
let meshInfo = lodInfo.lodMeshInfo, lastMeshInfo = generatedLODInfos[i - 1]?.lodMeshInfo;
|
|
2618
|
+
if (meshInfo && lastMeshInfo) {
|
|
2619
|
+
let vertexDifference = lastMeshInfo.totalVertexCount - meshInfo.totalVertexCount, diff012 = vertexDifference / lastMeshInfo.totalVertexCount;
|
|
2620
|
+
vertexDifference < 0 ? (logger.info(`[${NAME3}] Flag mesh LOD ${level}: vertex count did increase (${-vertexDifference.toFixed(0)} vertices, ${(-diff012 * 100).toFixed(4)}%) \u2192 LOD ${level} will be omitted. "${mesh.getName()}" at "${lodInfo.path}" ${JSON.stringify(lastMeshInfo)} \u2192 ${JSON.stringify(meshInfo)}`), shouldOmitLevel = !0) : (vertexDifference < 32 || diff012 < 0.05) && (logger.info(`[${NAME3}] Flag mesh LOD ${level}: vertex count difference below threshold (removed ${vertexDifference.toFixed(0)} vertices, ${(-diff012 * 100).toFixed(4)}%) \u2192 LOD ${level} will be omitted. "${mesh.getName()}" at "${lodInfo.path}"`), shouldOmitLevel = !0);
|
|
223
2621
|
}
|
|
2622
|
+
shouldOmitLevel && opts.useCache != !1 && lodInfo.cacheKey != null && addToCache(lodInfo.cacheKey, new Uint8Array(0));
|
|
2623
|
+
}
|
|
2624
|
+
shouldOmitLevel ? (logger.debug(`[${NAME3}] Omitting LOD ${level} for "${mesh.getName()}" at "${lodInfo.path}"`), generatedLODInfos.splice(i, 1), deleteFile(fullPath, opts), i--) : prevSize = sizeOnDisc;
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
let maxDensity = 0, primitiveIndex = 0, lodLevelInFile = generatedLODInfos.length, clonedData = { primitives: [], weights: [...mesh.getWeights()] };
|
|
2628
|
+
mesh.listPrimitives().forEach((prim, index2) => {
|
|
2629
|
+
let data = clonePrimitiveData(prim, logger);
|
|
2630
|
+
data != null && clonedData.primitives.push(data), logger.info(`[${NAME3}] Simplify mesh[${index2}] primitive[${primitiveIndex}] (embedded)`);
|
|
2631
|
+
let lastLod = LODS[lodLevelInFile], density = calculateMeshDensity(prim);
|
|
2632
|
+
maxDensity = Math.max(maxDensity, density);
|
|
2633
|
+
let task = simplifyMesh(doc, mesh, prim, primitiveIndex++, lastLod);
|
|
2634
|
+
tasks.push(task);
|
|
2635
|
+
}), await Promise.all(tasks), tasks.length = 0;
|
|
2636
|
+
let { totalVertexCount: totalVertexCountAfter } = getMeshInformation(mesh), difference = originalTotalVertexCount - totalVertexCountAfter, diff01 = difference / originalTotalVertexCount;
|
|
2637
|
+
if (totalVertexCountAfter <= 0)
|
|
2638
|
+
logger.error(`ERR: [${NAME3}]: Mesh[${index}] has no vertices after simplification: ${mesh.getName()}`);
|
|
2639
|
+
else if (difference < 32 || diff01 <= 0.05) {
|
|
2640
|
+
logger.info(`[${NAME3}]: Flag mesh LOD ${generatedLODInfos.length} (embedded): vertex count difference below threshold (removed ${difference} vertices, ${(-diff01 * 100).toFixed(2)} %) \u2192 will remove all LODs. "${mesh.getName()}"`);
|
|
2641
|
+
try {
|
|
2642
|
+
for (let lodInfo of generatedLODInfos)
|
|
2643
|
+
deleteFile(outputDirectory + "/" + lodInfo.path, opts);
|
|
2644
|
+
} catch {
|
|
2645
|
+
logger.error(`ERR: [${NAME3}] Failed to remove LOD files for "${mesh.getName()}"`);
|
|
2646
|
+
}
|
|
2647
|
+
let primitives = mesh.listPrimitives();
|
|
2648
|
+
if (clonedData.primitives.length == primitives.length) {
|
|
2649
|
+
clonedData.weights?.length > 0 && mesh.setWeights(clonedData.weights);
|
|
2650
|
+
for (let i = 0; i < primitives.length; i++)
|
|
2651
|
+
setPrimitiveData(primitives[i], clonedData.primitives[i]);
|
|
2652
|
+
}
|
|
2653
|
+
return;
|
|
2654
|
+
}
|
|
2655
|
+
if (generatedLODInfos.length > 0) {
|
|
2656
|
+
let model = progressiveExt.createMesh({
|
|
2657
|
+
guid: settings.guid,
|
|
2658
|
+
lods: generatedLODInfos.map((l) => (opts.results.push(resolve(outputDirectory, l.path)), {
|
|
2659
|
+
path: l.path,
|
|
2660
|
+
hash: l.content_hash.toString(),
|
|
2661
|
+
density: l.density,
|
|
2662
|
+
densities: l.densities,
|
|
2663
|
+
vertexCount: l.lodMeshInfo?.totalVertexCount,
|
|
2664
|
+
indexCount: l.lodMeshInfo?.totalIndexCount
|
|
2665
|
+
}))
|
|
2666
|
+
});
|
|
2667
|
+
mesh.setExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME, model), index++, visited.has(settings.guid) || visited.set(settings.guid, {
|
|
2668
|
+
model,
|
|
2669
|
+
infos: generatedLODInfos
|
|
2670
|
+
});
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
function deleteFile(filePath, _context) {
|
|
2676
|
+
rmSync2(filePath);
|
|
2677
|
+
}
|
|
2678
|
+
function cloneTypedArray(src) {
|
|
2679
|
+
return src.slice();
|
|
2680
|
+
}
|
|
2681
|
+
function clonePrimitiveData(prim, logger) {
|
|
2682
|
+
let semantics = prim.listSemantics();
|
|
2683
|
+
if (semantics.some((s) => s.includes("JOINTS")))
|
|
2684
|
+
return null;
|
|
2685
|
+
let prevIndicesArray = prim.getIndices()?.getArray(), indices = prevIndicesArray ? cloneTypedArray(prevIndicesArray) : new Uint32Array(), attributes = {};
|
|
2686
|
+
for (let attr of semantics) {
|
|
2687
|
+
logger.info(`[${NAME3}] Clone attribute ${attr}`);
|
|
2688
|
+
let src = prim.getAttribute(attr)?.getArray();
|
|
2689
|
+
src && (attributes[attr] = cloneTypedArray(src));
|
|
2690
|
+
}
|
|
2691
|
+
return { indices, attributes };
|
|
2692
|
+
}
|
|
2693
|
+
function setPrimitiveData(prim, data) {
|
|
2694
|
+
let indices = prim.getIndices();
|
|
2695
|
+
indices && indices.setArray(data.indices);
|
|
2696
|
+
for (let attr of prim.listSemantics()) {
|
|
2697
|
+
let accessor = prim.getAttribute(attr);
|
|
2698
|
+
accessor && accessor.setArray(data.attributes[attr]);
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
async function createMeshLod(inputFileName, doc, basePath, level, mesh, meshInfo, guid, lodLevel, opts) {
|
|
2702
|
+
let logger = doc.getLogger(), fileName = "mesh_lod_" + level + "_" + guid + ".glb", outPath = basePath + fileName, primitives = mesh.listPrimitives(), cacheKey, hash = mesh["needle:mesh-hash"];
|
|
2703
|
+
if (hash === void 0 && (logger.info(`[${NAME3}] Generating hash for mesh "${mesh.getName()}"`), hash = getHash(mesh), mesh["needle:mesh-hash"] = hash), hash += getHash({
|
|
2704
|
+
lodLevel,
|
|
2705
|
+
guid,
|
|
2706
|
+
config: opts.config
|
|
2707
|
+
}), opts.useCache !== !1) {
|
|
2708
|
+
cacheKey = `mesh_lod_${level}_${hash}`;
|
|
2709
|
+
let cachedValue = tryGetFromCache(cacheKey), meta = tryGetMetaFromCache(cacheKey);
|
|
2710
|
+
if (cachedValue && meta)
|
|
2711
|
+
return logger.info(`[${NAME3}] LOD ${level} loaded from cache for "${mesh.getName()}"`), writeFileSync2(outPath, cachedValue), {
|
|
2712
|
+
level,
|
|
2713
|
+
path: fileName,
|
|
2714
|
+
success: !0,
|
|
2715
|
+
cacheKey,
|
|
2716
|
+
content_hash: hash,
|
|
2717
|
+
lodMeshInfo: meta.meshInfo,
|
|
2718
|
+
density: meta.density,
|
|
2719
|
+
densities: meta.densities
|
|
2720
|
+
};
|
|
2721
|
+
}
|
|
2722
|
+
let newDoc = new Document7();
|
|
2723
|
+
writeNeedleAsset(newDoc, {
|
|
2724
|
+
source: {
|
|
2725
|
+
filename: inputFileName
|
|
2726
|
+
}
|
|
2727
|
+
});
|
|
2728
|
+
let newScene = newDoc.createScene();
|
|
2729
|
+
newDoc.createBuffer();
|
|
2730
|
+
let newNode = newDoc.createNode();
|
|
2731
|
+
newScene.addChild(newNode), newNode.setName("LOD " + level + "_" + guid), newNode.setTranslation([0, 0, 0]);
|
|
2732
|
+
let newMesh = newDoc.createMesh();
|
|
2733
|
+
newMesh.setName((mesh.getName() || "Unnamed") + " LOD " + level), newNode.setMesh(newMesh);
|
|
2734
|
+
let newMat = newDoc.createMaterial(), weights = mesh.getWeights();
|
|
2735
|
+
weights && newMesh.setWeights(weights);
|
|
2736
|
+
let tasks = new Array(), clonedAttributes = /* @__PURE__ */ new Map();
|
|
2737
|
+
for (let prim of primitives) {
|
|
2738
|
+
let newPrim = newDoc.createPrimitive();
|
|
2739
|
+
newMesh.addPrimitive(newPrim), newPrim.setName(prim.getName()), newPrim.setMode(prim.getMode()), newPrim.setMaterial(newMat);
|
|
2740
|
+
let indices = prim.getIndices();
|
|
2741
|
+
if (indices) {
|
|
2742
|
+
let newIndices = newDoc.createAccessor();
|
|
2743
|
+
newIndices.setArray(indices.getArray()), newIndices.setType(indices.getType()), newIndices.setSparse(indices.getSparse()), newIndices.setNormalized(indices.getNormalized()), newPrim.setIndices(newIndices);
|
|
2744
|
+
}
|
|
2745
|
+
let semantics = prim.listSemantics();
|
|
2746
|
+
for (let i = 0; i < semantics.length; i++) {
|
|
2747
|
+
let attr = prim.getAttribute(semantics[i]);
|
|
2748
|
+
if (attr)
|
|
2749
|
+
if (clonedAttributes.has(attr)) {
|
|
2750
|
+
let cloned = clonedAttributes.get(attr);
|
|
2751
|
+
newPrim.setAttribute(semantics[i], cloned);
|
|
2752
|
+
} else {
|
|
2753
|
+
let newAttr = newDoc.createAccessor();
|
|
2754
|
+
newAttr.setArray(attr.getArray()), newAttr.setType(attr.getType()), newAttr.setSparse(attr.getSparse()), newAttr.setNormalized(attr.getNormalized()), newPrim.setAttribute(semantics[i], newAttr), clonedAttributes.set(attr, newAttr);
|
|
2755
|
+
}
|
|
2756
|
+
else
|
|
2757
|
+
logger.warn(`[${NAME3}] Missing attribute ${semantics[i]} in mesh LOD ${level}`);
|
|
2758
|
+
}
|
|
2759
|
+
let targets = prim.listTargets();
|
|
2760
|
+
for (let target of targets) {
|
|
2761
|
+
let newTarget = newDoc.createPrimitiveTarget(target.getName());
|
|
2762
|
+
newPrim.addTarget(newTarget);
|
|
2763
|
+
let semantics2 = target.listSemantics();
|
|
2764
|
+
for (let attr of semantics2) {
|
|
2765
|
+
let accessor = target.getAttribute(attr);
|
|
2766
|
+
if (accessor) {
|
|
2767
|
+
let newAccessor = newDoc.createAccessor();
|
|
2768
|
+
newAccessor.setArray(accessor.getArray()), newAccessor.setType(accessor.getType()), newAccessor.setSparse(accessor.getSparse()), newAccessor.setNormalized(accessor.getNormalized()), newTarget.setAttribute(attr, newAccessor);
|
|
2769
|
+
} else
|
|
2770
|
+
console.error(`[${NAME3}] Missing target attribute ${attr} in mesh LOD ${level}`);
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
let extensions = prim.listExtensions();
|
|
2774
|
+
for (let ext of extensions) {
|
|
2775
|
+
let PropertyClass = ext.constructor, newProp = new PropertyClass(newDoc.getGraph());
|
|
2776
|
+
try {
|
|
2777
|
+
let copy = newProp.copy(ext), name = ext.extensionName;
|
|
2778
|
+
newPrim.setExtension(name, copy);
|
|
2779
|
+
} catch (err) {
|
|
2780
|
+
logger.error(`[${NAME3}] Failed to copy extension ${ext.extensionName} for mesh LOD ${level} \u2192 ${err}`);
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
let primitiveIndex = 0;
|
|
2785
|
+
if ((lodLevel.error != null || lodLevel.ratio != null) && (lodLevel.error > 0 || lodLevel.ratio < 1))
|
|
2786
|
+
for (let newPrim of newMesh.listPrimitives()) {
|
|
2787
|
+
let task = simplifyMesh(newDoc, newMesh, newPrim, primitiveIndex++, lodLevel);
|
|
2788
|
+
tasks.push(task);
|
|
2789
|
+
}
|
|
2790
|
+
await Promise.all(tasks), tasks.length = 0;
|
|
2791
|
+
let newMeshInformation = getMeshInformation(newMesh);
|
|
2792
|
+
if (newMeshInformation.totalVertexCount < 4)
|
|
2793
|
+
return logger.error(`[${NAME3}] mesh LOD ${level} is has less than 4 vertices \u2192 skipping`), {
|
|
2794
|
+
level,
|
|
2795
|
+
path: fileName,
|
|
2796
|
+
success: !1,
|
|
2797
|
+
cacheKey,
|
|
2798
|
+
content_hash: hash,
|
|
2799
|
+
lodMeshInfo: null,
|
|
2800
|
+
density: null,
|
|
2801
|
+
densities: null
|
|
2802
|
+
};
|
|
2803
|
+
let density = 0, densities = new Array(newMesh.listPrimitives().length);
|
|
2804
|
+
newMesh.listPrimitives().forEach((prim, index) => {
|
|
2805
|
+
let d = calculateMeshDensity(prim);
|
|
2806
|
+
density = Math.max(density, d), densities[index] = d;
|
|
2807
|
+
});
|
|
2808
|
+
let progressiveExt = newDoc.createExtension(NEEDLE_progressive);
|
|
2809
|
+
if (!progressiveExt || !progressiveExt.createMesh) {
|
|
2810
|
+
logger.error("Failed to create progressive extension");
|
|
2811
|
+
return;
|
|
2812
|
+
}
|
|
2813
|
+
newMesh.setExtension(NEEDLE_PROGRESSIVE_EXTENSION_NAME, progressiveExt.createMesh({
|
|
2814
|
+
guid
|
|
2815
|
+
}));
|
|
2816
|
+
let model = determineMeshCompression(doc, fileName);
|
|
2817
|
+
if (model) {
|
|
2818
|
+
let newProp = newDoc.createExtension(NEEDLE_mesh_compression).create(model);
|
|
2819
|
+
logger.info(`[${NAME3}] Pass compression format to mesh LOD ${level} \u2192 ${JSON.stringify(model)}`), newDoc.getRoot().setExtension(NEEDLE_mesh_compression.EXTENSION_NAME, newProp);
|
|
2820
|
+
}
|
|
2821
|
+
await newDoc.transform(
|
|
2822
|
+
sparse()
|
|
2823
|
+
);
|
|
2824
|
+
let newIo = new NodeIO();
|
|
2825
|
+
if (registerExtensions2(newIo), logger.info(`[${NAME3}] Write mesh LOD ${level} with to "${fileName}"`), await newIo.write(outPath, newDoc), cacheKey != null) {
|
|
2826
|
+
let bytes = readFileSync5(outPath), sizeInMB = (bytes.byteLength / 1024 / 1024).toFixed(2);
|
|
2827
|
+
logger.info(`[${NAME3}] Add LOD ${level} to cache (${sizeInMB} MB) for "${mesh.getName()}" as ${cacheKey}`), addToCache(cacheKey, bytes), addMetaToCache(cacheKey, { meshInfo: newMeshInformation, density, densities });
|
|
2828
|
+
}
|
|
2829
|
+
return {
|
|
2830
|
+
level,
|
|
2831
|
+
path: fileName,
|
|
2832
|
+
success: !0,
|
|
2833
|
+
lodMeshInfo: newMeshInformation,
|
|
2834
|
+
cacheKey,
|
|
2835
|
+
content_hash: hash,
|
|
2836
|
+
density,
|
|
2837
|
+
densities
|
|
2838
|
+
};
|
|
2839
|
+
}
|
|
2840
|
+
async function simplifyMesh(doc, mesh, prim, index, lodinfo) {
|
|
2841
|
+
let weldOptions = {
|
|
2842
|
+
...WELD_DEFAULTS3,
|
|
2843
|
+
overwrite: !0,
|
|
2844
|
+
cleanup: !1,
|
|
2845
|
+
tolerance: 1e-11,
|
|
2846
|
+
...lodinfo
|
|
2847
|
+
}, simplifyOptions = {
|
|
2848
|
+
...SIMPLIFY_DEFAULTS2,
|
|
2849
|
+
...lodinfo,
|
|
2850
|
+
simplifier: MeshoptSimplifier2
|
|
2851
|
+
};
|
|
2852
|
+
return compressPrimitive(doc, mesh, prim, index, weldOptions, simplifyOptions);
|
|
2853
|
+
}
|
|
2854
|
+
var UUID_RE_SRC = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", IMAGE_LOD_RE = new RegExp(`(?:^|[\\\\/])image_\\d+_${UUID_RE_SRC}\\.glb$`, "i"), MESH_LOD_RE = new RegExp(`(?:^|[\\\\/])mesh_lod_\\d+_${UUID_RE_SRC}\\.glb$`, "i");
|
|
2855
|
+
function isMeshLOD(filepath) {
|
|
2856
|
+
return MESH_LOD_RE.test(filepath);
|
|
2857
|
+
}
|
|
2858
|
+
function isImageLOD(filepath) {
|
|
2859
|
+
return IMAGE_LOD_RE.test(filepath);
|
|
2860
|
+
}
|
|
2861
|
+
function isLOD(filepath) {
|
|
2862
|
+
return isMeshLOD(filepath) || isImageLOD(filepath);
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
// src/utils/stats.ts
|
|
2866
|
+
import { inspect } from "@gltf-transform/functions";
|
|
2867
|
+
function printStats(stats, logger, config) {
|
|
2868
|
+
let durationInMinutes = (Date.now() - stats.startTime) / 1e3 / 60, msg = `[Needle Build Pipeline] v${getVersion()} \u2014 Finished compression "${config?.usecase}" of ${stats.totalFilesProcessed} files in ${durationInMinutes.toFixed(1)} minutes; total size ${stats.totalFileSizeInMBBefore.toFixed(1)} MB \u2192 ${stats.totalFileSizeInMB.toFixed(1)} MB, total GPU memory: ${stats.totalGPUMemoryInMB.toFixed(1)} MB`;
|
|
2869
|
+
logger ? logger.info(msg) : console.log(msg);
|
|
2870
|
+
}
|
|
2871
|
+
var Stats = class _Stats {
|
|
2872
|
+
/** Size in bytes */
|
|
2873
|
+
size;
|
|
2874
|
+
asset;
|
|
2875
|
+
json;
|
|
2876
|
+
nodes;
|
|
2877
|
+
materials;
|
|
2878
|
+
meshes;
|
|
2879
|
+
textures;
|
|
2880
|
+
animations;
|
|
2881
|
+
constructor(document, json, size) {
|
|
2882
|
+
let root = document.getRoot(), asset = root.getAsset();
|
|
2883
|
+
this.asset = {
|
|
2884
|
+
generator: asset.generator,
|
|
2885
|
+
version: asset.version,
|
|
2886
|
+
copyright: asset.copyright,
|
|
2887
|
+
extras: asset.extras
|
|
2888
|
+
};
|
|
2889
|
+
let report = null;
|
|
2890
|
+
try {
|
|
2891
|
+
report = inspect(document);
|
|
2892
|
+
} catch {
|
|
2893
|
+
}
|
|
2894
|
+
this.size = size, this.json = calculateJSONDocumentInfo(json), this.nodes = root.listNodes().length, this.materials = root.listMaterials().length, this.meshes = calculateMeshInfo(document, report), this.textures = calculateTextureInfo(document, report), this.animations = calculateAnimationInfo(document);
|
|
2895
|
+
}
|
|
2896
|
+
static combine(others, type) {
|
|
2897
|
+
let res = new _Stats(new Document8(), null, 0), foundAny = !1;
|
|
2898
|
+
for (let other of others) {
|
|
2899
|
+
if (type != null) {
|
|
2900
|
+
let filename = other.filename;
|
|
2901
|
+
if (filename) {
|
|
2902
|
+
if (isLOD(filename)) {
|
|
2903
|
+
if (type === "main") continue;
|
|
2904
|
+
} else if (type === "lods") continue;
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
foundAny = !0, res.size += other.size, res.json.addFrom(other.json), res.nodes += other.nodes, res.materials += other.materials, res.meshes.addFrom(other.meshes), res.textures.addFrom(other.textures), res.animations.addFrom(other.animations);
|
|
2908
|
+
}
|
|
2909
|
+
return foundAny ? res : null;
|
|
2910
|
+
}
|
|
2911
|
+
}, FileStats = class extends Stats {
|
|
2912
|
+
filename;
|
|
2913
|
+
isLOD;
|
|
2914
|
+
constructor(file, document, json) {
|
|
2915
|
+
super(document, json, statSync4(file).size), this.filename = getFileName(file), this.isLOD = isLOD(this.filename);
|
|
2916
|
+
}
|
|
2917
|
+
};
|
|
2918
|
+
function mergeUnique(a, b) {
|
|
2919
|
+
if (!(!a && !b))
|
|
2920
|
+
return Array.from(/* @__PURE__ */ new Set([...a ?? [], ...b ?? []]));
|
|
2921
|
+
}
|
|
2922
|
+
var MeshInfo = class {
|
|
2923
|
+
count = 0;
|
|
2924
|
+
primitives = 0;
|
|
2925
|
+
vertices = 0;
|
|
2926
|
+
triangles = 0;
|
|
2927
|
+
memory = 0;
|
|
2928
|
+
formats = [];
|
|
2929
|
+
errors;
|
|
2930
|
+
warnings;
|
|
2931
|
+
addFrom(other) {
|
|
2932
|
+
this.count += other.count, this.primitives += other.primitives, this.vertices += other.vertices, this.triangles += other.triangles, this.memory += other.memory, this.formats = Array.from(new Set(this.formats.concat(other.formats))), this.errors = mergeUnique(this.errors, other.errors), this.warnings = mergeUnique(this.warnings, other.warnings);
|
|
2933
|
+
}
|
|
2934
|
+
}, TextureInfo2 = class {
|
|
2935
|
+
count = 0;
|
|
2936
|
+
memory = 0;
|
|
2937
|
+
gpu_memory = 0;
|
|
2938
|
+
formats = [];
|
|
2939
|
+
errors;
|
|
2940
|
+
warnings;
|
|
2941
|
+
addFrom(other) {
|
|
2942
|
+
this.count += other.count, this.memory += other.memory, this.gpu_memory += other.gpu_memory, this.formats = Array.from(new Set(this.formats.concat(other.formats))), this.errors = mergeUnique(this.errors, other.errors), this.warnings = mergeUnique(this.warnings, other.warnings);
|
|
2943
|
+
}
|
|
2944
|
+
}, AnimationInfo = class {
|
|
2945
|
+
count = 0;
|
|
2946
|
+
size = 0;
|
|
2947
|
+
channels = 0;
|
|
2948
|
+
addFrom(other) {
|
|
2949
|
+
this.count += other.count, this.size += other.size, this.channels += other.channels;
|
|
2950
|
+
}
|
|
2951
|
+
}, JSONDocumentInfo = class {
|
|
2952
|
+
size = 0;
|
|
2953
|
+
addFrom(other) {
|
|
2954
|
+
this.size += other.size;
|
|
2955
|
+
}
|
|
2956
|
+
};
|
|
2957
|
+
function createNewFilestats(file, document, jsonDocument) {
|
|
2958
|
+
return new FileStats(file, document, jsonDocument);
|
|
2959
|
+
}
|
|
2960
|
+
function writeFileStatsToFile(filestats, output_path) {
|
|
2961
|
+
if (output_path == null)
|
|
2962
|
+
return console.error("No stats output path provided"), null;
|
|
2963
|
+
let res = {
|
|
2964
|
+
sum: Stats.combine(filestats),
|
|
2965
|
+
// main: Stats.combine(filestats, "main"),
|
|
2966
|
+
// lods: Stats.combine(filestats, "lods"),
|
|
2967
|
+
files: filestats
|
|
2968
|
+
}, json = JSON.stringify(res);
|
|
2969
|
+
return writeFileSync3(output_path, json), json;
|
|
2970
|
+
}
|
|
2971
|
+
function calculateMeshInfo(document, report) {
|
|
2972
|
+
let root = document.getRoot(), meshes = root.listMeshes(), res = new MeshInfo();
|
|
2973
|
+
res.count = meshes.length, res.errors = report?.meshes.errors, res.warnings = report?.meshes.warnings;
|
|
2974
|
+
for (let mesh of root.listMeshes()) {
|
|
2975
|
+
let primitives = mesh.listPrimitives();
|
|
2976
|
+
res.primitives += primitives.length;
|
|
2977
|
+
for (let prim of primitives) {
|
|
2978
|
+
let positions = prim.getAttribute("POSITION"), indices = prim.getIndices();
|
|
2979
|
+
positions && (res.vertices += positions.getCount()), indices ? res.triangles += indices.getCount() / 3 : res.triangles += positions.getCount() / 3;
|
|
2980
|
+
let semantics = prim.listSemantics();
|
|
2981
|
+
for (let semantic of semantics) {
|
|
2982
|
+
let accessor = prim.getAttribute(semantic);
|
|
2983
|
+
if (accessor) {
|
|
2984
|
+
let buffer = accessor.getByteLength();
|
|
2985
|
+
res.memory += buffer;
|
|
2986
|
+
}
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
let extensions = root.listExtensionsUsed();
|
|
2991
|
+
for (let ext of extensions)
|
|
2992
|
+
ext.extensionName.startsWith("EXT_meshopt_compression") ? res.formats.push("meshopt") : ext.extensionName.startsWith("KHR_draco_mesh_compression") && res.formats.push("draco");
|
|
2993
|
+
return res.formats = Array.from(new Set(res.formats)), res;
|
|
2994
|
+
}
|
|
2995
|
+
function calculateTextureInfo(document, report) {
|
|
2996
|
+
let textures = document.getRoot().listTextures(), res = new TextureInfo2();
|
|
2997
|
+
res.count = textures.length, res.formats = textures.map((t) => t.getMimeType()), res.errors = report?.textures.errors, res.warnings = report?.textures.warnings, res.gpu_memory = 0, res.memory = 0;
|
|
2998
|
+
for (let texture of textures) {
|
|
2999
|
+
let image = texture.getImage(), mimetype = texture.getMimeType();
|
|
3000
|
+
if (image && mimetype) {
|
|
3001
|
+
try {
|
|
3002
|
+
res.gpu_memory += ImageUtils.getVRAMByteLength(image, mimetype);
|
|
3003
|
+
} catch {
|
|
3004
|
+
}
|
|
3005
|
+
res.memory += image.byteLength;
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
return res.formats = Array.from(new Set(res.formats)), res;
|
|
3009
|
+
}
|
|
3010
|
+
function calculateAnimationInfo(document) {
|
|
3011
|
+
let animations = document.getRoot().listAnimations(), info = new AnimationInfo();
|
|
3012
|
+
info.count = animations.length, info.channels = 0, info.size = 0;
|
|
3013
|
+
for (let anim of animations) {
|
|
3014
|
+
let channels = anim.listChannels();
|
|
3015
|
+
info.channels += channels.length;
|
|
3016
|
+
for (let channel of channels) {
|
|
3017
|
+
let sampler = channel.getSampler(), times = sampler.getInput(), values = sampler.getOutput();
|
|
3018
|
+
times && (info.size += times.getArray()?.byteLength ?? 0), values && (info.size += values.getArray()?.byteLength ?? 0);
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
return info;
|
|
3022
|
+
}
|
|
3023
|
+
function calculateJSONDocumentInfo(json) {
|
|
3024
|
+
let info = new JSONDocumentInfo();
|
|
3025
|
+
return json && (info.size = JSON.stringify(json.json).length), info;
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
// src/utils/validate.ts
|
|
3029
|
+
import { ImageUtils as ImageUtils2 } from "@gltf-transform/core";
|
|
3030
|
+
function isMaterialOnlyGLB(document) {
|
|
3031
|
+
let root = document.getRoot();
|
|
3032
|
+
return root.listMeshes().length === 0 && root.listMaterials().length > 0;
|
|
3033
|
+
}
|
|
3034
|
+
function validateImageMimeType(mimetype, image, logger) {
|
|
3035
|
+
let actualMimeType = ImageUtils2.getMimeType(image);
|
|
3036
|
+
if (actualMimeType != null && actualMimeType != mimetype) {
|
|
3037
|
+
let msg = `Image reported wrong mime type "${mimetype}" but is actually "${actualMimeType}"`;
|
|
3038
|
+
return logger.warn(msg), {
|
|
3039
|
+
error: !0,
|
|
3040
|
+
message: msg,
|
|
3041
|
+
mimeType: actualMimeType
|
|
3042
|
+
};
|
|
3043
|
+
} else actualMimeType === null && logger.debug(`Could not validate image type: "${mimetype}"`);
|
|
3044
|
+
return null;
|
|
3045
|
+
}
|
|
3046
|
+
|
|
3047
|
+
// src/transforms/needle_toktx.ts
|
|
3048
|
+
import sharp3 from "sharp";
|
|
3049
|
+
var NUM_CPUS3 = os3.cpus().length || 1;
|
|
3050
|
+
var NeedleToktxContext = class {
|
|
3051
|
+
limit;
|
|
3052
|
+
basisuExtension;
|
|
3053
|
+
version;
|
|
3054
|
+
cacheDirectory;
|
|
3055
|
+
tmpPathBase;
|
|
3056
|
+
document;
|
|
3057
|
+
env;
|
|
3058
|
+
numTextures;
|
|
3059
|
+
_prepareFailed = !1;
|
|
3060
|
+
constructor(options) {
|
|
3061
|
+
this.limit = pLimit(options.jobs || NUM_CPUS3);
|
|
3062
|
+
let isUsingWindows = process.platform === "win32";
|
|
3063
|
+
if (this.env = {
|
|
3064
|
+
PATH: process.env.PATH ?? ""
|
|
3065
|
+
}, options?.toktxPath?.length && this.env && (this.env.PATH = `${options.toktxPath};${this.env.PATH}`), process.env.NEEDLE_TOKTX?.length && (existsSync7(process.env.NEEDLE_TOKTX) ? (options.debug && console.log('INFO: Adding NEEDLE_TOKTX to PATH: "' + process.env.NEEDLE_TOKTX + '"'), this.env.PATH = `${process.env.NEEDLE_TOKTX};${this.env.PATH}`) : options.debug && console.log('WARN: NEEDLE_TOKTX is set to a non-existing path: "' + process.env.NEEDLE_TOKTX + '"')), isUsingWindows) {
|
|
3066
|
+
let defaultPath = "C:\\Program Files\\KTX-Software\\bin";
|
|
3067
|
+
existsSync7(defaultPath) && (this.env.PATH = `${this.env.PATH};${defaultPath}`);
|
|
3068
|
+
} else {
|
|
3069
|
+
let defaultPath = "/usr/local/bin";
|
|
3070
|
+
existsSync7(defaultPath) && (this.env.PATH = `${this.env.PATH}:${defaultPath}`);
|
|
3071
|
+
}
|
|
3072
|
+
isUsingWindows && process.env.Path?.length && (this.env.PATH = `${this.env.PATH};${process.env.Path}`);
|
|
3073
|
+
let ktxPaths = this.env.PATH.split(";").filter((p) => p.toLocaleLowerCase().includes("ktx"));
|
|
3074
|
+
options.debug && console.log(`INFO: Found these paths including ktx:
|
|
3075
|
+
` + ktxPaths.join(`
|
|
3076
|
+
`));
|
|
3077
|
+
}
|
|
3078
|
+
async prepare(document) {
|
|
3079
|
+
try {
|
|
3080
|
+
this.document = document;
|
|
3081
|
+
let logger = document.getLogger();
|
|
3082
|
+
if (this.version = await checkKTXSoftware(logger, this.env), this.version === null)
|
|
3083
|
+
return logger.warn(`WARN: toktx not found, skipping KTX2 texture compression. Please install KTX-Software >= ${KTX_SOFTWARE_VERSION_MIN}. You may set the 'NEEDLE_TOKTX' environment variable to specify the directory of the toktx installation (path/to/bin)`), this._prepareFailed = !0, !1;
|
|
3084
|
+
this.basisuExtension = document.createExtension(KHRTextureBasisu).setRequired(!0);
|
|
3085
|
+
let tmpDir = `${tmp3.tmpdir}/gltf-transform/${uuid2()}`;
|
|
3086
|
+
this.cacheDirectory = tmpDir, mkdirSync5(tmpDir, { recursive: !0 }), this.tmpPathBase = tmpDir + "/" + uuid2(), this.numTextures = document.getRoot().listTextures().length;
|
|
3087
|
+
} catch (e) {
|
|
3088
|
+
return console.error("ERR: preparing toktx transform failed: " + e), this._prepareFailed = !0, !1;
|
|
3089
|
+
}
|
|
3090
|
+
return !0;
|
|
3091
|
+
}
|
|
3092
|
+
async process(index, texture, settings, context) {
|
|
3093
|
+
let task = async () => {
|
|
3094
|
+
if (this._prepareFailed) return !1;
|
|
3095
|
+
let logger = this.document.getLogger(), slots = listTextureSlots2(texture), channels = getTextureChannelMask(texture), prefix = `toktx:texture[${index}] ${texture.getName()}`, srcMimeType = texture.getMimeType();
|
|
3096
|
+
if (srcMimeType === "image/ktx2") {
|
|
3097
|
+
logger.debug(`${prefix}: Skipping, already KTX.`);
|
|
3098
|
+
return;
|
|
3099
|
+
} else if (srcMimeType !== "image/png" && srcMimeType !== "image/jpeg") {
|
|
3100
|
+
logger.warn(`${prefix}: Skipping, unsupported texture type "${texture.getMimeType()}".`);
|
|
3101
|
+
return;
|
|
3102
|
+
}
|
|
3103
|
+
slots.length > 0 ? logger.debug(`${prefix}: Slots \u2192 [${slots.join(", ")}]`) : logger.debug(`${prefix}: No slots, assuming default texture.`);
|
|
3104
|
+
let srcImage = texture.getImage(), srcExtension = texture.getURI() ? FileUtils.extension(texture.getURI()) : ImageUtils3.mimeTypeToExtension(texture.getMimeType()), srcSize = texture.getSize(), srcBytes = srcImage ? srcImage.byteLength : null;
|
|
3105
|
+
if (!srcImage || !srcSize || !srcBytes) {
|
|
3106
|
+
logger.warn(`${prefix}: Skipping, unreadable texture.`);
|
|
3107
|
+
return;
|
|
3108
|
+
}
|
|
3109
|
+
if (!isMultipleOfFour(srcSize[0]) || !isMultipleOfFour(srcSize[1])) {
|
|
3110
|
+
let instance = sharp3(srcImage, { limitInputPixels: !0 }).toFormat("png"), srcSize2 = ImageUtils3.getSize(srcImage, srcMimeType), dstSize = fitPowerOfTwo(srcSize2, "nearest-pot");
|
|
3111
|
+
dstSize[0] = ceilMultipleOfFour(dstSize[0]), dstSize[1] = ceilMultipleOfFour(dstSize[1]), logger.warn(`${prefix}: Resizing ${srcSize2.join("x")} \u2192 ${dstSize.join("x")}px`), instance.resize(dstSize[0], dstSize[1], { fit: "fill", kernel: TextureResizeFilter3.LANCZOS3 });
|
|
3112
|
+
let buffer2 = await instance.toBuffer();
|
|
3113
|
+
srcImage = BufferUtils2.toView(new Uint8Array(buffer2)), srcExtension = "png", srcMimeType = "image/png";
|
|
3114
|
+
}
|
|
3115
|
+
let tmpName = this.tmpPathBase + "_" + index, inPath = tmpName + "." + srcExtension, outPath = tmpName + ".ktx2", buffer = Buffer.from(srcImage);
|
|
3116
|
+
await fs2.writeFile(inPath, buffer);
|
|
3117
|
+
let mode = Mode.ETC1S, quality = 128, compression = 1;
|
|
3118
|
+
if (settings)
|
|
3119
|
+
if (settings.mode === "auto") {
|
|
3120
|
+
let useUASTC = slots.includes("normalTexture") || slots.includes("metallicRoughnessTexture");
|
|
3121
|
+
mode = useUASTC ? Mode.UASTC : Mode.ETC1S, quality = useUASTC ? 255 : 128, compression = useUASTC ? 4 : 1;
|
|
3122
|
+
} else
|
|
3123
|
+
mode = settings.mode === "ETC1S" ? Mode.ETC1S : Mode.UASTC;
|
|
3124
|
+
else if (slots) {
|
|
3125
|
+
let isNormal = slots.includes("normalTexture"), isMetallicRoughness = slots.includes("metallicRoughnessTexture"), betterQuality = isNormal || isMetallicRoughness;
|
|
3126
|
+
mode = Mode.ETC1S, quality = betterQuality ? 255 : 128, compression = betterQuality ? 4 : 1, context.config.usecase === "product" ? (betterQuality && (mode = Mode.UASTC), quality = 255, compression = 4) : (slots.includes("lightmapTexture") || isLightmap(texture)) && (quality = 255, compression = 4);
|
|
3127
|
+
}
|
|
3128
|
+
let defaults = mode === Mode.ETC1S ? ETC1S_DEFAULTS : UASTC_DEFAULTS, toktxParams = createParams(texture, slots, channels, srcSize, logger, this.numTextures, { ...defaults, mode, quality, compression });
|
|
3129
|
+
await fs2.writeFile(inPath, Buffer.from(srcImage));
|
|
3130
|
+
let params = [
|
|
3131
|
+
"create",
|
|
3132
|
+
...toktxParams,
|
|
3133
|
+
inPath,
|
|
3134
|
+
outPath
|
|
3135
|
+
];
|
|
3136
|
+
logger.debug(`${prefix}: Spawning \u2192 toktx ${mode.toUpperCase()} ${params.join(" ")}`);
|
|
3137
|
+
try {
|
|
3138
|
+
let [status, stdout, stderr] = await waitExit(spawn("ktx", params, { env: this.env }));
|
|
3139
|
+
if (status !== 0)
|
|
3140
|
+
logger.error(`${prefix}: ktx create failed (exit code ${status}) \u2192
|
|
3141
|
+
|
|
3142
|
+
${stderr.toString()}`);
|
|
3143
|
+
else if (!existsSync7(outPath))
|
|
3144
|
+
logger.error(`${prefix}: ktx create reported success but output file is missing: ${outPath}
|
|
3145
|
+
|
|
3146
|
+
stdout: ${stdout}
|
|
3147
|
+
stderr: ${stderr}`);
|
|
3148
|
+
else {
|
|
3149
|
+
let result = await fs2.readFile(outPath);
|
|
3150
|
+
if (texture.setImage(result).setMimeType("image/ktx2"), texture.getURI()) {
|
|
3151
|
+
let oldUri = texture.getURI(), newUri = replaceExtension(oldUri, "ktx2");
|
|
3152
|
+
texture.setURI(newUri);
|
|
3153
|
+
}
|
|
3154
|
+
let dstBytes = texture.getImage().byteLength;
|
|
3155
|
+
return logger.debug(`${prefix}: ${formatBytes(srcBytes)} \u2192 ${formatBytes(dstBytes)}`), !0;
|
|
3156
|
+
}
|
|
3157
|
+
} catch (err) {
|
|
3158
|
+
logger.error(`${prefix}: Toktx failed \u2192 ${err}`);
|
|
3159
|
+
}
|
|
3160
|
+
return !1;
|
|
3161
|
+
};
|
|
3162
|
+
return this.limit(task);
|
|
3163
|
+
}
|
|
3164
|
+
async finalize(document) {
|
|
3165
|
+
document.getRoot().listTextures().some((t) => t.getMimeType() === "image/ktx2") || this.basisuExtension?.dispose(), this.cacheDirectory && await safeRmDir(this.cacheDirectory);
|
|
3166
|
+
}
|
|
3167
|
+
};
|
|
3168
|
+
|
|
3169
|
+
// src/transforms/needle_webp.ts
|
|
3170
|
+
import sharp4 from "sharp";
|
|
3171
|
+
import { BufferUtils as BufferUtils3, HTTPUtils } from "@gltf-transform/core";
|
|
3172
|
+
import { EXTTextureWebP } from "@gltf-transform/extensions";
|
|
3173
|
+
var NeedleWebPContext = class {
|
|
3174
|
+
options;
|
|
3175
|
+
logger;
|
|
3176
|
+
compressed = 0;
|
|
3177
|
+
constructor(options) {
|
|
3178
|
+
this.options = options;
|
|
3179
|
+
}
|
|
3180
|
+
async prepare(document) {
|
|
3181
|
+
this.compressed = 0, this.logger = document.getLogger();
|
|
3182
|
+
}
|
|
3183
|
+
async process(index, texture, settings, context) {
|
|
3184
|
+
let size = texture.getSize(), lossless = !1;
|
|
3185
|
+
(size[0] < 64 || size[1] < 64) && (lossless = !0);
|
|
3186
|
+
let options = {
|
|
3187
|
+
lossless,
|
|
3188
|
+
...settings,
|
|
3189
|
+
quality: settings.quality
|
|
3190
|
+
// effort: remap(options.effort, 100, 6),
|
|
3191
|
+
// lossless: options.lossless,
|
|
3192
|
+
// nearLossless: options.nearLossless,
|
|
3193
|
+
};
|
|
3194
|
+
typeof options != "string" && options.quality >= 0 && (options.quality = Math.round(settings.quality * 100)), options.quality < 0 && (options.quality = void 0), this.logger.info(`webp:texture[${index}] ${texture.getName()}: Slots \u2192 [${settings.slot}] with quality '${options.quality === void 0 ? "default" : options.quality}'`);
|
|
3195
|
+
let buffer = await sharp4(texture.getImage()).toFormat("webp", options).toBuffer();
|
|
3196
|
+
return texture.setMimeType("image/webp").setImage(BufferUtils3.toView(buffer)).setURI(HTTPUtils.basename(texture.getURI()) + ".webp"), this.compressed += 1, !0;
|
|
3197
|
+
}
|
|
3198
|
+
async finalize(document) {
|
|
3199
|
+
this.compressed > 0 && document.createExtension(EXTTextureWebP).setRequired(!0);
|
|
3200
|
+
}
|
|
3201
|
+
};
|
|
3202
|
+
|
|
3203
|
+
// src/transforms/needle_texture_transform.ts
|
|
3204
|
+
import { ImageUtils as ImageUtils4 } from "@gltf-transform/core";
|
|
3205
|
+
|
|
3206
|
+
// src/transforms/needle_pmrem.ts
|
|
3207
|
+
import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, rmSync as rmSync3, chmodSync } from "fs";
|
|
3208
|
+
import { join as join5, dirname as dirname4 } from "path";
|
|
3209
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
3210
|
+
import { execFile } from "child_process";
|
|
3211
|
+
import { v4 as uuid3 } from "uuid";
|
|
3212
|
+
import { createHash } from "crypto";
|
|
3213
|
+
import tmp4 from "tmp";
|
|
3214
|
+
async function createPmremRuntime(logger) {
|
|
3215
|
+
let pmremDir = getPmremDir(), wasmJsPath = join5(pmremDir, "pkg", "pmrem_wasm.js"), wasmBinPath = join5(pmremDir, "pkg", "pmrem_wasm_bg.wasm");
|
|
3216
|
+
if (!existsSync8(wasmJsPath) || !existsSync8(wasmBinPath))
|
|
3217
|
+
return logger.warn("pmrem: WASM not found \u2014 EXR textures will not be processed"), testAssert(!1, "pmrem WASM files are missing. Please run `npm run build:pmrem` to build the tools/pmrem/ WASM module."), null;
|
|
3218
|
+
let basisuExe = resolveBasisuExe(pmremDir);
|
|
3219
|
+
if (!existsSync8(basisuExe))
|
|
3220
|
+
return logger.warn(`pmrem: basisu binary not found at ${basisuExe} \u2014 EXR textures will not be processed`), testAssert(!1, `basisu executable is missing for platform ${process.platform}. Please run \`npm run build:pmrem\` to build the tools/pmrem/ binaries.`), null;
|
|
3221
|
+
if (process.platform !== "win32")
|
|
3222
|
+
try {
|
|
3223
|
+
chmodSync(basisuExe, 493);
|
|
3224
|
+
} catch {
|
|
3225
|
+
}
|
|
3226
|
+
let wasmModule;
|
|
3227
|
+
try {
|
|
3228
|
+
let mod = await import(pathToFileURL(wasmJsPath).href), wasmBytes = readFileSync6(wasmBinPath);
|
|
3229
|
+
await mod.default({ module_or_path: wasmBytes }), wasmModule = mod;
|
|
3230
|
+
} catch (err) {
|
|
3231
|
+
return logger.warn(`pmrem: Failed to load WASM \u2014 ${err.message}`), testAssert(!1, `Failed to load pmrem WASM module: ${err.message}`), null;
|
|
3232
|
+
}
|
|
3233
|
+
let tmpDir = join5(tmp4.tmpdir, "needle-pmrem", uuid3());
|
|
3234
|
+
return mkdirSync6(tmpDir, { recursive: !0 }), logger.debug("pmrem: Ready (WASM + basisu loaded)"), { wasmModule, basisuExe, pmremDir, tmpDir, logger };
|
|
3235
|
+
}
|
|
3236
|
+
async function disposePmremRuntime(runtime) {
|
|
3237
|
+
runtime?.tmpDir && await safeRmDir(runtime.tmpDir);
|
|
3238
|
+
}
|
|
3239
|
+
function convertExrBytesToPmremKtx2(runtime, exrBytes, opts = {}) {
|
|
3240
|
+
return convertBytesToPmremKtx2(runtime, exrBytes, "exr", opts);
|
|
3241
|
+
}
|
|
3242
|
+
function convertHdrBytesToPmremKtx2(runtime, hdrBytes, opts = {}) {
|
|
3243
|
+
return convertBytesToPmremKtx2(runtime, hdrBytes, "hdr", opts);
|
|
3244
|
+
}
|
|
3245
|
+
async function convertBytesToPmremKtx2(runtime, inputBytes, kind, opts = {}) {
|
|
3246
|
+
let useCache = opts.useCache !== !1, label = opts.logLabel ?? "pmrem", logger = runtime.logger, contentHash = createHash("md5").update(inputBytes).digest("hex"), cacheKey = kind === "hdr" ? `pmrem-hdr-${contentHash}` : `pmrem-${contentHash}`;
|
|
3247
|
+
if (useCache) {
|
|
3248
|
+
let cached = tryGetFromCache(cacheKey);
|
|
3249
|
+
if (cached && cached.length > 0)
|
|
3250
|
+
return logger.debug(`${label}: loaded from cache`), cached;
|
|
3251
|
+
}
|
|
3252
|
+
let inputSize = inputBytes.byteLength < 100 * 1024 ? `${(inputBytes.byteLength / 1024).toFixed(0)} KB` : `${(inputBytes.byteLength / (1024 * 1024)).toFixed(2)} MB`, sourceLabel = kind === "hdr" ? "HDR" : "EXR";
|
|
3253
|
+
logger.debug(`${label}: Running PMREM WASM (${inputSize} ${sourceLabel}) \u2014 this may take a while...`), await new Promise((r) => setTimeout(r, 0));
|
|
3254
|
+
let t0 = Date.now(), pmremExrBytes = (kind === "hdr" ? runtime.wasmModule.pmrem_hdr : runtime.wasmModule.pmrem_exr)(inputBytes), elapsed = ((Date.now() - t0) / 1e3).toFixed(1);
|
|
3255
|
+
logger.debug(`${label}: PMREM done in ${elapsed}s (${(pmremExrBytes.byteLength / 1024 / 1024).toFixed(1)} MB)`);
|
|
3256
|
+
let id = uuid3(), tempExr = join5(runtime.tmpDir, `${id}.pmrem.exr`), tempKtx2 = join5(runtime.tmpDir, `${id}.ktx2`);
|
|
3257
|
+
if (writeFileSync4(tempExr, Buffer.from(pmremExrBytes)), logger.debug(`${label}: Encoding KTX2 HDR...`), await encodeKTX2WithBasisu(runtime.basisuExe, tempExr, tempKtx2, "hdr4x4", !0), !existsSync8(tempKtx2))
|
|
3258
|
+
throw new Error(`${label}: basisu did not produce output`);
|
|
3259
|
+
let ktx2Bytes = readFileSync6(tempKtx2);
|
|
3260
|
+
return useCache && addToCache(cacheKey, ktx2Bytes), new Uint8Array(ktx2Bytes);
|
|
3261
|
+
}
|
|
3262
|
+
function getPmremDir() {
|
|
3263
|
+
let thisDir = dirname4(fileURLToPath(import.meta.url));
|
|
3264
|
+
return join5(thisDir, "..", "..", "tools", "pmrem");
|
|
3265
|
+
}
|
|
3266
|
+
function resolveBasisuExe(pmremDir) {
|
|
3267
|
+
let platform = process.platform, base = join5(pmremDir, "basis");
|
|
3268
|
+
return platform === "win32" ? join5(base, "win", "basisu.exe") : platform === "darwin" ? join5(base, "osx", "basisu") : join5(base, "linux", "basisu");
|
|
3269
|
+
}
|
|
3270
|
+
function encodeKTX2WithBasisu(basisuExe, exrPath, outPath, variant, mipmaps) {
|
|
3271
|
+
return new Promise((resolve4, reject) => {
|
|
3272
|
+
let args = [];
|
|
3273
|
+
args.push(variant === "hdr6x6" ? "-hdr_6x6" : "-hdr_4x4"), mipmaps && args.push("-mipmap"), args.push("-file", exrPath, "-output_file", outPath, "-y_flip"), execFile(basisuExe, args, { windowsHide: !0, encoding: "utf8" }, (err, stdout, stderr) => {
|
|
3274
|
+
if (err) {
|
|
3275
|
+
let details = [stderr, stdout, err.message].filter(Boolean).join(`
|
|
3276
|
+
`);
|
|
3277
|
+
reject(new Error(`basisu failed (exit code ${err.code}):
|
|
3278
|
+
${details}`));
|
|
3279
|
+
return;
|
|
3280
|
+
}
|
|
3281
|
+
resolve4();
|
|
3282
|
+
});
|
|
3283
|
+
});
|
|
3284
|
+
}
|
|
3285
|
+
var NeedlePmremContext = class {
|
|
3286
|
+
runtime = null;
|
|
3287
|
+
processed = 0;
|
|
3288
|
+
logger;
|
|
3289
|
+
convertedTextures = [];
|
|
3290
|
+
/** In-memory dedup: keyed by EXR content hash, resolves to KTX2 bytes */
|
|
3291
|
+
processingPromises = /* @__PURE__ */ new Map();
|
|
3292
|
+
async prepare(document) {
|
|
3293
|
+
return this.logger = document.getLogger(), this.processed = 0, this.runtime = await createPmremRuntime(this.logger), this.runtime !== null;
|
|
3294
|
+
}
|
|
3295
|
+
async process(index, texture, _settings, context) {
|
|
3296
|
+
if (!this.runtime || texture.getMimeType() !== "image/exr") return !1;
|
|
3297
|
+
let image = texture.getImage();
|
|
3298
|
+
if (!image) return !1;
|
|
3299
|
+
let name = texture.getName() || `texture_${index}`, wasExternal = !!texture.getURI(), exrBytes = new Uint8Array(image.buffer, image.byteOffset, image.byteLength), cacheKey = `pmrem-${createHash("md5").update(exrBytes).digest("hex")}`, wasDeduplicated = this.processingPromises.has(cacheKey), ktx2Bytes = await this.getOrProcessExr(cacheKey, exrBytes, index, name, context.useCache), exrProp = texture.getExtension("EXT_texture_exr");
|
|
3300
|
+
if (exrProp && (texture.setExtension("EXT_texture_exr", null), exrProp.dispose()), texture.setMimeType("image/ktx2"), wasExternal) {
|
|
3301
|
+
let uri = texture.getURI(), newUri = uri.replace(/\.exr$/i, ".pmrem.ktx2"), ktx2FileName = newUri !== uri ? newUri : uri + ".pmrem.ktx2", outDir = dirname4(context.outfile);
|
|
3302
|
+
writeFileSync4(join5(outDir, ktx2FileName), ktx2Bytes);
|
|
3303
|
+
let originalExrPath = join5(outDir, uri);
|
|
3304
|
+
existsSync8(originalExrPath) && rmSync3(originalExrPath), texture.setURI(ktx2FileName), texture.setName(ktx2FileName), texture.setImage(null), this.logger.debug(`NEEDLE_pmrem[${index}] ${name}: external \u2192 ${ktx2FileName}`);
|
|
3305
|
+
} else
|
|
3306
|
+
texture.setImage(new Uint8Array(ktx2Bytes));
|
|
3307
|
+
if (wasDeduplicated)
|
|
3308
|
+
this.logger.debug(`NEEDLE_pmrem[${index}] ${name}: reused (identical content) \u2192 ${texture.getURI() || texture.getName() || name}`);
|
|
3309
|
+
else {
|
|
3310
|
+
let sizeStr = image.byteLength < 102400 ? `${(image.byteLength / 1024).toFixed(0)} KB` : `${(image.byteLength / 1048576).toFixed(2)} MB`, dstSizestr = ktx2Bytes.length < 100 * 1024 ? `${(ktx2Bytes.length / 1024).toFixed(0)} KB` : `${(ktx2Bytes.length / (1024 * 1024)).toFixed(2)} MB`;
|
|
3311
|
+
this.logger.info(`NEEDLE_pmrem[${index}] ${name}: ${sizeStr} EXR \u2192 ${dstSizestr} KTX2 (${texture.getURI() || texture.getName() || name})`);
|
|
3312
|
+
}
|
|
3313
|
+
return this.convertedTextures.push(texture), this.processed++, !0;
|
|
3314
|
+
}
|
|
3315
|
+
/** Get or process EXR bytes into KTX2, with in-memory dedup and disk caching */
|
|
3316
|
+
getOrProcessExr(cacheKey, exrBytes, index, name, useCache) {
|
|
3317
|
+
let existing = this.processingPromises.get(cacheKey);
|
|
3318
|
+
if (existing)
|
|
3319
|
+
return this.logger.debug(`NEEDLE_pmrem[${index}] ${name}: reusing in-flight result (identical content)`), existing;
|
|
3320
|
+
let promise = convertExrBytesToPmremKtx2(this.runtime, exrBytes, {
|
|
3321
|
+
useCache,
|
|
3322
|
+
logLabel: `NEEDLE_pmrem[${index}] ${name}`
|
|
3323
|
+
});
|
|
3324
|
+
return this.processingPromises.set(cacheKey, promise), promise;
|
|
3325
|
+
}
|
|
3326
|
+
async finalize(document) {
|
|
3327
|
+
if (this.processed > 0) {
|
|
3328
|
+
let pmremExt = document.createExtension(NEEDLE_pmrem);
|
|
3329
|
+
for (let tex of this.convertedTextures)
|
|
3330
|
+
pmremExt.addTexture(tex);
|
|
3331
|
+
if (!document.getRoot().listTextures().some((t) => t.getMimeType() === "image/exr")) {
|
|
3332
|
+
let exrExt = document.getRoot().listExtensionsUsed().find((e) => e.extensionName === "EXT_texture_exr");
|
|
3333
|
+
exrExt && exrExt.dispose();
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
await disposePmremRuntime(this.runtime), this.runtime = null;
|
|
3337
|
+
}
|
|
3338
|
+
};
|
|
3339
|
+
|
|
3340
|
+
// src/transforms/needle_texture_transform.ts
|
|
3341
|
+
import { createTransform as createTransform4, listTextureSlots as listTextureSlots3 } from "@gltf-transform/functions";
|
|
3342
|
+
import { dirname as dirname5 } from "path";
|
|
3343
|
+
import { existsSync as existsSync9, rmSync as rmSync4 } from "fs";
|
|
3344
|
+
async function resizeTextureIfNecessary(texture) {
|
|
3345
|
+
let ext = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME);
|
|
3346
|
+
if (ext?.model) {
|
|
3347
|
+
let mimeType = texture.getMimeType();
|
|
3348
|
+
if (mimeType === "image/jpeg" || mimeType === "image/png") {
|
|
3349
|
+
let settings = ext.model, size = texture.getSize();
|
|
3350
|
+
size && settings.maxSize > 4 && (size[0] > settings.maxSize || size[1] > settings.maxSize) && (console.log(`> Will resize texture ${texture.getName()} from ${size[0]}x${size[1]} to ${settings.maxSize}x${settings.maxSize}`), await resizeTextureToMax(texture, settings.maxSize, console));
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
var needle_texture_transform = function(options) {
|
|
3355
|
+
let webPContext = new NeedleWebPContext({}), toktxContext = new NeedleToktxContext({
|
|
3356
|
+
jobs: void 0,
|
|
3357
|
+
// default to number of cores,
|
|
3358
|
+
debug: options.debug
|
|
3359
|
+
}), pmremContext = new NeedlePmremContext(), context = {
|
|
3360
|
+
config: options.config,
|
|
3361
|
+
...options,
|
|
3362
|
+
webPContext,
|
|
3363
|
+
toktxContext,
|
|
3364
|
+
pmremContext
|
|
3365
|
+
};
|
|
3366
|
+
return createTransform4("needle_texture_transform", async (document) => {
|
|
3367
|
+
await webPContext.prepare(document), context.noToktx !== !0 && (await toktxContext.prepare(document) || (context.noToktx = !0)), await pmremContext.prepare(document);
|
|
3368
|
+
try {
|
|
3369
|
+
let logger = document.getLogger(), textures = document.getRoot().listTextures(), totalGpuSize = 0;
|
|
3370
|
+
if (await Promise.all(textures.map((texture, textureIndex) => processTexture(texture, textureIndex, document, logger, context).then(() => {
|
|
3371
|
+
try {
|
|
3372
|
+
let size = ImageUtils4.getVRAMByteLength(texture.getImage(), texture.getMimeType());
|
|
3373
|
+
totalGpuSize += size;
|
|
3374
|
+
} catch {
|
|
3375
|
+
}
|
|
3376
|
+
}))), totalGpuSize > 0) {
|
|
3377
|
+
let gpuMemoryEstimate = totalGpuSize / 1024 / 1024;
|
|
3378
|
+
context.reportGPUMemory ? context.reportGPUMemory(totalGpuSize) : console.log(`> Total GPU size: ${gpuMemoryEstimate.toFixed(2)} MB of ${textures.length} textures`), gpuMemoryEstimate > 1e3 && console.log("WARN: Total estimated GPU size is very large - this may cause issues on some devices. Consider changing the compression settings or reducing texture size.");
|
|
3379
|
+
}
|
|
3380
|
+
} finally {
|
|
3381
|
+
await webPContext.finalize(document), context.noToktx !== !0 && await toktxContext.finalize(document), await pmremContext.finalize(document);
|
|
3382
|
+
}
|
|
3383
|
+
});
|
|
3384
|
+
};
|
|
3385
|
+
async function processTexture(texture, index, document, logger, context) {
|
|
3386
|
+
let validationResult = validateImageMimeType(texture.getMimeType(), texture.getImage(), logger);
|
|
3387
|
+
validationResult?.error && (logger.warn(`WARN: Texture ${texture.getName()} [${index}] has an incorrect mime type "${texture.getMimeType()}" \u2192 auto-correcting to ${validationResult.mimeType}`), texture.setMimeType(validationResult.mimeType));
|
|
3388
|
+
let originalMimeType = texture.getMimeType();
|
|
3389
|
+
if (originalMimeType === "image/exr") {
|
|
3390
|
+
if (context.config.exr?.enabled === !1) {
|
|
3391
|
+
logger.debug(`\u2192 Skipping EXR -> KTX2 HDR for ${texture.getName()} [${index}] (config.exr.enabled = false)`);
|
|
3392
|
+
return;
|
|
3393
|
+
}
|
|
3394
|
+
await context.pmremContext.process(index, texture, null, context);
|
|
3395
|
+
return;
|
|
3396
|
+
}
|
|
3397
|
+
if (!(originalMimeType === "image/jpeg" || originalMimeType === "image/png" || originalMimeType === "image/webp")) return;
|
|
3398
|
+
let compressionSettings = texture.getExtension(NEEDLE_compression_texture.EXTENSION_NAME)?.model;
|
|
3399
|
+
if (compressionSettings?.mode === "none") {
|
|
3400
|
+
logger.info(`\u2192 Skipping texture compression for ${texture.getName()} [${index}] as configured in the texture extension`);
|
|
3401
|
+
return;
|
|
3402
|
+
}
|
|
3403
|
+
let key = context.useCache ? getKey(texture) + getHash(context.config) : void 0, cached = context.useCache && key ? tryGetFromCache(key) : void 0;
|
|
3404
|
+
cached && (cached.length <= 0 ? (logger.warn(`WARN: Cached texture ${texture.getName()} [${index}] is empty. Will reprocess.`), cached = void 0) : logger.info(`\u2192 Using cached texture ${texture.getName()} [${index}] \u2013 ${(cached.length / 1024).toFixed(0)} KB`));
|
|
3405
|
+
let successfullyProcessed = !1, useDefaultCompression = !0, canRunToktx = context.noToktx !== !0, originalUri = texture.getURI();
|
|
3406
|
+
if (compressionSettings && compressionSettings.mode !== "auto") {
|
|
3407
|
+
switch (compressionSettings.mode) {
|
|
3408
|
+
case "world":
|
|
3409
|
+
compressionSettings.mode = "ETC1S";
|
|
3410
|
+
break;
|
|
3411
|
+
case "product":
|
|
3412
|
+
switch (compressionSettings.slot) {
|
|
3413
|
+
default:
|
|
3414
|
+
compressionSettings.mode = "ETC1S";
|
|
3415
|
+
break;
|
|
3416
|
+
case "normalTexture":
|
|
3417
|
+
compressionSettings.mode = "UASTC";
|
|
3418
|
+
break;
|
|
3419
|
+
case "baseColorTexture":
|
|
3420
|
+
case "metallicRoughnessTexture":
|
|
3421
|
+
case "lightmapTexture":
|
|
3422
|
+
compressionSettings.mode = "webp", compressionSettings.quality = 0.8;
|
|
3423
|
+
break;
|
|
224
3424
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
3425
|
+
break;
|
|
3426
|
+
}
|
|
3427
|
+
switch (compressionSettings.mode) {
|
|
3428
|
+
case "webp":
|
|
3429
|
+
if (cached) {
|
|
3430
|
+
texture.setImage(cached).setMimeType("image/webp");
|
|
3431
|
+
return;
|
|
3432
|
+
}
|
|
3433
|
+
await resizeTextureIfNecessary(texture), useDefaultCompression = !1, successfullyProcessed = await context.webPContext.process(index, texture, compressionSettings, context);
|
|
3434
|
+
break;
|
|
3435
|
+
case "ETC1S":
|
|
3436
|
+
if (cached) {
|
|
3437
|
+
texture.setImage(cached).setMimeType("image/ktx2");
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
await resizeTextureIfNecessary(texture), useDefaultCompression = !1, successfullyProcessed = await context.toktxContext.process(index, texture, compressionSettings, context);
|
|
3441
|
+
break;
|
|
3442
|
+
case "UASTC":
|
|
3443
|
+
if (cached) {
|
|
3444
|
+
texture.setImage(cached).setMimeType("image/ktx2");
|
|
3445
|
+
return;
|
|
231
3446
|
}
|
|
3447
|
+
await resizeTextureIfNecessary(texture), useDefaultCompression = !1, successfullyProcessed = await context.toktxContext.process(index, texture, compressionSettings, context);
|
|
3448
|
+
break;
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
if (useDefaultCompression) {
|
|
3452
|
+
let mimeType = "image/ktx2", ktx2Format, slots = listTextureSlots3(texture), size = texture.getSize(), isVRM = context.file?.toLowerCase().endsWith(".vrm"), webpOptions = {};
|
|
3453
|
+
if ((slots.includes("lightmapTexture") || isLightmap(texture) || size[0] <= 32 || size[1] <= 32 || context.config.usecase === "product" && (slots.includes("normalTexture") || slots.includes("metallicRoughnessTexture"))) && (mimeType = "image/webp"), cached) {
|
|
3454
|
+
texture.setImage(cached).setMimeType(mimeType);
|
|
3455
|
+
return;
|
|
3456
|
+
}
|
|
3457
|
+
if (await resizeTextureIfNecessary(texture), mimeType === "image/webp")
|
|
3458
|
+
successfullyProcessed = await context.webPContext.process(index, texture, {
|
|
3459
|
+
...webpOptions,
|
|
3460
|
+
quality: 0.95,
|
|
3461
|
+
slot: slots.join(",")
|
|
3462
|
+
}, context);
|
|
3463
|
+
else if (canRunToktx) {
|
|
3464
|
+
let options = null;
|
|
3465
|
+
(ktx2Format || isVRM) && (options = { mode: ktx2Format || "ETC1S" }), successfullyProcessed = await context.toktxContext.process(index, texture, options, context);
|
|
3466
|
+
} else
|
|
3467
|
+
logger.warn("Toktx not found: Skipping texture compression: " + originalMimeType);
|
|
3468
|
+
}
|
|
3469
|
+
if (context.useCache && successfullyProcessed && key) {
|
|
3470
|
+
let data = texture.getImage();
|
|
3471
|
+
data && addToCache(key, data);
|
|
3472
|
+
}
|
|
3473
|
+
if (successfullyProcessed) {
|
|
3474
|
+
let newUri = texture.getURI();
|
|
3475
|
+
if (originalUri && originalUri != newUri) {
|
|
3476
|
+
let inDirectory = dirname5(context.file), outDirectory = dirname5(context.outfile), originalPath = inDirectory + "/" + originalUri;
|
|
3477
|
+
inDirectory == outDirectory && existsSync9(originalPath) && (logger.info(`Removing old texture "${originalUri}" \u2192 "${newUri}"`), rmSync4(originalPath));
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
}
|
|
3481
|
+
|
|
3482
|
+
// src/transforms/needle_animation_transform.ts
|
|
3483
|
+
var needle_animation_transform = function(_options) {
|
|
3484
|
+
return (document, _context) => {
|
|
3485
|
+
};
|
|
3486
|
+
};
|
|
3487
|
+
|
|
3488
|
+
// src/transforms/needle_audio.ts
|
|
3489
|
+
import { createTransform as createTransform5 } from "@gltf-transform/functions";
|
|
3490
|
+
import { createHash as createHash2 } from "crypto";
|
|
3491
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync7, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "fs";
|
|
3492
|
+
import { basename as basename3, dirname as dirname6, extname, join as join6 } from "path";
|
|
3493
|
+
import { v4 as uuid4 } from "uuid";
|
|
3494
|
+
import tmp5 from "tmp";
|
|
3495
|
+
|
|
3496
|
+
// src/transforms/needle_audio_ffmpeg.ts
|
|
3497
|
+
import { execFile as execFile2 } from "child_process";
|
|
3498
|
+
var _probe;
|
|
3499
|
+
function findFfmpeg() {
|
|
3500
|
+
return _probe === void 0 && (_probe = probe()), _probe;
|
|
3501
|
+
}
|
|
3502
|
+
function probe() {
|
|
3503
|
+
return new Promise((resolve4) => {
|
|
3504
|
+
execFile2("ffmpeg", ["-hide_banner", "-codecs"], { timeout: 5e3, windowsHide: !0 }, (err, stdout) => {
|
|
3505
|
+
if (err) {
|
|
3506
|
+
resolve4(null);
|
|
3507
|
+
return;
|
|
3508
|
+
}
|
|
3509
|
+
let hasLibopus = /libopus/i.test(stdout) && /opus/i.test(stdout);
|
|
3510
|
+
resolve4({ path: "ffmpeg", hasLibopus });
|
|
232
3511
|
});
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
3512
|
+
});
|
|
3513
|
+
}
|
|
3514
|
+
function encodeOpusOgg(ffmpegPath, inputPath, outputPath, bitrateKbps) {
|
|
3515
|
+
return new Promise((resolve4, reject) => {
|
|
3516
|
+
let args = [
|
|
3517
|
+
"-hide_banner",
|
|
3518
|
+
"-loglevel",
|
|
3519
|
+
"error",
|
|
3520
|
+
"-y",
|
|
3521
|
+
"-i",
|
|
3522
|
+
inputPath,
|
|
3523
|
+
"-vn",
|
|
3524
|
+
"-c:a",
|
|
3525
|
+
"libopus",
|
|
3526
|
+
"-b:a",
|
|
3527
|
+
`${bitrateKbps}k`,
|
|
3528
|
+
outputPath
|
|
3529
|
+
];
|
|
3530
|
+
execFile2(ffmpegPath, args, { windowsHide: !0 }, (err, _stdout, stderr) => {
|
|
3531
|
+
if (err) {
|
|
3532
|
+
reject(new Error(`ffmpeg failed (exit ${err.code}):
|
|
3533
|
+
${stderr || err.message}`));
|
|
3534
|
+
return;
|
|
3535
|
+
}
|
|
3536
|
+
resolve4();
|
|
242
3537
|
});
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
3538
|
+
});
|
|
3539
|
+
}
|
|
3540
|
+
|
|
3541
|
+
// src/transforms/needle_audio.ts
|
|
3542
|
+
var DEFAULT_BITRATE_KBPS = 128;
|
|
3543
|
+
function needle_audio_transform(options) {
|
|
3544
|
+
return createTransform5("needle_audio_transform", async (document) => {
|
|
3545
|
+
let refs = listAudioRefs();
|
|
3546
|
+
if (refs.length === 0) return;
|
|
3547
|
+
let logger = document.getLogger(), audioCfg = options.config.audio ?? {};
|
|
3548
|
+
if (audioCfg.enabled === !1) {
|
|
3549
|
+
logger.debug(`audio: disabled in config \u2014 ${refs.length} external audio reference(s) left untouched`);
|
|
3550
|
+
return;
|
|
3551
|
+
}
|
|
3552
|
+
let bitrate = audioCfg.bitrate ?? DEFAULT_BITRATE_KBPS, ffmpeg = await findFfmpeg();
|
|
3553
|
+
if (!ffmpeg) {
|
|
3554
|
+
logger.warn(`audio: ffmpeg not found on PATH \u2014 ${refs.length} audio file(s) will pass through uncompressed`);
|
|
3555
|
+
return;
|
|
3556
|
+
}
|
|
3557
|
+
if (!ffmpeg.hasLibopus) {
|
|
3558
|
+
logger.warn(`audio: ffmpeg is installed but libopus codec is missing \u2014 ${refs.length} audio file(s) will pass through uncompressed`);
|
|
3559
|
+
return;
|
|
3560
|
+
}
|
|
3561
|
+
let outDir = dirname6(options.outfile), bySource = /* @__PURE__ */ new Map();
|
|
3562
|
+
for (let ref of refs) {
|
|
3563
|
+
let list = bySource.get(ref.sourcePath) ?? [];
|
|
3564
|
+
list.push(ref), bySource.set(ref.sourcePath, list);
|
|
3565
|
+
}
|
|
3566
|
+
let tmpDir = join6(tmp5.tmpdir, "needle-audio", uuid4());
|
|
3567
|
+
mkdirSync7(tmpDir, { recursive: !0 });
|
|
3568
|
+
try {
|
|
3569
|
+
for (let [sourcePath, refsForSource] of bySource) {
|
|
3570
|
+
if (!existsSync10(sourcePath)) {
|
|
3571
|
+
logger.warn(`audio: source not found at write time, skipping: ${sourcePath}`);
|
|
3572
|
+
continue;
|
|
3573
|
+
}
|
|
3574
|
+
let sourceUri = refsForSource[0].sourceUri, newUri = computeOpusOggUri(sourceUri), sourceBytes = readFileSync7(sourcePath), cacheKey = `audio-opus-${createHash2("md5").update(sourceBytes).digest("hex")}-${bitrate}k`, oggBytes = null;
|
|
3575
|
+
if (options.useCache) {
|
|
3576
|
+
let cached = tryGetFromCache(cacheKey);
|
|
3577
|
+
cached && cached.length > 0 && (logger.debug(`audio: cache hit for ${sourceUri} (${cacheKey})`), oggBytes = cached);
|
|
3578
|
+
}
|
|
3579
|
+
if (!oggBytes) {
|
|
3580
|
+
let tmpOgg = join6(tmpDir, `${uuid4()}.ogg`), t0 = Date.now();
|
|
3581
|
+
if (await encodeOpusOgg(ffmpeg.path, sourcePath, tmpOgg, bitrate), !existsSync10(tmpOgg)) {
|
|
3582
|
+
logger.error(`audio: ffmpeg did not produce output for ${sourceUri}`);
|
|
3583
|
+
continue;
|
|
3584
|
+
}
|
|
3585
|
+
oggBytes = new Uint8Array(readFileSync7(tmpOgg));
|
|
3586
|
+
let elapsed = ((Date.now() - t0) / 1e3).toFixed(1), srcKb = sourceBytes.length / 1024, dstKb = oggBytes.length / 1024;
|
|
3587
|
+
logger.info(`audio: ${sourceUri} (${srcKb.toFixed(0)} KB) \u2192 ${newUri} (${dstKb.toFixed(0)} KB) in ${elapsed}s`), options.useCache && addToCache(cacheKey, oggBytes);
|
|
3588
|
+
}
|
|
3589
|
+
let outPath = join6(outDir, newUri);
|
|
3590
|
+
mkdirSync7(dirname6(outPath), { recursive: !0 }), writeFileSync5(outPath, oggBytes);
|
|
3591
|
+
let sourceInOutDir = join6(outDir, sourceUri);
|
|
3592
|
+
existsSync10(sourceInOutDir) && rmSync5(sourceInOutDir);
|
|
3593
|
+
for (let ref of refsForSource)
|
|
3594
|
+
ref.newUri = newUri;
|
|
3595
|
+
}
|
|
3596
|
+
} finally {
|
|
3597
|
+
await safeRmDir(tmpDir);
|
|
3598
|
+
}
|
|
3599
|
+
});
|
|
3600
|
+
}
|
|
3601
|
+
function computeOpusOggUri(sourceUri) {
|
|
3602
|
+
let dir = dirname6(sourceUri), ext = extname(sourceUri), newName = `${basename3(sourceUri, ext)}.opus.ogg`;
|
|
3603
|
+
return dir === "." || dir === "" ? newName : join6(dir, newName);
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
// src/scripts/pack-gltf.ts
|
|
3607
|
+
async function packGLTF(inputFile, outputFile, options) {
|
|
3608
|
+
options.logger || (options.logger = new Logger(Verbosity2.INFO));
|
|
3609
|
+
let { debug, stats, packedFiles, useCache, logger } = options;
|
|
3610
|
+
if (!existsSync11(inputFile))
|
|
3611
|
+
return logger.error(`WARN: can not pack, file does not exist: "${inputFile}"`), !1;
|
|
3612
|
+
let cacheKey;
|
|
3613
|
+
if (useCache && isMeshLOD(inputFile)) {
|
|
3614
|
+
let existing = readFileSync8(inputFile);
|
|
3615
|
+
cacheKey = "packed-" + getHash(existing);
|
|
3616
|
+
let cached = tryGetFromCache(cacheKey);
|
|
3617
|
+
if (cached)
|
|
3618
|
+
return logger.info(`\u2192 Loaded compressed file from cache: "${path5.basename(inputFile)}"`), writeFileSync6(inputFile, cached), !0;
|
|
3619
|
+
}
|
|
3620
|
+
if (packedFiles) {
|
|
3621
|
+
if (packedFiles.has(inputFile)) return !0;
|
|
3622
|
+
packedFiles.add(inputFile);
|
|
3623
|
+
}
|
|
3624
|
+
try {
|
|
3625
|
+
let config = options.config;
|
|
3626
|
+
outputFile ? outputFile = getOutputPath(inputFile, outputFile) : outputFile = inputFile;
|
|
3627
|
+
let prevSizeInMB = statSync5(inputFile).size / 1024 / 1024;
|
|
3628
|
+
logger.debug(`\u2192 Compressing ${prevSizeInMB.toFixed(1)} MB: ${inputFile}`);
|
|
3629
|
+
let startTime = Date.now(), io = new NodeIO2().registerExtensions(ALL_EXTENSIONS3).registerExtensions(ALL_EXTENSIONS).registerExtensions([
|
|
3630
|
+
NEEDLE_compression_texture,
|
|
3631
|
+
NEEDLE_mesh_compression,
|
|
3632
|
+
NEEDLE_pmrem,
|
|
3633
|
+
NEEDLE_lightmaps_ext
|
|
3634
|
+
]).registerDependencies({
|
|
3635
|
+
"draco3d.decoder": await draco3d2.createDecoderModule(),
|
|
3636
|
+
"draco3d.encoder": await draco3d2.createEncoderModule(),
|
|
3637
|
+
"meshopt.decoder": MeshoptDecoder2,
|
|
3638
|
+
"meshopt.encoder": MeshoptEncoder3
|
|
3639
|
+
}), assetSourceFile = options.sourceFile ?? inputFile;
|
|
3640
|
+
setExtensionInputFile(assetSourceFile), clearAudioRegistry();
|
|
3641
|
+
let document = await ioTryReadWithMissingResources(io, inputFile);
|
|
3642
|
+
options.logger ? document.setLogger(options.logger) : document.getLogger().verbosity = options.verbose ? Verbosity2.DEBUG : options.debug ? Verbosity2.INFO : Verbosity2.WARN, copyExternalResources(document, assetSourceFile, outputFile);
|
|
3643
|
+
let totalGPUTextureMemory = 0, transforms = [
|
|
3644
|
+
needle_asset(),
|
|
3645
|
+
metalRough2(),
|
|
3646
|
+
needle_texture_transform({
|
|
3647
|
+
file: inputFile,
|
|
3648
|
+
outfile: outputFile,
|
|
3649
|
+
useCache,
|
|
3650
|
+
noToktx: !1,
|
|
3651
|
+
debug,
|
|
3652
|
+
reportGPUMemory: (val) => {
|
|
3653
|
+
totalGPUTextureMemory += val;
|
|
3654
|
+
},
|
|
3655
|
+
config
|
|
3656
|
+
}),
|
|
3657
|
+
needle_mesh_transform({ file: inputFile, config }),
|
|
3658
|
+
needle_audio_transform({ outfile: outputFile, useCache, config }),
|
|
3659
|
+
needle_animation_transform({}),
|
|
3660
|
+
resample({
|
|
3661
|
+
tolerance: 1e-6
|
|
3662
|
+
// NOTE: lowered from 1e-4 to 1e-6 to fix https://linear.app/needle/issue/NE-6872
|
|
3663
|
+
}),
|
|
3664
|
+
// Can not dedup "materials" because progressive textures will then assigned to the wrong material instance
|
|
3665
|
+
// HACK: keepUniqueNames is enabled to fix https://linear.app/needle/issue/NE-6288
|
|
3666
|
+
dedup2({ propertyTypes: [PropertyType12.MESH, PropertyType12.MATERIAL] })
|
|
3667
|
+
], isProgressiveAsset = isLOD(inputFile), materialOnly = isMaterialOnlyGLB(document);
|
|
3668
|
+
if (!isProgressiveAsset && !materialOnly && transforms.push(prune2({
|
|
3669
|
+
// Pruning animations is not supported yet (e.g. if the animation is only referenced by a component)
|
|
3670
|
+
propertyTypes: [
|
|
3671
|
+
PropertyType12.MESH,
|
|
3672
|
+
PropertyType12.MATERIAL,
|
|
3673
|
+
PropertyType12.TEXTURE,
|
|
3674
|
+
PropertyType12.ACCESSOR,
|
|
3675
|
+
PropertyType12.BUFFER
|
|
3676
|
+
],
|
|
3677
|
+
keepAttributes: !0,
|
|
3678
|
+
// for materialx
|
|
3679
|
+
keepIndices: !0,
|
|
3680
|
+
// required when keepAttributes is true for https://linear.app/needle/issue/NE-6635/
|
|
3681
|
+
keepExtras: !0,
|
|
3682
|
+
keepSolidTextures: !0
|
|
3683
|
+
})), await document.transform(...transforms), options.externalFiles) {
|
|
3684
|
+
let outDir = path5.dirname(outputFile), root = document.getRoot();
|
|
3685
|
+
for (let tex of root.listTextures()) {
|
|
3686
|
+
let uri = tex.getURI();
|
|
3687
|
+
if (uri && !uri.startsWith("data:")) {
|
|
3688
|
+
let absPath = path5.resolve(outDir, uri);
|
|
3689
|
+
existsSync11(absPath) && options.externalFiles.push(absPath);
|
|
3690
|
+
}
|
|
3691
|
+
}
|
|
3692
|
+
for (let buf of root.listBuffers()) {
|
|
3693
|
+
let uri = buf.getURI();
|
|
3694
|
+
if (uri && !uri.startsWith("data:")) {
|
|
3695
|
+
let absPath = path5.resolve(outDir, uri);
|
|
3696
|
+
existsSync11(absPath) && options.externalFiles.push(absPath);
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
for (let ref of listAudioRefs()) {
|
|
3700
|
+
let uri = ref.newUri ?? ref.sourceUri, absPath = path5.resolve(outDir, uri);
|
|
3701
|
+
existsSync11(absPath) && options.externalFiles.push(absPath);
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
logger.debug(`\u2190 Writing to ${outputFile}`), await writeNodeIO(io, outputFile, document), useCache && cacheKey != null && existsSync11(outputFile) && addToCache(cacheKey, readFileSync8(outputFile));
|
|
3705
|
+
let duration = Date.now() - startTime, sizeInMB = statSync5(outputFile).size / 1024 / 1024, filename = path5.basename(outputFile), gpuMemoryInMB = totalGPUTextureMemory / 1024 / 1024;
|
|
3706
|
+
return logger.info(`\u2190 Compressed '${filename}' ${prevSizeInMB.toFixed(1)} MB \u2192 ${sizeInMB.toFixed(1)} MB (GPU: ${gpuMemoryInMB.toFixed(1)} MB textures) in ${(duration / 1e3).toFixed(1)} sec`), stats && (stats.totalFilesProcessed++, stats.totalFileSizeInMB += sizeInMB, stats.totalFileSizeInMBBefore += prevSizeInMB, stats.totalGPUMemoryInMB += gpuMemoryInMB), !0;
|
|
3707
|
+
} catch (err) {
|
|
3708
|
+
if (err instanceof TestAssertionError) throw err;
|
|
3709
|
+
let shortedStackTrace = err instanceof Error && err.stack ? err.stack.split(`
|
|
3710
|
+
`).slice(0, 2).join(`
|
|
3711
|
+
`) : "";
|
|
3712
|
+
if (logger.error(`Packing of "${path5.basename(inputFile)}" using version ${getVersion()} failed with error:
|
|
3713
|
+
${err instanceof Error ? err.message : String(err)}
|
|
3714
|
+
${shortedStackTrace}`), debug) throw err;
|
|
3715
|
+
return !1;
|
|
3716
|
+
}
|
|
3717
|
+
}
|
|
3718
|
+
|
|
3719
|
+
// src/scripts/stats.ts
|
|
3720
|
+
import { Logger as Logger2, NodeIO as NodeIO3, Verbosity as Verbosity3 } from "@gltf-transform/core";
|
|
3721
|
+
import { ALL_EXTENSIONS as ALL_EXTENSIONS4 } from "@gltf-transform/extensions";
|
|
3722
|
+
import draco3d3 from "draco3dgltf";
|
|
3723
|
+
import { MeshoptDecoder as MeshoptDecoder3, MeshoptEncoder as MeshoptEncoder4 } from "meshoptimizer";
|
|
3724
|
+
async function calculateStats(inputfile, options) {
|
|
3725
|
+
let io = new NodeIO3().setLogger(new Logger2(options?.verbose ? Verbosity3.DEBUG : Verbosity3.ERROR)).registerExtensions(ALL_EXTENSIONS4).registerDependencies({
|
|
3726
|
+
"draco3d.decoder": await draco3d3.createDecoderModule(),
|
|
3727
|
+
"draco3d.encoder": await draco3d3.createEncoderModule(),
|
|
3728
|
+
"meshopt.decoder": MeshoptDecoder3,
|
|
3729
|
+
"meshopt.encoder": MeshoptEncoder4
|
|
3730
|
+
}), document = await io.read(inputfile), json = await io.readAsJSON(inputfile);
|
|
3731
|
+
return createNewFilestats(inputfile, document, json);
|
|
3732
|
+
}
|
|
3733
|
+
|
|
3734
|
+
// src/config/index.ts
|
|
3735
|
+
import { Logger as Logger3, Verbosity as Verbosity4 } from "@gltf-transform/core";
|
|
3736
|
+
import { existsSync as existsSync12, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
|
|
3737
|
+
import path6, { dirname as dirname7, resolve as resolve2 } from "path";
|
|
3738
|
+
var UsecaseOptions = ["product", "world"], defaultConfig = {
|
|
3739
|
+
usecase: "default"
|
|
3740
|
+
};
|
|
3741
|
+
function createConfig(usecase) {
|
|
3742
|
+
if (!UsecaseOptions.includes(usecase))
|
|
3743
|
+
throw new Error(`Invalid usecase: "${usecase}". Valid usecases: ${UsecaseOptions.join(", ")}`);
|
|
3744
|
+
return {
|
|
3745
|
+
usecase
|
|
3746
|
+
};
|
|
3747
|
+
}
|
|
3748
|
+
function getConfig(configPath, fallbackSearchDirectory, opts) {
|
|
3749
|
+
let logger = opts?.logger;
|
|
3750
|
+
if (logger || (logger = new Logger3(Verbosity4.WARN)), configPath != null) {
|
|
3751
|
+
if (configPath = resolve2(process.cwd(), configPath), !existsSync12(configPath))
|
|
3752
|
+
throw new Error(`No config found at "${configPath}"`);
|
|
3753
|
+
if (statSync6(configPath).isDirectory()) {
|
|
3754
|
+
let res2 = searchConfig(configPath, logger);
|
|
3755
|
+
if (res2)
|
|
3756
|
+
return res2;
|
|
3757
|
+
throw new Error(`No config found in directory "${configPath}"`);
|
|
3758
|
+
}
|
|
3759
|
+
let res = resolveConfig(configPath, readFileSync9(configPath, "utf8"), logger);
|
|
3760
|
+
if (res)
|
|
3761
|
+
return res;
|
|
3762
|
+
throw new Error(`Failed parsing config at "${configPath}"`);
|
|
3763
|
+
}
|
|
3764
|
+
if (_cachedConfig !== void 0)
|
|
3765
|
+
return { ..._cachedConfig };
|
|
3766
|
+
if (fallbackSearchDirectory) {
|
|
3767
|
+
let result = searchConfig(fallbackSearchDirectory, logger);
|
|
3768
|
+
result && (_cachedConfig = { ...defaultConfig, ...result }, logger.info(`Using config with usecase: ${_cachedConfig.usecase}`));
|
|
3769
|
+
}
|
|
3770
|
+
return _cachedConfig || (logger.debug("No config found. Using default config."), _cachedConfig = { ...defaultConfig }), { ..._cachedConfig };
|
|
3771
|
+
}
|
|
3772
|
+
var _cachedConfig;
|
|
3773
|
+
function searchConfig(directory, logger) {
|
|
3774
|
+
for (statSync6(directory).isFile() && (directory = dirname7(directory)), directory = directory.replaceAll("\\", "/"); directory.length > 0; ) {
|
|
3775
|
+
let configPath = path6.join(directory, "needle.config.json");
|
|
3776
|
+
if (existsSync12(configPath)) {
|
|
3777
|
+
let content = readFileSync9(configPath, "utf8"), config = resolveConfig(configPath, content, logger);
|
|
3778
|
+
if (config)
|
|
3779
|
+
return config;
|
|
3780
|
+
}
|
|
3781
|
+
let lastSlash = directory.lastIndexOf("/");
|
|
3782
|
+
if (lastSlash < 0)
|
|
3783
|
+
break;
|
|
3784
|
+
directory = directory.slice(0, lastSlash);
|
|
3785
|
+
}
|
|
3786
|
+
return null;
|
|
3787
|
+
}
|
|
3788
|
+
var loggedConfigPaths = /* @__PURE__ */ new Set();
|
|
3789
|
+
function resolveConfig(filename, content, logger) {
|
|
3790
|
+
if (filename.endsWith("needle.config.json"))
|
|
3791
|
+
try {
|
|
3792
|
+
let config = JSON.parse(content);
|
|
3793
|
+
return config.gltf ? (logger.info(`Found "gltf" config at "${filename.replaceAll("\\", "/")}".`), typeof config.gltf == "string" ? createConfig(config.gltf) : config.gltf) : (loggedConfigPaths.has(filename) || (logger.debug(`No "gltf" config found in needle.config.json at "${filename.replaceAll("\\", "/")}". You may add a "gltf" field to the config with the optimization config. Example: { "gltf": { "usecase": "product" } }. Using default config for glTF optimization now.`), loggedConfigPaths.add(filename)), null);
|
|
3794
|
+
} catch (err) {
|
|
3795
|
+
logger.error(`Failed parsing config "${err.message}" at ${filename.replaceAll("\\", "/")}`);
|
|
3796
|
+
}
|
|
3797
|
+
else if (content.trimStart().startsWith("{"))
|
|
3798
|
+
try {
|
|
3799
|
+
return JSON.parse(content);
|
|
3800
|
+
} catch (err) {
|
|
3801
|
+
err instanceof Error ? logger.error(`Failed parsing config "${err.message}" at ${filename.replaceAll("\\", "/")}`) : logger.error(`Failed parsing config "${err}" at ${filename.replaceAll("\\", "/")}`);
|
|
3802
|
+
}
|
|
3803
|
+
else
|
|
3804
|
+
logger.error("Invalid config file format. Expected JSON object at " + filename.replaceAll("\\", "/"));
|
|
3805
|
+
}
|
|
3806
|
+
|
|
3807
|
+
// src/cli/index.ts
|
|
3808
|
+
import { existsSync as existsSync13, readFileSync as readFileSync10, readdirSync as readdirSync3, statSync as statSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
3809
|
+
import path7, { basename as basename4, dirname as dirname8, resolve as resolve3 } from "path";
|
|
3810
|
+
|
|
3811
|
+
// src/constants.ts
|
|
3812
|
+
var ERROR_CODES = {
|
|
3813
|
+
UNKNOWN_ERROR: 1,
|
|
3814
|
+
PACKING_FAILED: 2,
|
|
3815
|
+
PROGRESSIVE_FAILED: 3,
|
|
3816
|
+
INVALID_ARGS: 4,
|
|
3817
|
+
LOST_FILE: 5,
|
|
3818
|
+
AUTH_FAILED: 6
|
|
3819
|
+
};
|
|
3820
|
+
|
|
3821
|
+
// src/utils/analytics.ts
|
|
3822
|
+
import os4 from "os";
|
|
3823
|
+
import https from "https";
|
|
3824
|
+
var RYBBIT_URL = "https://needle.tools/api/v1/rum/t", SITE_ID = "5c44f60eb2d7";
|
|
3825
|
+
function getUserAgent() {
|
|
3826
|
+
let v = getVersion(), platform = os4.platform(), release = os4.release(), arch = os4.arch(), node = process.version, osToken;
|
|
3827
|
+
return platform === "darwin" ? osToken = `Macintosh; Intel Mac OS X ${release.replace(/\./g, "_")}` : platform === "win32" ? osToken = `Windows NT ${release}; Win64; ${arch}` : osToken = `X11; Linux ${arch}`, `Mozilla/5.0 (${osToken}) NeedleBuildPipeline/${v} Node/${node}`;
|
|
3828
|
+
}
|
|
3829
|
+
function sendEvent(eventName, properties, type = "custom_event") {
|
|
3830
|
+
try {
|
|
3831
|
+
let body = JSON.stringify({
|
|
3832
|
+
site_id: SITE_ID,
|
|
3833
|
+
type,
|
|
3834
|
+
event_name: eventName,
|
|
3835
|
+
properties: JSON.stringify(properties),
|
|
3836
|
+
user_agent: getUserAgent()
|
|
3837
|
+
}), url = new URL(RYBBIT_URL), req = https.request({
|
|
3838
|
+
hostname: url.hostname,
|
|
3839
|
+
path: url.pathname,
|
|
3840
|
+
method: "POST",
|
|
3841
|
+
headers: {
|
|
3842
|
+
"Content-Type": "application/json",
|
|
3843
|
+
"Content-Length": Buffer.byteLength(body)
|
|
3844
|
+
},
|
|
3845
|
+
timeout: 5e3
|
|
3846
|
+
});
|
|
3847
|
+
req.on("error", () => {
|
|
3848
|
+
}), req.on("timeout", () => {
|
|
3849
|
+
req.destroy();
|
|
3850
|
+
}), req.on("socket", (socket) => {
|
|
3851
|
+
socket.unref();
|
|
3852
|
+
}), req.end(body);
|
|
3853
|
+
} catch {
|
|
3854
|
+
}
|
|
3855
|
+
}
|
|
3856
|
+
function trackPipelineStart(info) {
|
|
3857
|
+
sendEvent("pipeline_start", {
|
|
3858
|
+
version: getVersion(),
|
|
3859
|
+
mode: info.mode,
|
|
3860
|
+
usecase: info.usecase,
|
|
3861
|
+
platform: process.platform,
|
|
3862
|
+
arch: process.arch,
|
|
3863
|
+
node: process.version
|
|
3864
|
+
});
|
|
3865
|
+
}
|
|
3866
|
+
var recentErrors = /* @__PURE__ */ new Map(), ERROR_DEDUP_MS = 6e4;
|
|
3867
|
+
function trackError(error, context) {
|
|
3868
|
+
let err = error instanceof Error ? error : new Error(String(error)), message = (err.message || "Unknown error").substring(0, 500), stack = (err.stack || "").substring(0, 2e3), errorName = err.name || "Error", key = `${errorName}|${message}`, now = Date.now(), cached = recentErrors.get(key);
|
|
3869
|
+
if (cached && now - cached.time < ERROR_DEDUP_MS) {
|
|
3870
|
+
cached.count++;
|
|
3871
|
+
return;
|
|
3872
|
+
}
|
|
3873
|
+
recentErrors.set(key, { time: now, count: (cached?.count || 0) + 1 });
|
|
3874
|
+
let properties = {
|
|
3875
|
+
version: getVersion(),
|
|
3876
|
+
error_name: errorName + (cached && cached.count > 1 ? ` x${cached.count}` : ""),
|
|
3877
|
+
message,
|
|
3878
|
+
platform: process.platform,
|
|
3879
|
+
arch: process.arch,
|
|
3880
|
+
node: process.version
|
|
3881
|
+
};
|
|
3882
|
+
stack && (properties.stack = stack), context?.mode && (properties.mode = context.mode), context?.usecase && (properties.usecase = context.usecase), context?.file && (properties.file = context.file), sendEvent(errorName, properties, "error");
|
|
3883
|
+
}
|
|
3884
|
+
function trackPipelineEnd(info) {
|
|
3885
|
+
let reductionPct = info.sizeBefore_MB > 0 ? ((1 - info.sizeAfter_MB / info.sizeBefore_MB) * 100).toFixed(1) : "0";
|
|
3886
|
+
sendEvent("pipeline_end", {
|
|
3887
|
+
version: getVersion(),
|
|
3888
|
+
mode: info.mode,
|
|
3889
|
+
usecase: info.usecase,
|
|
3890
|
+
files: info.filesProcessed,
|
|
3891
|
+
size_before_mb: +info.sizeBefore_MB.toFixed(2),
|
|
3892
|
+
size_after_mb: +info.sizeAfter_MB.toFixed(2),
|
|
3893
|
+
reduction_pct: +reductionPct,
|
|
3894
|
+
gpu_memory_mb: +info.gpuMemory_MB.toFixed(2),
|
|
3895
|
+
duration_ms: info.duration_ms,
|
|
3896
|
+
extensions: info.extensionsUsed?.join(","),
|
|
3897
|
+
platform: process.platform,
|
|
3898
|
+
arch: process.arch,
|
|
3899
|
+
node: process.version
|
|
3900
|
+
});
|
|
3901
|
+
}
|
|
3902
|
+
|
|
3903
|
+
// src/auth/verify.ts
|
|
3904
|
+
import { jwtVerify, importJWK } from "jose";
|
|
3905
|
+
|
|
3906
|
+
// src/auth/keys.ts
|
|
3907
|
+
var PROD_KEYS = [
|
|
3908
|
+
// needle-cloud licensing public key (ECDSA P-256). Same key needle-engine
|
|
3909
|
+
// uses to verify license JWTs at runtime — see engine_license.ts.
|
|
3910
|
+
// Pipeline tokens are minted by needle-cloud with this private key AND
|
|
3911
|
+
// must include `kid: "needle-cloud-v1"` in the JWT header.
|
|
3912
|
+
{
|
|
3913
|
+
kty: "EC",
|
|
3914
|
+
crv: "P-256",
|
|
3915
|
+
x: "A34nyKMjhQYVgzeE4tyLUYdx34TAKogDa7v7PRaO9Lg",
|
|
3916
|
+
y: "JZI9IQavGCpGjEG_-pa0J-MHQYWJYINUM-MnvSu0TmE",
|
|
3917
|
+
kid: "needle-cloud-v1",
|
|
3918
|
+
alg: "ES256",
|
|
3919
|
+
use: "sig"
|
|
3920
|
+
}
|
|
3921
|
+
];
|
|
3922
|
+
var trusted = [...PROD_KEYS], TRUSTED_KEYS = trusted;
|
|
3923
|
+
|
|
3924
|
+
// src/auth/verify.ts
|
|
3925
|
+
var AuthError = class extends Error {
|
|
3926
|
+
constructor(message) {
|
|
3927
|
+
super(message), this.name = "AuthError";
|
|
3928
|
+
}
|
|
3929
|
+
};
|
|
3930
|
+
async function verifyAuthToken(token) {
|
|
3931
|
+
if (!token)
|
|
3932
|
+
throw new AuthError("no token provided");
|
|
3933
|
+
if (token.startsWith("nc_"))
|
|
3934
|
+
throw new AuthError("NEEDLE_CLOUD_TOKEN is a needle-cloud access token (nc_*), not a JWT.");
|
|
3935
|
+
try {
|
|
3936
|
+
await jwtVerify(token, async (header) => {
|
|
3937
|
+
if (!header.kid)
|
|
3938
|
+
throw new AuthError("token header missing 'kid'");
|
|
3939
|
+
let match = TRUSTED_KEYS.find((k) => k.kid === header.kid);
|
|
3940
|
+
if (!match)
|
|
3941
|
+
throw new AuthError(`token signed by unknown key '${header.kid}'`);
|
|
3942
|
+
if (!match.alg)
|
|
3943
|
+
throw new AuthError(`trusted key '${header.kid}' is missing 'alg'`);
|
|
3944
|
+
return importJWK(match, match.alg);
|
|
3945
|
+
}, {
|
|
3946
|
+
// jose checks `exp` automatically when present; requiredClaims forces
|
|
3947
|
+
// the issuer to include it. A token without `exp` would otherwise
|
|
3948
|
+
// verify as never-expiring.
|
|
3949
|
+
requiredClaims: ["exp"]
|
|
3950
|
+
});
|
|
3951
|
+
} catch (err) {
|
|
3952
|
+
if (err instanceof AuthError) throw err;
|
|
3953
|
+
if (err && typeof err == "object" && "code" in err) {
|
|
3954
|
+
let code = err.code;
|
|
3955
|
+
if (code === "ERR_JWT_EXPIRED")
|
|
3956
|
+
throw new AuthError("token expired");
|
|
3957
|
+
if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && "claim" in err && err.claim === "exp")
|
|
3958
|
+
throw new AuthError("token missing 'exp' claim");
|
|
3959
|
+
}
|
|
3960
|
+
let message = err instanceof Error ? err.message : String(err);
|
|
3961
|
+
throw new AuthError(message);
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
async function requireAuth(cliToken) {
|
|
3965
|
+
let token = typeof cliToken == "string" && cliToken.length > 0 ? cliToken : process.env.NEEDLE_CLOUD_TOKEN;
|
|
3966
|
+
if (!token)
|
|
3967
|
+
throw new AuthError("pass --auth-token or set NEEDLE_CLOUD_TOKEN");
|
|
3968
|
+
await verifyAuthToken(token);
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
// src/cli/index.ts
|
|
3972
|
+
async function gateAuth(authToken, logger) {
|
|
3973
|
+
try {
|
|
3974
|
+
await requireAuth(authToken);
|
|
3975
|
+
} catch (err) {
|
|
3976
|
+
let message = err instanceof AuthError || err instanceof Error ? err.message : String(err);
|
|
3977
|
+
logger.error(`[Needle Build Pipeline] Auth failed: ${message}`), process.exit(ERROR_CODES.AUTH_FAILED);
|
|
3978
|
+
}
|
|
3979
|
+
}
|
|
3980
|
+
program.cast(!1);
|
|
3981
|
+
program.command("version", "Print current version").action(async ({ logger }) => {
|
|
3982
|
+
logger.info(getVersion());
|
|
3983
|
+
}).command("clear-caches", "Clear all caches").help(`Clears all cached files
|
|
3984
|
+
Caches are limited to ${cacheSizeLimit} MB disc space by default.
|
|
3985
|
+
`).action(async ({ logger }) => {
|
|
3986
|
+
logger.info("Clearing caches"), clearCache(logger);
|
|
3987
|
+
}).command("stats", "Calculate glTF stats").help(`
|
|
3988
|
+
`).argument("<input>", "Path to a glTF, GLB or VRM file OR a directory").argument("<output>", "Output path for the stats", { default: null, validator: program.STRING }).option("--verbose", "Enable verbose output", { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).action(async ({ logger, args, options }) => {
|
|
3989
|
+
await gateAuth(options.authToken, logger), logger.level = options.verbose ? "debug" : "info", await ensureHashReady(), logger.info('Calculating stats for "' + args.input + '"');
|
|
3990
|
+
let input = args.input.toString(), filestats = new Array();
|
|
3991
|
+
await foreachGLTF(input, async (file) => {
|
|
3992
|
+
let stats = await calculateStats(file, { verbose: !!options.verbose });
|
|
3993
|
+
filestats.push(stats);
|
|
3994
|
+
});
|
|
3995
|
+
let output = args.output?.toString();
|
|
3996
|
+
output || (isDirectory(input) ? output = path7.join(input, "stats.needle.json") : output = input + ".needle.stats.json"), logger.info("Writing stats to: " + output), writeFileStatsToFile(filestats, output), process.exit(0);
|
|
3997
|
+
}).command("transform", "Transform (progressive loading) and compress glTF, GLB or VRM files").help(`
|
|
3998
|
+
This will produce multiple versions of the input file, each with a different level of optimization.
|
|
3999
|
+
Each version will be compressed and written to the output directory.
|
|
4000
|
+
`).argument("<input>", "The input glTF, GLB or VRM file that should be compressed OR a directory that contains files to be compressed. Multiple files can be separated by commas.", { validator: program.STRING }).argument("<output>", "The output file or directory. It can be an absolute path or a relative path to the input file. If not provided, the input file will be overwritten.", { default: null, validator: program.STRING }).option("--compress", "When enabled files will be compressed", { validator: program.BOOLEAN, default: !0 }).option("--progressive", "When enabled files will processed to be progressively loaded", { validator: program.BOOLEAN, default: !0 }).option("--usecase <usecase>", `The usecase for the compression. This will set the compression settings. Possible options: [${UsecaseOptions.join(", ")}]`, { validator: program.STRING }).option("--config <config>", 'The path to a JSON file containing the compression settings. This can also be a needle.config.json file with a "compression" object or usecase string.', { validator: program.STRING }).option("--cache", `Use "--cache False" to disable caching.
|
|
4001
|
+
When caching is enabled then previously processed files will be detected and loaded from disc cache instead of being processed again if settings or the file contents have not changed.`, { validator: program.BOOLEAN, default: !0 }).option("--debug", 'Enable for more verbose outout with "--debug True"', { validator: program.BOOLEAN, default: !1 }).option("--verbose", 'Enable for more verbose outout with "--verbose True"', { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).action(async ({ logger, args, options }) => {
|
|
4002
|
+
if (await gateAuth(options.authToken, logger), logger.level = options.debug || options.verbose ? "debug" : "info", options.compress === !1 && options.progressive === !1) {
|
|
4003
|
+
logger.error(`[Needle Build Pipeline] v${getVersion()} You need to enable at least one of the options: --compress or --progressive`);
|
|
4004
|
+
return;
|
|
4005
|
+
}
|
|
4006
|
+
await ensureHashReady();
|
|
4007
|
+
let inputPaths = parseInputPaths(args.input.toString()), input = inputPaths[0], isMultiInput = inputPaths.length > 1;
|
|
4008
|
+
logger.info(`[Needle Build Pipeline] v${getVersion()} \u2014 Transform ${isMultiInput ? `${inputPaths.length} files` : `'${input}'`}`);
|
|
4009
|
+
let pipelineMode = [options.progressive && "progressive", options.compress && "compress"].filter(Boolean).join("+");
|
|
4010
|
+
trackPipelineStart({ mode: pipelineMode, usecase: options.usecase?.toString() });
|
|
4011
|
+
let stats = {
|
|
4012
|
+
startTime: Date.now(),
|
|
4013
|
+
totalGPUMemoryInMB: 0,
|
|
4014
|
+
totalFilesProcessed: 0,
|
|
4015
|
+
totalFileSizeInMB: 0,
|
|
4016
|
+
totalFileSizeInMBBefore: 0
|
|
4017
|
+
}, config = getConfig(options.config?.toString(), input, {
|
|
4018
|
+
logger
|
|
4019
|
+
});
|
|
4020
|
+
options.usecase && (logger.info("Using usecase: " + options.usecase), config = { ...createConfig(options.usecase.toString()), ...config }, config.usecase != "default" && config.usecase != options.usecase.toString() ? logger.warn(`Conflicting usecase. Your specific config at "${options.config}" has a different usecase than the one provided by the CLI: "${options.usecase}". Using the usecase from the config file.`) : config.usecase = options.usecase.toString());
|
|
4021
|
+
let inputIsDirectory = !isMultiInput && isDirectory(input), output = args.output?.toString();
|
|
4022
|
+
isMultiInput && output && !isDirectory(output) && (logger.error("When <input> contains multiple files then <output> must be a directory"), trackError(new Error("Invalid args: multi-input but output is not a directory"), { mode: pipelineMode }), process.exit(ERROR_CODES.INVALID_ARGS)), !inputIsDirectory && !isMultiInput && !output && (output = input);
|
|
4023
|
+
let outputIsDirectory = output && isDirectory(output);
|
|
4024
|
+
if (inputIsDirectory && output && !outputIsDirectory && (logger.error("When <input> is a directory then <output> must also be a directory"), trackError(new Error("Invalid args: input is directory but output is not"), { mode: pipelineMode }), process.exit(ERROR_CODES.INVALID_ARGS)), output && path7.isAbsolute(output) === !1) {
|
|
4025
|
+
let base = ensureIsDirectory(input);
|
|
4026
|
+
output = resolve3(base, output);
|
|
4027
|
+
}
|
|
4028
|
+
let set = /* @__PURE__ */ new Set(), useCache = options.cache !== !1, debug = options.debug === !0, verbose = options.verbose === !0;
|
|
4029
|
+
await foreachGLTF(inputPaths, async (file) => {
|
|
4030
|
+
if (existsSync13(file)) {
|
|
4031
|
+
if (file != input && options.progressive === !0 && isLOD(file)) {
|
|
4032
|
+
logger.debug(`\u2192 Ignore existing LOD file at ${file}`);
|
|
251
4033
|
return;
|
|
4034
|
+
}
|
|
4035
|
+
} else if (isLOD(file)) {
|
|
4036
|
+
logger.warn(`WARN: Ignore previously found file that does not exist anymore: "${file}"`);
|
|
4037
|
+
return;
|
|
4038
|
+
} else
|
|
4039
|
+
logger.error(`ERR: Previously found file is now missing: "${file}"`), trackError(new Error(`Lost file: ${file}`), { mode: pipelineMode, usecase: options.usecase?.toString(), file }), process.exit(ERROR_CODES.LOST_FILE);
|
|
4040
|
+
let jobKey = useCache ? computeJobKey({
|
|
4041
|
+
compress: options.compress === !0,
|
|
4042
|
+
progressive: options.progressive === !0,
|
|
4043
|
+
config
|
|
4044
|
+
}, file) : void 0;
|
|
4045
|
+
if (jobKey) {
|
|
4046
|
+
let outputDir = output ? existsSync13(output) && isDirectory(output) ? output : dirname8(output) : dirname8(file), restored = tryRestoreJobResult(jobKey, outputDir, logger);
|
|
4047
|
+
if (restored) {
|
|
4048
|
+
let inputFileSize = statSync7(file).size / 1024 / 1024;
|
|
4049
|
+
for (let f of restored)
|
|
4050
|
+
if (set.add(f), stats) {
|
|
4051
|
+
let sizeInMB = statSync7(f).size / 1024 / 1024;
|
|
4052
|
+
stats.totalFilesProcessed++, stats.totalFileSizeInMB += sizeInMB, stats.totalFileSizeInMBBefore += inputFileSize;
|
|
4053
|
+
}
|
|
4054
|
+
logger.info(`\u2192 [CACHE] Restored ${restored.length} file(s) for job ${jobKey}`);
|
|
4055
|
+
return;
|
|
4056
|
+
}
|
|
252
4057
|
}
|
|
253
|
-
|
|
254
|
-
|
|
4058
|
+
logger.info(`\u2192 Transform ${file}`);
|
|
4059
|
+
let progressive_results = new Array();
|
|
4060
|
+
options.progressive === !0 && (await make_progressive({
|
|
4061
|
+
path: file,
|
|
4062
|
+
outpath: output,
|
|
4063
|
+
results: progressive_results,
|
|
4064
|
+
config,
|
|
4065
|
+
debug,
|
|
4066
|
+
verbose,
|
|
4067
|
+
useCache,
|
|
4068
|
+
logger
|
|
4069
|
+
}).catch((err) => {
|
|
4070
|
+
logger.error(err), trackError(err, { mode: pipelineMode, usecase: options.usecase?.toString(), file }), process.exit(ERROR_CODES.PROGRESSIVE_FAILED);
|
|
4071
|
+
}) === !1 && (trackError(new Error("Progressive processing returned false"), { mode: pipelineMode, usecase: options.usecase?.toString(), file }), process.exit(ERROR_CODES.PROGRESSIVE_FAILED)), verbose && console.log(`Progressive results:
|
|
4072
|
+
`, progressive_results));
|
|
4073
|
+
let externalFiles = [];
|
|
4074
|
+
if (options.compress === !0) {
|
|
4075
|
+
let opts = {
|
|
4076
|
+
config,
|
|
4077
|
+
stats,
|
|
4078
|
+
packedFiles: set,
|
|
4079
|
+
debug,
|
|
4080
|
+
verbose,
|
|
4081
|
+
useCache,
|
|
4082
|
+
logger,
|
|
4083
|
+
// When progressive ran first, inputFile points to the progressive output copy.
|
|
4084
|
+
// Pass the original source path so extensions can resolve sibling assets (e.g. .exr files).
|
|
4085
|
+
sourceFile: progressive_results.length > 0 ? file : void 0,
|
|
4086
|
+
externalFiles
|
|
4087
|
+
};
|
|
4088
|
+
if (progressive_results.length > 0)
|
|
4089
|
+
for (let res of progressive_results)
|
|
4090
|
+
await packGLTF(
|
|
4091
|
+
res,
|
|
4092
|
+
res,
|
|
4093
|
+
opts
|
|
4094
|
+
) === !1 && (trackError(new Error("Packing failed"), { mode: pipelineMode, usecase: options.usecase?.toString(), file: res }), process.exit(ERROR_CODES.PACKING_FAILED));
|
|
4095
|
+
else
|
|
4096
|
+
await packGLTF(
|
|
4097
|
+
file,
|
|
4098
|
+
output,
|
|
4099
|
+
opts
|
|
4100
|
+
) === !1 && (trackError(new Error("Packing failed"), { mode: pipelineMode, usecase: options.usecase?.toString(), file }), process.exit(ERROR_CODES.PACKING_FAILED));
|
|
4101
|
+
}
|
|
4102
|
+
if (jobKey) {
|
|
4103
|
+
let allOutputFiles = progressive_results.length > 0 ? progressive_results : [output || file];
|
|
4104
|
+
saveJobResult(jobKey, [...allOutputFiles, ...externalFiles], logger);
|
|
4105
|
+
}
|
|
4106
|
+
}), printStats(stats, logger, config), trackPipelineEnd({
|
|
4107
|
+
mode: pipelineMode,
|
|
4108
|
+
usecase: config?.usecase?.toString(),
|
|
4109
|
+
filesProcessed: stats.totalFilesProcessed,
|
|
4110
|
+
sizeBefore_MB: stats.totalFileSizeInMBBefore,
|
|
4111
|
+
sizeAfter_MB: stats.totalFileSizeInMB,
|
|
4112
|
+
gpuMemory_MB: stats.totalGPUMemoryInMB,
|
|
4113
|
+
duration_ms: Date.now() - stats.startTime
|
|
4114
|
+
}), useCache && limitCacheSize();
|
|
4115
|
+
}).command("pmrem", "Convert EXR / HDR files to PMREM-processed KTX2 HDR (Needle PMREM)").help(`Runs the PMREM WASM + basisu encoder on .exr or .hdr (Radiance RGBE) files,
|
|
4116
|
+
producing <name>.pmrem.ktx2. This is the same processing the Needle build pipeline
|
|
4117
|
+
applies to EXR textures inside GLB/GLTF files, exposed as a standalone command for
|
|
4118
|
+
raw .exr / .hdr inputs.
|
|
4119
|
+
`).argument("<input>", "Path to a .exr/.hdr file OR a directory containing .exr/.hdr files (recursive)", { validator: program.STRING }).argument("<output>", "Output file (when input is a single .exr/.hdr) or output directory. Defaults to writing next to the input file.", { default: null, validator: program.STRING }).option("--cache", 'Use "--cache False" to disable caching.', { validator: program.BOOLEAN, default: !0 }).option("--debug", 'Enable verbose output with "--debug True"', { validator: program.BOOLEAN, default: !1 }).option("--verbose", 'Enable verbose output with "--verbose True"', { validator: program.BOOLEAN, default: !1 }).option("--auth-token <jwt>", "Required. A JWT minted by needle-cloud (alternatively set NEEDLE_CLOUD_TOKEN). Note: an `nc_*` needle-cloud access token is NOT a JWT and will be rejected.", { validator: program.STRING }).hide().action(async ({ logger, args, options }) => {
|
|
4120
|
+
await gateAuth(options.authToken, logger), logger.level = options.debug || options.verbose ? "debug" : "info", await ensureHashReady();
|
|
4121
|
+
let input = args.input.toString();
|
|
4122
|
+
existsSync13(input) || (logger.error(`Input does not exist: ${input}`), process.exit(ERROR_CODES.INVALID_ARGS));
|
|
4123
|
+
let inputFiles = [], inputIsDirectory = isDirectory(input);
|
|
4124
|
+
if (inputIsDirectory ? collectPmremInputFiles(input, inputFiles) : isPmremInputFile(input) ? inputFiles.push(input) : (logger.error(`Input is not an .exr/.hdr file or directory: ${input}`), process.exit(ERROR_CODES.INVALID_ARGS)), inputFiles.length === 0) {
|
|
4125
|
+
logger.warn(`No .exr/.hdr files found in ${input}`);
|
|
4126
|
+
return;
|
|
4127
|
+
}
|
|
4128
|
+
let rawOutput = args.output?.toString() || null, outputArg = rawOutput && rawOutput !== "null" ? rawOutput : null;
|
|
4129
|
+
if (outputArg && !path7.isAbsolute(outputArg)) {
|
|
4130
|
+
let base = inputIsDirectory ? input : dirname8(input);
|
|
4131
|
+
outputArg = resolve3(base, outputArg);
|
|
4132
|
+
}
|
|
4133
|
+
let useCache = options.cache !== !1;
|
|
4134
|
+
logger.info(`[Needle Build Pipeline] v${getVersion()} \u2014 pmrem: ${inputFiles.length} file(s)`);
|
|
4135
|
+
let runtime = await createPmremRuntime(logger);
|
|
4136
|
+
runtime || (logger.error("pmrem runtime is not available (WASM or basisu binary missing). Run `npm run build:pmrem` in the package directory."), process.exit(ERROR_CODES.PACKING_FAILED));
|
|
4137
|
+
try {
|
|
4138
|
+
for (let inPath of inputFiles) {
|
|
4139
|
+
let outPath = resolvePmremOutputPath(inPath, input, inputIsDirectory, outputArg);
|
|
4140
|
+
logger.info(`\u2192 pmrem ${inPath} \u2192 ${outPath}`);
|
|
4141
|
+
let srcBytes = readFileSync10(inPath), bytes = new Uint8Array(srcBytes.buffer, srcBytes.byteOffset, srcBytes.byteLength), ktx2Bytes = await (inPath.toLowerCase().endsWith(".hdr") ? convertHdrBytesToPmremKtx2 : convertExrBytesToPmremKtx2)(
|
|
4142
|
+
runtime,
|
|
4143
|
+
bytes,
|
|
4144
|
+
{ useCache, logLabel: `pmrem ${basename4(inPath)}` }
|
|
4145
|
+
);
|
|
4146
|
+
writeFileSync7(outPath, ktx2Bytes);
|
|
4147
|
+
}
|
|
4148
|
+
} finally {
|
|
4149
|
+
await disposePmremRuntime(runtime);
|
|
4150
|
+
}
|
|
4151
|
+
useCache && limitCacheSize();
|
|
4152
|
+
});
|
|
4153
|
+
function isPmremInputFile(name) {
|
|
4154
|
+
let lower = name.toLowerCase();
|
|
4155
|
+
return lower.endsWith(".exr") || lower.endsWith(".hdr");
|
|
4156
|
+
}
|
|
4157
|
+
function collectPmremInputFiles(dir, out) {
|
|
4158
|
+
for (let entry of readdirSync3(dir)) {
|
|
4159
|
+
if (entry === "node_modules" || entry.startsWith(".")) continue;
|
|
4160
|
+
let full = path7.join(dir, entry);
|
|
4161
|
+
statSync7(full).isDirectory() ? collectPmremInputFiles(full, out) : isPmremInputFile(entry) && out.push(full);
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4164
|
+
function resolvePmremOutputPath(srcPath, input, inputIsDirectory, outputArg) {
|
|
4165
|
+
let outName = basename4(srcPath).replace(/\.(exr|hdr)$/i, ".pmrem.ktx2");
|
|
4166
|
+
if (!outputArg)
|
|
4167
|
+
return path7.join(dirname8(srcPath), outName);
|
|
4168
|
+
if (inputIsDirectory) {
|
|
4169
|
+
let rel = path7.relative(input, srcPath), relDir = dirname8(rel), outDir = relDir === "." ? outputArg : path7.join(outputArg, relDir);
|
|
4170
|
+
return ensureIsDirectory(outDir), path7.join(outDir, outName);
|
|
4171
|
+
}
|
|
4172
|
+
return existsSync13(outputArg) && isDirectory(outputArg) ? path7.join(outputArg, outName) : outputArg.toLowerCase().endsWith(".ktx2") ? (ensureIsDirectory(dirname8(outputArg)), outputArg) : (ensureIsDirectory(outputArg), path7.join(outputArg, outName));
|
|
4173
|
+
}
|
|
4174
|
+
program.run().catch((err) => {
|
|
4175
|
+
if (!(err.message.includes("Unknown command") && !err.message.includes("Did you mean")))
|
|
4176
|
+
throw trackError(err), err;
|
|
255
4177
|
});
|