Line data Source code
1 : import {
2 : createPolygonEdgesGeometry,
3 : polygonMeshFromTriangles
4 : } from '@comfyorg/quad-wireframe-three'
5 : import * as THREE from 'three'
6 :
7 : import { faceSizesFor } from './faceSizesRegistry'
8 :
9 24 : export class QuadWireframeOverlay extends THREE.LineSegments {}
10 :
11 : export const MAX_TRIANGLE_OUTLINE = 300_000
12 :
13 0 : function isDeforming(mesh: THREE.Mesh): boolean {
14 0 : const hasMorphs = Object.keys(mesh.geometry.morphAttributes).length > 0
15 0 : return mesh instanceof THREE.SkinnedMesh || hasMorphs
16 : }
17 :
18 0 : function triangleCount(geometry: THREE.BufferGeometry): number {
19 0 : const corners =
20 : geometry.index?.count ?? geometry.getAttribute('position').count
21 0 : return Math.floor(corners / 3)
22 : }
23 :
24 24 : export class QuadWireframeManager {
25 : private readonly overlays = new Map<THREE.Mesh, QuadWireframeOverlay>()
26 : private readonly cache = new Map<THREE.BufferGeometry, THREE.BufferGeometry>()
27 : private readonly material = new THREE.LineBasicMaterial({ color: 0xffffff })
28 :
29 : show(model: THREE.Object3D): THREE.Mesh[] {
30 0 : this.hide()
31 0 : const quads: THREE.Mesh[] = []
32 0 : const triangles: THREE.Mesh[] = []
33 0 : let triangleTotal = 0
34 0 : model.traverse((child) => {
35 0 : if (!(child instanceof THREE.Mesh) || isDeforming(child)) return
36 0 : if (faceSizesFor(child.geometry)) {
37 0 : quads.push(child)
38 : } else {
39 0 : triangles.push(child)
40 0 : triangleTotal += triangleCount(child.geometry)
41 : }
42 : })
43 0 : const outlined =
44 : triangleTotal > MAX_TRIANGLE_OUTLINE ? quads : [...quads, ...triangles]
45 0 : for (const child of outlined) {
46 0 : const overlay = new QuadWireframeOverlay(
47 : this.edgesFor(child.geometry),
48 : this.material
49 : )
50 0 : overlay.renderOrder = 1
51 0 : child.add(overlay)
52 0 : this.overlays.set(child, overlay)
53 : }
54 0 : return outlined
55 : }
56 :
57 : hide(): void {
58 47 : for (const [mesh, overlay] of this.overlays) mesh.remove(overlay)
59 47 : this.overlays.clear()
60 : }
61 :
62 : clear(): void {
63 47 : this.hide()
64 47 : for (const edges of this.cache.values()) edges.dispose()
65 47 : this.cache.clear()
66 : }
67 :
68 : dispose(): void {
69 1 : this.clear()
70 1 : this.material.dispose()
71 : }
72 :
73 : private edgesFor(geometry: THREE.BufferGeometry): THREE.BufferGeometry {
74 0 : let edges = this.cache.get(geometry)
75 0 : if (!edges) {
76 0 : edges = createPolygonEdgesGeometry(
77 : polygonMeshFromTriangles(geometry, faceSizesFor(geometry))
78 : )
79 0 : this.cache.set(geometry, edges)
80 : }
81 0 : return edges
82 : }
83 : }
|