-
-
Notifications
You must be signed in to change notification settings - Fork 148
/
dedup.ts
executable file
·309 lines (263 loc) · 9.9 KB
/
dedup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
137
138
139
140
141
142
143
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import {
Accessor,
BufferUtils,
Document,
ILogger,
Material,
Mesh,
Primitive,
PrimitiveTarget,
PropertyType,
Root,
Texture,
Transform,
} from '@gltf-transform/core';
import { createTransform } from './utils';
const NAME = 'dedup';
export interface DedupOptions {
/** List of {@link PropertyType} identifiers to be de-duplicated.*/
propertyTypes: string[];
}
const DEDUP_DEFAULTS: Required<DedupOptions> = {
propertyTypes: [PropertyType.ACCESSOR, PropertyType.MESH, PropertyType.TEXTURE, PropertyType.MATERIAL],
};
/**
* Removes duplicate {@link Accessor}, {@link Mesh}, {@link Texture}, and {@link Material}
* properties. Partially based on a
* [gist by mattdesl](https://gist.github.com/mattdesl/aea40285e2d73916b6b9101b36d84da8). Only
* accessors in mesh primitives, morph targets, and animation samplers are processed.
*
* Example:
*
* ```ts
* document.getRoot().listMeshes(); // → [Mesh, Mesh, Mesh]
*
* await document.transform(dedup({propertyTypes: [PropertyType.MESH]}));
*
* document.getRoot().listMeshes(); // → [Mesh]
* ```
*/
export const dedup = function (_options: DedupOptions = DEDUP_DEFAULTS): Transform {
const options = { ...DEDUP_DEFAULTS, ..._options } as Required<DedupOptions>;
const propertyTypes = new Set(options.propertyTypes);
for (const propertyType of options.propertyTypes) {
if (!DEDUP_DEFAULTS.propertyTypes.includes(propertyType)) {
throw new Error(`${NAME}: Unsupported deduplication on type "${propertyType}".`);
}
}
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();
if (propertyTypes.has(PropertyType.ACCESSOR)) dedupAccessors(logger, doc);
if (propertyTypes.has(PropertyType.TEXTURE)) dedupImages(logger, doc);
if (propertyTypes.has(PropertyType.MATERIAL)) dedupMaterials(logger, doc);
if (propertyTypes.has(PropertyType.MESH)) dedupMeshes(logger, doc);
logger.debug(`${NAME}: Complete.`);
});
};
function dedupAccessors(logger: ILogger, doc: Document): void {
// Find all accessors used for mesh data.
const indicesAccessors: Set<Accessor> = new Set();
const attributeAccessors: Set<Accessor> = new Set();
const inputAccessors: Set<Accessor> = new Set();
const outputAccessors: Set<Accessor> = new Set();
const meshes = doc.getRoot().listMeshes();
meshes.forEach((mesh) => {
mesh.listPrimitives().forEach((primitive) => {
primitive.listAttributes().forEach((accessor) => attributeAccessors.add(accessor));
const indices = primitive.getIndices();
if (indices) indicesAccessors.add(indices);
});
});
for (const animation of doc.getRoot().listAnimations()) {
for (const sampler of animation.listSamplers()) {
const input = sampler.getInput();
const output = sampler.getOutput();
if (input) inputAccessors.add(input);
if (output) outputAccessors.add(output);
}
}
// Find duplicate accessors of a given type.
function detectDuplicates(accessors: Accessor[]): Map<Accessor, Accessor> {
const duplicateAccessors: Map<Accessor, Accessor> = new Map();
for (let i = 0; i < accessors.length; i++) {
const a = accessors[i];
const aData = BufferUtils.toView(a.getArray()!);
if (duplicateAccessors.has(a)) continue;
for (let j = 0; j < accessors.length; j++) {
const b = accessors[j];
if (a === b) continue;
if (duplicateAccessors.has(b)) continue;
if (a.getType() !== b.getType()) continue;
if (a.getComponentType() !== b.getComponentType()) continue;
if (a.getCount() !== b.getCount()) continue;
if (a.getNormalized() !== b.getNormalized()) continue;
if (BufferUtils.equals(aData, BufferUtils.toView(b.getArray()!))) {
duplicateAccessors.set(b, a);
}
}
}
return duplicateAccessors;
}
const duplicateIndices = detectDuplicates(Array.from(indicesAccessors));
logger.debug(`${NAME}: Found ${duplicateIndices.size} duplicates among ${indicesAccessors.size} indices.`);
const duplicateAttributes = detectDuplicates(Array.from(attributeAccessors));
logger.debug(
`${NAME}: Found ${duplicateAttributes.size} duplicates among ${attributeAccessors.size}` + ' attributes.'
);
const duplicateInputs = detectDuplicates(Array.from(inputAccessors));
const duplicateOutputs = detectDuplicates(Array.from(outputAccessors));
logger.debug(
`${NAME}: Found ${duplicateInputs.size + duplicateOutputs.size} duplicates among` +
` ${inputAccessors.size + outputAccessors.size} animation accessors.`
);
// Dissolve duplicate vertex attributes and indices.
meshes.forEach((mesh) => {
mesh.listPrimitives().forEach((primitive) => {
primitive.listAttributes().forEach((accessor) => {
if (duplicateAttributes.has(accessor)) {
primitive.swap(accessor, duplicateAttributes.get(accessor) as Accessor);
}
});
const indices = primitive.getIndices();
if (indices && duplicateIndices.has(indices)) {
primitive.swap(indices, duplicateIndices.get(indices) as Accessor);
}
});
});
Array.from(duplicateIndices.keys()).forEach((indices) => indices.dispose());
Array.from(duplicateAttributes.keys()).forEach((attribute) => attribute.dispose());
// Dissolve duplicate animation sampler inputs and outputs.
for (const animation of doc.getRoot().listAnimations()) {
for (const sampler of animation.listSamplers()) {
const input = sampler.getInput();
const output = sampler.getOutput();
if (input && duplicateInputs.has(input)) {
sampler.swap(input, duplicateInputs.get(input) as Accessor);
}
if (output && duplicateOutputs.has(output)) {
sampler.swap(output, duplicateOutputs.get(output) as Accessor);
}
}
}
Array.from(duplicateInputs.keys()).forEach((input) => input.dispose());
Array.from(duplicateOutputs.keys()).forEach((output) => output.dispose());
}
function dedupMeshes(logger: ILogger, doc: Document): void {
const root = doc.getRoot();
// Create Reference -> ID lookup table.
const refs = new Map<Accessor | Material, number>();
root.listAccessors().forEach((accessor, index) => refs.set(accessor, index));
root.listMaterials().forEach((material, index) => refs.set(material, index));
// For each mesh, create a hashkey.
const numMeshes = root.listMeshes().length;
const uniqueMeshes = new Map<string, Mesh>();
for (const src of root.listMeshes()) {
// For each mesh, create a hashkey.
const srcKeyItems = [];
for (const prim of src.listPrimitives()) {
srcKeyItems.push(createPrimitiveKey(prim, refs));
}
// If another mesh exists with the same key, replace all instances with that, and dispose
// of the duplicate. If not, just cache it.
const meshKey = srcKeyItems.join(';');
if (uniqueMeshes.has(meshKey)) {
const targetMesh = uniqueMeshes.get(meshKey)!;
src.listParents().forEach((parent) => {
if (parent.propertyType !== PropertyType.ROOT) {
parent.swap(src, targetMesh);
}
});
src.dispose();
} else {
uniqueMeshes.set(meshKey, src);
}
}
logger.debug(`${NAME}: Found ${numMeshes - uniqueMeshes.size} duplicates among ${numMeshes} meshes.`);
}
function dedupImages(logger: ILogger, doc: Document): void {
const root = doc.getRoot();
const textures = root.listTextures();
const duplicates: Map<Texture, Texture> = new Map();
// Compare each texture to every other texture — O(n²) — and mark duplicates for replacement.
for (let i = 0; i < textures.length; i++) {
const a = textures[i];
const aData = a.getImage();
if (duplicates.has(a)) continue;
for (let j = 0; j < textures.length; j++) {
const b = textures[j];
const bData = b.getImage();
if (a === b) continue;
if (duplicates.has(b)) continue;
// URIs are intentionally not compared.
if (a.getMimeType() !== b.getMimeType()) continue;
const aSize = a.getSize();
const bSize = b.getSize();
if (!aSize || !bSize) continue;
if (aSize[0] !== bSize[0]) continue;
if (aSize[1] !== bSize[1]) continue;
if (!aData || !bData) continue;
if (BufferUtils.equals(aData, bData)) {
duplicates.set(b, a);
}
}
}
logger.debug(`${NAME}: Found ${duplicates.size} duplicates among ${root.listTextures().length} textures.`);
Array.from(duplicates.entries()).forEach(([src, dst]) => {
src.listParents().forEach((property) => {
if (!(property instanceof Root)) property.swap(src, dst);
});
src.dispose();
});
}
function dedupMaterials(logger: ILogger, doc: Document): void {
const root = doc.getRoot();
const materials = root.listMaterials();
const duplicates: Map<Material, Material> = new Map();
const skip = new Set(['name']);
// Compare each material to every other material — O(n²) — and mark duplicates for replacement.
for (let i = 0; i < materials.length; i++) {
const a = materials[i];
if (duplicates.has(a)) continue;
for (let j = 0; j < materials.length; j++) {
const b = materials[j];
if (a === b) continue;
if (duplicates.has(b)) continue;
if (a.equals(b, skip)) {
duplicates.set(b, a);
}
}
}
logger.debug(
// eslint-disable-next-line max-len
`${NAME}: Found ${duplicates.size} duplicates among ${root.listMaterials().length} materials.`
);
Array.from(duplicates.entries()).forEach(([src, dst]) => {
src.listParents().forEach((property) => {
if (!(property instanceof Root)) property.swap(src, dst);
});
src.dispose();
});
}
/** Generates a key unique to the content of a primitive or target. */
function createPrimitiveKey(prim: Primitive | PrimitiveTarget, refs: Map<Accessor | Material, number>): string {
const primKeyItems = [];
for (const semantic of prim.listSemantics()) {
const attribute = prim.getAttribute(semantic)!;
primKeyItems.push(semantic + ':' + refs.get(attribute));
}
if (prim instanceof Primitive) {
const indices = prim.getIndices();
if (indices) {
primKeyItems.push('indices:' + refs.get(indices));
}
const material = prim.getMaterial();
if (material) {
primKeyItems.push('material:' + refs.get(material));
}
primKeyItems.push('mode:' + prim.getMode());
for (const target of prim.listTargets()) {
primKeyItems.push('target:' + createPrimitiveKey(target, refs));
}
}
return primKeyItems.join(',');
}