comfy-ts 2.22.0 → 2.24.0

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.
Files changed (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -0,0 +1,199 @@
1
+ // a fly-through back into 3D: MoGe (or DA3) measures the depth of every few frames of the clips (on
2
+ // the box), each frame's depth is scaled to the frame before it (the first to the picture's own mesh)
3
+ // where they overlap, set at the camera we chose for it, and all of them become one cloud of
4
+ // small gaussians (a 3DGS ply the world viewers open). Wider than one viewpoint: what the video
5
+ // model invented beyond the picture gets a place too. Reads what flythroughChain.ts wrote into <out>.
6
+ //
7
+ // run: bun examples/rvion/flythroughFuse.ts <out> [every] [points] [moge|da3]
8
+ // writes <out>/fused.ply and <out>/fuse.json (each frame's scale and how much of it the guide covered)
9
+ import { $ } from 'bun'
10
+ import { mkdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs'
11
+ import { join } from 'pathe'
12
+ import sharp from 'sharp'
13
+ import { ComfyTS, v } from 'comfy-ts'
14
+ import { dropStretched, readGlb, renderGuideFrame, type GuideMesh } from './flythroughGuide.ts'
15
+ import type { PathCamera } from './flythroughPath.ts'
16
+
17
+ /** a frame's mesh (its camera space: y up, -z ahead) scaled, turned to the camera's heading and moved there */
18
+ export function placeMesh(positions: Float32Array, scale: number, camera: PathCamera): Float32Array {
19
+ const fx = camera.target[0] - camera.position[0]
20
+ const fz = camera.target[2] - camera.position[2]
21
+ const psi = Math.atan2(fx, -fz)
22
+ const c = Math.cos(psi)
23
+ const s = Math.sin(psi)
24
+ const out = new Float32Array(positions.length)
25
+ for (let i = 0; i < out.length; i += 3) {
26
+ const x = positions[i]! * scale
27
+ const y = positions[i + 1]! * scale
28
+ const z = positions[i + 2]! * scale
29
+ out[i] = c * x - s * z + camera.position[0]
30
+ out[i + 1] = y + camera.position[1]
31
+ out[i + 2] = s * x + c * z + camera.position[2]
32
+ }
33
+ return out
34
+ }
35
+
36
+ /** points as a 3DGS ply: each a small round gaussian of its colour */
37
+ export function gaussianPly(p: { xyz: number[]; rgb: number[]; size: number }): Uint8Array {
38
+ const n = p.xyz.length / 3
39
+ const props = ['x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3']
40
+ const header = `ply\nformat binary_little_endian 1.0\nelement vertex ${n}\n${props.map((x) => `property float ${x}`).join('\n')}\nend_header\n`
41
+ const head = new TextEncoder().encode(header)
42
+ const body = new Float32Array(n * props.length)
43
+ const SH0 = 0.28209479177387814
44
+ const logScale = Math.log(p.size)
45
+ for (let i = 0; i < n; i++) {
46
+ const o = i * props.length
47
+ body.set([p.xyz[i * 3]!, p.xyz[i * 3 + 1]!, p.xyz[i * 3 + 2]!], o)
48
+ for (let c = 0; c < 3; c++) body[o + 3 + c] = (p.rgb[i * 3 + c]! / 255 - 0.5) / SH0
49
+ body[o + 6] = 4.6 // opacity logit: 0.99
50
+ body.set([logScale, logScale, logScale, 1, 0, 0, 0], o + 7)
51
+ }
52
+ const out = new Uint8Array(head.length + body.byteLength)
53
+ out.set(head)
54
+ out.set(new Uint8Array(body.buffer), head.length)
55
+ return out
56
+ }
57
+
58
+ const loadMesh = async (bytes: Uint8Array): Promise<GuideMesh> => {
59
+ const g = readGlb(bytes)
60
+ const t = await sharp(g.textureBytes).removeAlpha().raw().toBuffer({ resolveWithObject: true })
61
+ return { ...g, positions: new Float32Array(g.positions), texture: { width: t.info.width, height: t.info.height, rgb: new Uint8Array(t.data) } }
62
+ }
63
+
64
+ if (import.meta.main) {
65
+ const [out, everyArg, pointsArg, depthArg] = process.argv.slice(2)
66
+ if (out == null) throw new Error('usage: bun examples/rvion/flythroughFuse.ts <out> [every] [points] [moge|da3]')
67
+ const depthModel = depthArg ?? 'moge'
68
+ if (depthModel !== 'moge' && depthModel !== 'da3') throw new Error(`fuse: depth model '${depthModel}', not moge or da3`)
69
+ const every = Number(everyArg ?? 10)
70
+ const budget = Number(pointsArg ?? 1_500_000)
71
+ const rig = JSON.parse(readFileSync(join(out, 'cameras.json'), 'utf8')) as {
72
+ fovY: number
73
+ width: number
74
+ height: number
75
+ length: number
76
+ cameras: PathCamera[]
77
+ }
78
+ const fovX = (2 * Math.atan((Math.tan((rig.fovY * Math.PI) / 360) * rig.width) / rig.height) * 180) / Math.PI
79
+
80
+ // the frames, and the camera of each
81
+ const frames: { file: string; camera: PathCamera; index: number }[] = []
82
+ const framesDir = join(out, 'fuse-frames')
83
+ mkdirSync(framesDir, { recursive: true })
84
+ for (let k = 0; existsSync(join(out, `clip-${k}.mp4`)); k++) {
85
+ await $`ffmpeg -loglevel error -y -i ${join(out, `clip-${k}.mp4`)} ${join(framesDir, `c${k}-%04d.png`)}`
86
+ for (let j = k === 0 ? 0 : every; j < rig.length; j += every) {
87
+ const index = k * (rig.length - 1) + j
88
+ const camera = rig.cameras[index]
89
+ if (camera != null) frames.push({ file: join(framesDir, `c${k}-${String(j + 1).padStart(4, '0')}.png`), camera, index })
90
+ }
91
+ }
92
+
93
+ // depth of every frame, one prompt, one glb each, kept in <out>/fuse-meshes so a new fusion
94
+ // costs no box time
95
+ const meshesDir = join(out, 'fuse-meshes')
96
+ mkdirSync(meshesDir, { recursive: true })
97
+ const cached = (i: number) => join(meshesDir, `${depthModel}-${frames[i]!.index}.glb`)
98
+ const missing = frames.map((_, i) => i).filter((i) => !existsSync(cached(i)))
99
+ if (missing.length > 0) {
100
+ const host = ComfyTS.create().host({ id: 'windows-1' })
101
+ await host.loadSchemaFromCache()
102
+ const inputs = missing.map((i) => v.image(frames[i]!.file))
103
+ const measure = host.defineWorkflow({
104
+ id: 'flythrough-fuse',
105
+ vars: {},
106
+ build: async (b, _vars, wf) => {
107
+ // one loader each, made on first use
108
+ let mogeModel: ReturnType<typeof b.LoadMoGeModel> | undefined
109
+ let da3Model: ReturnType<typeof b.LoadDA3Model> | undefined
110
+ const moge = () => (mogeModel ??= b.LoadMoGeModel({ model_name: 'moge_2_vitl_normal_fp16.safetensors' }))
111
+ const da3 = () => (da3Model ??= b.LoadDA3Model({ model_name: 'depth_anything_3_mono_large.safetensors' }))
112
+ for (const [j, input] of inputs.entries()) {
113
+ const image = await input.loadInWorkflow(wf)
114
+ const mesh =
115
+ depthModel === 'moge'
116
+ ? b.MoGePointMapToMesh({
117
+ moge_geometry: b.MoGeInference({ moge_model: moge(), image, fov_x_degrees: fovX, resolution_level: 6 }),
118
+ decimation: 2,
119
+ })
120
+ : b.DA3GeometryToMesh({
121
+ // DA3's mono model knows no field of view: it unprojects at about 60°
122
+ da3_geometry: b.DA3Inference({ da3_model: da3(), image, mode: 'mono' }),
123
+ decimation: 2,
124
+ })
125
+ b.SaveGLB({ mesh, filename_prefix: 'comfy-ts-example/flythrough-fuse' }, { tag: `frame-${missing[j]}` })
126
+ }
127
+ },
128
+ })
129
+ const t0 = Date.now()
130
+ const measured = await measure.run({})
131
+ console.log(`🟢 ${depthModel} on ${missing.length} frames in ${((Date.now() - t0) / 1000).toFixed(0)} s`)
132
+ host.disconnect()
133
+ for (const i of missing) {
134
+ const glb = measured.models3d.find((m) => m.tags.includes(`frame-${i}`))
135
+ if (glb == null) throw new Error(`fuse: no mesh came back for frame ${frames[i]!.index}`)
136
+ writeFileSync(cached(i), glb.bytes)
137
+ }
138
+ }
139
+
140
+ // scale: the first frame to the picture's mesh (the guide), each next one to the frame before it,
141
+ // where they overlap; the picture's mesh is only right near the picture's own view, the frame
142
+ // before is right wherever the camera has just been
143
+ const source = await loadMesh(new Uint8Array(readFileSync(join(out, 'mesh.glb'))))
144
+ const origin: PathCamera = { position: [0, 0, 0], target: [0, 0, -1] }
145
+ const W = Math.round(rig.width / 2)
146
+ const H = Math.round(rig.height / 2)
147
+ const median = (reference: Float32Array, own: Float32Array) => {
148
+ const ratios: number[] = []
149
+ for (let k = 0; k < W * H; k++) if (Number.isFinite(reference[k]!) && Number.isFinite(own[k]!)) ratios.push(reference[k]! / own[k]!)
150
+ ratios.sort((x, y) => x - y)
151
+ return { scale: ratios[Math.floor(ratios.length / 2)] ?? Number.NaN, covered: ratios.length / (W * H) }
152
+ }
153
+ const fused: { mesh: GuideMesh; placed: GuideMesh; scale: number; covered: number; against: string; camera: PathCamera; index: number }[] = []
154
+ for (const [i, f] of frames.entries()) {
155
+ const mesh = dropStretched(await loadMesh(new Uint8Array(readFileSync(cached(i)))), 3)
156
+ const own = renderGuideFrame({ mesh, camera: origin, width: W, height: H, fovY: rig.fovY }).metres
157
+ const before = fused.at(-1)
158
+ const reference = before == null ? source : before.placed
159
+ let fit = median(renderGuideFrame({ mesh: reference, camera: f.camera, width: W, height: H, fovY: rig.fovY }).metres, own)
160
+ let against = before == null ? 'picture' : 'previous'
161
+ if (!(fit.covered > 0.15) && before != null) {
162
+ fit = { scale: before.scale, covered: fit.covered }
163
+ against = 'previous scale'
164
+ }
165
+ if (!Number.isFinite(fit.scale)) throw new Error(`fuse: frame ${f.index} overlaps nothing to set its scale`)
166
+ const placed = { ...mesh, positions: placeMesh(mesh.positions, fit.scale, f.camera) }
167
+ fused.push({ mesh, placed, scale: fit.scale, covered: fit.covered, against, camera: f.camera, index: f.index })
168
+ }
169
+
170
+ // the cloud: every frame's vertices, thinned to the budget
171
+ const total = fused.reduce((n, f) => n + f.mesh.positions.length / 3, 0)
172
+ const stride = Math.max(1, Math.ceil(total / budget))
173
+ const xyz: number[] = []
174
+ const rgb: number[] = []
175
+ for (const f of fused) {
176
+ const placed = f.placed.positions
177
+ const tex = f.mesh.texture
178
+ for (let i = 0; i < placed.length / 3; i += stride) {
179
+ const x = placed[i * 3]!
180
+ const y = placed[i * 3 + 1]!
181
+ const z = placed[i * 3 + 2]!
182
+ if (!Number.isFinite(x + y + z)) continue
183
+ const u = Math.round(f.mesh.uvs[i * 2]! * (tex.width - 1))
184
+ const w = Math.round(f.mesh.uvs[i * 2 + 1]! * (tex.height - 1))
185
+ const o = (w * tex.width + u) * 3
186
+ // written in the axes of SHARP's splats (x right, y down, z ahead), as the world viewers expect
187
+ xyz.push(x, -y, -z)
188
+ rgb.push(tex.rgb[o]!, tex.rgb[o + 1]!, tex.rgb[o + 2]!)
189
+ }
190
+ }
191
+ writeFileSync(join(out, 'fused.ply'), gaussianPly({ xyz, rgb, size: 0.03 }))
192
+ writeFileSync(
193
+ join(out, 'fuse.json'),
194
+ JSON.stringify(fused.map((f) => ({ frame: f.index, scale: f.scale, against: f.against, covered: Number(f.covered.toFixed(3)) })), null, 1),
195
+ )
196
+ await $`rm -rf ${framesDir}`
197
+ console.log(`🟢 ${xyz.length / 3} points from ${fused.length} frames: ${join(out, 'fused.ply')}`)
198
+ process.exit(0)
199
+ }
@@ -0,0 +1,300 @@
1
+ // the guide of 19-flythrough drawn on this machine: the picture's MoGe mesh (a glb) rasterized from
2
+ // every camera of the path, a colour frame, a depth frame (inverse depth, near = bright, spread between
3
+ // its 2nd and 98th percentile, as a monocular depth model draws one) and its coverage. A z-buffered triangle rasterizer, perspective correct, in plain TypeScript: about a
4
+ // tenth of a second a frame where the box's ray tracer takes seconds
5
+ import { levelPoint, type PathCamera } from './flythroughPath.ts'
6
+
7
+ /** a textured triangle mesh in the render's world (y up, -z ahead) */
8
+ export type GuideMesh = {
9
+ positions: Float32Array
10
+ uvs: Float32Array
11
+ indices: Uint32Array
12
+ texture: { width: number; height: number; rgb: Uint8Array }
13
+ }
14
+
15
+ /** `metres`: each pixel's distance along the view axis, Infinity where the mesh has no data */
16
+ export type GuideFrame = { color: Uint8Array; depth: Uint8Array; coverage: Uint8Array; metres: Float32Array }
17
+
18
+ /** the parts of a glb this needs: the first primitive's positions, uvs, indices, and its texture's
19
+ * encoded bytes (decode them with sharp, then pass `texture`) */
20
+ export function readGlb(bytes: Uint8Array): Omit<GuideMesh, 'texture'> & { textureBytes: Uint8Array } {
21
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
22
+ if (view.getUint32(0, true) !== 0x46546c67) throw new Error('readGlb: not a glb file')
23
+ let off = 12
24
+ let json: unknown = null
25
+ let bin: Uint8Array = new Uint8Array()
26
+ while (off < bytes.length) {
27
+ const len = view.getUint32(off, true)
28
+ const type = view.getUint32(off + 4, true)
29
+ const chunk = bytes.subarray(off + 8, off + 8 + len)
30
+ if (type === 0x4e4f534a) json = JSON.parse(new TextDecoder().decode(chunk))
31
+ else if (type === 0x004e4942) bin = chunk
32
+ off += 8 + len
33
+ }
34
+ const gltf = json as GltfJson
35
+ const prim = gltf.meshes?.[0]?.primitives?.[0]
36
+ if (prim == null) throw new Error('readGlb: no mesh primitive')
37
+ const view_ = (i: number) => {
38
+ const bv = gltf.bufferViews?.[i]
39
+ if (bv == null) throw new Error(`readGlb: no buffer view ${i}`)
40
+ return bin.subarray(bv.byteOffset ?? 0, (bv.byteOffset ?? 0) + bv.byteLength)
41
+ }
42
+ const accessor = (i: number | undefined): Uint8Array & { componentType: number; count: number } => {
43
+ const a = i == null ? undefined : gltf.accessors?.[i]
44
+ if (a == null) throw new Error(`readGlb: no accessor ${i}`)
45
+ const raw = view_(a.bufferView).slice(a.byteOffset ?? 0)
46
+ return Object.assign(raw, { componentType: a.componentType, count: a.count })
47
+ }
48
+ const floats = (i: number | undefined, n: number) => {
49
+ const a = accessor(i)
50
+ if (a.componentType !== 5126) throw new Error('readGlb: positions and uvs must be float32')
51
+ return new Float32Array(a.buffer, a.byteOffset, a.count * n)
52
+ }
53
+ const idx = accessor(prim.indices)
54
+ const indices =
55
+ idx.componentType === 5125
56
+ ? new Uint32Array(idx.buffer, idx.byteOffset, idx.count)
57
+ : Uint32Array.from(new Uint16Array(idx.buffer, idx.byteOffset, idx.count))
58
+ const image = gltf.images?.[0]
59
+ if (image?.bufferView == null) throw new Error('readGlb: no embedded texture')
60
+ return {
61
+ positions: floats(prim.attributes.POSITION, 3),
62
+ uvs: floats(prim.attributes.TEXCOORD_0, 2),
63
+ indices,
64
+ textureBytes: view_(image.bufferView),
65
+ }
66
+ }
67
+
68
+ type GltfJson = {
69
+ meshes?: { primitives?: { attributes: { POSITION?: number; TEXCOORD_0?: number }; indices?: number }[] }[]
70
+ accessors?: { bufferView: number; byteOffset?: number; componentType: number; count: number }[]
71
+ bufferViews?: { byteOffset?: number; byteLength: number }[]
72
+ images?: { bufferView?: number }[]
73
+ }
74
+
75
+ /**
76
+ * the mesh without its curtains: a picture's mesh joins a near surface to the far one behind it
77
+ * with long thin triangles, short from the picture's camera (the origin) and long in depth. Seen
78
+ * from the side they stretch into streaks the video model copies, where a hole makes it invent.
79
+ * A triangle goes when an edge is longer than `ratio` times what its angle from the origin spans
80
+ */
81
+ export function dropStretched(mesh: GuideMesh, ratio = 4): GuideMesh {
82
+ const P = mesh.positions
83
+ const kept: number[] = []
84
+ const edge = (i: number, j: number) => {
85
+ const ax = P[i * 3]!
86
+ const ay = P[i * 3 + 1]!
87
+ const az = P[i * 3 + 2]!
88
+ const bx = P[j * 3]!
89
+ const by = P[j * 3 + 1]!
90
+ const bz = P[j * 3 + 2]!
91
+ const la = Math.hypot(ax, ay, az)
92
+ const lb = Math.hypot(bx, by, bz)
93
+ // the angle between the two rays from the origin, times the nearer distance: the edge as the
94
+ // picture's camera saw it
95
+ const across = Math.hypot(ax / la - bx / lb, ay / la - by / lb, az / la - bz / lb) * Math.min(la, lb)
96
+ return Math.hypot(ax - bx, ay - by, az - bz) <= ratio * across + 1e-4
97
+ }
98
+ const idx = mesh.indices
99
+ for (let t = 0; t < idx.length; t += 3) {
100
+ const a = idx[t]!
101
+ const b = idx[t + 1]!
102
+ const c = idx[t + 2]!
103
+ if (edge(a, b) && edge(b, c) && edge(c, a)) kept.push(a, b, c)
104
+ }
105
+ return { ...mesh, indices: Uint32Array.from(kept) }
106
+ }
107
+
108
+ /** the mesh in the path's levelled world: every vertex turned by the picture's `pitch` (levelPoint) */
109
+ export function levelMesh(mesh: GuideMesh, pitch: number): GuideMesh {
110
+ if (pitch === 0) return mesh
111
+ const positions = new Float32Array(mesh.positions.length)
112
+ for (let i = 0; i < positions.length; i += 3) {
113
+ const q = levelPoint([mesh.positions[i]!, mesh.positions[i + 1]!, mesh.positions[i + 2]!], pitch)
114
+ positions.set(q, i)
115
+ }
116
+ return { ...mesh, positions }
117
+ }
118
+
119
+ /** one frame from one camera: `fovY` vertical, degrees; the camera looks at its target, y up.
120
+ * `fill`: the depth frame's holes take the depth around them (fillHoles), so the video model sees a
121
+ * surface to invent rather than a black void it copies */
122
+ export function renderGuideFrame(p: { mesh: GuideMesh; camera: PathCamera; width: number; height: number; fovY: number; fill?: boolean }): GuideFrame {
123
+ const { mesh, camera, width: W, height: H } = p
124
+ const [ex, ey, ez] = camera.position
125
+ // camera axes: forward f, right r, up u (three.js look-at with world up +y)
126
+ let fx = camera.target[0] - ex
127
+ let fy = camera.target[1] - ey
128
+ let fz = camera.target[2] - ez
129
+ const fl = Math.hypot(fx, fy, fz) || 1
130
+ fx /= fl
131
+ fy /= fl
132
+ fz /= fl
133
+ let rx = -fz
134
+ let rz = fx
135
+ const rl = Math.hypot(rx, rz) || 1
136
+ rx /= rl
137
+ rz /= rl
138
+ const ux = -rz * fy
139
+ const uy = rz * fx - rx * fz
140
+ const uz = rx * fy
141
+ const focal = H / 2 / Math.tan((p.fovY * Math.PI) / 360)
142
+ const n = mesh.positions.length / 3
143
+ // every vertex once: screen x, y, its view depth
144
+ const sx = new Float32Array(n)
145
+ const sy = new Float32Array(n)
146
+ const sz = new Float32Array(n)
147
+ for (let i = 0; i < n; i++) {
148
+ const dx = mesh.positions[i * 3]! - ex
149
+ const dy = mesh.positions[i * 3 + 1]! - ey
150
+ const dz = mesh.positions[i * 3 + 2]! - ez
151
+ const z = dx * fx + dy * fy + dz * fz
152
+ sz[i] = z
153
+ sx[i] = W / 2 + (focal * (dx * rx + dz * rz)) / z
154
+ sy[i] = H / 2 - (focal * (dx * ux + dy * uy + dz * uz)) / z
155
+ }
156
+ const zbuf = new Float32Array(W * H).fill(Infinity)
157
+ const ubuf = new Float32Array(W * H)
158
+ const vbuf = new Float32Array(W * H)
159
+ const NEAR = 0.05
160
+ const idx = mesh.indices
161
+ for (let t = 0; t < idx.length; t += 3) {
162
+ const a = idx[t]!
163
+ const b = idx[t + 1]!
164
+ const c = idx[t + 2]!
165
+ const za = sz[a]!
166
+ const zb = sz[b]!
167
+ const zc = sz[c]!
168
+ // a triangle crossing the near plane is dropped whole: at the guide's scale it is a sliver
169
+ if (za < NEAR || zb < NEAR || zc < NEAR) continue
170
+ const ax = sx[a]!
171
+ const ay = sy[a]!
172
+ const bx = sx[b]!
173
+ const by = sy[b]!
174
+ const cx = sx[c]!
175
+ const cy = sy[c]!
176
+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
177
+ if (area === 0 || !Number.isFinite(area)) continue
178
+ const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)))
179
+ const x1 = Math.min(W - 1, Math.ceil(Math.max(ax, bx, cx)))
180
+ const y0 = Math.max(0, Math.floor(Math.min(ay, by, cy)))
181
+ const y1 = Math.min(H - 1, Math.ceil(Math.max(ay, by, cy)))
182
+ if (x0 > x1 || y0 > y1) continue
183
+ const ia = 1 / za
184
+ const ib = 1 / zb
185
+ const ic = 1 / zc
186
+ for (let y = y0; y <= y1; y++) {
187
+ const py = y + 0.5
188
+ for (let x = x0; x <= x1; x++) {
189
+ const px = x + 0.5
190
+ const w0 = ((bx - px) * (cy - py) - (by - py) * (cx - px)) / area
191
+ const w1 = ((cx - px) * (ay - py) - (cy - py) * (ax - px)) / area
192
+ const w2 = 1 - w0 - w1
193
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue
194
+ // perspective correct: interpolate 1/z, and uv/z
195
+ const iz = w0 * ia + w1 * ib + w2 * ic
196
+ const z = 1 / iz
197
+ const k = y * W + x
198
+ if (z >= zbuf[k]!) continue
199
+ zbuf[k] = z
200
+ ubuf[k] = (w0 * mesh.uvs[a * 2]! * ia + w1 * mesh.uvs[b * 2]! * ib + w2 * mesh.uvs[c * 2]! * ic) * z
201
+ vbuf[k] = (w0 * mesh.uvs[a * 2 + 1]! * ia + w1 * mesh.uvs[b * 2 + 1]! * ib + w2 * mesh.uvs[c * 2 + 1]! * ic) * z
202
+ }
203
+ }
204
+ }
205
+ const color = new Uint8Array(W * H * 3)
206
+ const depth = new Uint8Array(W * H * 3)
207
+ const coverage = new Uint8Array(W * H * 3)
208
+ // inverse depth between robust ends: a far outlier (the mesh's back wall, 100 m away) must not
209
+ // squash every near surface into one white
210
+ const seen: number[] = []
211
+ for (let k = 0; k < W * H; k += 7) if (zbuf[k]! !== Infinity) seen.push(1 / zbuf[k]!)
212
+ seen.sort((a, b) => a - b)
213
+ const lo = seen[Math.floor(seen.length * 0.02)] ?? 0
214
+ const hi = seen[Math.floor(seen.length * 0.98)] ?? 1
215
+ const range = Math.max(hi - lo, 1e-9)
216
+ const tex = mesh.texture
217
+ for (let k = 0; k < W * H; k++) {
218
+ const z = zbuf[k]!
219
+ if (z === Infinity) continue
220
+ const tu = Math.min(tex.width - 1, Math.max(0, Math.round(ubuf[k]! * (tex.width - 1))))
221
+ const tv = Math.min(tex.height - 1, Math.max(0, Math.round(vbuf[k]! * (tex.height - 1))))
222
+ const o = (tv * tex.width + tu) * 3
223
+ const d = Math.max(0, Math.min(255, Math.round(((1 / z - lo) / range) * 255)))
224
+ for (let ch = 0; ch < 3; ch++) {
225
+ color[k * 3 + ch] = tex.rgb[o + ch]!
226
+ depth[k * 3 + ch] = d
227
+ coverage[k * 3 + ch] = 255
228
+ }
229
+ }
230
+ return { color, depth: p.fill ? fillHoles(depth, coverage, W, H) : depth, coverage, metres: zbuf }
231
+ }
232
+
233
+ /**
234
+ * the holes of a frame filled from what is around them, push-pull: the covered pixels averaged down
235
+ * a pyramid until every cell has some, then each hole takes the coarser level's value on the way up,
236
+ * so a hole gets a smooth blend of its edges. `coverage` is 255 where the frame has data
237
+ */
238
+ export function fillHoles(rgb: Uint8Array, coverage: Uint8Array, W: number, H: number): Uint8Array {
239
+ type Level = { w: number; h: number; v: Float32Array; a: Float32Array }
240
+ const first: Level = { w: W, h: H, v: new Float32Array(W * H * 3), a: new Float32Array(W * H) }
241
+ for (let k = 0; k < W * H; k++) {
242
+ const a = coverage[k * 3]! > 127 ? 1 : 0
243
+ first.a[k] = a
244
+ for (let c = 0; c < 3; c++) first.v[k * 3 + c] = rgb[k * 3 + c]! * a
245
+ }
246
+ const levels = [first]
247
+ while (levels.at(-1)!.w > 1 || levels.at(-1)!.h > 1) {
248
+ const up = levels.at(-1)!
249
+ const w = Math.max(1, Math.ceil(up.w / 2))
250
+ const h = Math.max(1, Math.ceil(up.h / 2))
251
+ const next: Level = { w, h, v: new Float32Array(w * h * 3), a: new Float32Array(w * h) }
252
+ for (let y = 0; y < up.h; y++)
253
+ for (let x = 0; x < up.w; x++) {
254
+ const i = y * up.w + x
255
+ const j = (y >> 1) * w + (x >> 1)
256
+ next.a[j]! += up.a[i]!
257
+ for (let c = 0; c < 3; c++) next.v[j * 3 + c]! += up.v[i * 3 + c]!
258
+ }
259
+ // every level stays premultiplied by its weight, the weight capped at 1
260
+ for (let j = 0; j < w * h; j++) {
261
+ const a = next.a[j]!
262
+ if (a > 1) for (let c = 0; c < 3; c++) next.v[j * 3 + c]! /= a
263
+ next.a[j] = Math.min(1, a)
264
+ }
265
+ levels.push(next)
266
+ }
267
+ // up again: what a cell lacks of its weight comes from its parent, by then complete
268
+ for (let l = levels.length - 2; l >= 0; l--) {
269
+ const fine = levels[l]!
270
+ const coarse = levels[l + 1]!
271
+ for (let y = 0; y < fine.h; y++)
272
+ for (let x = 0; x < fine.w; x++) {
273
+ const i = y * fine.w + x
274
+ const a = fine.a[i]!
275
+ if (a >= 1) continue
276
+ // bilinear in the parent level, else a hole fills in blocks
277
+ const gx = Math.min(coarse.w - 1, Math.max(0, (x + 0.5) / 2 - 0.5))
278
+ const gy = Math.min(coarse.h - 1, Math.max(0, (y + 0.5) / 2 - 0.5))
279
+ const x0 = Math.floor(gx)
280
+ const y0 = Math.floor(gy)
281
+ const x1 = Math.min(coarse.w - 1, x0 + 1)
282
+ const y1 = Math.min(coarse.h - 1, y0 + 1)
283
+ const tx = gx - x0
284
+ const ty = gy - y0
285
+ const at = (cx: number, cy: number, c: number) => {
286
+ const j = cy * coarse.w + cx
287
+ return coarse.v[j * 3 + c]! / Math.max(coarse.a[j]!, 1e-6)
288
+ }
289
+ for (let c = 0; c < 3; c++) {
290
+ const top = at(x0, y0, c) * (1 - tx) + at(x1, y0, c) * tx
291
+ const bottom = at(x0, y1, c) * (1 - tx) + at(x1, y1, c) * tx
292
+ fine.v[i * 3 + c] = fine.v[i * 3 + c]! + (1 - a) * (top * (1 - ty) + bottom * ty)
293
+ }
294
+ fine.a[i] = 1
295
+ }
296
+ }
297
+ const out = new Uint8Array(W * H * 3)
298
+ for (let k = 0; k < out.length; k++) out[k] = Math.max(0, Math.min(255, Math.round(first.v[k]!)))
299
+ return out
300
+ }