forked from webaverse/app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeometry-texture-atlas.js
More file actions
590 lines (541 loc) · 17.7 KB
/
Copy pathgeometry-texture-atlas.js
File metadata and controls
590 lines (541 loc) · 17.7 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import * as THREE from 'three';
import {MaxRectsPacker} from 'maxrects-packer';
import {getRenderer} from './renderer.js';
import {modUv} from './util.js';
const defaultTextureSize = 4096;
const startAtlasSize = 512;
const localVector2D = new THREE.Vector2();
const localVector2D2 = new THREE.Vector2();
const textureTypes = ['map', 'emissiveMap', 'normalMap', 'shadeTexture'];
class AttributeLayout {
constructor(name, TypedArrayConstructor, itemSize) {
this.name = name;
this.TypedArrayConstructor = TypedArrayConstructor;
this.itemSize = itemSize;
this.count = 0;
}
makeDefault(g) {
return new THREE.BufferAttribute(
new this.TypedArrayConstructor(
g.attributes.position.count * this.itemSize,
),
this.itemSize,
);
}
}
class MorphAttributeLayout extends AttributeLayout {
constructor(name, TypedArrayConstructor, itemSize, arraySize) {
super(name, TypedArrayConstructor, itemSize);
this.arraySize = arraySize;
}
makeDefault(g) {
return Array(this.arraySize).fill(super.makeDefault(g));
}
}
const getObjectKeyDefault = (type, object, material) => {
const renderer = getRenderer();
return [type, renderer.getProgramCacheKey(object, material)].join(',');
};
export const getMergeableObjects = (
model,
getObjectKey = getObjectKeyDefault,
) => {
const mergeables = new Map();
model.traverse(o => {
if (o.isMesh && o.geometry.type === 'BufferGeometry') {
let type;
if (o.isSkinnedMesh) {
type = 'skinnedMesh';
} else {
type = 'mesh';
}
const objectGeometry = o.geometry;
const morphTargetDictionary = o.morphTargetDictionary;
const morphTargetInfluences = o.morphTargetInfluences;
const objectMaterials = Array.isArray(o.material)
? o.material
: [o.material];
for (const objectMaterial of objectMaterials) {
const {
map = null,
emissiveMap = null,
normalMap = null,
shadeTexture = null,
} = objectMaterial;
const skeleton = o.skeleton ?? null;
const key = getObjectKey(type, o, objectMaterial);
let m = mergeables.get(key);
if (!m) {
m = {
type,
material: objectMaterial,
geometries: [],
maps: [],
emissiveMaps: [],
normalMaps: [],
shadeTextures: [],
skeletons: [],
morphTargetDictionaryArray: [],
morphTargetInfluencesArray: [],
};
mergeables.set(key, m);
}
m.geometries.push(objectGeometry);
m.maps.push(map);
m.emissiveMaps.push(emissiveMap);
m.normalMaps.push(normalMap);
m.shadeTextures.push(shadeTexture);
m.skeletons.push(skeleton);
m.morphTargetDictionaryArray.push(morphTargetDictionary);
m.morphTargetInfluencesArray.push(morphTargetInfluences);
}
}
});
return Array.from(mergeables.values());
};
export const mergeGeometryTextureAtlas = (mergeable, textureSize) => {
const {
type,
material,
geometries,
maps,
emissiveMaps,
normalMaps,
skeletons,
morphTargetDictionaryArray,
morphTargetInfluencesArray,
} = mergeable;
// compute texture sizes
const textureSizes = maps.map((map, i) => {
const emissiveMap = emissiveMaps[i];
const normalMap = normalMaps[i];
const maxSize = new THREE.Vector2(0, 0);
if (map) {
maxSize.x = Math.max(maxSize.x, map.image.width);
maxSize.y = Math.max(maxSize.y, map.image.height);
}
if (emissiveMap) {
maxSize.x = Math.max(maxSize.x, emissiveMap.image.width);
maxSize.y = Math.max(maxSize.y, emissiveMap.image.height);
}
if (normalMap) {
maxSize.x = Math.max(maxSize.x, normalMap.image.width);
maxSize.y = Math.max(maxSize.y, normalMap.image.height);
}
return maxSize;
});
// generate atlas layouts
const _packAtlases = () => {
const _attemptPack = (textureSizes, atlasSize) => {
const maxRectsPacker = new MaxRectsPacker(atlasSize, atlasSize, 1);
const rects = textureSizes.map((textureSize, index) => {
const {x: width, y: height} = textureSize;
return {
width,
height,
data: {
index,
},
};
});
maxRectsPacker.addArray(rects);
let oversized = maxRectsPacker.bins.length > 1;
maxRectsPacker.bins.forEach(bin => {
bin.rects.forEach(rect => {
if (rect.oversized) {
oversized = true;
}
});
});
if (!oversized) {
return maxRectsPacker;
} else {
return null;
}
};
const hasTextures = textureSizes.some(
textureSize => textureSize.x > 0 || textureSize.y > 0,
);
if (hasTextures) {
let atlas;
let atlasSize = startAtlasSize;
while (!(atlas = _attemptPack(textureSizes, atlasSize))) {
atlasSize *= 2;
}
return atlas;
} else {
return null;
}
};
const atlas = _packAtlases();
// draw atlas images
const originalTextures = new Map(); // map of canvas to the texture that generated it
const _drawAtlasImages = atlas => {
const _getTexturesKey = textures =>
textures.map(t => (t ? t.uuid : '')).join(',');
const _drawAtlasImage = textures => {
if (atlas && textures.some(t => t !== null)) {
const canvasSize = Math.min(atlas.width, textureSize);
const canvasScale = canvasSize / atlas.width;
const canvas = document.createElement('canvas');
canvas.width = canvasSize;
canvas.height = canvasSize;
const ctx = canvas.getContext('2d');
atlas.bins.forEach(bin => {
bin.rects.forEach(rect => {
const {
x,
y,
width: w,
height: h,
data: {index},
} = rect;
const texture = textures[index];
if (texture) {
const image = texture.image;
// draw the image in the correct box on the canvas
const tx = x * canvasScale;
const ty = y * canvasScale;
const tw = w * canvasScale;
const th = h * canvasScale;
ctx.drawImage(
image,
0,
0,
image.width,
image.height,
tx,
ty,
tw,
th,
);
if (!originalTextures.has(canvas)) {
originalTextures.set(canvas, texture);
}
}
});
});
return canvas;
} else {
return null;
}
};
const atlasImages = {};
const atlasImagesMap = new Map(); // cache to alias identical textures
for (const textureType of textureTypes) {
const textures = mergeable[`${textureType}s`];
const key = _getTexturesKey(textures);
let atlasImage = atlasImagesMap.get(key);
if (atlasImage === undefined) {
// cache miss
atlasImage = _drawAtlasImage(textures);
if (atlasImage !== null) {
atlasImage.key = key;
}
atlasImagesMap.set(key, atlasImage);
}
atlasImages[textureType] = atlasImage;
}
return atlasImages;
};
const atlasImages = _drawAtlasImages(atlas);
/* // XXX debug
{
const debugWidth = 300;
let textureTypeIndex = 0;
for (const textureType of textureTypes) {
const atlasImage = atlasImages[textureType];
if (atlasImage) {
atlasImage.style.cssText = `\
position: fixed;
top: ${mergeableIndex * debugWidth}px;
left: ${textureTypeIndex * debugWidth}px;
min-width: ${debugWidth}px;
max-width: ${debugWidth}px;
min-height: ${debugWidth}px;
z-index: 100;
`;
atlasImage.setAttribute('type', textureType);
document.body.appendChild(atlasImage);
textureTypeIndex++;
}
}
} */
// build attribute layouts
const _makeAttributeLayoutsFromGeometries = geometries => {
const attributeLayouts = [];
for (const g of geometries) {
const attributes = g.attributes;
for (const attributeName in attributes) {
const attribute = attributes[attributeName];
let layout = attributeLayouts.find(
layout => layout.name === attributeName,
);
if (layout) {
// sanity check that item size is the same
if (layout.itemSize !== attribute.itemSize) {
throw new Error(
`attribute ${attributeName} has different itemSize: ${layout.itemSize}, ${attribute.itemSize}`,
);
}
} else {
layout = new AttributeLayout(
attributeName,
attribute.array.constructor,
attribute.itemSize,
);
attributeLayouts.push(layout);
}
layout.count += attribute.count * attribute.itemSize;
}
}
return attributeLayouts;
};
const attributeLayouts = _makeAttributeLayoutsFromGeometries(geometries);
const _makeMorphAttributeLayoutsFromGeometries = geometries => {
// create morph layouts
const morphAttributeLayouts = [];
for (const g of geometries) {
const morphAttributes = g.morphAttributes;
for (const morphAttributeName in morphAttributes) {
const morphAttribute = morphAttributes[morphAttributeName];
let morphLayout = morphAttributeLayouts.find(
l => l.name === morphAttributeName,
);
if (!morphLayout) {
morphLayout = new MorphAttributeLayout(
morphAttributeName,
morphAttribute[0].array.constructor,
morphAttribute[0].itemSize,
morphAttribute.length,
);
morphAttributeLayouts.push(morphLayout);
}
morphLayout.count +=
morphAttribute[0].count * morphAttribute[0].itemSize;
}
}
return morphAttributeLayouts;
};
const morphAttributeLayouts =
_makeMorphAttributeLayoutsFromGeometries(geometries);
// console.log('got attribute layouts', attributeLayouts, morphAttributeLayouts);
const _forceGeometriesAttributeLayouts = (attributeLayouts, geometries) => {
for (const layout of attributeLayouts) {
for (const g of geometries) {
let gAttribute = g.attributes[layout.name];
if (!gAttribute) {
if (layout.name === 'skinIndex' || layout.name === 'skinWeight') {
gAttribute = layout.makeDefault(g);
g.setAttribute(layout.name, gAttribute);
layout.count += gAttribute.count * gAttribute.itemSize;
} else {
throw new Error(`unknown layout ${layout.name}`);
}
}
}
}
for (const morphLayout of morphAttributeLayouts) {
for (const g of geometries) {
let morphAttribute = g.morphAttributes[morphLayout.name];
if (!morphAttribute) {
// console.log('missing morph attribute', morphLayout, morphAttribute);
morphAttribute = morphLayout.makeDefault(g);
g.morphAttributes[morphLayout.name] = morphAttribute;
morphLayout.count +=
morphAttribute[0].count * morphAttribute[0].itemSize;
/* if (layout.name === 'skinIndex' || layout.name === 'skinWeight') {
gAttribute = new THREE.BufferAttribute(new Float32Array(g.attributes.position.count * layout.itemSize), layout.itemSize);
g.setAttribute(layout.name, gAttribute);
} else {
throw new Error(`unknown layout ${layout.name}`);
} */
}
}
}
};
const _mergeAttributes = (geometry, geometries, attributeLayouts) => {
for (const layout of attributeLayouts) {
const attributeData = new layout.TypedArrayConstructor(layout.count);
const attribute = new THREE.BufferAttribute(
attributeData,
layout.itemSize,
);
let attributeDataIndex = 0;
for (const g of geometries) {
const gAttribute = g.attributes[layout.name];
attributeData.set(gAttribute.array, attributeDataIndex);
attributeDataIndex += gAttribute.count * gAttribute.itemSize;
}
// sanity check
if (attributeDataIndex !== layout.count) {
console.warn(
'desynced attribute data 1',
layout.name,
attributeDataIndex,
layout.count,
);
debugger;
}
geometry.setAttribute(layout.name, attribute);
}
};
const _mergeMorphAttributes = (
geometry,
geometries,
morphAttributeLayouts,
) => {
for (const morphLayout of morphAttributeLayouts) {
const morphsArray = Array(morphLayout.arraySize);
for (let i = 0; i < morphLayout.arraySize; i++) {
const morphData = new morphLayout.TypedArrayConstructor(
morphLayout.count,
);
const morphAttribute = new THREE.BufferAttribute(
morphData,
morphLayout.itemSize,
);
morphsArray[i] = morphAttribute;
let morphDataIndex = 0;
for (const g of geometries) {
let gMorphAttribute = g.morphAttributes[morphLayout.name];
gMorphAttribute = gMorphAttribute?.[i];
if (gMorphAttribute) {
morphData.set(gMorphAttribute.array, morphDataIndex);
morphDataIndex += gMorphAttribute.count * gMorphAttribute.itemSize;
} else {
const matchingAttribute = g.attributes[morphLayout.name];
morphDataIndex +=
matchingAttribute.count * matchingAttribute.itemSize;
}
}
// sanity check
if (morphDataIndex !== morphLayout.count) {
console.warn(
'desynced morph data 2',
morphLayout.name,
morphDataIndex,
morphLayout.count,
);
}
}
geometry.morphAttributes[morphLayout.name] = morphsArray;
}
};
const _mergeIndices = (geometry, geometries) => {
let indexCount = 0;
for (const g of geometries) {
indexCount += g.index.count;
}
const indexData = new Uint32Array(indexCount);
let positionOffset = 0;
let indexOffset = 0;
for (const g of geometries) {
const srcIndexData = g.index.array;
for (let i = 0; i < srcIndexData.length; i++) {
indexData[indexOffset++] = srcIndexData[i] + positionOffset;
}
positionOffset += g.attributes.position.count;
}
geometry.setIndex(new THREE.BufferAttribute(indexData, 1));
};
const _remapGeometryUvs = (geometry, geometries) => {
if (atlas) {
let uvIndex = 0;
const geometryUvOffsets = geometries.map(g => {
const start = uvIndex;
const count = g.attributes.uv.count;
uvIndex += count;
return {
start,
count,
};
});
const canvasSize = Math.min(atlas.width, textureSize);
const canvasScale = canvasSize / atlas.width;
atlas.bins.forEach(bin => {
bin.rects.forEach(rect => {
const {
x,
y,
width: w,
height: h,
data: {index},
} = rect;
if (w > 0 && h > 0) {
const {start, count} = geometryUvOffsets[index];
const tx = x * canvasScale;
const ty = y * canvasScale;
const tw = w * canvasScale;
const th = h * canvasScale;
for (let i = 0; i < count; i++) {
const uvIndex = start + i;
localVector2D.fromArray(
geometry.attributes.uv.array,
uvIndex * 2,
);
modUv(localVector2D);
localVector2D
.multiply(localVector2D2.set(tw / canvasSize, th / canvasSize))
.add(localVector2D2.set(tx / canvasSize, ty / canvasSize));
localVector2D.toArray(geometry.attributes.uv.array, uvIndex * 2);
}
}
});
});
}
};
const _mergeGeometries = geometries => {
const geometry = new THREE.BufferGeometry();
geometry.morphTargetsRelative = true;
_forceGeometriesAttributeLayouts(attributeLayouts, geometries);
_mergeAttributes(geometry, geometries, attributeLayouts);
_mergeMorphAttributes(geometry, geometries, morphAttributeLayouts);
_mergeIndices(geometry, geometries);
_remapGeometryUvs(geometry, geometries);
return geometry;
};
const geometry = _mergeGeometries(geometries);
// console.log('got geometry', geometry);
const _makeAtlasTextures = atlasImages => {
const _makeAtlasTexture = atlasImage => {
const originalTexture = originalTextures.get(atlasImage);
const t = new THREE.Texture(atlasImage);
t.minFilter = originalTexture.minFilter;
t.magFilter = originalTexture.magFilter;
t.wrapS = originalTexture.wrapS;
t.wrapT = originalTexture.wrapT;
t.mapping = originalTexture.mapping;
// t.encoding = originalTexture.encoding;
t.flipY = false;
t.needsUpdate = true;
return t;
};
const result = {};
const textureMap = new Map(); // cache to alias identical textures
for (const textureType of textureTypes) {
const atlasImage = atlasImages[textureType];
if (atlasImage) {
let atlasTexture = textureMap.get(atlasImage.key);
if (atlasTexture === undefined) {
// cache miss
atlasTexture = _makeAtlasTexture(atlasImage);
textureMap.set(atlasImage.key, atlasTexture);
}
result[textureType] = atlasTexture;
} else {
result[textureType] = null;
}
}
return result;
};
const atlasTextures = atlasImages ? _makeAtlasTextures(atlasImages) : null;
return {
atlas,
atlasImages,
attributeLayouts,
morphAttributeLayouts,
geometry,
atlasTextures,
};
};