gui.ts

examples/lcc/gui.ts · raw · open the example · all examples · site home

Exports: MonitormakeGui

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
// Tweakpane v4 panel of the LCC viewer, after examples/splats/gui.ts.
// Bindings write straight into the viewer state, the streamer's settings and
// the splat renderer and its params, which main.ts, the streamer and the
// renderer apply every frame; changes that need work (framing, export) go
// through actions. Every folder but Monitors starts collapsed.
import * as EssentialsPlugin from "@tweakpane/plugin-essentials";
import { Pane, type BindingParams, type FolderApi } from "tweakpane";
import type { WebGPURenderer } from "three/webgpu";
import { Hdr, type CameraControls, type GpuProfile, type GpuProfiler, type SplatRenderer } from "@sparkjsdev/radix";
import { addControlsFolder } from "./controlsPane.js";
import type { LccStreamerSettings } from "./LccStreamer.js";
import type { ViewerState } from "./main.js";

const fixed = (digits: number) => (v: number) => v.toFixed(digits);
// GPU "-": no timestamps (GPU timing off)
const ms = (gpu: number | undefined, cpu: number) => `${gpu === undefined ? "-" : gpu.toFixed(2)} · ${cpu.toFixed(2)}`;

let groups = 0;
function segmented<T extends string | number>(label: string, values: T[], titles?: string[]): BindingParams {
  groups += 1;
  return {
    label,
    view: "radiogrid",
    groupName: `segmented-${groups}`,
    size: [values.length, 1],
    cells: (x: number) => ({ title: titles?.[x] ?? String(values[x]), value: values[x] }),
  };
}

// Nested plain objects (a preset) into the target, key by key: only keys
// the target has
function assignDeep(target: object, source: object = {}) {
  const into = target as Record<string, unknown>;
  for (const [key, value] of Object.entries(source)) {
    if (!(key in into)) {
      continue;
    }
    if (typeof into[key] === "object" && into[key] !== null && typeof value === "object" && value !== null) {
      assignDeep(into[key], value);
    } else {
      into[key] = value;
    }
  }
}

export interface Monitor {
  scene: string;
  drawn: string;
  levels: string;
  blocks: string;
  cache: string;
  decode: string;
  sh: string;
  environment: string;
  collision: string;
  walk: string;
}

