Files
ttstd-3d-director/src/editor/canvas/viewportBokeh.tsx
T
tongtong ada16fa3ec fix(timeline): 修复拖动播放头时画布不实时更新
拖动期间改用 performance.now() 时间片节流替代 requestAnimationFrame,避免在窗口被遮挡或后台节流时整段拖动不写 playhead。同时草稿档不再跳过景深渲染,仅降低模糊采样点数以保留移焦与变焦预览。
2026-09-21 10:19:43 +08:00

215 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Vector2, Vector4, type PerspectiveCamera, type Scene, type WebGLRenderer } from "three";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
import { BokehPass } from "three/examples/jsm/postprocessing/BokehPass.js";
import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
import { apertureToBokeh, type ResolvedLens } from "../schema/cameraGeometry";
import { BOKEH_MIN_TAPS, computeBokehUniforms } from "./bokehSettings";
import { configureAdaptiveBokeh } from "./adaptiveBokehShader";
/**
* 复用的景深后处理:用一份按 WebGLRenderer 缓存的 EffectComposer(RenderPass + BokehPass + OutputPass)
* 渲染场景,让浅景深虚化在三处完全一致 —— 主视口机位视角(ActiveCameraPlaybackSync)、
* 镜头监视器(LensMonitor)、视频逐帧导出(videoExport),另外机位截图也走这里。
*
* 这是「监视器 / 机位视角 / 导出」唯一的渲染实现,三处只负责解析出「当前显示机位 + 该时刻镜头」
* 再调用本函数,因此取景、焦距、虚化不会各写一套而漂移。
* 合成器按 gl 缓存(每个 Canvas 一份),尺寸 / 像素比变化时按需重建。
* 失败(如浏览器后处理不支持)则回退到普通渲染,画面永远可用。
*
* 景深参数(focus / aperture / maxblur / aspect / 采样点数)统一由 computeBokehUniforms 算;
* 采样点用自适应版本(configureAdaptiveBokeh);深度 pass 期间还会摘掉场景背景
* (withoutSceneBackground / makeDepthPassBackgroundSafe)—— 三条都是为了「三处看到的虚化一致」。
*/
/**
* 渲染期间临时摘掉 scene.background,渲完(含抛错)原样恢复。
*
* 为什么景深必须这么做 —— three 的一个坑,源码依据:
* 1. BokehPass 把「打包深度」(RGBADepthPacking) 写在渲染目标的**颜色**通道里(不是深度缓冲);
* 2. scene.background 是贴图时(全景图 / 贴图背景),three 会往同一个目标里再画一张全屏背景面:
* 它的材质是 `depthWrite:false` + `allowOverride:false`(见 WebGLBackground),看着"不影响深度",
* 但 **colorWrite 照样是开的** → 它一旦排在模型之后被画,就把整张打包深度覆盖成背景图的像素值;
* 3. 不透明物体的绘制顺序由 painterSortStable 决定,而它**先比 material.id**(为了少切状态)再比深度 ——
* 背景面材质 id 的大小完全取决于「全景图 / 贴图背景与模型谁先加载」,所以它既可能最先画(没事),
* 也可能最后画(把已经写好的深度整片冲掉)。
*
* 深度被冲掉之后,`getViewZ()` 解出来的距离全是垃圾(≈ 远平面)→ `factor` 巨大 → `dofblur` 直接
* 顶到 maxblur → **整幅画面(连合焦的主体)都按最大模糊糊成一片**,而背景贴图的明暗还会渗进"距离"里,
* 在渐变背景上留下横向条带。这正是「机位视角很糊、镜头监视器却正常」的成因:两个 Canvas 各自一份场景、
* 模型材质与背景材质的创建顺序不同,背景面排序结果就不一样。
*
* 背景早就被 RenderPass 画进颜色缓冲了,景深 depth pass 根本不需要它 —— 摘掉零副作用。
*/
export function withoutSceneBackground<T>(scene: { background: Scene["background"] }, render: () => T): T {
const background = scene.background;
scene.background = null;
try {
return render();
} finally {
scene.background = background;
}
}
/**
* 把 BokehPass 的 render 包一层「渲染期间不带场景背景」。
* 只影响它内部那次「overrideMaterial 深度渲染」,合成用的全屏四边形与颜色缓冲都不受影响。
*/
function makeDepthPassBackgroundSafe(pass: BokehPass, scene: Scene) {
const renderBokehPass = pass.render.bind(pass);
pass.render = ((...args: Parameters<BokehPass["render"]>) =>
withoutSceneBackground(scene, () => renderBokehPass(...args))) as BokehPass["render"];
return pass;
}
interface BokehState {
composer: EffectComposer;
bokeh: BokehPass;
width: number;
height: number;
pixelRatio: number;
scene: Scene;
camera: PerspectiveCamera;
}
const bokehCache = new WeakMap<WebGLRenderer, BokehState>();
const sizeVector = new Vector2();
/** 读取画布 CSS 尺寸(DOM 口径的 y 轴换算用),与 sizeVector 分开避免相互覆盖 */
const canvasSizeVector = new Vector2();
function readSize(gl: WebGLRenderer): { width: number; height: number; pixelRatio: number } {
gl.getSize(sizeVector);
return { width: sizeVector.x, height: sizeVector.y, pixelRatio: gl.getPixelRatio() };
}
function ensureBokehState(
gl: WebGLRenderer,
scene: Scene,
camera: PerspectiveCamera,
sizeOverride?: { width: number; height: number; pixelRatio: number }
): BokehState | null {
const { width, height, pixelRatio } = sizeOverride ?? readSize(gl);
// 合成器必须按画布真实分辨率(CSS 尺寸 × pixelRatio = drawing buffer)渲染:
// 如果只按 CSS 尺寸渲染,结果会被放大 dpr 倍,整幅画面发虚(实测主视口糊成一团就是这个原因),
// 而且不同画布 dpr 不同(主视口 dpr 更高、监视器被夹到 1.5)时两边糊的程度还不一样。
const existing = bokehCache.get(gl);
if (
existing &&
existing.scene === scene &&
existing.camera === camera &&
existing.width === width &&
existing.height === height &&
existing.pixelRatio === pixelRatio
) {
return existing;
}
try {
const composer = new EffectComposer(gl);
composer.setPixelRatio(pixelRatio);
composer.setSize(width, height);
composer.addPass(new RenderPass(scene, camera));
const bokeh = new BokehPass(scene, camera, {
focus: 5,
aperture: apertureToBokeh(2.8),
maxblur: 0.012,
});
// 换成自适应采样的合成 shader(原版 41 个点按同心圆环摆,大画布上半径一大就看出重影)
configureAdaptiveBokeh(bokeh, BOKEH_MIN_TAPS);
// 深度 pass 期间摘掉背景贴图,否则打包深度会被背景面覆盖,虚化整幅饱和(见函数注释)
makeDepthPassBackgroundSafe(bokeh, scene);
composer.addPass(bokeh);
// OutputPass 负责把线性结果做色调映射 + sRGB 转换,否则经后处理的画面会偏暗/发灰
composer.addPass(new OutputPass());
const next: BokehState = { composer, bokeh, width, height, pixelRatio, scene, camera };
bokehCache.set(gl, next);
return next;
} catch {
bokehCache.delete(gl);
return null;
}
}
/**
* 用景深后处理渲染一帧;lens 提供对焦距离 / 光圈 / 最大模糊量。
* viewportRect(CSS 像素,相对画布左上角,与 ViewportFrameRect / 画幅框同口径)用于「机位视角」:
* 那里把机位画面渲染到传感器画幅等比适配出来的矩形里。
* 监视器 / 导出本就按传感器画幅渲染;机位视角若按整个视口渲染,相机投影画幅更宽 →
* 水平视场角更大、物体被压得更窄,而虚化半径按画面宽度的固定比例(UV)不变 →
* 物体相对于自身看起来就更糊。传入 viewportRect 后,合成器按矩形尺寸渲染、
* 并经 setViewport/setScissor 把结果落到该矩形,让机位视角的取景 / 虚化与监视器逐像素一致。
*/
export function renderSceneWithBokeh(
gl: WebGLRenderer,
scene: Scene,
camera: PerspectiveCamera,
lens: ResolvedLens,
viewportRect?: { left: number; top: number; width: number; height: number },
options: { draft?: boolean } = {}
): void {
const state = ensureBokehState(
gl,
scene,
camera,
viewportRect ? { width: viewportRect.width, height: viewportRect.height, pixelRatio: gl.getPixelRatio() } : undefined
);
if (!state) {
gl.render(scene, camera);
return;
}
// 三处(机位视角 / 监视器 / 导出)共用同一份口径算景深参数:focus / aperture / maxblur / aspect
// 只由 lens + 这块画布的尺寸决定;采样点数还会按模糊半径的设备像素数自适应加密。
const settings = computeBokehUniforms({
lens,
renderWidth: state.width,
renderHeight: state.height,
pixelRatio: state.pixelRatio,
});
// 草稿档(拖动播放头时):**景深照常渲染**,只把采样点数压到最低档。
// 拖动时恰恰要看着「移焦 / 变焦 / 虚化强弱」跟着变,直接跳过景深会让人以为镜头没动(画面里根本没有虚化),
// 所以这里只省最贵的「逐像素 41~96 次采样」,模糊的观感几乎不变。
// 特意没采用「拖动时降分辨率」:那会重建合成器的渲染目标(几十 MB 显存回收 + 重新分配),
// 反倒让每次开始拖动的头几帧卡一下。
configureAdaptiveBokeh(state.bokeh, options.draft ? BOKEH_MIN_TAPS : settings.taps);
const uniforms = (state.bokeh as unknown as { uniforms?: Record<string, { value: number }> }).uniforms;
if (uniforms) {
if (uniforms.focus) uniforms.focus.value = settings.focus;
if (uniforms.aperture) uniforms.aperture.value = settings.aperture;
if (uniforms.maxblur) uniforms.maxblur.value = settings.maxblur;
// aspect 必须等于渲染画幅(合成器尺寸的宽高比):竖直方向的扩散量按它缩放,
// 画幅对了虚化形状才和监视器一致。合成器是缓存复用的,每帧显式写避免残留。
if (uniforms.aspect) uniforms.aspect.value = settings.aspect;
}
// 有遮幅矩形时,把最终结果落到画布上那个矩形里(中间 pass 仍渲染到完整目标,不受影响)。
const prevViewport = new Vector4();
const prevScissor = new Vector4();
let prevScissorTest = false;
if (viewportRect) {
gl.getViewport(prevViewport);
gl.getScissor(prevScissor);
prevScissorTest = gl.getScissorTest();
// 两处换算:WebGL 视口原点在画布左下角,而传进来的矩形是 DOM 口径(左上角原点),y 要翻一次。
// 另外 setViewport / setScissor 收的是「逻辑像素」(CSS 像素),three 内部自己乘 pixelRatio;
// 这里若再乘一遍 dpr,遮幅会在高分屏上被放大 dpr 倍、并锚到画布左下角 ——
// 表现就是左边 / 下边留白、右边 / 上边被裁掉,机位画面显示不全。
const canvasSize = gl.getSize(canvasSizeVector);
const viewportLeft = viewportRect.left;
const viewportBottom = canvasSize.y - viewportRect.top - viewportRect.height;
gl.setViewport(viewportLeft, viewportBottom, viewportRect.width, viewportRect.height);
gl.setScissor(viewportLeft, viewportBottom, viewportRect.width, viewportRect.height);
gl.setScissorTest(true);
}
state.composer.render();
if (viewportRect) {
gl.setScissorTest(prevScissorTest);
gl.setScissor(prevScissor);
gl.setViewport(prevViewport);
}
}