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,114 @@
1
+ // place a splat lifted from one filled view into the world: fit its scale on the pixels the world already
2
+ // covers, keep only the gaussians that land in the hole, move them from the view's camera to world axes
3
+ import { F, STRIDE, type Splat, type SplatCamera } from './ply.ts'
4
+ import { IDENTITY, matToQuat, render, type Pose, type Render } from './raster.ts'
5
+
6
+ type Quat = [number, number, number, number]
7
+
8
+ function quatMul(a: Quat, b: Quat): Quat {
9
+ return [
10
+ a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
11
+ a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2],
12
+ a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1],
13
+ a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0],
14
+ ]
15
+ }
16
+
17
+ function quantile(sorted: Float64Array, q: number): number {
18
+ if (sorted.length === 0) return Number.NaN
19
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))))] ?? Number.NaN
20
+ }
21
+
22
+ export type ScaleFit = {
23
+ /** world metres per lifted metre */
24
+ scale: number
25
+ /** the 25 % and 75 % quantiles of the per pixel ratio: how much the two depths disagree in shape */
26
+ spread: [number, number]
27
+ /** how many pixels the fit used */
28
+ pixels: number
29
+ }
30
+
31
+ /** the scale that best maps the lifted depth onto the world's depth, on pixels both cover well (median of ratios) */
32
+ export function fitScale(world: Render, lifted: Render, minCover = 0.95): ScaleFit {
33
+ const logs: number[] = []
34
+ for (let i = 0; i < world.alpha.length; i++) {
35
+ if (world.alpha[i]! < minCover || lifted.alpha[i]! < minCover) continue
36
+ const a = world.depth[i]!
37
+ const b = lifted.depth[i]!
38
+ if (a > 0 && b > 0) logs.push(Math.log(a / b))
39
+ }
40
+ if (logs.length < 1000) throw new Error(`scale fit: only ${logs.length} pixels covered by both splats, the views do not overlap enough`)
41
+ const sorted = Float64Array.from(logs).sort()
42
+ return {
43
+ scale: Math.exp(quantile(sorted, 0.5)),
44
+ spread: [Math.exp(quantile(sorted, 0.25)), Math.exp(quantile(sorted, 0.75))],
45
+ pixels: logs.length,
46
+ }
47
+ }
48
+
49
+ /** only the gaussians whose centre falls inside the picture: SHARP pushes some past its border, where nothing
50
+ * was seen, and from a turned camera they show as a dark smudge beyond the picture's edge */
51
+ export function trimToFrame(s: Splat, cam: SplatCamera): Splat {
52
+ const keep: number[] = []
53
+ for (let g = 0; g < s.n; g++) {
54
+ const b = g * STRIDE
55
+ const z = s.data[b + 2]!
56
+ if (z <= 0) continue
57
+ const u = (cam.f * s.data[b]!) / z + cam.cx
58
+ const v = (cam.f * s.data[b + 1]!) / z + cam.cy
59
+ if (u >= 0 && v >= 0 && u < cam.width && v < cam.height) keep.push(g)
60
+ }
61
+ const data = new Float32Array(keep.length * STRIDE)
62
+ keep.forEach((g, k) => data.set(s.data.subarray(g * STRIDE, (g + 1) * STRIDE), k * STRIDE))
63
+ return { n: keep.length, data, camera: s.camera }
64
+ }
65
+
66
+ export type Placed ={ kept: Splat; fit: ScaleFit; total: number }
67
+
68
+ /**
69
+ * `lifted` is SHARP's splat of the filled view, in that view's camera axes; `world` is the render of the grown
70
+ * splat from the same pose. Its gaussians whose centre lands where the world covered less than `keepBelow` are kept,
71
+ * scaled by the fit, and moved to world axes.
72
+ */
73
+ export function place(p: { lifted: Splat; world: Render; cam: SplatCamera; pose: Pose; keepBelow: number; minCover?: number }): Placed {
74
+ const lc = p.lifted.camera
75
+ if (lc == null) throw new Error('place: the lifted splat has no camera (intrinsic, image_size): not a SHARP ply')
76
+ if (Math.abs(lc.f - p.cam.f) > 0.01 * p.cam.f || lc.width !== p.cam.width || lc.height !== p.cam.height)
77
+ throw new Error(`place: the lifted splat was made for f=${lc.f} ${lc.width}x${lc.height}, the view is f=${p.cam.f} ${p.cam.width}x${p.cam.height}`)
78
+ const liftedView = render(p.lifted, p.cam, { R: IDENTITY, C: [0, 0, 0] })
79
+ const fit = fitScale(p.world, liftedView, p.minCover)
80
+ const s = fit.scale
81
+ const logS = Math.log(s)
82
+ const R = p.pose.R
83
+ const qR = matToQuat(R)
84
+ const src = p.lifted.data
85
+ const keep: number[] = []
86
+ const W = p.cam.width
87
+ const H = p.cam.height
88
+ for (let g = 0; g < p.lifted.n; g++) {
89
+ const b = g * STRIDE
90
+ const z = src[b + 2]!
91
+ if (z <= 0) continue
92
+ const u = Math.floor((p.cam.f * src[b]!) / z + p.cam.cx)
93
+ const v = Math.floor((p.cam.f * src[b + 1]!) / z + p.cam.cy)
94
+ if (u < 0 || v < 0 || u >= W || v >= H) continue
95
+ if (p.world.alpha[v * W + u]! < p.keepBelow) keep.push(g)
96
+ }
97
+ const data = new Float32Array(keep.length * STRIDE)
98
+ keep.forEach((g, k) => {
99
+ const b = g * STRIDE
100
+ const o = k * STRIDE
101
+ const x = src[b]! * s
102
+ const y = src[b + 1]! * s
103
+ const z = src[b + 2]! * s
104
+ data[o] = R[0] * x + R[1] * y + R[2] * z + p.pose.C[0]
105
+ data[o + 1] = R[3] * x + R[4] * y + R[5] * z + p.pose.C[1]
106
+ data[o + 2] = R[6] * x + R[7] * y + R[8] * z + p.pose.C[2]
107
+ for (let c = 0; c < 3; c++) data[o + F.dc + c] = src[b + F.dc + c]!
108
+ data[o + F.opacity] = src[b + F.opacity]!
109
+ for (let c = 0; c < 3; c++) data[o + F.scale + c] = src[b + F.scale + c]! + logS
110
+ const q = quatMul(qR, [src[b + F.rot]!, src[b + F.rot + 1]!, src[b + F.rot + 2]!, src[b + F.rot + 3]!])
111
+ for (let c = 0; c < 4; c++) data[o + F.rot + c] = q[c]!
112
+ })
113
+ return { kept: { n: keep.length, data, camera: null }, fit, total: p.lifted.n }
114
+ }
@@ -0,0 +1,198 @@
1
+ // grow a one picture splat into a world, round after round: render it from a new camera, let the image model fill
2
+ // what is empty (20-grow-splat.cflow.ts), lift the filled view with SHARP, keep only its new part at the world's
3
+ // scale, merge. The world folder holds `splat.ply` (SHARP's splat of the picture, OpenCV axes, metres); the loop
4
+ // writes `splat-grown.ply` beside it and the pictures of each round under `grow/`.
5
+ //
6
+ // bun examples/rvion/grow-splat/grow.ts <world folder> [--rounds "30 -30 60 -60"] [--extend "<what lies beyond>"]
7
+ // [--seed 1] [--fresh] [--reuse] [--views]
8
+ // a round is `<yaw>[@<x>,<z>]`: turn left by yaw degrees (negative turns right), standing at x metres right and
9
+ // z metres forward of the picture's camera. Without --fresh the rounds go on from the last grown splat; --reuse
10
+ // takes a round's filled view and lifted splat from an earlier run when they exist (tuning the merge alone).
11
+ // --views only draws the grown splat (and the picture's) from a fixed set of cameras, into grow/views.png
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import { join, resolve } from 'pathe'
14
+ import sharp from 'sharp'
15
+ import { FILL_PROMPT, growSplatFill } from '../20-grow-splat.cflow.ts'
16
+ import { place, trimToFrame } from './align.ts'
17
+ import { concatSplats, readSplat, writeSplat, type Splat, type SplatCamera } from './ply.ts'
18
+ import { render, turn, type Pose, type Render } from './raster.ts'
19
+ import { sharpPredict } from './sharp.ts'
20
+
21
+ /** a pixel covered less than this is painted by the model */
22
+ const COVERED = 0.9
23
+ /** a lifted gaussian is kept where the world covered less than this */
24
+ const KEEP_BELOW = 0.6
25
+
26
+ type Round = { yaw: number; x: number; z: number }
27
+ type RoundLog = Round & { round: number; seed: number; seconds: number; scale: number; spread: [number, number]; fitPixels: number; hole: number; kept: number; total: number; gaussians: number }
28
+
29
+ function parseRound(token: string): Round {
30
+ const m = /^(-?\d+(?:\.\d+)?)(?:@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?))?$/.exec(token)
31
+ if (m == null) throw new Error(`a round is <yaw>[@<x>,<z>], got '${token}'`)
32
+ return { yaw: Number(m[1]), x: Number(m[2] ?? 0), z: Number(m[3] ?? 0) }
33
+ }
34
+
35
+ const poseOf = (r: Round): Pose => ({ R: turn(r.yaw), C: [r.x, 0, r.z] })
36
+ const roundName = (r: Round): string => `${r.yaw >= 0 ? 'l' : 'r'}${Math.abs(r.yaw)}${r.x !== 0 || r.z !== 0 ? `-at${r.x},${r.z}` : ''}`
37
+
38
+ const to8 = (x: number): number => Math.max(0, Math.min(255, Math.round(x * 255)))
39
+
40
+ /** the render as a png: rgb over black, alpha = how much the splat covers (LoadImage's mask is 1 − alpha) */
41
+ async function writeRender(path: string, r: Render, withAlpha: boolean, width = r.width): Promise<void> {
42
+ const px = Buffer.alloc(r.width * r.height * 4)
43
+ for (let i = 0; i < r.width * r.height; i++) {
44
+ px[i * 4] = to8(r.color[i * 3]!)
45
+ px[i * 4 + 1] = to8(r.color[i * 3 + 1]!)
46
+ px[i * 4 + 2] = to8(r.color[i * 3 + 2]!)
47
+ px[i * 4 + 3] = withAlpha ? to8(r.alpha[i]!) : 255
48
+ }
49
+ await sharp(px, { raw: { width: r.width, height: r.height, channels: 4 } }).resize(width).png().toFile(path)
50
+ }
51
+
52
+ async function writeMask(path: string, r: Render): Promise<number> {
53
+ const px = Buffer.alloc(r.width * r.height)
54
+ let hole = 0
55
+ for (let i = 0; i < px.length; i++) {
56
+ const empty = r.alpha[i]! < COVERED
57
+ px[i] = empty ? 255 : 0
58
+ if (empty) hole++
59
+ }
60
+ await sharp(px, { raw: { width: r.width, height: r.height, channels: 1 } }).png().toFile(path)
61
+ return hole / px.length
62
+ }
63
+
64
+ async function fill(renderPng: string, seed: number, extend: string): Promise<Uint8Array> {
65
+ growSplatFill.vars.render.set(renderPng)
66
+ growSplatFill.vars.seed.set(seed)
67
+ growSplatFill.vars.prompt.set(extend === '' ? FILL_PROMPT : `${FILL_PROMPT} Beyond the picture: ${extend}`)
68
+ const execution = await growSplatFill.run({ log: false })
69
+ const filled = execution.images.find((i) => i.tags.includes('filled'))
70
+ if (filled == null) throw new Error(`the fill run gave no 'filled' image (${execution.images.length} images)`)
71
+ return filled.buffer
72
+ }
73
+
74
+ /** the camera rounds are drawn with: the picture's own */
75
+ function cameraOf(s: Splat): SplatCamera {
76
+ if (s.camera == null) throw new Error('the world splat has no camera (intrinsic, image_size): grow needs a SHARP ply')
77
+ return s.camera
78
+ }
79
+
80
+ /** a round at a glance: the render, its empty part, the filled view, the world after the merge (2 × 2, 768 px each) */
81
+ async function sheet(path: string, pictures: string[]): Promise<void> {
82
+ const W = 768
83
+ const H = 512
84
+ const tiles = await Promise.all(
85
+ pictures.map(async (p, i) => ({
86
+ input: await sharp(p).flatten({ background: '#000000' }).resize(W, H).png().toBuffer(),
87
+ left: (i % 2) * (W + 8),
88
+ top: Math.floor(i / 2) * (H + 8),
89
+ })),
90
+ )
91
+ await sharp({ create: { width: 2 * W + 8, height: 2 * H + 8, channels: 3, background: '#ffffff' } }).composite(tiles).webp().toFile(path)
92
+ }
93
+
94
+ async function grow(dir: string, rounds: Round[], extend: string, seed0: number, fresh: boolean, reuse: boolean): Promise<void> {
95
+ const out = join(dir, 'grow')
96
+ mkdirSync(out, { recursive: true })
97
+ const grownPath = join(dir, 'splat-grown.ply')
98
+ const logPath = join(out, 'rounds.json')
99
+ const resume = !fresh && existsSync(grownPath) && existsSync(logPath)
100
+ const log: RoundLog[] = resume ? (JSON.parse(readFileSync(logPath, 'utf8')) as RoundLog[]) : []
101
+ const picture = readSplat(join(dir, 'splat.ply'))
102
+ const cam = cameraOf(picture)
103
+ let world = resume ? readSplat(grownPath) : trimToFrame(picture, cam)
104
+ console.log(`${resume ? 'resume' : 'start'}: ${world.n} gaussians, ${log.length} rounds done`)
105
+ for (const r of rounds) {
106
+ const t0 = performance.now()
107
+ const n = log.length + 1
108
+ const tag = `r${String(n).padStart(2, '0')}-${roundName(r)}`
109
+ const pose = poseOf(r)
110
+ const view = render(world, cam, pose)
111
+ const renderPng = join(out, `${tag}-render.png`)
112
+ await writeRender(renderPng, view, true)
113
+ const hole = await writeMask(join(out, `${tag}-mask.png`), view)
114
+ console.log(`${tag}: ${(hole * 100).toFixed(1)} % empty, filling`)
115
+ const seedN = seed0 + n
116
+ const filledPng = join(out, `${tag}-filled.png`)
117
+ if (!(reuse && existsSync(filledPng))) await sharp(await fill(renderPng, seedN, extend)).removeAlpha().png().toFile(filledPng)
118
+ const liftedPly = join(out, `${tag}-lifted.ply`)
119
+ const tf = performance.now()
120
+ console.log(`${tag}: filled in ${Math.round((tf - t0) / 1000)} s, lifting`)
121
+ if (!(reuse && existsSync(liftedPly))) sharpPredict(filledPng, liftedPly)
122
+ const tl = performance.now()
123
+ const placed = place({ lifted: readSplat(liftedPly), world: view, cam, pose, keepBelow: KEEP_BELOW })
124
+ world = concatSplats([world, placed.kept])
125
+ await writeRender(join(out, `${tag}-after.png`), render(world, cam, pose), false)
126
+ await sheet(join(out, `${tag}-sheet.webp`), [renderPng, join(out, `${tag}-mask.png`), filledPng, join(out, `${tag}-after.png`)])
127
+ writeSplat(grownPath, world)
128
+ const seconds = Math.round((performance.now() - t0) / 1000)
129
+ log.push({ ...r, round: n, seed: seedN, seconds, scale: placed.fit.scale, spread: placed.fit.spread, fitPixels: placed.fit.pixels, hole, kept: placed.kept.n, total: placed.total, gaussians: world.n })
130
+ writeFileSync(logPath, `${JSON.stringify(log, null, 3)}\n`)
131
+ console.log(
132
+ `${tag}: ${seconds} s (fill ${Math.round((tf - t0) / 1000)} s, SHARP ${Math.round((tl - tf) / 1000)} s), scale ×${placed.fit.scale.toFixed(3)} ` +
133
+ `(half the pixels within ×${placed.fit.spread[0].toFixed(2)}..×${placed.fit.spread[1].toFixed(2)}), kept ${placed.kept.n} of ${placed.total}, world ${world.n}`,
134
+ )
135
+ }
136
+ }
137
+
138
+ /** the cameras a grown world is judged from: turns to each side, then steps forward */
139
+ const VIEW_ROUNDS: Round[] = [
140
+ { yaw: 90, x: 0, z: 0 },
141
+ { yaw: 60, x: 0, z: 0 },
142
+ { yaw: 30, x: 0, z: 0 },
143
+ { yaw: 0, x: 0, z: 0 },
144
+ { yaw: -30, x: 0, z: 0 },
145
+ { yaw: -60, x: 0, z: 0 },
146
+ { yaw: -90, x: 0, z: 0 },
147
+ { yaw: 0, x: 0, z: 1.5 },
148
+ { yaw: 0, x: 0, z: 3 },
149
+ { yaw: 30, x: 0, z: 2 },
150
+ { yaw: -30, x: 0, z: 2 },
151
+ { yaw: 0, x: 1, z: 1 },
152
+ ]
153
+
154
+ /** one sheet: a row per camera, the picture's splat on the left and the grown one on the right */
155
+ async function views(dir: string): Promise<void> {
156
+ const out = join(dir, 'grow')
157
+ mkdirSync(out, { recursive: true })
158
+ const seedSplat = readSplat(join(dir, 'splat.ply'))
159
+ const grown = readSplat(join(dir, 'splat-grown.ply'))
160
+ const cam = cameraOf(seedSplat)
161
+ const W = 640
162
+ const H = Math.round((W * cam.height) / cam.width)
163
+ const tiles: { input: string; left: number; top: number }[] = []
164
+ for (const [i, r] of VIEW_ROUNDS.entries()) {
165
+ for (const [j, s] of [seedSplat, grown].entries()) {
166
+ const p = join(out, `view-${roundName(r)}-${j === 0 ? 'seed' : 'grown'}.png`)
167
+ await writeRender(p, render(s, cam, poseOf(r)), false, W)
168
+ tiles.push({ input: p, left: j * (W + 8), top: i * (H + 8) })
169
+ }
170
+ }
171
+ const sheet = join(out, 'views.png')
172
+ await sharp({ create: { width: 2 * W + 8, height: VIEW_ROUNDS.length * (H + 8), channels: 3, background: '#ffffff' } })
173
+ .composite(tiles)
174
+ .png()
175
+ .toFile(sheet)
176
+ console.log(`🟢 ${sheet} (rows: ${VIEW_ROUNDS.map(roundName).join(' ')})`)
177
+ }
178
+
179
+ if (import.meta.main) {
180
+ const args = process.argv.slice(2)
181
+ const flag = (name: string): string | null => {
182
+ const i = args.indexOf(name)
183
+ return i >= 0 ? (args[i + 1] ?? null) : null
184
+ }
185
+ const dirArg = args[0]
186
+ if (dirArg == null || dirArg.startsWith('--')) throw new Error('usage: grow.ts <world folder holding splat.ply> [--rounds "30 -30"] [--extend "…"] [--seed n] [--fresh] [--views]')
187
+ const dir = resolve(dirArg)
188
+ if (!existsSync(join(dir, 'splat.ply'))) throw new Error(`${dir} has no splat.ply`)
189
+ try {
190
+ if (args.includes('--views')) await views(dir)
191
+ else {
192
+ const rounds = (flag('--rounds') ?? '30 -30 60 -60').trim().split(/\s+/).map(parseRound)
193
+ await grow(dir, rounds, flag('--extend') ?? '', Number(flag('--seed') ?? 1), args.includes('--fresh'), args.includes('--reuse'))
194
+ }
195
+ } finally {
196
+ growSplatFill.host.disconnect()
197
+ }
198
+ }
@@ -0,0 +1,166 @@
1
+ // 3D gaussians in the binary ply layout of 3DGS (x y z, f_dc_0..2, opacity, scale_0..2, rot_0..3), plus the
2
+ // camera elements SHARP writes after the vertices (intrinsic, image_size): the world viewer frames a splat with them
3
+ import { readFileSync, writeFileSync } from 'node:fs'
4
+
5
+ /** the fields of one gaussian, in the order a 3DGS ply stores them */
6
+ export const FIELDS = [
7
+ 'x', 'y', 'z',
8
+ 'f_dc_0', 'f_dc_1', 'f_dc_2',
9
+ 'opacity',
10
+ 'scale_0', 'scale_1', 'scale_2',
11
+ 'rot_0', 'rot_1', 'rot_2', 'rot_3',
12
+ ] as const
13
+ export const STRIDE = FIELDS.length
14
+ /** field offsets inside one gaussian's row */
15
+ export const F = { x: 0, dc: 3, opacity: 6, scale: 7, rot: 10 } as const
16
+
17
+ /** the pinhole a splat was made for: focal and principal point in pixels, image size */
18
+ export type SplatCamera = { f: number; cx: number; cy: number; width: number; height: number }
19
+
20
+ /** n gaussians, STRIDE floats each (raw ply values: sh dc color, opacity logit, log scales, quaternion w x y z) */
21
+ export type Splat = { n: number; data: Float32Array; camera: SplatCamera | null }
22
+
23
+ const SIZES: Record<string, number> = { char: 1, uchar: 1, int8: 1, uint8: 1, short: 2, ushort: 2, int: 4, uint: 4, float: 4, float32: 4, double: 8 }
24
+
25
+ type Prop = { name: string; type: string }
26
+ type Element = { name: string; count: number; props: Prop[] }
27
+
28
+ function readValue(view: DataView, at: number, type: string): number {
29
+ switch (type) {
30
+ case 'float':
31
+ case 'float32':
32
+ return view.getFloat32(at, true)
33
+ case 'double':
34
+ return view.getFloat64(at, true)
35
+ case 'uint':
36
+ return view.getUint32(at, true)
37
+ case 'int':
38
+ return view.getInt32(at, true)
39
+ case 'uchar':
40
+ case 'uint8':
41
+ return view.getUint8(at)
42
+ case 'char':
43
+ case 'int8':
44
+ return view.getInt8(at)
45
+ case 'ushort':
46
+ return view.getUint16(at, true)
47
+ case 'short':
48
+ return view.getInt16(at, true)
49
+ default:
50
+ throw new Error(`ply: unknown property type '${type}'`)
51
+ }
52
+ }
53
+
54
+ export function parseSplat(bytes: Uint8Array): Splat {
55
+ const marker = 'end_header\n'
56
+ const head = Buffer.from(bytes.subarray(0, Math.min(bytes.length, 16384))).toString('latin1')
57
+ const end = head.indexOf(marker)
58
+ if (!head.startsWith('ply\n') || end < 0) throw new Error('ply: no header')
59
+ const lines = head.slice(0, end).split('\n')
60
+ if (!lines.some((l) => l.trim() === 'format binary_little_endian 1.0'))
61
+ throw new Error('ply: only binary_little_endian is read')
62
+ const elements: Element[] = []
63
+ for (const line of lines) {
64
+ const w = line.trim().split(/\s+/)
65
+ if (w[0] === 'element') elements.push({ name: String(w[1]), count: Number(w[2]), props: [] })
66
+ else if (w[0] === 'property') {
67
+ const el = elements[elements.length - 1]
68
+ if (el == null) throw new Error('ply: property before any element')
69
+ if (w[1] === 'list') throw new Error('ply: list properties are not read')
70
+ el.props.push({ type: String(w[1]), name: String(w[2]) })
71
+ }
72
+ }
73
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
74
+ let at = end + marker.length
75
+ let splat: { n: number; data: Float32Array } | null = null
76
+ const scalars = new Map<string, number[]>()
77
+ for (const el of elements) {
78
+ const offsets: number[] = []
79
+ let stride = 0
80
+ for (const p of el.props) {
81
+ const size = SIZES[p.type]
82
+ if (size == null) throw new Error(`ply: unknown property type '${p.type}'`)
83
+ offsets.push(stride)
84
+ stride += size
85
+ }
86
+ if (el.name === 'vertex') {
87
+ const src = FIELDS.map((name) => {
88
+ const i = el.props.findIndex((p) => p.name === name)
89
+ if (i < 0) throw new Error(`ply: vertex has no '${name}': not a 3D gaussian splat`)
90
+ const prop = el.props[i]
91
+ if (prop?.type !== 'float' && prop?.type !== 'float32') throw new Error(`ply: '${name}' is not a float`)
92
+ return offsets[i] ?? 0
93
+ })
94
+ const data = new Float32Array(el.count * STRIDE)
95
+ for (let g = 0; g < el.count; g++) {
96
+ const row = at + g * stride
97
+ for (let k = 0; k < STRIDE; k++) data[g * STRIDE + k] = view.getFloat32(row + (src[k] ?? 0), true)
98
+ }
99
+ splat = { n: el.count, data }
100
+ } else if (el.props.length === 1) {
101
+ const prop = el.props[0]
102
+ if (prop != null) {
103
+ const values: number[] = []
104
+ for (let i = 0; i < el.count; i++) values.push(readValue(view, at + i * stride, prop.type))
105
+ scalars.set(el.name, values)
106
+ }
107
+ }
108
+ at += el.count * stride
109
+ }
110
+ if (splat == null) throw new Error('ply: no vertex element')
111
+ if (at > bytes.length) throw new Error(`ply: truncated (${bytes.length} bytes, the header needs ${at})`)
112
+ const intr = scalars.get('intrinsic')
113
+ const size = scalars.get('image_size')
114
+ const camera =
115
+ intr != null && intr.length === 9 && size != null && size.length === 2
116
+ ? { f: intr[0] ?? 0, cx: intr[2] ?? 0, cy: intr[5] ?? 0, width: size[0] ?? 0, height: size[1] ?? 0 }
117
+ : null
118
+ return { ...splat, camera }
119
+ }
120
+
121
+ export function readSplat(path: string): Splat {
122
+ return parseSplat(readFileSync(path))
123
+ }
124
+
125
+ /** the binary ply: the gaussians, then the camera as SHARP writes it (identity extrinsic) when there is one */
126
+ export function encodeSplat(s: Splat): Uint8Array {
127
+ if (s.data.length !== s.n * STRIDE) throw new Error(`ply: ${s.n} gaussians need ${s.n * STRIDE} floats, got ${s.data.length}`)
128
+ const head = ['ply', 'format binary_little_endian 1.0', `element vertex ${s.n}`, ...FIELDS.map((f) => `property float ${f}`)]
129
+ const c = s.camera
130
+ if (c != null)
131
+ head.push('element extrinsic 16', 'property float extrinsic', 'element intrinsic 9', 'property float intrinsic', 'element image_size 2', 'property uint image_size')
132
+ head.push('end_header', '')
133
+ const header = Buffer.from(head.join('\n'), 'latin1')
134
+ const tail = c == null ? 0 : 16 * 4 + 9 * 4 + 2 * 4
135
+ const out = new Uint8Array(header.length + s.data.byteLength + tail)
136
+ out.set(header, 0)
137
+ const view = new DataView(out.buffer)
138
+ let at = header.length
139
+ for (let i = 0; i < s.data.length; i++, at += 4) view.setFloat32(at, s.data[i] ?? 0, true)
140
+ if (c != null) {
141
+ for (let i = 0; i < 16; i++, at += 4) view.setFloat32(at, i % 5 === 0 ? 1 : 0, true)
142
+ for (const v of [c.f, 0, c.cx, 0, c.f, c.cy, 0, 0, 1]) {
143
+ view.setFloat32(at, v, true)
144
+ at += 4
145
+ }
146
+ view.setUint32(at, c.width, true)
147
+ view.setUint32(at + 4, c.height, true)
148
+ }
149
+ return out
150
+ }
151
+
152
+ export function writeSplat(path: string, s: Splat): void {
153
+ writeFileSync(path, encodeSplat(s))
154
+ }
155
+
156
+ /** one splat after the other; the first one's camera stays */
157
+ export function concatSplats(parts: Splat[]): Splat {
158
+ const n = parts.reduce((a, p) => a + p.n, 0)
159
+ const data = new Float32Array(n * STRIDE)
160
+ let at = 0
161
+ for (const p of parts) {
162
+ data.set(p.data, at)
163
+ at += p.data.length
164
+ }
165
+ return { n, data, camera: parts[0]?.camera ?? null }
166
+ }
@@ -0,0 +1,207 @@
1
+ // a CPU gaussian splat rasterizer (EWA: each gaussian a projected ellipse, sorted near to far, blended front to back)
2
+ // with the three maps the grow loop needs from one camera: color, coverage (alpha) and depth in metres.
3
+ // axes are SHARP's (OpenCV): x right, y down, z forward; a pose is camera to world
4
+ import { F, STRIDE, type Splat, type SplatCamera } from './ply.ts'
5
+
6
+ export type Vec3 = [number, number, number]
7
+ /** a 3x3 matrix, row major */
8
+ export type Mat3 = [number, number, number, number, number, number, number, number, number]
9
+ /** where a camera stands (C) and how it is turned (R: its x, y, z axes as the columns, in world axes) */
10
+ export type Pose = { R: Mat3; C: Vec3 }
11
+
12
+ export const IDENTITY: Mat3 = [1, 0, 0, 0, 1, 0, 0, 0, 1]
13
+
14
+ export function mul3(a: Mat3, b: Mat3): Mat3 {
15
+ const o: number[] = []
16
+ for (let r = 0; r < 3; r++)
17
+ for (let c = 0; c < 3; c++) o.push(a[r * 3]! * b[c]! + a[r * 3 + 1]! * b[3 + c]! + a[r * 3 + 2]! * b[6 + c]!)
18
+ return o as Mat3
19
+ }
20
+
21
+ export function transpose3(a: Mat3): Mat3 {
22
+ return [a[0], a[3], a[6], a[1], a[4], a[7], a[2], a[5], a[8]]
23
+ }
24
+
25
+ export function apply3(m: Mat3, v: Vec3): Vec3 {
26
+ return [
27
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
28
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
29
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
30
+ ]
31
+ }
32
+
33
+ /** the turn of a camera: yaw to its left (degrees, about the down axis), then pitch up */
34
+ export function turn(yawLeft: number, pitchUp = 0): Mat3 {
35
+ const y = (yawLeft * Math.PI) / 180
36
+ const p = (pitchUp * Math.PI) / 180
37
+ const yaw: Mat3 = [Math.cos(y), 0, -Math.sin(y), 0, 1, 0, Math.sin(y), 0, Math.cos(y)]
38
+ const pitch: Mat3 = [1, 0, 0, 0, Math.cos(p), -Math.sin(p), 0, Math.sin(p), Math.cos(p)]
39
+ return mul3(yaw, pitch)
40
+ }
41
+
42
+ export function quatToMat(w: number, x: number, y: number, z: number): Mat3 {
43
+ const n = Math.hypot(w, x, y, z) || 1
44
+ w /= n
45
+ x /= n
46
+ y /= n
47
+ z /= n
48
+ return [
49
+ 1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y),
50
+ 2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x),
51
+ 2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y),
52
+ ]
53
+ }
54
+
55
+ export function matToQuat(m: Mat3): [number, number, number, number] {
56
+ const t = m[0] + m[4] + m[8]
57
+ if (t > 0) {
58
+ const s = Math.sqrt(t + 1) * 2
59
+ return [0.25 * s, (m[7] - m[5]) / s, (m[2] - m[6]) / s, (m[3] - m[1]) / s]
60
+ }
61
+ if (m[0] > m[4] && m[0] > m[8]) {
62
+ const s = Math.sqrt(1 + m[0] - m[4] - m[8]) * 2
63
+ return [(m[7] - m[5]) / s, 0.25 * s, (m[1] + m[3]) / s, (m[2] + m[6]) / s]
64
+ }
65
+ if (m[4] > m[8]) {
66
+ const s = Math.sqrt(1 + m[4] - m[0] - m[8]) * 2
67
+ return [(m[2] - m[6]) / s, (m[1] + m[3]) / s, 0.25 * s, (m[5] + m[7]) / s]
68
+ }
69
+ const s = Math.sqrt(1 + m[8] - m[0] - m[4]) * 2
70
+ return [(m[3] - m[1]) / s, (m[2] + m[6]) / s, (m[5] + m[7]) / s, 0.25 * s]
71
+ }
72
+
73
+ const SH_C0 = 0.28209479177387814
74
+
75
+ export type Render = {
76
+ width: number
77
+ height: number
78
+ /** rgb 0..1 over black, 3 floats a pixel */
79
+ color: Float32Array
80
+ /** how much of each pixel the gaussians cover, 0..1 */
81
+ alpha: Float32Array
82
+ /** the blended distance along the camera's z, metres; 0 where nothing is */
83
+ depth: Float32Array
84
+ }
85
+
86
+ export type RenderOptions = {
87
+ /** gaussians nearer than this to the camera plane are skipped (metres) */
88
+ near?: number
89
+ /** an ellipse never reaches past this many pixels from its centre */
90
+ maxRadius?: number
91
+ /** rgb 0..1 a gaussian, in place of its sh dc colour (a view dependent colour evaluated for this camera) */
92
+ colors?: Float32Array
93
+ }
94
+
95
+ export function render(s: Splat, cam: SplatCamera, pose: Pose, o: RenderOptions = {}): Render {
96
+ const W = cam.width
97
+ const H = cam.height
98
+ const near = o.near ?? 0.05
99
+ const maxRadius = o.maxRadius ?? 400
100
+ const toCam = transpose3(pose.R)
101
+ const d = s.data
102
+ // the projected ellipses, kept for the visible ones only
103
+ const u0 = new Float32Array(s.n)
104
+ const v0 = new Float32Array(s.n)
105
+ const depthOf = new Float32Array(s.n)
106
+ const conic = new Float32Array(s.n * 3)
107
+ const radius = new Uint16Array(s.n)
108
+ const visible: number[] = []
109
+ for (let g = 0; g < s.n; g++) {
110
+ const b = g * STRIDE
111
+ const px = d[b]! - pose.C[0]
112
+ const py = d[b + 1]! - pose.C[1]
113
+ const pz = d[b + 2]! - pose.C[2]
114
+ const x = toCam[0] * px + toCam[1] * py + toCam[2] * pz
115
+ const y = toCam[3] * px + toCam[4] * py + toCam[5] * pz
116
+ const z = toCam[6] * px + toCam[7] * py + toCam[8] * pz
117
+ if (z < near) continue
118
+ const u = (cam.f * x) / z + cam.cx
119
+ const v = (cam.f * y) / z + cam.cy
120
+ // M = toCam · Rg · diag(scale); the camera covariance is M Mᵀ, the image one J M (J M)ᵀ
121
+ const rg = quatToMat(d[b + F.rot]!, d[b + F.rot + 1]!, d[b + F.rot + 2]!, d[b + F.rot + 3]!)
122
+ const sx = Math.exp(d[b + F.scale]!)
123
+ const sy = Math.exp(d[b + F.scale + 1]!)
124
+ const sz = Math.exp(d[b + F.scale + 2]!)
125
+ const m = mul3(toCam, rg)
126
+ const fz = cam.f / z
127
+ const fxz = (cam.f * x) / (z * z)
128
+ const fyz = (cam.f * y) / (z * z)
129
+ // rows of J M, each column scaled by its axis' size
130
+ const a0 = (fz * m[0] - fxz * m[6]) * sx
131
+ const a1 = (fz * m[1] - fxz * m[7]) * sy
132
+ const a2 = (fz * m[2] - fxz * m[8]) * sz
133
+ const c0 = (fz * m[3] - fyz * m[6]) * sx
134
+ const c1 = (fz * m[4] - fyz * m[7]) * sy
135
+ const c2 = (fz * m[5] - fyz * m[8]) * sz
136
+ // the 0.3 px² low pass of the 3DGS rasterizer: no ellipse thinner than a pixel
137
+ const sxx = a0 * a0 + a1 * a1 + a2 * a2 + 0.3
138
+ const sxy = a0 * c0 + a1 * c1 + a2 * c2
139
+ const syy = c0 * c0 + c1 * c1 + c2 * c2 + 0.3
140
+ const det = sxx * syy - sxy * sxy
141
+ if (det <= 0) continue
142
+ const mid = 0.5 * (sxx + syy)
143
+ const lmax = mid + Math.sqrt(Math.max(0.1, mid * mid - det))
144
+ const r = Math.min(maxRadius, Math.ceil(3 * Math.sqrt(lmax)))
145
+ if (u + r < 0 || u - r >= W || v + r < 0 || v - r >= H) continue
146
+ u0[g] = u
147
+ v0[g] = v
148
+ depthOf[g] = z
149
+ conic[g * 3] = syy / det
150
+ conic[g * 3 + 1] = -sxy / det
151
+ conic[g * 3 + 2] = sxx / det
152
+ radius[g] = r
153
+ visible.push(g)
154
+ }
155
+ visible.sort((a, b) => depthOf[a]! - depthOf[b]!)
156
+
157
+ const color = new Float32Array(W * H * 3)
158
+ const T = new Float32Array(W * H).fill(1)
159
+ const depthSum = new Float32Array(W * H)
160
+ for (const g of visible) {
161
+ const b = g * STRIDE
162
+ const op = 1 / (1 + Math.exp(-d[b + F.opacity]!))
163
+ if (op < 1 / 255) continue
164
+ const cr = o.colors != null ? o.colors[g * 3]! : Math.min(1, Math.max(0, 0.5 + SH_C0 * d[b + F.dc]!))
165
+ const cg = o.colors != null ? o.colors[g * 3 + 1]! : Math.min(1, Math.max(0, 0.5 + SH_C0 * d[b + F.dc + 1]!))
166
+ const cb = o.colors != null ? o.colors[g * 3 + 2]! : Math.min(1, Math.max(0, 0.5 + SH_C0 * d[b + F.dc + 2]!))
167
+ const u = u0[g]!
168
+ const v = v0[g]!
169
+ const z = depthOf[g]!
170
+ const ca = conic[g * 3]!
171
+ const cbc = conic[g * 3 + 1]!
172
+ const cc = conic[g * 3 + 2]!
173
+ const r = radius[g]!
174
+ const xa = Math.max(0, Math.floor(u - r))
175
+ const xb = Math.min(W - 1, Math.ceil(u + r))
176
+ const ya = Math.max(0, Math.floor(v - r))
177
+ const yb = Math.min(H - 1, Math.ceil(v + r))
178
+ for (let py = ya; py <= yb; py++) {
179
+ const dy = py + 0.5 - v
180
+ const row = py * W
181
+ for (let px = xa; px <= xb; px++) {
182
+ const i = row + px
183
+ const t = T[i]!
184
+ if (t < 1e-4) continue
185
+ const dx = px + 0.5 - u
186
+ const power = -0.5 * (ca * dx * dx + cc * dy * dy) - cbc * dx * dy
187
+ if (power > 0 || power < -4.5) continue
188
+ const al = Math.min(0.99, op * Math.exp(power))
189
+ if (al < 1 / 255) continue
190
+ const w = t * al
191
+ color[i * 3] = color[i * 3]! + w * cr
192
+ color[i * 3 + 1] = color[i * 3 + 1]! + w * cg
193
+ color[i * 3 + 2] = color[i * 3 + 2]! + w * cb
194
+ depthSum[i] = depthSum[i]! + w * z
195
+ T[i] = t * (1 - al)
196
+ }
197
+ }
198
+ }
199
+ const alpha = new Float32Array(W * H)
200
+ const depth = new Float32Array(W * H)
201
+ for (let i = 0; i < W * H; i++) {
202
+ const a = 1 - T[i]!
203
+ alpha[i] = a
204
+ depth[i] = a > 1e-3 ? depthSum[i]! / a : 0
205
+ }
206
+ return { width: W, height: H, color, alpha, depth }
207
+ }