export function makeGui({ state, settings, hdr, renderer, profiler, splats, controls, actions }: {
  state: ViewerState;
  settings: LccStreamerSettings;
  hdr: boolean;
  renderer: WebGPURenderer;
  profiler?: GpuProfiler;
  splats: SplatRenderer;
  controls: CameraControls;
  actions: {
    frame(): void;
    resetView(): void;
    exportFile(): void;
    toggleWalk(): void;
  };
}) {
  const pane = new Pane({ title: "Radix LCC" });
  pane.registerPlugin(EssentialsPlugin);
  const folder = (title: string, parent: FolderApi | Pane = pane) => parent.addFolder({ title, expanded: false });
  const slider = <T extends object>(c: FolderApi, target: T, key: keyof T & string, label: string, min: number, max: number, digits = 2) =>
    c.addBinding(target, key, { label, min, max, step: 10 ** -digits, format: fixed(digits) });

  // --- Monitors ---
  const monitors = pane.addFolder({ title: "Monitors" });
  const fpsGraph = monitors.addBlade({ view: "fpsgraph", label: "fps", rows: 2, min: 0, max: 144 }) as unknown as { begin(): void; end(): void };
  const frame = { ms: ms(undefined, 0) };
  const values: Monitor = { scene: "none", drawn: "0", levels: "", blocks: "", cache: "", decode: "", sh: "", environment: "", collision: "", walk: "" };
  monitors.addBinding(values, "scene", { readonly: true });
  monitors.addBinding(frame, "ms", { readonly: true, label: "GPU · CPU ms" });
  // GPU timestamps cost frame time (their queries resolve every report), so
  // they start off (?profile=1 starts them on); CPU phases are timed either way
  if (profiler) {
    const timing = { get on() { return profiler.active; }, set on(value: boolean) { profiler.active = value; } };
    monitors.addBinding(timing, "on", { label: profiler.supported ? "GPU timing" : "GPU timing (n/a)", disabled: !profiler.supported });
  }
  monitors.addBinding(values, "drawn", { readonly: true, label: "drawn (in view)" });
  monitors.addBinding(values, "levels", { readonly: true, label: "per level" });
  monitors.addBinding(values, "blocks", { readonly: true, label: "blocks" });
  monitors.addBinding(values, "cache", { readonly: true, label: "GPU cache" });
  monitors.addBinding(values, "decode", { readonly: true, label: "decoded" });
  monitors.addBinding(values, "sh", { readonly: true, label: "SH" });
  monitors.addBinding(values, "environment", { readonly: true, label: "environment" });
  monitors.addBinding(values, "collision", { readonly: true, label: "collision" });
  monitors.addBinding(values, "walk", { readonly: true, label: "walk" });
  const phaseFolder = monitors.addFolder({ title: "Phases  (GPU · CPU ms)", expanded: false });
  const phases: Record<string, string> = {};

  // --- Level of detail ---
  const lod = folder("Level of detail");
  const level = { auto: settings.level === "auto", fixed: settings.level === "auto" ? 0 : settings.level };
  const fixedLevel = lod.addBinding(level, "fixed", { label: "fixed level", min: 0, max: 7, step: 1 });
  lod.addBinding(level, "auto", { label: "auto (by distance)" }).on("change", () => {
    settings.level = level.auto ? "auto" : level.fixed;
  });
  fixedLevel.on("change", () => {
    if (!level.auto) {
      settings.level = level.fixed;
    }
  });
  slider(lod, settings, "lodDistance", "level 0 within", 0.05, 50);
  slider(lod, settings, "hysteresis", "hysteresis (v1)", 0, 1);
  slider(lod, settings, "behindPenalty", "behind penalty (LCC2)", 1, 4);
  lod.addBinding(settings, "budget", { label: "splat budget", min: 100_000, max: 20_000_000, step: 100_000, format: (v: number) => `${(v / 1e6).toFixed(1)} M` });
  lod.addBinding(settings, "budgetMode", segmented("budget (LCC2)", ["limit", "target"]));
  const cache = { mb: settings.cacheBytes / 1e6 };
  lod.addBinding(cache, "mb", { label: "GPU cache (MB)", min: 128, max: 8192, step: 64 }).on("change", () => (settings.cacheBytes = cache.mb * 1e6));
  lod.addBinding(settings, "freeze", { label: "freeze selection" });
  lod.addBinding(settings, "colorByLevel", { label: "color by level" });
  lod.addBinding(settings, "environment", { label: "environment" });
  lod.addBinding(state, "showCells", { label: "cell boxes" });

  // --- Collision: the debug overlay and walk mode (G) ---
  const collision = folder("Collision");
  const c = state.collision;
  collision.addBinding(c, "mesh", { label: "wireframe" });
  collision.addBinding(c, "boxes", { label: "chunk boxes" });
  collision.addBinding(c, "leaves", { label: "BVH boxes" });
  collision.addBinding(c, "leafDepth", { label: "BVH depth", min: 0, max: 24, step: 1 });
  collision.addBinding(c, "depthTest", { label: "depth test" });
  slider(collision, c, "opacity", "opacity", 0.05, 1);
  collision.addBinding(c, "radius", { label: "load radius", min: 5, max: 1000, step: 5 });
  collision.addButton({ title: "Walk / stop (G)" }).on("click", () => actions.toggleWalk());
  const walk = state.walk;
  slider(collision, walk, "eyeHeight", "eye height", 0.05, 3);
  slider(collision, walk, "radius", "radius", 0.01, 1);
  slider(collision, walk, "stepHeight", "step height", 0, 1);
  slider(collision, walk, "speed", "walk speed", 0.1, 5);
  slider(collision, walk, "gravity", "gravity", 0, 30, 1);
  slider(collision, walk, "jumpSpeed", "jump speed", 0, 10, 1);

  // --- Spherical harmonics ---
  const sh = folder("Spherical harmonics");
  sh.addBinding(state.sh, "enabled", { label: "on" });
  sh.addBinding(state.sh, "degree", segmented("degree", [0, 1, 2, 3]));

  // --- Renderer (method, sort and key bits are in the quick bar) ---
  const p = splats.params;
  const o = splats.objectParams;
  const render = folder("Renderer");
  const cpuSort = folder("CPU sort (WebGL2 fallback)", render);
  slider(cpuSort, o, "sortGuard", "guard band", 0, 3);
  if (splats.autoSort) {
    slider(cpuSort, splats.autoSort, "distance", "re-sort after (m)", 0, 1, 3);
    const autoSort = splats.autoSort;
    const turn = { get degrees() { return autoSort.angle * 180 / Math.PI; }, set degrees(value) { autoSort.angle = value * Math.PI / 180; } };
    slider(cpuSort, turn, "degrees", "or after (deg)", 0, 45, 1);
  }

  const quality = folder("Quality");
  slider(quality, p, "minAlpha", "min alpha", 0, 0.1, 3);
  slider(quality, p, "maxStdDev", "max std dev", 1, 4);
  slider(quality, p, "falloff", "falloff (0: discs)", 0, 1);
  slider(quality, o, "minPixelRadius", "min px radius", 0, 4);
  slider(quality, o, "maxPixelRadius", "max px radius", 16, 2048, 0);
  slider(quality, o, "blurAmount", "blur", 0, 2);
  slider(quality, o, "preBlurAmount", "pre-blur", 0, 2);
  slider(quality, o, "clipXY", "clip xy", 1, 2);

  const lens = folder("Depth of field");
  slider(lens, o, "focalDistance", "focal dist", 0, 20);
  slider(lens, o, "apertureTan", "aperture tan", 0, 0.05, 3);

  // --- Display: HDR canvas, headroom tone mapping, background ---
  const display = folder("Display");
  const output = { extended: hdr };
  display.addBinding(output, "extended", { label: hdr ? "HDR canvas" : "HDR (?hdr=1)", disabled: !hdr }).on("change", (event) => Hdr.setOutput(renderer, event.value));
  const toneMapping = Hdr.useToneMapping(renderer, { enabled: false });
  display.addBinding(toneMapping, "enabled", { label: "tone mapping" });
  slider(display, toneMapping.headroom as { value: number }, "value", "headroom", 1, 16);
  display.addBinding(toneMapping, "exposure", { min: 0, max: 4, format: fixed(2) });
  display.addBinding(state, "background", { color: { type: "float" } });

  addControlsFolder(pane, controls);

  const camera = folder("Camera");
  camera.addButton({ title: "Start view" }).on("click", () => actions.resetView());
  camera.addButton({ title: "Frame" }).on("click", () => actions.frame());

  // --- Export: the drawn blocks as ext splats, in the file's frame ---
  const exporter = folder("Export");
  exporter.addBinding(state, "exportFormat", segmented("format", ["rdx", "ply", "compressed-ply", "spz"], ["rdx", "ply", "c.ply", "spz"]));
  // Read as each block decodes; without copies, export reads the GPU back
  exporter.addBinding(settings, "keepCpu", { label: "keep CPU copies" });
  exporter.addButton({ title: "Download drawn blocks" }).on("click", () => actions.exportFile());

  // --- Presets: LoD, SH and render settings as JSON ---
  const presets = folder("Presets");
  const preset = { json: "" };
  presets.addButton({ title: "Export to JSON (copies)" }).on("click", () => {
    preset.json = JSON.stringify({ settings, sh: state.sh, method: splats.method, sortBits: splats.sortBits, params: p, objectParams: o });
    void navigator.clipboard?.writeText(preset.json);
    pane.refresh();
  });
  presets.addBinding(preset, "json", { label: "json", multiline: true, rows: 3 });
  presets.addButton({ title: "Import JSON" }).on("click", () => {
    const parsed = JSON.parse(preset.json) as { settings?: object; sh?: object; method?: SplatRenderer["method"]; sortBits?: SplatRenderer["sortBits"]; params?: object; objectParams?: object };
    assignDeep(settings, parsed.settings);
    assignDeep(state.sh, parsed.sh);
    assignDeep(p, parsed.params);
    assignDeep(o, parsed.objectParams);
    splats.method = parsed.method ?? splats.method;
    splats.sortBits = parsed.sortBits ?? splats.sortBits;
    level.auto = settings.level === "auto";
    level.fixed = settings.level === "auto" ? level.fixed : settings.level;
    cache.mb = settings.cacheBytes / 1e6;
    pane.refresh();
  });

  return {
    frameBegin: () => fpsGraph.begin(),
    frameEnd: () => fpsGraph.end(),
    refresh() {
      level.auto = settings.level === "auto";
      if (settings.level !== "auto") {
        level.fixed = settings.level;
      }
      pane.refresh();
    },
    monitor(next: Partial<Monitor>) {
      Object.assign(values, next);
    },
    profile(profile: GpuProfile | undefined) {
      if (!profile) {
        return;
      }
      const sum = (entries: Record<string, number>) => Object.values(entries).reduce((a, b) => a + b, 0);
      const timed = Object.keys(profile.gpu).length > 0;
      frame.ms = ms(timed ? sum(profile.gpu) : undefined, sum(profile.cpu));
      for (const name of new Set([...Object.keys(profile.gpu), ...Object.keys(profile.cpu)])) {
        if (!(name in phases)) {
          phases[name] = "";
          phaseFolder.addBinding(phases, name, { readonly: true, label: name });
        }
        phases[name] = ms(timed ? profile.gpu[name] ?? 0 : undefined, profile.cpu[name] ?? 0);
      }
    },
  };
}